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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6370f16bd30161ef0727917c49f9040c6d5f1486 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/linear_algebra/matrix/symmetric.lean | 8533144a3d85d010c903f5c427ab7fcfcfbb3c95 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 4,118 | lean | /-
Copyright (c) 2021 Lu-Ming Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Lu-Ming Zhang
-/
import data.matrix.block
/-!
# Symmetric matrices
This file contains the definition and basic results about symmetric matrices.
## Main definition
* `matrix.is_symm `: a matrix `A : matrix n n α` is "symmetric" if `Aᵀ = A`.
## Tags
symm, symmetric, matrix
-/
variables {α β n m R : Type*}
namespace matrix
open_locale matrix
/-- A matrix `A : matrix n n α` is "symmetric" if `Aᵀ = A`. -/
def is_symm (A : matrix n n α) : Prop := Aᵀ = A
lemma is_symm.eq {A : matrix n n α} (h : A.is_symm) : Aᵀ = A := h
/-- A version of `matrix.ext_iff` that unfolds the `matrix.transpose`. -/
lemma is_symm.ext_iff {A : matrix n n α} : A.is_symm ↔ ∀ i j, A j i = A i j :=
matrix.ext_iff.symm
/-- A version of `matrix.ext` that unfolds the `matrix.transpose`. -/
@[ext]
lemma is_symm.ext {A : matrix n n α} : (∀ i j, A j i = A i j) → A.is_symm :=
matrix.ext
lemma is_symm.apply {A : matrix n n α} (h : A.is_symm) (i j : n) : A j i = A i j :=
is_symm.ext_iff.1 h i j
lemma is_symm_mul_transpose_self [fintype n] [comm_semiring α] (A : matrix n n α) :
(A ⬝ Aᵀ).is_symm :=
transpose_mul _ _
lemma is_symm_transpose_mul_self [fintype n] [comm_semiring α] (A : matrix n n α) :
(Aᵀ ⬝ A).is_symm :=
transpose_mul _ _
lemma is_symm_add_transpose_self [add_comm_semigroup α] (A : matrix n n α) :
(A + Aᵀ).is_symm :=
add_comm _ _
lemma is_symm_transpose_add_self [add_comm_semigroup α] (A : matrix n n α) :
(Aᵀ + A).is_symm :=
add_comm _ _
@[simp] lemma is_symm_zero [has_zero α] :
(0 : matrix n n α).is_symm :=
transpose_zero
@[simp] lemma is_symm_one [decidable_eq n] [has_zero α] [has_one α] :
(1 : matrix n n α).is_symm :=
transpose_one
@[simp] lemma is_symm.map {A : matrix n n α} (h : A.is_symm) (f : α → β) :
(A.map f).is_symm :=
transpose_map.symm.trans (h.symm ▸ rfl)
@[simp] lemma is_symm.transpose {A : matrix n n α} (h : A.is_symm) :
Aᵀ.is_symm :=
congr_arg _ h
@[simp] lemma is_symm.conj_transpose [has_star α] {A : matrix n n α} (h : A.is_symm) :
Aᴴ.is_symm :=
h.transpose.map _
@[simp] lemma is_symm.neg [has_neg α] {A : matrix n n α} (h : A.is_symm) :
(-A).is_symm :=
(transpose_neg _).trans (congr_arg _ h)
@[simp] lemma is_symm.add {A B : matrix n n α} [has_add α] (hA : A.is_symm) (hB : B.is_symm) :
(A + B).is_symm :=
(transpose_add _ _).trans (hA.symm ▸ hB.symm ▸ rfl)
@[simp] lemma is_symm.sub {A B : matrix n n α} [has_sub α] (hA : A.is_symm) (hB : B.is_symm) :
(A - B).is_symm :=
(transpose_sub _ _).trans (hA.symm ▸ hB.symm ▸ rfl)
@[simp] lemma is_symm.smul [has_scalar R α] {A : matrix n n α} (h : A.is_symm) (k : R) :
(k • A).is_symm :=
(transpose_smul _ _).trans (congr_arg _ h)
@[simp] lemma is_symm.minor {A : matrix n n α} (h : A.is_symm) (f : m → n) :
(A.minor f f).is_symm :=
(transpose_minor _ _ _).trans (h.symm ▸ rfl)
/-- The diagonal matrix `diagonal v` is symmetric. -/
@[simp] lemma is_symm_diagonal [decidable_eq n] [has_zero α] (v : n → α) :
(diagonal v).is_symm :=
diagonal_transpose _
/-- A block matrix `A.from_blocks B C D` is symmetric,
if `A` and `D` are symmetric and `Bᵀ = C`. -/
lemma is_symm.from_blocks
{A : matrix m m α} {B : matrix m n α} {C : matrix n m α} {D : matrix n n α}
(hA : A.is_symm) (hBC : Bᵀ = C) (hD : D.is_symm) :
(A.from_blocks B C D).is_symm :=
begin
have hCB : Cᵀ = B, {rw ← hBC, simp},
unfold matrix.is_symm,
rw from_blocks_transpose,
congr;
assumption
end
/-- This is the `iff` version of `matrix.is_symm.from_blocks`. -/
lemma is_symm_from_blocks_iff
{A : matrix m m α} {B : matrix m n α} {C : matrix n m α} {D : matrix n n α} :
(A.from_blocks B C D).is_symm ↔ A.is_symm ∧ Bᵀ = C ∧ Cᵀ = B ∧ D.is_symm :=
⟨λ h, ⟨congr_arg to_blocks₁₁ h, congr_arg to_blocks₂₁ h,
congr_arg to_blocks₁₂ h, congr_arg to_blocks₂₂ h⟩,
λ ⟨hA, hBC, hCB, hD⟩, is_symm.from_blocks hA hBC hD⟩
end matrix
|
a4cd1675746afad6979488532d3f328777569f7a | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/limits/yoneda.lean | ab1a2a9f7275fe806a11764d6bab38d89f1ef2e9 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,400 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Bhavik Mehta
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.limits.limits
import Mathlib.category_theory.limits.functor_category
import Mathlib.PostPort
universes v u
namespace Mathlib
/-!
# Limit properties relating to the (co)yoneda embedding.
We calculate the colimit of `Y ↦ (X ⟶ Y)`, which is just `punit`.
(This is used in characterising cofinal functors.)
We also show the (co)yoneda embeddings preserve limits and jointly reflect them.
-/
namespace category_theory
namespace coyoneda
/--
The colimit cocone over `coyoneda.obj X`, with cocone point `punit`.
-/
@[simp] theorem colimit_cocone_ι_app {C : Type v} [small_category C] (X : Cᵒᵖ) (X_1 : C) : ∀ (ᾰ : functor.obj (functor.obj coyoneda X) X_1),
nat_trans.app (limits.cocone.ι (colimit_cocone X)) X_1 ᾰ =
id
(fun (ᾰ : functor.obj (functor.obj coyoneda X) X_1) =>
id (fun (X : Cᵒᵖ) (X_1 : C) (ᾰ : opposite.unop X ⟶ X_1) => PUnit.unit) X X_1 ᾰ)
ᾰ :=
fun (ᾰ : functor.obj (functor.obj coyoneda X) X_1) => Eq.refl (nat_trans.app (limits.cocone.ι (colimit_cocone X)) X_1 ᾰ)
/--
The proposed colimit cocone over `coyoneda.obj X` is a colimit cocone.
-/
def colimit_cocone_is_colimit {C : Type v} [small_category C] (X : Cᵒᵖ) : limits.is_colimit (colimit_cocone X) :=
limits.is_colimit.mk
fun (s : limits.cocone (functor.obj coyoneda X)) (x : limits.cocone.X (colimit_cocone X)) =>
nat_trans.app (limits.cocone.ι s) (opposite.unop X) 𝟙
protected instance obj.category_theory.limits.has_colimit {C : Type v} [small_category C] (X : Cᵒᵖ) : limits.has_colimit (functor.obj coyoneda X) :=
limits.has_colimit.mk (limits.colimit_cocone.mk (colimit_cocone X) (colimit_cocone_is_colimit X))
/--
The colimit of `coyoneda.obj X` is isomorphic to `punit`.
-/
def colimit_coyoneda_iso {C : Type v} [small_category C] (X : Cᵒᵖ) : limits.colimit (functor.obj coyoneda X) ≅ PUnit :=
limits.colimit.iso_colimit_cocone (limits.colimit_cocone.mk (colimit_cocone X) (colimit_cocone_is_colimit X))
end coyoneda
/-- The yoneda embedding `yoneda.obj X : Cᵒᵖ ⥤ Type v` for `X : C` preserves limits. -/
protected instance yoneda_preserves_limits {C : Type u} [category C] (X : C) : limits.preserves_limits (functor.obj yoneda X) :=
limits.preserves_limits.mk
fun (J : Type v) (𝒥 : small_category J) =>
limits.preserves_limits_of_shape.mk
fun (K : J ⥤ (Cᵒᵖ)) =>
limits.preserves_limit.mk
fun (c : limits.cone K) (t : limits.is_limit c) =>
limits.is_limit.mk
fun (s : limits.cone (K ⋙ functor.obj yoneda X)) (x : limits.cone.X s) =>
has_hom.hom.unop
(limits.is_limit.lift t
(limits.cone.mk (opposite.op X)
(nat_trans.mk fun (j : J) => has_hom.hom.op (nat_trans.app (limits.cone.π s) j x))))
/-- The coyoneda embedding `coyoneda.obj X : C ⥤ Type v` for `X : Cᵒᵖ` preserves limits. -/
protected instance coyoneda_preserves_limits {C : Type u} [category C] (X : Cᵒᵖ) : limits.preserves_limits (functor.obj coyoneda X) :=
limits.preserves_limits.mk
fun (J : Type v) (𝒥 : small_category J) =>
limits.preserves_limits_of_shape.mk
fun (K : J ⥤ C) =>
limits.preserves_limit.mk
fun (c : limits.cone K) (t : limits.is_limit c) =>
limits.is_limit.mk
fun (s : limits.cone (K ⋙ functor.obj coyoneda X)) (x : limits.cone.X s) =>
limits.is_limit.lift t
(limits.cone.mk (opposite.unop X) (nat_trans.mk fun (j : J) => nat_trans.app (limits.cone.π s) j x))
/-- The yoneda embeddings jointly reflect limits. -/
def yoneda_jointly_reflects_limits {C : Type u} [category C] (J : Type v) [small_category J] (K : J ⥤ (Cᵒᵖ)) (c : limits.cone K) (t : (X : C) → limits.is_limit (functor.map_cone (functor.obj yoneda X) c)) : limits.is_limit c :=
let s' : (s : limits.cone K) → limits.cone (K ⋙ functor.obj yoneda (opposite.unop (limits.cone.X s))) :=
fun (s : limits.cone K) =>
limits.cone.mk PUnit
(nat_trans.mk
fun (j : J) (_x : functor.obj (functor.obj (functor.const J) PUnit) j) =>
has_hom.hom.unop (nat_trans.app (limits.cone.π s) j));
limits.is_limit.mk
fun (s : limits.cone K) =>
has_hom.hom.op (limits.is_limit.lift (t (opposite.unop (limits.cone.X s))) (s' s) PUnit.unit)
/-- The coyoneda embeddings jointly reflect limits. -/
def coyoneda_jointly_reflects_limits {C : Type u} [category C] (J : Type v) [small_category J] (K : J ⥤ C) (c : limits.cone K) (t : (X : Cᵒᵖ) → limits.is_limit (functor.map_cone (functor.obj coyoneda X) c)) : limits.is_limit c :=
let s' : (s : limits.cone K) → limits.cone (K ⋙ functor.obj coyoneda (opposite.op (limits.cone.X s))) :=
fun (s : limits.cone K) =>
limits.cone.mk PUnit
(nat_trans.mk
fun (j : J) (_x : functor.obj (functor.obj (functor.const J) PUnit) j) => nat_trans.app (limits.cone.π s) j);
limits.is_limit.mk fun (s : limits.cone K) => limits.is_limit.lift (t (opposite.op (limits.cone.X s))) (s' s) PUnit.unit
|
caef715a2d5f837523326ae7eeffebbcbf794918 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/category_theory/limits/over.lean | ded0f055a4151d3d6428bb8523cf55d9bc81f3b1 | [
"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 | 4,950 | lean | /-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Reid Barton, Bhavik Mehta
-/
import category_theory.over
import category_theory.adjunction.opposites
import category_theory.limits.preserves.basic
import category_theory.limits.shapes.pullbacks
import category_theory.limits.creates
import category_theory.limits.comma
/-!
# Limits and colimits in the over and under categories
Show that the forgetful functor `forget X : over X ⥤ C` creates colimits, and hence `over X` has
any colimits that `C` has (as well as the dual that `forget X : under X ⟶ C` creates limits).
Note that the folder `category_theory.limits.shapes.constructions.over` further shows that
`forget X : over X ⥤ C` creates connected limits (so `over X` has connected limits), and that
`over X` has `J`-indexed products if `C` has `J`-indexed wide pullbacks.
TODO: If `C` has binary products, then `forget X : over X ⥤ C` has a right adjoint.
-/
noncomputable theory
universes v u -- morphism levels before object levels. See note [category_theory universes].
open category_theory category_theory.limits
variables {J : Type v} [small_category J]
variables {C : Type u} [category.{v} C]
variable {X : C}
namespace category_theory.over
instance has_colimit_of_has_colimit_comp_forget
(F : J ⥤ over X) [i : has_colimit (F ⋙ forget X)] : has_colimit F :=
@@costructured_arrow.has_colimit _ _ _ _ i _
instance [has_colimits_of_shape J C] : has_colimits_of_shape J (over X) := {}
instance [has_colimits C] : has_colimits (over X) := {}
instance creates_colimits : creates_colimits (forget X) := costructured_arrow.creates_colimits
-- We can automatically infer that the forgetful functor preserves and reflects colimits.
example [has_colimits C] : preserves_colimits (forget X) := infer_instance
example : reflects_colimits (forget X) := infer_instance
section
variables [has_pullbacks C]
open tactic
/-- When `C` has pullbacks, a morphism `f : X ⟶ Y` induces a functor `over Y ⥤ over X`,
by pulling back a morphism along `f`. -/
@[simps]
def pullback {X Y : C} (f : X ⟶ Y) : over Y ⥤ over X :=
{ obj := λ g, over.mk (pullback.snd : pullback g.hom f ⟶ X),
map := λ g h k,
over.hom_mk
(pullback.lift (pullback.fst ≫ k.left) pullback.snd (by simp [pullback.condition]))
(by tidy) }
/-- `over.map f` is left adjoint to `over.pullback f`. -/
def map_pullback_adj {A B : C} (f : A ⟶ B) :
over.map f ⊣ pullback f :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ g h,
{ to_fun := λ X, over.hom_mk (pullback.lift X.left g.hom (over.w X)) (pullback.lift_snd _ _ _),
inv_fun := λ Y,
begin
refine over.hom_mk _ _,
refine Y.left ≫ pullback.fst,
dsimp,
rw [← over.w Y, category.assoc, pullback.condition, category.assoc], refl,
end,
left_inv := λ X, by { ext, dsimp, simp, },
right_inv := λ Y, begin
ext, dsimp,
simp only [pullback.lift_fst],
dsimp,
rw [pullback.lift_snd, ← over.w Y],
refl,
end } }
/-- pullback (𝟙 A) : over A ⥤ over A is the identity functor. -/
def pullback_id {A : C} : pullback (𝟙 A) ≅ 𝟭 _ :=
adjunction.right_adjoint_uniq
(map_pullback_adj _)
(adjunction.id.of_nat_iso_left over.map_id.symm)
/-- pullback commutes with composition (up to natural isomorphism). -/
def pullback_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) :
pullback (f ≫ g) ≅ pullback g ⋙ pullback f :=
adjunction.right_adjoint_uniq
(map_pullback_adj _)
(((map_pullback_adj _).comp _ _ (map_pullback_adj _)).of_nat_iso_left
(over.map_comp _ _).symm)
instance pullback_is_right_adjoint {A B : C} (f : A ⟶ B) :
is_right_adjoint (pullback f) :=
⟨_, map_pullback_adj f⟩
end
end category_theory.over
namespace category_theory.under
instance has_limit_of_has_limit_comp_forget
(F : J ⥤ under X) [i : has_limit (F ⋙ forget X)] : has_limit F :=
@@structured_arrow.has_limit _ _ _ _ i _
instance [has_limits_of_shape J C] : has_limits_of_shape J (under X) := {}
instance [has_limits C] : has_limits (under X) := {}
instance creates_limits : creates_limits (forget X) := structured_arrow.creates_limits
-- We can automatically infer that the forgetful functor preserves and reflects limits.
example [has_limits C] : preserves_limits (forget X) := infer_instance
example : reflects_limits (forget X) := infer_instance
section
variables [has_pushouts C]
/-- When `C` has pushouts, a morphism `f : X ⟶ Y` induces a functor `under X ⥤ under Y`,
by pushing a morphism forward along `f`. -/
@[simps]
def pushout {X Y : C} (f : X ⟶ Y) : under X ⥤ under Y :=
{ obj := λ g, under.mk (pushout.inr : Y ⟶ pushout g.hom f),
map := λ g h k,
under.hom_mk
(pushout.desc (k.right ≫ pushout.inl) pushout.inr (by { simp [←pushout.condition], }))
(by tidy) }
end
end category_theory.under
|
b5cb665adc032593b5b6d0ea8cc1146cb809bca2 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/simp_univ_metavars.lean | 278f9933442307f58740c51f0878a71714f491b9 | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 2,636 | lean | meta def blast : tactic unit := using_smt $ return ()
structure { u v } Category :=
(Obj : Type u )
(Hom : Obj -> Obj -> Type v)
(identity : Π X : Obj, Hom X X)
(compose : Π ⦃X Y Z : Obj⦄, Hom X Y → Hom Y Z → Hom X Z)
(left_identity : ∀ ⦃X Y : Obj⦄ (f : Hom X Y), compose (identity _) f = f)
#check @Category.mk.inj_eq
structure Functor (C : Category) (D : Category) :=
(onObjects : C^.Obj → D^.Obj)
(onMorphisms : Π ⦃X Y : C^.Obj⦄,
C^.Hom X Y → D^.Hom (onObjects X) (onObjects Y))
structure NaturalTransformation { C D : Category } ( F G : Functor C D ) :=
(components: Π X : C^.Obj, D^.Hom (F^.onObjects X) (G^.onObjects X))
definition IdentityNaturalTransformation { C D : Category } (F : Functor C D) : NaturalTransformation F F :=
{
components := λ X, D^.identity (F^.onObjects X)
}
definition vertical_composition_of_NaturalTransformations
{ C D : Category }
{ F G H : Functor C D }
( α : NaturalTransformation F G )
( β : NaturalTransformation G H ) : NaturalTransformation F H :=
{
components := λ X, D^.compose (α^.components X) (β^.components X)
}
-- We'll want to be able to prove that two natural transformations are equal if they are componentwise equal.
lemma NaturalTransformations_componentwise_equal
{ C D : Category }
{ F G : Functor C D }
( α β : NaturalTransformation F G )
( w : ∀ X : C^.Obj, α^.components X = β^.components X ) : α = β :=
begin
induction α with αc,
induction β with βc,
have hc : αc = βc := funext w,
subst hc
end
@[simp]
lemma vertical_composition_of_NaturalTransformations_components
{ C D : Category }
{ F G H : Functor C D }
{ α : NaturalTransformation F G }
{ β : NaturalTransformation G H }
{ X : C^.Obj } :
(vertical_composition_of_NaturalTransformations α β)^.components X = D^.compose (α^.components X) (β^.components X) :=
by blast
@[simp]
lemma IdentityNaturalTransformation_components
{ C D : Category }
{ F : Functor C D }
{ X : C^.Obj } :
(IdentityNaturalTransformation F)^.components X = D^.identity (F^.onObjects X) :=
by blast
definition FunctorCategory ( C D : Category ) : Category :=
{
Obj := Functor C D,
Hom := λ F G, NaturalTransformation F G,
identity := λ F, IdentityNaturalTransformation F,
compose := @vertical_composition_of_NaturalTransformations C D,
left_identity := begin
intros F G f,
apply NaturalTransformations_componentwise_equal,
intros,
simp [ D^.left_identity ]
end
}
|
e3dc1963ffd2b343ae43f52b53af65d19cb523db | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/number_theory/legendre_symbol/quadratic_char/basic.lean | 8d64425b47fff286b9f0d3be1e013a6ff288f0a5 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 13,171 | 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
/-!
# Quadratic characters of finite fields
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
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
end special_values
|
8848597939d9e70ac5017a03424c70fabdc261dd | 6b10c15e653d49d146378acda9f3692e9b5b1950 | /examples/logic/unnamed_128.lean | 06afcd92a6ad67fefb9f03314352e93fa93bfee0 | [] | no_license | gebner/mathematics_in_lean | 3cf7f18767208ea6c3307ec3a67c7ac266d8514d | 6d1462bba46d66a9b948fc1aef2714fd265cde0b | refs/heads/master | 1,655,301,945,565 | 1,588,697,505,000 | 1,588,697,505,000 | 261,523,603 | 0 | 0 | null | 1,588,695,611,000 | 1,588,695,610,000 | null | UTF-8 | Lean | false | false | 164 | lean | variables A B C : Prop
-- BEGIN
example : (A → B) → (B → C) → A → C :=
begin
intros h₁ h₂ h₃,
apply h₂,
apply h₁,
apply h₃
end
-- END |
27b71c6018b3d9f0cf7fa92417848e895719ae71 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/monad/types.lean | 7cd4345b1dc4534b5bce25cf415f225628b16bce | [] | 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,206 | 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, Bhavik Mehta
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.monad.basic
import Mathlib.category_theory.monad.kleisli
import Mathlib.category_theory.category.Kleisli
import Mathlib.category_theory.types
import Mathlib.PostPort
universes u
namespace Mathlib
/-!
# Convert from `monad` (i.e. Lean's `Type`-based monads) to `category_theory.monad`
This allows us to use these monads in category theory.
-/
namespace category_theory
protected instance of_type_functor.monad (m : Type u → Type u) [Monad m] [is_lawful_monad m] : monad (of_type_functor m) :=
monad.mk (nat_trans.mk pure) (nat_trans.mk mjoin)
/--
The `Kleisli` category of a `control.monad` is equivalent to the `kleisli` category of its
category-theoretic version, provided the monad is lawful.
-/
@[simp] theorem eq_unit_iso (m : Type u → Type u) [Monad m] [is_lawful_monad m] : equivalence.unit_iso (eq m) = nat_iso.of_components (fun (X : Kleisli m) => iso.refl X) (eq._proof_7 m) :=
Eq.refl (equivalence.unit_iso (eq m))
|
0a1e2960ca5d77b2fd3d5bd56d757589c260976b | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/field_theory/finite/basic.lean | 10bdbca3f5ac3a65e8803cd7b124096fe7a16885 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,817 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Joey van Langen, Casper Putz
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.apply_fun
import Mathlib.data.equiv.ring
import Mathlib.data.zmod.basic
import Mathlib.linear_algebra.basis
import Mathlib.ring_theory.integral_domain
import Mathlib.field_theory.separable
import Mathlib.PostPort
universes u_2 u_1
namespace Mathlib
/-!
# Finite fields
This file contains basic results about finite fields.
Throughout most of this file, `K` denotes a finite field
and `q` is notation for the cardinality of `K`.
See `ring_theory.integral_domain` for the fact that the unit group of a finite field is a
cyclic group, as well as the fact that every finite integral domain is a field (`field_of_integral_domain`).
## Main results
1. `card_units`: The unit group of a finite field is has cardinality `q - 1`.
2. `sum_pow_units`: The sum of `x^i`, where `x` ranges over the units of `K`, is
- `q-1` if `q-1 ∣ i`
- `0` otherwise
3. `finite_field.card`: The cardinality `q` is a power of the characteristic of `K`.
See `card'` for a variant.
## Notation
Throughout most of this file, `K` denotes a finite field
and `q` is notation for the cardinality of `K`.
-/
namespace finite_field
/-- The cardinality of a field is at most `n` times the cardinality of the image of a degree `n`
polynomial -/
theorem card_image_polynomial_eval {R : Type u_2} [integral_domain R] [DecidableEq R] [fintype R] {p : polynomial R} (hp : 0 < polynomial.degree p) : fintype.card R ≤ polynomial.nat_degree p * finset.card (finset.image (fun (x : R) => polynomial.eval x p) finset.univ) := sorry
/-- If `f` and `g` are quadratic polynomials, then the `f.eval a + g.eval b = 0` has a solution. -/
theorem exists_root_sum_quadratic {R : Type u_2} [integral_domain R] [fintype R] {f : polynomial R} {g : polynomial R} (hf2 : polynomial.degree f = bit0 1) (hg2 : polynomial.degree g = bit0 1) (hR : fintype.card R % bit0 1 = 1) : ∃ (a : R), ∃ (b : R), polynomial.eval a f + polynomial.eval b g = 0 := sorry
theorem card_units {K : Type u_1} [field K] [fintype K] : fintype.card (units K) = fintype.card K - 1 := sorry
theorem prod_univ_units_id_eq_neg_one {K : Type u_1} [field K] [fintype K] : (finset.prod finset.univ fun (x : units K) => x) = -1 := sorry
theorem pow_card_sub_one_eq_one {K : Type u_1} [field K] [fintype K] (a : K) (ha : a ≠ 0) : a ^ (fintype.card K - 1) = 1 := sorry
theorem pow_card {K : Type u_1} [field K] [fintype K] (a : K) : a ^ fintype.card K = a := sorry
theorem card (K : Type u_1) [field K] [fintype K] (p : ℕ) [char_p K p] : ∃ (n : ℕ+), nat.prime p ∧ fintype.card K = p ^ ↑n := sorry
theorem card' {K : Type u_1} [field K] [fintype K] : ∃ (p : ℕ), ∃ (n : ℕ+), nat.prime p ∧ fintype.card K = p ^ ↑n := sorry
@[simp] theorem cast_card_eq_zero (K : Type u_1) [field K] [fintype K] : ↑(fintype.card K) = 0 := sorry
theorem forall_pow_eq_one_iff (K : Type u_1) [field K] [fintype K] (i : ℕ) : (∀ (x : units K), x ^ i = 1) ↔ fintype.card K - 1 ∣ i := sorry
/-- The sum of `x ^ i` as `x` ranges over the units of a finite field of cardinality `q`
is equal to `0` unless `(q - 1) ∣ i`, in which case the sum is `q - 1`. -/
theorem sum_pow_units (K : Type u_1) [field K] [fintype K] (i : ℕ) : (finset.sum finset.univ fun (x : units K) => ↑x ^ i) = ite (fintype.card K - 1 ∣ i) (-1) 0 := sorry
/-- The sum of `x ^ i` as `x` ranges over a finite field of cardinality `q`
is equal to `0` if `i < q - 1`. -/
theorem sum_pow_lt_card_sub_one {K : Type u_1} [field K] [fintype K] (i : ℕ) (h : i < fintype.card K - 1) : (finset.sum finset.univ fun (x : K) => x ^ i) = 0 := sorry
theorem frobenius_pow {K : Type u_1} [field K] [fintype K] {p : ℕ} [fact (nat.prime p)] [char_p K p] {n : ℕ} (hcard : fintype.card K = p ^ n) : frobenius K p ^ n = 1 := sorry
theorem expand_card {K : Type u_1} [field K] [fintype K] (f : polynomial K) : coe_fn (polynomial.expand K (fintype.card K)) f = f ^ fintype.card K := sorry
end finite_field
namespace zmod
theorem sum_two_squares (p : ℕ) [hp : fact (nat.prime p)] (x : zmod p) : ∃ (a : zmod p), ∃ (b : zmod p), a ^ bit0 1 + b ^ bit0 1 = x := sorry
end zmod
namespace char_p
theorem sum_two_squares (R : Type u_1) [integral_domain R] (p : ℕ) [fact (0 < p)] [char_p R p] (x : ℤ) : ∃ (a : ℕ), ∃ (b : ℕ), ↑a ^ bit0 1 + ↑b ^ bit0 1 = ↑x := sorry
end char_p
/-- The Fermat-Euler totient theorem. `nat.modeq.pow_totient` is an alternative statement
of the same theorem. -/
@[simp] theorem zmod.pow_totient {n : ℕ} [fact (0 < n)] (x : units (zmod n)) : x ^ nat.totient n = 1 :=
eq.mpr (id (Eq._oldrec (Eq.refl (x ^ nat.totient n = 1)) (Eq.symm (zmod.card_units_eq_totient n))))
(eq.mpr (id (Eq._oldrec (Eq.refl (x ^ fintype.card (units (zmod n)) = 1)) (pow_card_eq_one x))) (Eq.refl 1))
/-- The Fermat-Euler totient theorem. `zmod.pow_totient` is an alternative statement
of the same theorem. -/
theorem nat.modeq.pow_totient {x : ℕ} {n : ℕ} (h : nat.coprime x n) : nat.modeq n (x ^ nat.totient n) 1 := sorry
namespace zmod
/-- A variation on Fermat's little theorem. See `zmod.pow_card_sub_one_eq_one` -/
@[simp] theorem pow_card {p : ℕ} [fact (nat.prime p)] (x : zmod p) : x ^ p = x :=
eq.mp (Eq._oldrec (Eq.refl (x ^ fintype.card (zmod p) = x)) (card p)) (finite_field.pow_card x)
@[simp] theorem frobenius_zmod (p : ℕ) [hp : fact (nat.prime p)] : frobenius (zmod p) p = ring_hom.id (zmod p) := sorry
@[simp] theorem card_units (p : ℕ) [fact (nat.prime p)] : fintype.card (units (zmod p)) = p - 1 :=
eq.mpr (id (Eq._oldrec (Eq.refl (fintype.card (units (zmod p)) = p - 1)) finite_field.card_units))
(eq.mpr (id (Eq._oldrec (Eq.refl (fintype.card (zmod p) - 1 = p - 1)) (card p))) (Eq.refl (p - 1)))
/-- Fermat's Little Theorem: for every unit `a` of `zmod p`, we have `a ^ (p - 1) = 1`. -/
theorem units_pow_card_sub_one_eq_one (p : ℕ) [fact (nat.prime p)] (a : units (zmod p)) : a ^ (p - 1) = 1 :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ^ (p - 1) = 1)) (Eq.symm (card_units p))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ^ fintype.card (units (zmod p)) = 1)) (pow_card_eq_one a))) (Eq.refl 1))
/-- Fermat's Little Theorem: for all nonzero `a : zmod p`, we have `a ^ (p - 1) = 1`. -/
theorem pow_card_sub_one_eq_one {p : ℕ} [fact (nat.prime p)] {a : zmod p} (ha : a ≠ 0) : a ^ (p - 1) = 1 :=
eq.mp (Eq._oldrec (Eq.refl (a ^ (fintype.card (zmod p) - 1) = 1)) (card p)) (finite_field.pow_card_sub_one_eq_one a ha)
theorem expand_card {p : ℕ} [fact (nat.prime p)] (f : polynomial (zmod p)) : coe_fn (polynomial.expand (zmod p) p) f = f ^ p := sorry
|
c528bb4069b5ad8ff8e241a2133287abdadaa36b | ad3e8f15221a986da27c99f371922c0b3f5792b6 | /src/week05/solutions/e00_intro.lean | 060639607c02e090f8508badc5fb422ab2d35bc3 | [] | no_license | VArtem/lean-itmo | a0e1424c8cc4c2de2ac85ab6fd4a12d80e9b85f1 | dc44cd06f9f5b984d051831b3aaa7364e64c2dc4 | refs/heads/main | 1,683,761,214,467 | 1,622,821,295,000 | 1,622,821,295,000 | 357,236,048 | 12 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,696 | lean | import data.finset
import data.fintype.basic
import data.set.finite
import tactic.derive_fintype
section intro
variable {α : Type*}
-- Конечность типа или множества представлена в mathlib тремя основными типами: `A : finset α`, `fintype A` и `finite A`
-- 1. finset - конструктивно конечное множество
-- `finset` = `multiset` + `nodup`
-- `multiset` = классы эквивалентности `list` по отношению "a - перестановка b"
-- Для того, чтобы применять большинство операций (добавление/объединение/...), нужен инстанс `decidable_eq α`: нужно уметь разрешимо сравнивать элементы (чтобы, например, знать `card`)
variable (A : finset α)
#check A.card
#reduce ({0,1,2,3} : finset ℕ).card
#check @finset.card_insert_of_mem
-- 2. fintype α - класс, говорящий о том, что α - конечный тип
-- fintype α = (elems [] : finset α) (complete : ∀ x : α, x ∈ elems)
-- Можно использовать @[derive fintype], для новосозданных `inductive`
-- https://github.com/leanprover-community/mathlib/pull/3772
variable [fintype α]
example : fintype bool := by show_term {apply_instance}
example : fintype (fin 10) := by show_term {apply_instance}
#check @finset.univ
@[derive fintype]
inductive test (α : Type) [fintype α] : Type
| c1 : bool → test
| c2 : (fin 2) → (fin 3) → test
| c3 : α × α → test
-- 3. finite B - доказательство конечности множества B
-- def finite (s : set α) : Prop := nonempty (fintype s)
-- `nonempty (fintype s)` - Prop-версия того, что существует элемент типа `fintype s`
-- `fintype s` - то же самое, что `fintype {x : α // x ∈ s}` или `fintype (subtype s)` - подтип `α` состоящий из пар `⟨x, h : x ∈ s⟩`
-- Удобно использовать тогда, когда в API `finset` нет того, что хочется делать с множествами, а в `set` есть
open set
variables (β : Type) (B : set β) (hB : finite B)
#check @finite.of_fintype
end intro
-- Докажем несколько лемм про `finset`
namespace finset
variables {α : Type} {A B : finset α} [decidable_eq α]
lemma card_erase_of_mem' {x} (h : x ∈ A) : (A.erase x).card + 1 = A.card :=
begin
rw [card_erase_of_mem h, nat.add_one, nat.succ_pred_eq_of_pos],
refine card_pos.2 ⟨_, h⟩,
end
end finset |
8a96eb304ccbad319d36d2e2eb203aa4a474e67c | ff5230333a701471f46c57e8c115a073ebaaa448 | /tests/lean/run/heap_mem.lean | 1946f417b0b9cd97cd6569746799260e2365bf43 | [
"Apache-2.0"
] | permissive | stanford-cs242/lean | f81721d2b5d00bc175f2e58c57b710d465e6c858 | 7bd861261f4a37326dcf8d7a17f1f1f330e4548c | refs/heads/master | 1,600,957,431,849 | 1,576,465,093,000 | 1,576,465,093,000 | 225,779,423 | 0 | 3 | Apache-2.0 | 1,575,433,936,000 | 1,575,433,935,000 | null | UTF-8 | Lean | false | false | 3,816 | lean | /- We use the following auxiliary type instead of (Σ α : Type, α)
because the code generator produces better code for `pointed`.
For `pointed`, the code generator erases the field `α`. -/
structure pointed :=
(α : Type) (a : α)
/- The following two commands demonstrate the difference.
To remove the overhead in the `sigma` case, the code
generator would have to support code specialization. -/
#eval pointed.mk nat 10
#eval (⟨nat, 10⟩ : Σ α : Type, α)
structure heap :=
(size : nat)
(mem : array size pointed)
structure ref (α : Type) :=
(idx : nat)
def in_heap {α : Type} (r : ref α) (h : heap) : Prop :=
∃ hlt : r.idx < h.size, (h.mem.read ⟨r.idx, hlt⟩).1 = α
lemma lt_of_in_heap {α : Type} {r : ref α} {h : heap} (hin : in_heap r h) : r.idx < h.size :=
by cases hin; assumption
lemma cast_of_in_heap {α : Type} {r : ref α} {h : heap} (hin : in_heap r h) : (h.mem.read ⟨r.idx, lt_of_in_heap hin⟩).1 = α :=
by cases hin; exact hin_h
def mk_ref : heap → Π {α : Type}, α → ref α × heap
| ⟨n, mem⟩ α v := ({idx := n}, { size := n+1, mem := mem.push_back ⟨α, v⟩ })
def read : Π (h : heap) {α : Type} (r : ref α) (prf : in_heap r h), α
| ⟨n, mem⟩ α r hin := eq.rec_on (cast_of_in_heap hin) (mem.read ⟨r.idx, lt_of_in_heap hin⟩).2
def write : Π (h : heap) {α : Type} (r : ref α) (prf : in_heap r h) (a : α), heap
| ⟨n, mem⟩ α r hin a := { size := n, mem := mem.write ⟨r.idx, lt_of_in_heap hin⟩ ⟨α, a⟩ }
lemma in_heap_mk_ref (h : heap) {α : Type} (a : α) : in_heap (mk_ref h a).1 (mk_ref h a).2 :=
begin
cases h, simp [mk_ref, in_heap], dsimp,
have : h_size < h_size + 1, { apply nat.lt_succ_self },
existsi this,
simp [array.push_back, array.read, d_array.read, *]
end
lemma in_heap_mk_ref_of_in_heap {α β : Type} {h : heap} {r : ref α} (b : β) : in_heap r h → in_heap r (mk_ref h b).2 :=
begin
intro hin,
have := lt_of_in_heap hin,
have hlt := nat.lt_succ_of_lt this,
cases h, simp [in_heap, mk_ref, *] at *, dsimp,
have : r.idx ≠ h_size, { intro heq, subst heq, exact absurd this (irrefl _) },
simp [array.push_back, array.read, d_array.read, *],
existsi hlt, cases hin, assumption
end
@[simp] lemma fin.mk_eq {n : nat} {i j : nat} (h₁ : i < n) (h₂ : j < n) (h₃ : i ≠ j) : fin.mk i h₁ ≠ fin.mk j h₂ :=
fin.ne_of_vne h₃
lemma in_heap_write_of_in_heap {α β : Type} {h : heap} {r₁ : ref β} {r₂ : ref α} (a : α) : ∀ (hin₁ : in_heap r₁ h) (hin₂ : in_heap r₂ h), in_heap r₁ (write h r₂ hin₂ a) :=
begin
intros,
have := lt_of_in_heap hin₁,
have := lt_of_in_heap hin₂,
have := cast_of_in_heap hin₁,
have := cast_of_in_heap hin₂,
cases h, simp [in_heap, write, *] at *,
dsimp, existsi this,
by_cases r₂.idx = r₁.idx,
{ simp [*] at * },
{ simp [*] }
end
inductive is_extension : heap → heap → Prop
| refl : ∀ h, is_extension h h
| by_mk_ref (h' h : heap) {α : Type} (a : α) (he : is_extension h' h) : is_extension (mk_ref h' a).2 h
| by_write (h' h : heap) {α : Type} (r : ref α) (hin : in_heap r h') (a : α) (he : is_extension h' h) : is_extension (write h' r hin a) h
lemma is_extension.trans {h₁ h₂ h₃ : heap} : is_extension h₁ h₂ → is_extension h₂ h₃ → is_extension h₁ h₃ :=
begin
intro he₁, induction he₁,
{ intros, assumption },
all_goals { intro he₂, constructor, apply he₁_ih, assumption }
end
lemma in_heap_of_is_extension_of_in_heap {α : Type} {r : ref α} {h h' : heap} : is_extension h' h → in_heap r h → in_heap r h' :=
begin
intro he, induction he generalizing α r,
{ intros, assumption },
{ intro hin, apply in_heap_mk_ref_of_in_heap, apply he_ih, assumption },
{ intro hin, apply in_heap_write_of_in_heap, apply he_ih, assumption }
end
|
6466a1c97d501014ee8e86f51bcf25be46704ea8 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/topology/metric_space/gromov_hausdorff_realized_auto.lean | 7268c14bc6055141da47762e8a38cb8bfcde4e9c | [] | 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 | 9,110 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sébastien Gouëzel
Construction of a good coupling between nonempty compact metric spaces, minimizing
their Hausdorff distance. This construction is instrumental to study the Gromov-Hausdorff
distance between nonempty compact metric spaces -/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.topology.metric_space.gluing
import Mathlib.topology.metric_space.hausdorff_distance
import Mathlib.PostPort
universes u v
namespace Mathlib
namespace Gromov_Hausdorff
/- This section shows that the Gromov-Hausdorff distance
is realized. For this, we consider candidate distances on the disjoint union
α ⊕ β of two compact nonempty metric spaces, almost realizing the Gromov-Hausdorff
distance, and show that they form a compact family by applying Arzela-Ascoli
theorem. The existence of a minimizer follows. -/
/-- The set of functions on α ⊕ β that are candidates distances to realize the
minimum of the Hausdorff distances between α and β in a coupling -/
def candidates (α : Type u) (β : Type v) [metric_space α] [compact_space α] [Nonempty α]
[metric_space β] [compact_space β] [Nonempty β] : set (prod_space_fun α β) :=
set_of
fun (f : prod_space_fun α β) =>
(((((∀ (x y : α), f (sum.inl x, sum.inl y) = dist x y) ∧
∀ (x y : β), f (sum.inr x, sum.inr y) = dist x y) ∧
∀ (x y : α ⊕ β), f (x, y) = f (y, x)) ∧
∀ (x y z : α ⊕ β), f (x, z) ≤ f (x, y) + f (y, z)) ∧
∀ (x : α ⊕ β), f (x, x) = 0) ∧
∀ (x y : α ⊕ β), f (x, y) ≤ ↑(max_var α β)
/-- Version of the set of candidates in bounded_continuous_functions, to apply
Arzela-Ascoli -/
/-- candidates are bounded by max_var α β -/
/-- Technical lemma to prove that candidates are Lipschitz -/
/-- Candidates are Lipschitz -/
/-- candidates give rise to elements of bounded_continuous_functions -/
def candidates_b_of_candidates {α : Type u} {β : Type v} [metric_space α] [compact_space α]
[Nonempty α] [metric_space β] [compact_space β] [Nonempty β] (f : prod_space_fun α β)
(fA : f ∈ candidates α β) : Cb α β :=
bounded_continuous_function.mk_of_compact f sorry
theorem candidates_b_of_candidates_mem {α : Type u} {β : Type v} [metric_space α] [compact_space α]
[Nonempty α] [metric_space β] [compact_space β] [Nonempty β] (f : prod_space_fun α β)
(fA : f ∈ candidates α β) : candidates_b_of_candidates f fA ∈ candidates_b α β :=
fA
/-- The distance on α ⊕ β is a candidate -/
def candidates_b_dist (α : Type u) (β : Type v) [metric_space α] [compact_space α] [Inhabited α]
[metric_space β] [compact_space β] [Inhabited β] : Cb α β :=
candidates_b_of_candidates (fun (p : (α ⊕ β) × (α ⊕ β)) => dist (prod.fst p) (prod.snd p)) sorry
theorem candidates_b_dist_mem_candidates_b {α : Type u} {β : Type v} [metric_space α]
[compact_space α] [Nonempty α] [metric_space β] [compact_space β] [Nonempty β] :
candidates_b_dist α β ∈ candidates_b α β :=
candidates_b_of_candidates_mem (fun (p : (α ⊕ β) × (α ⊕ β)) => dist (prod.fst p) (prod.snd p))
(candidates_b_dist._proof_1 α β)
/-- To apply Arzela-Ascoli, we need to check that the set of candidates is closed and equicontinuous.
Equicontinuity follows from the Lipschitz control, we check closedness -/
/-- Compactness of candidates (in bounded_continuous_functions) follows -/
/-- We will then choose the candidate minimizing the Hausdorff distance. Except that we are not
in a metric space setting, so we need to define our custom version of Hausdorff distance,
called HD, and prove its basic properties. -/
def HD {α : Type u} {β : Type v} [metric_space α] [compact_space α] [Nonempty α] [metric_space β]
[compact_space β] [Nonempty β] (f : Cb α β) : ℝ :=
max (supr fun (x : α) => infi fun (y : β) => coe_fn f (sum.inl x, sum.inr y))
(supr fun (y : β) => infi fun (x : α) => coe_fn f (sum.inl x, sum.inr y))
/- We will show that HD is continuous on bounded_continuous_functions, to deduce that its
minimum on the compact set candidates_b is attained. Since it is defined in terms of
infimum and supremum on ℝ, which is only conditionnally complete, we will need all the time
to check that the defining sets are bounded below or above. This is done in the next few
technical lemmas -/
theorem HD_below_aux1 {α : Type u} {β : Type v} [metric_space α] [compact_space α] [Nonempty α]
[metric_space β] [compact_space β] [Nonempty β] {f : Cb α β} (C : ℝ) {x : α} :
bdd_below (set.range fun (y : β) => coe_fn f (sum.inl x, sum.inr y) + C) :=
sorry
theorem HD_below_aux2 {α : Type u} {β : Type v} [metric_space α] [compact_space α] [Nonempty α]
[metric_space β] [compact_space β] [Nonempty β] {f : Cb α β} (C : ℝ) {y : β} :
bdd_below (set.range fun (x : α) => coe_fn f (sum.inl x, sum.inr y) + C) :=
sorry
/-- Explicit bound on HD (dist). This means that when looking for minimizers it will
be sufficient to look for functions with HD(f) bounded by this bound. -/
theorem HD_candidates_b_dist_le {α : Type u} {β : Type v} [metric_space α] [compact_space α]
[Nonempty α] [metric_space β] [compact_space β] [Nonempty β] :
HD (candidates_b_dist α β) ≤ metric.diam set.univ + 1 + metric.diam set.univ :=
sorry
/- To check that HD is continuous, we check that it is Lipschitz. As HD is a max, we
prove separately inequalities controlling the two terms (relying too heavily on copy-paste...) -/
/-- Conclude that HD, being Lipschitz, is continuous -/
/- Now that we have proved that the set of candidates is compact, and that HD is continuous,
we can finally select a candidate minimizing HD. This will be the candidate realizing the
optimal coupling. -/
/-- With the optimal candidate, construct a premetric space structure on α ⊕ β, on which the
predistance is given by the candidate. Then, we will identify points at 0 predistance
to obtain a genuine metric space -/
def premetric_optimal_GH_dist (α : Type u) (β : Type v) [metric_space α] [compact_space α]
[Nonempty α] [metric_space β] [compact_space β] [Nonempty β] : premetric_space (α ⊕ β) :=
premetric_space.mk sorry sorry sorry
/-- A metric space which realizes the optimal coupling between α and β -/
def optimal_GH_coupling (α : Type u) (β : Type v) [metric_space α] [compact_space α] [Nonempty α]
[metric_space β] [compact_space β] [Nonempty β] :=
premetric.metric_quot (α ⊕ β)
/-- Injection of α in the optimal coupling between α and β -/
def optimal_GH_injl (α : Type u) (β : Type v) [metric_space α] [compact_space α] [Nonempty α]
[metric_space β] [compact_space β] [Nonempty β] (x : α) : optimal_GH_coupling α β :=
quotient.mk (sum.inl x)
/-- The injection of α in the optimal coupling between α and β is an isometry. -/
theorem isometry_optimal_GH_injl (α : Type u) (β : Type v) [metric_space α] [compact_space α]
[Nonempty α] [metric_space β] [compact_space β] [Nonempty β] : isometry (optimal_GH_injl α β) :=
iff.mpr isometry_emetric_iff_metric
fun (x y : α) => id (candidates_dist_inl (optimal_GH_dist_mem_candidates_b α β) x y)
/-- Injection of β in the optimal coupling between α and β -/
def optimal_GH_injr (α : Type u) (β : Type v) [metric_space α] [compact_space α] [Nonempty α]
[metric_space β] [compact_space β] [Nonempty β] (y : β) : optimal_GH_coupling α β :=
quotient.mk (sum.inr y)
/-- The injection of β in the optimal coupling between α and β is an isometry. -/
theorem isometry_optimal_GH_injr (α : Type u) (β : Type v) [metric_space α] [compact_space α]
[Nonempty α] [metric_space β] [compact_space β] [Nonempty β] : isometry (optimal_GH_injr α β) :=
iff.mpr isometry_emetric_iff_metric
fun (x y : β) => id (candidates_dist_inr (optimal_GH_dist_mem_candidates_b α β) x y)
/-- The optimal coupling between two compact spaces α and β is still a compact space -/
protected instance compact_space_optimal_GH_coupling (α : Type u) (β : Type v) [metric_space α]
[compact_space α] [Nonempty α] [metric_space β] [compact_space β] [Nonempty β] :
compact_space (optimal_GH_coupling α β) :=
sorry
/-- For any candidate f, HD(f) is larger than or equal to the Hausdorff distance in the
optimal coupling. This follows from the fact that HD of the optimal candidate is exactly
the Hausdorff distance in the optimal coupling, although we only prove here the inequality
we need. -/
theorem Hausdorff_dist_optimal_le_HD (α : Type u) (β : Type v) [metric_space α] [compact_space α]
[Nonempty α] [metric_space β] [compact_space β] [Nonempty β] {f : Cb α β}
(h : f ∈ candidates_b α β) :
metric.Hausdorff_dist (set.range (optimal_GH_injl α β)) (set.range (optimal_GH_injr α β)) ≤
HD f :=
sorry
end Mathlib |
15b64b78bb1d03f3683f6b92c4767324e92a923e | f4bff2062c030df03d65e8b69c88f79b63a359d8 | /ideas/ds_wellOrd_ceil.lean | 395926753b9520973fac641cf32f37e5661c952e | [
"Apache-2.0"
] | permissive | adastra7470/real-number-game | 776606961f52db0eb824555ed2f8e16f92216ea3 | f9dcb7d9255a79b57e62038228a23346c2dc301b | refs/heads/master | 1,669,221,575,893 | 1,594,669,800,000 | 1,594,669,800,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,444 | lean | import data.real.basic
axiom well_ordered_Zplus
(A : set ℤ) (h1A : A.nonempty) (h2A : ∀ (a:ℤ), a ∈ A → 0 < a):
∃ m ∈ A, ∀ k ∈ A, m ≤ k
-- this does work!
lemma wellOrd_ceil_existence (x : ℝ) (hx : 0 < x) :
∃ m : ℤ, m > 0 ∧ (m-1 : ℝ) ≤ x ∧ x < (m : ℝ) :=
begin
have H := exists_nat_gt x,
cases H with n hn,
have h1 : 0 < (n : ℝ), exact lt_trans hx hn,
set A := { k : ℤ | x < k } with hA,
have h2a : ∀ (a : ℤ), a ∈ A → 0 < a,
intros a ha,
have h2a1 : x < a, exact ha,
have h2a2 : 0 < (a:ℝ), exact lt_trans hx h2a1,
exact int.cast_lt.mp h2a2,
have h2 : (n : ℤ) ∈ A, exact hn,
have h3 : A.nonempty, existsi (n : ℤ), exact h2,
have h4 := well_ordered_Zplus A h3 h2a,
cases h4 with m hmn,
cases hmn with hm hk,
have h5 : x < m, exact hm,
set m1 := m-1 with hm1,
have h6 : (m1 : ℝ) ≤ x,
by_contradiction hf,
push_neg at hf,
have h6a : m1 ∈ A, exact hf,
have h6b := hk m1 h6a, rw hm1 at h6b, linarith,
existsi m,
split, swap, split, swap, exact h5, swap,
have h7 : 0 < (m : ℝ), exact lt_trans hx h5,
exact int.cast_lt.mp h7,
rw hm1 at h6, convert h6, norm_cast, done
end
-- how to deal with the lambda (uniqueness part)?
-- needs more work
lemma wellOrd_ceil_existuniq (x : ℝ) (hx : 0 < x) :
∃! m : ℕ, m > 0 ∧ (m-1 : ℝ) ≤ x ∧ x < (m : ℝ) :=
begin
split,
split,
sorry, sorry,
end
|
f9498126d514557307b8640943e72ca945140ad5 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/combinatorics/simple_graph/finsubgraph.lean | 3d37c06ebae0aae44c5bd8b414c3de23d2be5a26 | [
"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 | 5,895 | lean | /-
Copyright (c) 2022 Joanna Choules. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joanna Choules
-/
import category_theory.cofiltered_system
import combinatorics.simple_graph.subgraph
/-!
# Homomorphisms from finite subgraphs
This file defines the type of finite subgraphs of a `simple_graph` and proves a compactness result
for homomorphisms to a finite codomain.
## Main statements
* `simple_graph.exists_hom_of_all_finite_homs`: If every finite subgraph of a (possibly infinite)
graph `G` has a homomorphism to some finite graph `F`, then there is also a homomorphism `G →g F`.
## Notations
`→fg` is a module-local variant on `→g` where the domain is a finite subgraph of some supergraph
`G`.
## Implementation notes
The proof here uses compactness as formulated in `nonempty_sections_of_finite_inverse_system`. For
finite subgraphs `G'' ≤ G'`, the inverse system `finsubgraph_hom_functor` restricts homomorphisms
`G' →fg F` to domain `G''`.
-/
open set
universes u v
variables {V : Type u} {W : Type v} {G : simple_graph V} {F : simple_graph W}
namespace simple_graph
/-- The subtype of `G.subgraph` comprising those subgraphs with finite vertex sets. -/
abbreviation finsubgraph (G : simple_graph V) := { G' : G.subgraph // G'.verts.finite }
/-- A graph homomorphism from a finite subgraph of G to F. -/
abbreviation finsubgraph_hom (G' : G.finsubgraph) (F : simple_graph W) := G'.val.coe →g F
local infix ` →fg ` : 50 := finsubgraph_hom
instance : order_bot G.finsubgraph :=
{ bot := ⟨⊥, finite_empty⟩,
bot_le := λ _, bot_le }
instance : has_sup G.finsubgraph := ⟨λ G₁ G₂, ⟨G₁ ⊔ G₂, G₁.2.union G₂.2⟩⟩
instance : has_inf G.finsubgraph := ⟨λ G₁ G₂, ⟨G₁ ⊓ G₂, G₁.2.subset $ inter_subset_left _ _⟩⟩
instance : distrib_lattice G.finsubgraph :=
subtype.coe_injective.distrib_lattice _ (λ _ _, rfl) (λ _ _, rfl)
instance [finite V] : has_top G.finsubgraph := ⟨⟨⊤, finite_univ⟩⟩
instance [finite V] : has_Sup G.finsubgraph := ⟨λ s, ⟨⨆ G ∈ s, ↑G, set.to_finite _⟩⟩
instance [finite V] : has_Inf G.finsubgraph := ⟨λ s, ⟨⨅ G ∈ s, ↑G, set.to_finite _⟩⟩
instance [finite V] : complete_distrib_lattice G.finsubgraph :=
subtype.coe_injective.complete_distrib_lattice _ (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl) rfl
rfl
/-- The finite subgraph of G generated by a single vertex. -/
def singleton_finsubgraph (v : V) : G.finsubgraph := ⟨simple_graph.singleton_subgraph _ v, by simp⟩
/-- The finite subgraph of G generated by a single edge. -/
def finsubgraph_of_adj {u v : V} (e : G.adj u v) : G.finsubgraph :=
⟨simple_graph.subgraph_of_adj _ e, by simp⟩
/- Lemmas establishing the ordering between edge- and vertex-generated subgraphs. -/
lemma singleton_finsubgraph_le_adj_left {u v : V} {e : G.adj u v} :
singleton_finsubgraph u ≤ finsubgraph_of_adj e :=
by simp [singleton_finsubgraph, finsubgraph_of_adj]
lemma singleton_finsubgraph_le_adj_right {u v : V} {e : G.adj u v} :
singleton_finsubgraph v ≤ finsubgraph_of_adj e :=
by simp [singleton_finsubgraph, finsubgraph_of_adj]
/-- Given a homomorphism from a subgraph to `F`, construct its restriction to a sub-subgraph. -/
def finsubgraph_hom.restrict {G' G'' : G.finsubgraph} (h : G'' ≤ G') (f : G' →fg F) : G'' →fg F :=
begin
refine ⟨λ ⟨v, hv⟩, f.to_fun ⟨v, h.1 hv⟩, _⟩,
rintros ⟨u, hu⟩ ⟨v, hv⟩ huv,
exact f.map_rel' (h.2 huv),
end
/-- The inverse system of finite homomorphisms. -/
def finsubgraph_hom_functor (G : simple_graph V) (F : simple_graph W) :
(G.finsubgraph)ᵒᵖ ⥤ Type (max u v) :=
{ obj := λ G', G'.unop →fg F,
map := λ G' G'' g f, f.restrict (category_theory.le_of_hom g.unop), }
/-- If every finite subgraph of a graph `G` has a homomorphism to a finite graph `F`, then there is
a homomorphism from the whole of `G` to `F`. -/
lemma nonempty_hom_of_forall_finite_subgraph_hom [finite W]
(h : Π (G' : G.subgraph), G'.verts.finite → G'.coe →g F) : nonempty (G →g F) :=
begin
/- Obtain a `fintype` instance for `W`. -/
casesI nonempty_fintype W,
/- Establish the required interface instances. -/
haveI : ∀ (G' : (G.finsubgraph)ᵒᵖ), nonempty ((finsubgraph_hom_functor G F).obj G') :=
λ G', ⟨h G'.unop G'.unop.property⟩,
haveI : Π (G' : (G.finsubgraph)ᵒᵖ), fintype ((finsubgraph_hom_functor G F).obj G') :=
begin
intro G',
haveI : fintype (↥(G'.unop.val.verts)) := G'.unop.property.fintype,
haveI : fintype (↥(G'.unop.val.verts) → W) := begin
classical,
exact pi.fintype
end,
exact fintype.of_injective (λ f, f.to_fun) rel_hom.coe_fn_injective
end,
/- Use compactness to obtain a section. -/
obtain ⟨u, hu⟩ := nonempty_sections_of_finite_inverse_system (finsubgraph_hom_functor G F),
refine ⟨⟨λ v, _, _⟩⟩,
{ /- Map each vertex using the homomorphism provided for its singleton subgraph. -/
exact (u (opposite.op (singleton_finsubgraph v))).to_fun
⟨v, by {unfold singleton_finsubgraph, simp}⟩, },
{ /- Prove that the above mapping preserves adjacency. -/
intros v v' e,
/- The homomorphism for each edge's singleton subgraph agrees with those for its source and
target vertices. -/
have hv : opposite.op (finsubgraph_of_adj e) ⟶ opposite.op (singleton_finsubgraph v) :=
quiver.hom.op (category_theory.hom_of_le singleton_finsubgraph_le_adj_left),
have hv' : opposite.op (finsubgraph_of_adj e) ⟶ opposite.op (singleton_finsubgraph v') :=
quiver.hom.op (category_theory.hom_of_le singleton_finsubgraph_le_adj_right),
rw [← (hu hv), ← (hu hv')],
apply simple_graph.hom.map_adj,
/- `v` and `v'` are definitionally adjacent in `finsubgraph_of_adj e` -/
simp [finsubgraph_of_adj], }
end
end simple_graph
|
8b36883503b792c974408a9e351c6cd0d1f24657 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/analysis/calculus/fderiv_measurable.lean | 047eeaa37efb266240e3449e940208776c1c77f2 | [
"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 | 41,039 | lean | /-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Yury Kudryashov
-/
import analysis.calculus.deriv
import measure_theory.constructions.borel_space
import measure_theory.function.strongly_measurable
import tactic.ring_exp
/-!
# Derivative is measurable
In this file we prove that the derivative of any function with complete codomain is a measurable
function. Namely, we prove:
* `measurable_set_of_differentiable_at`: the set `{x | differentiable_at 𝕜 f x}` is measurable;
* `measurable_fderiv`: the function `fderiv 𝕜 f` is measurable;
* `measurable_fderiv_apply_const`: for a fixed vector `y`, the function `λ x, fderiv 𝕜 f x y`
is measurable;
* `measurable_deriv`: the function `deriv f` is measurable (for `f : 𝕜 → F`).
We also show the same results for the right derivative on the real line
(see `measurable_deriv_within_Ici` and ``measurable_deriv_within_Ioi`), following the same
proof strategy.
## Implementation
We give a proof that avoids second-countability issues, by expressing the differentiability set
as a function of open sets in the following way. Define `A (L, r, ε)` to be the set of points
where, on a ball of radius roughly `r` around `x`, the function is uniformly approximated by the
linear map `L`, up to `ε r`. It is an open set.
Let also `B (L, r, s, ε) = A (L, r, ε) ∩ A (L, s, ε)`: we require that at two possibly different
scales `r` and `s`, the function is well approximated by the linear map `L`. It is also open.
We claim that the differentiability set of `f` is exactly
`D = ⋂ ε > 0, ⋃ δ > 0, ⋂ r, s < δ, ⋃ L, B (L, r, s, ε)`.
In other words, for any `ε > 0`, we require that there is a size `δ` such that, for any two scales
below this size, the function is well approximated by a linear map, common to the two scales.
The set `⋃ L, B (L, r, s, ε)` is open, as a union of open sets. Converting the intersections and
unions to countable ones (using real numbers of the form `2 ^ (-n)`), it follows that the
differentiability set is measurable.
To prove the claim, there are two inclusions. One is trivial: if the function is differentiable
at `x`, then `x` belongs to `D` (just take `L` to be the derivative, and use that the
differentiability exactly says that the map is well approximated by `L`). This is proved in
`mem_A_of_differentiable` and `differentiable_set_subset_D`.
For the other direction, the difficulty is that `L` in the union may depend on `ε, r, s`. The key
point is that, in fact, it doesn't depend too much on them. First, if `x` belongs both to
`A (L, r, ε)` and `A (L', r, ε)`, then `L` and `L'` have to be close on a shell, and thus
`∥L - L'∥` is bounded by `ε` (see `norm_sub_le_of_mem_A`). Assume now `x ∈ D`. If one has two maps
`L` and `L'` such that `x` belongs to `A (L, r, ε)` and to `A (L', r', ε')`, one deduces that `L` is
close to `L'` by arguing as follows. Consider another scale `s` smaller than `r` and `r'`. Take a
linear map `L₁` that approximates `f` around `x` both at scales `r` and `s` w.r.t. `ε` (it exists as
`x` belongs to `D`). Take also `L₂` that approximates `f` around `x` both at scales `r'` and `s`
w.r.t. `ε'`. Then `L₁` is close to `L` (as they are close on a shell of radius `r`), and `L₂` is
close to `L₁` (as they are close on a shell of radius `s`), and `L'` is close to `L₂` (as they are
close on a shell of radius `r'`). It follows that `L` is close to `L'`, as we claimed.
It follows that the different approximating linear maps that show up form a Cauchy sequence when
`ε` tends to `0`. When the target space is complete, this sequence converges, to a limit `f'`.
With the same kind of arguments, one checks that `f` is differentiable with derivative `f'`.
To show that the derivative itself is measurable, add in the definition of `B` and `D` a set
`K` of continuous linear maps to which `L` should belong. Then, when `K` is complete, the set `D K`
is exactly the set of points where `f` is differentiable with a derivative in `K`.
## Tags
derivative, measurable function, Borel σ-algebra
-/
noncomputable theory
open set metric asymptotics filter continuous_linear_map
open topological_space (second_countable_topology) measure_theory
open_locale topological_space
namespace continuous_linear_map
variables {𝕜 E F : Type*} [nondiscrete_normed_field 𝕜]
[normed_group E] [normed_space 𝕜 E] [normed_group F] [normed_space 𝕜 F]
lemma measurable_apply₂ [measurable_space E] [opens_measurable_space E]
[second_countable_topology E] [second_countable_topology (E →L[𝕜] F)]
[measurable_space F] [borel_space F] :
measurable (λ p : (E →L[𝕜] F) × E, p.1 p.2) :=
is_bounded_bilinear_map_apply.continuous.measurable
end continuous_linear_map
section fderiv
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E]
variables {F : Type*} [normed_group F] [normed_space 𝕜 F]
variables {f : E → F} (K : set (E →L[𝕜] F))
namespace fderiv_measurable_aux
/-- The set `A f L r ε` is the set of points `x` around which the function `f` is well approximated
at scale `r` by the linear map `L`, up to an error `ε`. We tweak the definition to make sure that
this is an open set.-/
def A (f : E → F) (L : E →L[𝕜] F) (r ε : ℝ) : set E :=
{x | ∃ r' ∈ Ioc (r/2) r, ∀ y z ∈ ball x r', ∥f z - f y - L (z-y)∥ ≤ ε * r}
/-- The set `B f K r s ε` is the set of points `x` around which there exists a continuous linear map
`L` belonging to `K` (a given set of continuous linear maps) that approximates well the
function `f` (up to an error `ε`), simultaneously at scales `r` and `s`. -/
def B (f : E → F) (K : set (E →L[𝕜] F)) (r s ε : ℝ) : set E :=
⋃ (L ∈ K), (A f L r ε) ∩ (A f L s ε)
/-- The set `D f K` is a complicated set constructed using countable intersections and unions. Its
main use is that, when `K` is complete, it is exactly the set of points where `f` is differentiable,
with a derivative in `K`. -/
def D (f : E → F) (K : set (E →L[𝕜] F)) : set E :=
⋂ (e : ℕ), ⋃ (n : ℕ), ⋂ (p ≥ n) (q ≥ n), B f K ((1/2) ^ p) ((1/2) ^ q) ((1/2) ^ e)
lemma is_open_A (L : E →L[𝕜] F) (r ε : ℝ) : is_open (A f L r ε) :=
begin
rw metric.is_open_iff,
rintros x ⟨r', r'_mem, hr'⟩,
obtain ⟨s, s_gt, s_lt⟩ : ∃ (s : ℝ), r / 2 < s ∧ s < r' := exists_between r'_mem.1,
have : s ∈ Ioc (r/2) r := ⟨s_gt, le_of_lt (s_lt.trans_le r'_mem.2)⟩,
refine ⟨r' - s, by linarith, λ x' hx', ⟨s, this, _⟩⟩,
have B : ball x' s ⊆ ball x r' := ball_subset (le_of_lt hx'),
assume y hy z hz,
exact hr' y (B hy) z (B hz)
end
lemma is_open_B {K : set (E →L[𝕜] F)} {r s ε : ℝ} : is_open (B f K r s ε) :=
by simp [B, is_open_Union, is_open.inter, is_open_A]
lemma A_mono (L : E →L[𝕜] F) (r : ℝ) {ε δ : ℝ} (h : ε ≤ δ) :
A f L r ε ⊆ A f L r δ :=
begin
rintros x ⟨r', r'r, hr'⟩,
refine ⟨r', r'r, λ y hy z hz, (hr' y hy z hz).trans (mul_le_mul_of_nonneg_right h _)⟩,
linarith [mem_ball.1 hy, r'r.2, @dist_nonneg _ _ y x],
end
lemma le_of_mem_A {r ε : ℝ} {L : E →L[𝕜] F} {x : E} (hx : x ∈ A f L r ε)
{y z : E} (hy : y ∈ closed_ball x (r/2)) (hz : z ∈ closed_ball x (r/2)) :
∥f z - f y - L (z-y)∥ ≤ ε * r :=
begin
rcases hx with ⟨r', r'mem, hr'⟩,
exact hr' _ ((mem_closed_ball.1 hy).trans_lt r'mem.1) _ ((mem_closed_ball.1 hz).trans_lt r'mem.1)
end
lemma mem_A_of_differentiable {ε : ℝ} (hε : 0 < ε) {x : E} (hx : differentiable_at 𝕜 f x) :
∃ R > 0, ∀ r ∈ Ioo (0 : ℝ) R, x ∈ A f (fderiv 𝕜 f x) r ε :=
begin
have := hx.has_fderiv_at,
simp only [has_fderiv_at, has_fderiv_at_filter, is_o_iff] at this,
rcases eventually_nhds_iff_ball.1 (this (half_pos hε)) with ⟨R, R_pos, hR⟩,
refine ⟨R, R_pos, λ r hr, _⟩,
have : r ∈ Ioc (r/2) r := ⟨half_lt_self hr.1, le_rfl⟩,
refine ⟨r, this, λ y hy z hz, _⟩,
calc ∥f z - f y - (fderiv 𝕜 f x) (z - y)∥
= ∥(f z - f x - (fderiv 𝕜 f x) (z - x)) - (f y - f x - (fderiv 𝕜 f x) (y - x))∥ :
by { congr' 1, simp only [continuous_linear_map.map_sub], abel }
... ≤ ∥(f z - f x - (fderiv 𝕜 f x) (z - x))∥ + ∥f y - f x - (fderiv 𝕜 f x) (y - x)∥ :
norm_sub_le _ _
... ≤ ε / 2 * ∥z - x∥ + ε / 2 * ∥y - x∥ :
add_le_add (hR _ (lt_trans (mem_ball.1 hz) hr.2)) (hR _ (lt_trans (mem_ball.1 hy) hr.2))
... ≤ ε / 2 * r + ε / 2 * r :
add_le_add
(mul_le_mul_of_nonneg_left (le_of_lt (mem_ball_iff_norm.1 hz)) (le_of_lt (half_pos hε)))
(mul_le_mul_of_nonneg_left (le_of_lt (mem_ball_iff_norm.1 hy)) (le_of_lt (half_pos hε)))
... = ε * r : by ring
end
lemma norm_sub_le_of_mem_A {c : 𝕜} (hc : 1 < ∥c∥)
{r ε : ℝ} (hε : 0 < ε) (hr : 0 < r) {x : E} {L₁ L₂ : E →L[𝕜] F}
(h₁ : x ∈ A f L₁ r ε) (h₂ : x ∈ A f L₂ r ε) : ∥L₁ - L₂∥ ≤ 4 * ∥c∥ * ε :=
begin
have : 0 ≤ 4 * ∥c∥ * ε :=
mul_nonneg (mul_nonneg (by norm_num : (0 : ℝ) ≤ 4) (norm_nonneg _)) hε.le,
refine op_norm_le_of_shell (half_pos hr) this hc _,
assume y ley ylt,
rw [div_div,
div_le_iff' (mul_pos (by norm_num : (0 : ℝ) < 2) (zero_lt_one.trans hc))] at ley,
calc ∥(L₁ - L₂) y∥
= ∥(f (x + y) - f x - L₂ ((x + y) - x)) - (f (x + y) - f x - L₁ ((x + y) - x))∥ : by simp
... ≤ ∥(f (x + y) - f x - L₂ ((x + y) - x))∥ + ∥(f (x + y) - f x - L₁ ((x + y) - x))∥ :
norm_sub_le _ _
... ≤ ε * r + ε * r :
begin
apply add_le_add,
{ apply le_of_mem_A h₂,
{ simp only [le_of_lt (half_pos hr), mem_closed_ball, dist_self] },
{ simp only [dist_eq_norm, add_sub_cancel', mem_closed_ball, ylt.le], } },
{ apply le_of_mem_A h₁,
{ simp only [le_of_lt (half_pos hr), mem_closed_ball, dist_self] },
{ simp only [dist_eq_norm, add_sub_cancel', mem_closed_ball, ylt.le] } },
end
... = 2 * ε * r : by ring
... ≤ 2 * ε * (2 * ∥c∥ * ∥y∥) : mul_le_mul_of_nonneg_left ley (mul_nonneg (by norm_num) hε.le)
... = 4 * ∥c∥ * ε * ∥y∥ : by ring
end
/-- Easy inclusion: a differentiability point with derivative in `K` belongs to `D f K`. -/
lemma differentiable_set_subset_D : {x | differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ K} ⊆ D f K :=
begin
assume x hx,
rw [D, mem_Inter],
assume e,
have : (0 : ℝ) < (1/2) ^ e := pow_pos (by norm_num) _,
rcases mem_A_of_differentiable this hx.1 with ⟨R, R_pos, hR⟩,
obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1/2) ^ n < R :=
exists_pow_lt_of_lt_one R_pos (by norm_num : (1 : ℝ)/2 < 1),
simp only [mem_Union, mem_Inter, B, mem_inter_eq],
refine ⟨n, λ p hp q hq, ⟨fderiv 𝕜 f x, hx.2, ⟨_, _⟩⟩⟩;
{ refine hR _ ⟨pow_pos (by norm_num) _, lt_of_le_of_lt _ hn⟩,
exact pow_le_pow_of_le_one (by norm_num) (by norm_num) (by assumption) }
end
/-- Harder inclusion: at a point in `D f K`, the function `f` has a derivative, in `K`. -/
lemma D_subset_differentiable_set {K : set (E →L[𝕜] F)} (hK : is_complete K) :
D f K ⊆ {x | differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ K} :=
begin
have P : ∀ {n : ℕ}, (0 : ℝ) < (1/2) ^ n := pow_pos (by norm_num),
rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩,
have cpos : 0 < ∥c∥ := lt_trans zero_lt_one hc,
assume x hx,
have : ∀ (e : ℕ), ∃ (n : ℕ), ∀ p q, n ≤ p → n ≤ q → ∃ L ∈ K,
x ∈ A f L ((1/2) ^ p) ((1/2) ^ e) ∩ A f L ((1/2) ^ q) ((1/2) ^ e),
{ assume e,
have := mem_Inter.1 hx e,
rcases mem_Union.1 this with ⟨n, hn⟩,
refine ⟨n, λ p q hp hq, _⟩,
simp only [mem_Inter, ge_iff_le] at hn,
rcases mem_Union.1 (hn p hp q hq) with ⟨L, hL⟩,
exact ⟨L, mem_Union.1 hL⟩, },
/- Recast the assumptions: for each `e`, there exist `n e` and linear maps `L e p q` in `K`
such that, for `p, q ≥ n e`, then `f` is well approximated by `L e p q` at scale `2 ^ (-p)` and
`2 ^ (-q)`, with an error `2 ^ (-e)`. -/
choose! n L hn using this,
/- All the operators `L e p q` that show up are close to each other. To prove this, we argue
that `L e p q` is close to `L e p r` (where `r` is large enough), as both approximate `f` at
scale `2 ^(- p)`. And `L e p r` is close to `L e' p' r` as both approximate `f` at scale
`2 ^ (- r)`. And `L e' p' r` is close to `L e' p' q'` as both approximate `f` at scale
`2 ^ (- p')`. -/
have M : ∀ e p q e' p' q', n e ≤ p → n e ≤ q → n e' ≤ p' → n e' ≤ q' → e ≤ e' →
∥L e p q - L e' p' q'∥ ≤ 12 * ∥c∥ * (1/2) ^ e,
{ assume e p q e' p' q' hp hq hp' hq' he',
let r := max (n e) (n e'),
have I : ((1:ℝ)/2)^e' ≤ (1/2)^e := pow_le_pow_of_le_one (by norm_num) (by norm_num) he',
have J1 : ∥L e p q - L e p r∥ ≤ 4 * ∥c∥ * (1/2)^e,
{ have I1 : x ∈ A f (L e p q) ((1 / 2) ^ p) ((1/2)^e) :=
(hn e p q hp hq).2.1,
have I2 : x ∈ A f (L e p r) ((1 / 2) ^ p) ((1/2)^e) :=
(hn e p r hp (le_max_left _ _)).2.1,
exact norm_sub_le_of_mem_A hc P P I1 I2 },
have J2 : ∥L e p r - L e' p' r∥ ≤ 4 * ∥c∥ * (1/2)^e,
{ have I1 : x ∈ A f (L e p r) ((1 / 2) ^ r) ((1/2)^e) :=
(hn e p r hp (le_max_left _ _)).2.2,
have I2 : x ∈ A f (L e' p' r) ((1 / 2) ^ r) ((1/2)^e') :=
(hn e' p' r hp' (le_max_right _ _)).2.2,
exact norm_sub_le_of_mem_A hc P P I1 (A_mono _ _ I I2) },
have J3 : ∥L e' p' r - L e' p' q'∥ ≤ 4 * ∥c∥ * (1/2)^e,
{ have I1 : x ∈ A f (L e' p' r) ((1 / 2) ^ p') ((1/2)^e') :=
(hn e' p' r hp' (le_max_right _ _)).2.1,
have I2 : x ∈ A f (L e' p' q') ((1 / 2) ^ p') ((1/2)^e') :=
(hn e' p' q' hp' hq').2.1,
exact norm_sub_le_of_mem_A hc P P (A_mono _ _ I I1) (A_mono _ _ I I2) },
calc ∥L e p q - L e' p' q'∥
= ∥(L e p q - L e p r) + (L e p r - L e' p' r) + (L e' p' r - L e' p' q')∥ :
by { congr' 1, abel }
... ≤ ∥L e p q - L e p r∥ + ∥L e p r - L e' p' r∥ + ∥L e' p' r - L e' p' q'∥ :
le_trans (norm_add_le _ _) (add_le_add_right (norm_add_le _ _) _)
... ≤ 4 * ∥c∥ * (1/2)^e + 4 * ∥c∥ * (1/2)^e + 4 * ∥c∥ * (1/2)^e :
by apply_rules [add_le_add]
... = 12 * ∥c∥ * (1/2)^e : by ring },
/- For definiteness, use `L0 e = L e (n e) (n e)`, to have a single sequence. We claim that this
is a Cauchy sequence. -/
let L0 : ℕ → (E →L[𝕜] F) := λ e, L e (n e) (n e),
have : cauchy_seq L0,
{ rw metric.cauchy_seq_iff',
assume ε εpos,
obtain ⟨e, he⟩ : ∃ (e : ℕ), (1/2) ^ e < ε / (12 * ∥c∥) :=
exists_pow_lt_of_lt_one (div_pos εpos (mul_pos (by norm_num) cpos)) (by norm_num),
refine ⟨e, λ e' he', _⟩,
rw [dist_comm, dist_eq_norm],
calc ∥L0 e - L0 e'∥
≤ 12 * ∥c∥ * (1/2)^e : M _ _ _ _ _ _ le_rfl le_rfl le_rfl le_rfl he'
... < 12 * ∥c∥ * (ε / (12 * ∥c∥)) :
mul_lt_mul' le_rfl he (le_of_lt P) (mul_pos (by norm_num) cpos)
... = ε : by { field_simp [(by norm_num : (12 : ℝ) ≠ 0), ne_of_gt cpos], ring } },
/- As it is Cauchy, the sequence `L0` converges, to a limit `f'` in `K`.-/
obtain ⟨f', f'K, hf'⟩ : ∃ f' ∈ K, tendsto L0 at_top (𝓝 f') :=
cauchy_seq_tendsto_of_is_complete hK (λ e, (hn e (n e) (n e) le_rfl le_rfl).1) this,
have Lf' : ∀ e p, n e ≤ p → ∥L e (n e) p - f'∥ ≤ 12 * ∥c∥ * (1/2)^e,
{ assume e p hp,
apply le_of_tendsto (tendsto_const_nhds.sub hf').norm,
rw eventually_at_top,
exact ⟨e, λ e' he', M _ _ _ _ _ _ le_rfl hp le_rfl le_rfl he'⟩ },
/- Let us show that `f` has derivative `f'` at `x`. -/
have : has_fderiv_at f f' x,
{ simp only [has_fderiv_at_iff_is_o_nhds_zero, is_o_iff],
/- to get an approximation with a precision `ε`, we will replace `f` with `L e (n e) m` for
some large enough `e` (yielding a small error by uniform approximation). As one can vary `m`,
this makes it possible to cover all scales, and thus to obtain a good linear approximation in
the whole ball of radius `(1/2)^(n e)`. -/
assume ε εpos,
have pos : 0 < 4 + 12 * ∥c∥ :=
add_pos_of_pos_of_nonneg (by norm_num) (mul_nonneg (by norm_num) (norm_nonneg _)),
obtain ⟨e, he⟩ : ∃ (e : ℕ), (1 / 2) ^ e < ε / (4 + 12 * ∥c∥) :=
exists_pow_lt_of_lt_one (div_pos εpos pos) (by norm_num),
rw eventually_nhds_iff_ball,
refine ⟨(1/2) ^ (n e + 1), P, λ y hy, _⟩,
-- We need to show that `f (x + y) - f x - f' y` is small. For this, we will work at scale
-- `k` where `k` is chosen with `∥y∥ ∼ 2 ^ (-k)`.
by_cases y_pos : y = 0, {simp [y_pos] },
have yzero : 0 < ∥y∥ := norm_pos_iff.mpr y_pos,
have y_lt : ∥y∥ < (1/2) ^ (n e + 1), by simpa using mem_ball_iff_norm.1 hy,
have yone : ∥y∥ ≤ 1 :=
le_trans (y_lt.le) (pow_le_one _ (by norm_num) (by norm_num)),
-- define the scale `k`.
obtain ⟨k, hk, h'k⟩ : ∃ (k : ℕ), (1/2) ^ (k + 1) < ∥y∥ ∧ ∥y∥ ≤ (1/2) ^ k :=
exists_nat_pow_near_of_lt_one yzero yone (by norm_num : (0 : ℝ) < 1/2)
(by norm_num : (1 : ℝ)/2 < 1),
-- the scale is large enough (as `y` is small enough)
have k_gt : n e < k,
{ have : ((1:ℝ)/2) ^ (k + 1) < (1/2) ^ (n e + 1) := lt_trans hk y_lt,
rw pow_lt_pow_iff_of_lt_one (by norm_num : (0 : ℝ) < 1/2) (by norm_num) at this,
linarith },
set m := k - 1 with hl,
have m_ge : n e ≤ m := nat.le_pred_of_lt k_gt,
have km : k = m + 1 := (nat.succ_pred_eq_of_pos (lt_of_le_of_lt (zero_le _) k_gt)).symm,
rw km at hk h'k,
-- `f` is well approximated by `L e (n e) k` at the relevant scale
-- (in fact, we use `m = k - 1` instead of `k` because of the precise definition of `A`).
have J1 : ∥f (x + y) - f x - L e (n e) m ((x + y) - x)∥ ≤ (1/2) ^ e * (1/2) ^ m,
{ apply le_of_mem_A (hn e (n e) m le_rfl m_ge).2.2,
{ simp only [mem_closed_ball, dist_self],
exact div_nonneg (le_of_lt P) (zero_le_two) },
{ simpa only [dist_eq_norm, add_sub_cancel', mem_closed_ball, pow_succ', mul_one_div]
using h'k } },
have J2 : ∥f (x + y) - f x - L e (n e) m y∥ ≤ 4 * (1/2) ^ e * ∥y∥ := calc
∥f (x + y) - f x - L e (n e) m y∥ ≤ (1/2) ^ e * (1/2) ^ m :
by simpa only [add_sub_cancel'] using J1
... = 4 * (1/2) ^ e * (1/2) ^ (m + 2) : by { field_simp, ring_exp }
... ≤ 4 * (1/2) ^ e * ∥y∥ :
mul_le_mul_of_nonneg_left (le_of_lt hk) (mul_nonneg (by norm_num) (le_of_lt P)),
-- use the previous estimates to see that `f (x + y) - f x - f' y` is small.
calc ∥f (x + y) - f x - f' y∥
= ∥(f (x + y) - f x - L e (n e) m y) + (L e (n e) m - f') y∥ :
congr_arg _ (by simp)
... ≤ 4 * (1/2) ^ e * ∥y∥ + 12 * ∥c∥ * (1/2) ^ e * ∥y∥ :
norm_add_le_of_le J2
((le_op_norm _ _).trans (mul_le_mul_of_nonneg_right (Lf' _ _ m_ge) (norm_nonneg _)))
... = (4 + 12 * ∥c∥) * ∥y∥ * (1/2) ^ e : by ring
... ≤ (4 + 12 * ∥c∥) * ∥y∥ * (ε / (4 + 12 * ∥c∥)) :
mul_le_mul_of_nonneg_left he.le
(mul_nonneg (add_nonneg (by norm_num) (mul_nonneg (by norm_num) (norm_nonneg _)))
(norm_nonneg _))
... = ε * ∥y∥ : by { field_simp [ne_of_gt pos], ring } },
rw ← this.fderiv at f'K,
exact ⟨this.differentiable_at, f'K⟩
end
theorem differentiable_set_eq_D (hK : is_complete K) :
{x | differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ K} = D f K :=
subset.antisymm (differentiable_set_subset_D _) (D_subset_differentiable_set hK)
end fderiv_measurable_aux
open fderiv_measurable_aux
variables [measurable_space E] [opens_measurable_space E]
variables (𝕜 f)
/-- The set of differentiability points of a function, with derivative in a given complete set,
is Borel-measurable. -/
theorem measurable_set_of_differentiable_at_of_is_complete
{K : set (E →L[𝕜] F)} (hK : is_complete K) :
measurable_set {x | differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ K} :=
by simp [differentiable_set_eq_D K hK, D, is_open_B.measurable_set, measurable_set.Inter_Prop,
measurable_set.Inter, measurable_set.Union]
variable [complete_space F]
/-- The set of differentiability points of a function taking values in a complete space is
Borel-measurable. -/
theorem measurable_set_of_differentiable_at :
measurable_set {x | differentiable_at 𝕜 f x} :=
begin
have : is_complete (univ : set (E →L[𝕜] F)) := complete_univ,
convert measurable_set_of_differentiable_at_of_is_complete 𝕜 f this,
simp
end
@[measurability] lemma measurable_fderiv : measurable (fderiv 𝕜 f) :=
begin
refine measurable_of_is_closed (λ s hs, _),
have : fderiv 𝕜 f ⁻¹' s = {x | differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ s} ∪
({x | ¬differentiable_at 𝕜 f x} ∩ {x | (0 : E →L[𝕜] F) ∈ s}) :=
set.ext (λ x, mem_preimage.trans fderiv_mem_iff),
rw this,
exact (measurable_set_of_differentiable_at_of_is_complete _ _ hs.is_complete).union
((measurable_set_of_differentiable_at _ _).compl.inter (measurable_set.const _))
end
@[measurability] lemma measurable_fderiv_apply_const [measurable_space F] [borel_space F] (y : E) :
measurable (λ x, fderiv 𝕜 f x y) :=
(continuous_linear_map.measurable_apply y).comp (measurable_fderiv 𝕜 f)
variable {𝕜}
@[measurability] lemma measurable_deriv [measurable_space 𝕜] [opens_measurable_space 𝕜]
[measurable_space F] [borel_space F] (f : 𝕜 → F) : measurable (deriv f) :=
by simpa only [fderiv_deriv] using measurable_fderiv_apply_const 𝕜 f 1
lemma strongly_measurable_deriv [measurable_space 𝕜] [opens_measurable_space 𝕜]
[second_countable_topology F] (f : 𝕜 → F) :
strongly_measurable (deriv f) :=
by { borelize F, exact (measurable_deriv f).strongly_measurable }
lemma ae_measurable_deriv [measurable_space 𝕜] [opens_measurable_space 𝕜] [measurable_space F]
[borel_space F] (f : 𝕜 → F) (μ : measure 𝕜) : ae_measurable (deriv f) μ :=
(measurable_deriv f).ae_measurable
lemma ae_strongly_measurable_deriv [measurable_space 𝕜] [opens_measurable_space 𝕜]
[second_countable_topology F] (f : 𝕜 → F) (μ : measure 𝕜) :
ae_strongly_measurable (deriv f) μ :=
(strongly_measurable_deriv f).ae_strongly_measurable
end fderiv
section right_deriv
variables {F : Type*} [normed_group F] [normed_space ℝ F]
variables {f : ℝ → F} (K : set F)
namespace right_deriv_measurable_aux
/-- The set `A f L r ε` is the set of points `x` around which the function `f` is well approximated
at scale `r` by the linear map `h ↦ h • L`, up to an error `ε`. We tweak the definition to
make sure that this is open on the right. -/
def A (f : ℝ → F) (L : F) (r ε : ℝ) : set ℝ :=
{x | ∃ r' ∈ Ioc (r/2) r, ∀ y z ∈ Icc x (x + r'), ∥f z - f y - (z-y) • L∥ ≤ ε * r}
/-- The set `B f K r s ε` is the set of points `x` around which there exists a vector
`L` belonging to `K` (a given set of vectors) such that `h • L` approximates well `f (x + h)`
(up to an error `ε`), simultaneously at scales `r` and `s`. -/
def B (f : ℝ → F) (K : set F) (r s ε : ℝ) : set ℝ :=
⋃ (L ∈ K), (A f L r ε) ∩ (A f L s ε)
/-- The set `D f K` is a complicated set constructed using countable intersections and unions. Its
main use is that, when `K` is complete, it is exactly the set of points where `f` is differentiable,
with a derivative in `K`. -/
def D (f : ℝ → F) (K : set F) : set ℝ :=
⋂ (e : ℕ), ⋃ (n : ℕ), ⋂ (p ≥ n) (q ≥ n), B f K ((1/2) ^ p) ((1/2) ^ q) ((1/2) ^ e)
lemma A_mem_nhds_within_Ioi {L : F} {r ε x : ℝ} (hx : x ∈ A f L r ε) :
A f L r ε ∈ 𝓝[>] x :=
begin
rcases hx with ⟨r', rr', hr'⟩,
rw mem_nhds_within_Ioi_iff_exists_Ioo_subset,
obtain ⟨s, s_gt, s_lt⟩ : ∃ (s : ℝ), r / 2 < s ∧ s < r' := exists_between rr'.1,
have : s ∈ Ioc (r/2) r := ⟨s_gt, le_of_lt (s_lt.trans_le rr'.2)⟩,
refine ⟨x + r' - s, by { simp only [mem_Ioi], linarith }, λ x' hx', ⟨s, this, _⟩⟩,
have A : Icc x' (x' + s) ⊆ Icc x (x + r'),
{ apply Icc_subset_Icc hx'.1.le,
linarith [hx'.2] },
assume y hy z hz,
exact hr' y (A hy) z (A hz)
end
lemma B_mem_nhds_within_Ioi {K : set F} {r s ε x : ℝ} (hx : x ∈ B f K r s ε) :
B f K r s ε ∈ 𝓝[>] x :=
begin
obtain ⟨L, LK, hL₁, hL₂⟩ : ∃ (L : F), L ∈ K ∧ x ∈ A f L r ε ∧ x ∈ A f L s ε,
by simpa only [B, mem_Union, mem_inter_eq, exists_prop] using hx,
filter_upwards [A_mem_nhds_within_Ioi hL₁, A_mem_nhds_within_Ioi hL₂] with y hy₁ hy₂,
simp only [B, mem_Union, mem_inter_eq, exists_prop],
exact ⟨L, LK, hy₁, hy₂⟩
end
lemma measurable_set_B {K : set F} {r s ε : ℝ} : measurable_set (B f K r s ε) :=
measurable_set_of_mem_nhds_within_Ioi (λ x hx, B_mem_nhds_within_Ioi hx)
lemma A_mono (L : F) (r : ℝ) {ε δ : ℝ} (h : ε ≤ δ) :
A f L r ε ⊆ A f L r δ :=
begin
rintros x ⟨r', r'r, hr'⟩,
refine ⟨r', r'r, λ y hy z hz, (hr' y hy z hz).trans (mul_le_mul_of_nonneg_right h _)⟩,
linarith [hy.1, hy.2, r'r.2],
end
lemma le_of_mem_A {r ε : ℝ} {L : F} {x : ℝ} (hx : x ∈ A f L r ε)
{y z : ℝ} (hy : y ∈ Icc x (x + r/2)) (hz : z ∈ Icc x (x + r/2)) :
∥f z - f y - (z-y) • L∥ ≤ ε * r :=
begin
rcases hx with ⟨r', r'mem, hr'⟩,
have A : x + r / 2 ≤ x + r', by linarith [r'mem.1],
exact hr' _ ((Icc_subset_Icc le_rfl A) hy) _ ((Icc_subset_Icc le_rfl A) hz),
end
lemma mem_A_of_differentiable {ε : ℝ} (hε : 0 < ε) {x : ℝ}
(hx : differentiable_within_at ℝ f (Ici x) x) :
∃ R > 0, ∀ r ∈ Ioo (0 : ℝ) R, x ∈ A f (deriv_within f (Ici x) x) r ε :=
begin
have := hx.has_deriv_within_at,
simp_rw [has_deriv_within_at_iff_is_o, is_o_iff] at this,
rcases mem_nhds_within_Ici_iff_exists_Ico_subset.1 (this (half_pos hε)) with ⟨m, xm, hm⟩,
refine ⟨m - x, by linarith [show x < m, from xm], λ r hr, _⟩,
have : r ∈ Ioc (r/2) r := ⟨half_lt_self hr.1, le_rfl⟩,
refine ⟨r, this, λ y hy z hz, _⟩,
calc ∥f z - f y - (z - y) • deriv_within f (Ici x) x∥
= ∥(f z - f x - (z - x) • deriv_within f (Ici x) x)
- (f y - f x - (y - x) • deriv_within f (Ici x) x)∥ :
by { congr' 1, simp only [sub_smul], abel }
... ≤ ∥f z - f x - (z - x) • deriv_within f (Ici x) x∥
+ ∥f y - f x - (y - x) • deriv_within f (Ici x) x∥ :
norm_sub_le _ _
... ≤ ε / 2 * ∥z - x∥ + ε / 2 * ∥y - x∥ :
add_le_add (hm ⟨hz.1, hz.2.trans_lt (by linarith [hr.2])⟩)
(hm ⟨hy.1, hy.2.trans_lt (by linarith [hr.2])⟩)
... ≤ ε / 2 * r + ε / 2 * r :
begin
apply add_le_add,
{ apply mul_le_mul_of_nonneg_left _ (le_of_lt (half_pos hε)),
rw [real.norm_of_nonneg];
linarith [hz.1, hz.2] },
{ apply mul_le_mul_of_nonneg_left _ (le_of_lt (half_pos hε)),
rw [real.norm_of_nonneg];
linarith [hy.1, hy.2] },
end
... = ε * r : by ring
end
lemma norm_sub_le_of_mem_A
{r x : ℝ} (hr : 0 < r) (ε : ℝ) {L₁ L₂ : F}
(h₁ : x ∈ A f L₁ r ε) (h₂ : x ∈ A f L₂ r ε) : ∥L₁ - L₂∥ ≤ 4 * ε :=
begin
suffices H : ∥(r/2) • (L₁ - L₂)∥ ≤ (r / 2) * (4 * ε),
by rwa [norm_smul, real.norm_of_nonneg (half_pos hr).le, mul_le_mul_left (half_pos hr)] at H,
calc
∥(r/2) • (L₁ - L₂)∥
= ∥(f (x + r/2) - f x - (x + r/2 - x) • L₂) - (f (x + r/2) - f x - (x + r/2 - x) • L₁)∥ :
by simp [smul_sub]
... ≤ ∥f (x + r/2) - f x - (x + r/2 - x) • L₂∥ + ∥f (x + r/2) - f x - (x + r/2 - x) • L₁∥ :
norm_sub_le _ _
... ≤ ε * r + ε * r :
begin
apply add_le_add,
{ apply le_of_mem_A h₂;
simp [(half_pos hr).le] },
{ apply le_of_mem_A h₁;
simp [(half_pos hr).le] },
end
... = (r / 2) * (4 * ε) : by ring
end
/-- Easy inclusion: a differentiability point with derivative in `K` belongs to `D f K`. -/
lemma differentiable_set_subset_D :
{x | differentiable_within_at ℝ f (Ici x) x ∧ deriv_within f (Ici x) x ∈ K} ⊆ D f K :=
begin
assume x hx,
rw [D, mem_Inter],
assume e,
have : (0 : ℝ) < (1/2) ^ e := pow_pos (by norm_num) _,
rcases mem_A_of_differentiable this hx.1 with ⟨R, R_pos, hR⟩,
obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1/2) ^ n < R :=
exists_pow_lt_of_lt_one R_pos (by norm_num : (1 : ℝ)/2 < 1),
simp only [mem_Union, mem_Inter, B, mem_inter_eq],
refine ⟨n, λ p hp q hq, ⟨deriv_within f (Ici x) x, hx.2, ⟨_, _⟩⟩⟩;
{ refine hR _ ⟨pow_pos (by norm_num) _, lt_of_le_of_lt _ hn⟩,
exact pow_le_pow_of_le_one (by norm_num) (by norm_num) (by assumption) }
end
/-- Harder inclusion: at a point in `D f K`, the function `f` has a derivative, in `K`. -/
lemma D_subset_differentiable_set {K : set F} (hK : is_complete K) :
D f K ⊆ {x | differentiable_within_at ℝ f (Ici x) x ∧ deriv_within f (Ici x) x ∈ K} :=
begin
have P : ∀ {n : ℕ}, (0 : ℝ) < (1/2) ^ n := pow_pos (by norm_num),
assume x hx,
have : ∀ (e : ℕ), ∃ (n : ℕ), ∀ p q, n ≤ p → n ≤ q → ∃ L ∈ K,
x ∈ A f L ((1/2) ^ p) ((1/2) ^ e) ∩ A f L ((1/2) ^ q) ((1/2) ^ e),
{ assume e,
have := mem_Inter.1 hx e,
rcases mem_Union.1 this with ⟨n, hn⟩,
refine ⟨n, λ p q hp hq, _⟩,
simp only [mem_Inter, ge_iff_le] at hn,
rcases mem_Union.1 (hn p hp q hq) with ⟨L, hL⟩,
exact ⟨L, mem_Union.1 hL⟩, },
/- Recast the assumptions: for each `e`, there exist `n e` and linear maps `L e p q` in `K`
such that, for `p, q ≥ n e`, then `f` is well approximated by `L e p q` at scale `2 ^ (-p)` and
`2 ^ (-q)`, with an error `2 ^ (-e)`. -/
choose! n L hn using this,
/- All the operators `L e p q` that show up are close to each other. To prove this, we argue
that `L e p q` is close to `L e p r` (where `r` is large enough), as both approximate `f` at
scale `2 ^(- p)`. And `L e p r` is close to `L e' p' r` as both approximate `f` at scale
`2 ^ (- r)`. And `L e' p' r` is close to `L e' p' q'` as both approximate `f` at scale
`2 ^ (- p')`. -/
have M : ∀ e p q e' p' q', n e ≤ p → n e ≤ q → n e' ≤ p' → n e' ≤ q' → e ≤ e' →
∥L e p q - L e' p' q'∥ ≤ 12 * (1/2) ^ e,
{ assume e p q e' p' q' hp hq hp' hq' he',
let r := max (n e) (n e'),
have I : ((1:ℝ)/2)^e' ≤ (1/2)^e := pow_le_pow_of_le_one (by norm_num) (by norm_num) he',
have J1 : ∥L e p q - L e p r∥ ≤ 4 * (1/2)^e,
{ have I1 : x ∈ A f (L e p q) ((1 / 2) ^ p) ((1/2)^e) :=
(hn e p q hp hq).2.1,
have I2 : x ∈ A f (L e p r) ((1 / 2) ^ p) ((1/2)^e) :=
(hn e p r hp (le_max_left _ _)).2.1,
exact norm_sub_le_of_mem_A P _ I1 I2 },
have J2 : ∥L e p r - L e' p' r∥ ≤ 4 * (1/2)^e,
{ have I1 : x ∈ A f (L e p r) ((1 / 2) ^ r) ((1/2)^e) :=
(hn e p r hp (le_max_left _ _)).2.2,
have I2 : x ∈ A f (L e' p' r) ((1 / 2) ^ r) ((1/2)^e') :=
(hn e' p' r hp' (le_max_right _ _)).2.2,
exact norm_sub_le_of_mem_A P _ I1 (A_mono _ _ I I2) },
have J3 : ∥L e' p' r - L e' p' q'∥ ≤ 4 * (1/2)^e,
{ have I1 : x ∈ A f (L e' p' r) ((1 / 2) ^ p') ((1/2)^e') :=
(hn e' p' r hp' (le_max_right _ _)).2.1,
have I2 : x ∈ A f (L e' p' q') ((1 / 2) ^ p') ((1/2)^e') :=
(hn e' p' q' hp' hq').2.1,
exact norm_sub_le_of_mem_A P _ (A_mono _ _ I I1) (A_mono _ _ I I2) },
calc ∥L e p q - L e' p' q'∥
= ∥(L e p q - L e p r) + (L e p r - L e' p' r) + (L e' p' r - L e' p' q')∥ :
by { congr' 1, abel }
... ≤ ∥L e p q - L e p r∥ + ∥L e p r - L e' p' r∥ + ∥L e' p' r - L e' p' q'∥ :
le_trans (norm_add_le _ _) (add_le_add_right (norm_add_le _ _) _)
... ≤ 4 * (1/2)^e + 4 * (1/2)^e + 4 * (1/2)^e :
by apply_rules [add_le_add]
... = 12 * (1/2)^e : by ring },
/- For definiteness, use `L0 e = L e (n e) (n e)`, to have a single sequence. We claim that this
is a Cauchy sequence. -/
let L0 : ℕ → F := λ e, L e (n e) (n e),
have : cauchy_seq L0,
{ rw metric.cauchy_seq_iff',
assume ε εpos,
obtain ⟨e, he⟩ : ∃ (e : ℕ), (1/2) ^ e < ε / 12 :=
exists_pow_lt_of_lt_one (div_pos εpos (by norm_num)) (by norm_num),
refine ⟨e, λ e' he', _⟩,
rw [dist_comm, dist_eq_norm],
calc ∥L0 e - L0 e'∥
≤ 12 * (1/2)^e : M _ _ _ _ _ _ le_rfl le_rfl le_rfl le_rfl he'
... < 12 * (ε / 12) :
mul_lt_mul' le_rfl he (le_of_lt P) (by norm_num)
... = ε : by { field_simp [(by norm_num : (12 : ℝ) ≠ 0)], ring } },
/- As it is Cauchy, the sequence `L0` converges, to a limit `f'` in `K`.-/
obtain ⟨f', f'K, hf'⟩ : ∃ f' ∈ K, tendsto L0 at_top (𝓝 f') :=
cauchy_seq_tendsto_of_is_complete hK (λ e, (hn e (n e) (n e) le_rfl le_rfl).1) this,
have Lf' : ∀ e p, n e ≤ p → ∥L e (n e) p - f'∥ ≤ 12 * (1/2)^e,
{ assume e p hp,
apply le_of_tendsto (tendsto_const_nhds.sub hf').norm,
rw eventually_at_top,
exact ⟨e, λ e' he', M _ _ _ _ _ _ le_rfl hp le_rfl le_rfl he'⟩ },
/- Let us show that `f` has right derivative `f'` at `x`. -/
have : has_deriv_within_at f f' (Ici x) x,
{ simp only [has_deriv_within_at_iff_is_o, is_o_iff],
/- to get an approximation with a precision `ε`, we will replace `f` with `L e (n e) m` for
some large enough `e` (yielding a small error by uniform approximation). As one can vary `m`,
this makes it possible to cover all scales, and thus to obtain a good linear approximation in
the whole interval of length `(1/2)^(n e)`. -/
assume ε εpos,
obtain ⟨e, he⟩ : ∃ (e : ℕ), (1 / 2) ^ e < ε / 16 :=
exists_pow_lt_of_lt_one (div_pos εpos (by norm_num)) (by norm_num),
have xmem : x ∈ Ico x (x + (1/2)^(n e + 1)),
by simp only [one_div, left_mem_Ico, lt_add_iff_pos_right, inv_pos, pow_pos, zero_lt_bit0,
zero_lt_one],
filter_upwards [Icc_mem_nhds_within_Ici xmem] with y hy,
-- We need to show that `f y - f x - f' (y - x)` is small. For this, we will work at scale
-- `k` where `k` is chosen with `∥y - x∥ ∼ 2 ^ (-k)`.
rcases eq_or_lt_of_le hy.1 with rfl|xy,
{ simp only [sub_self, zero_smul, norm_zero, mul_zero]},
have yzero : 0 < y - x := sub_pos.2 xy,
have y_le : y - x ≤ (1/2) ^ (n e + 1), by linarith [hy.2],
have yone : y - x ≤ 1 := le_trans y_le (pow_le_one _ (by norm_num) (by norm_num)),
-- define the scale `k`.
obtain ⟨k, hk, h'k⟩ : ∃ (k : ℕ), (1/2) ^ (k + 1) < y - x ∧ y - x ≤ (1/2) ^ k :=
exists_nat_pow_near_of_lt_one yzero yone (by norm_num : (0 : ℝ) < 1/2)
(by norm_num : (1 : ℝ)/2 < 1),
-- the scale is large enough (as `y - x` is small enough)
have k_gt : n e < k,
{ have : ((1:ℝ)/2) ^ (k + 1) < (1/2) ^ (n e + 1) := lt_of_lt_of_le hk y_le,
rw pow_lt_pow_iff_of_lt_one (by norm_num : (0 : ℝ) < 1/2) (by norm_num) at this,
linarith },
set m := k - 1 with hl,
have m_ge : n e ≤ m := nat.le_pred_of_lt k_gt,
have km : k = m + 1 := (nat.succ_pred_eq_of_pos (lt_of_le_of_lt (zero_le _) k_gt)).symm,
rw km at hk h'k,
-- `f` is well approximated by `L e (n e) k` at the relevant scale
-- (in fact, we use `m = k - 1` instead of `k` because of the precise definition of `A`).
have J : ∥f y - f x - (y - x) • L e (n e) m∥ ≤ 4 * (1/2) ^ e * ∥y - x∥ := calc
∥f y - f x - (y - x) • L e (n e) m∥ ≤ (1/2) ^ e * (1/2) ^ m :
begin
apply le_of_mem_A (hn e (n e) m le_rfl m_ge).2.2,
{ simp only [one_div, inv_pow, left_mem_Icc, le_add_iff_nonneg_right],
exact div_nonneg (inv_nonneg.2 (pow_nonneg zero_le_two _)) zero_le_two },
{ simp only [pow_add, tsub_le_iff_left] at h'k,
simpa only [hy.1, mem_Icc, true_and, one_div, pow_one] using h'k }
end
... = 4 * (1/2) ^ e * (1/2) ^ (m + 2) : by { field_simp, ring_exp }
... ≤ 4 * (1/2) ^ e * (y - x) :
mul_le_mul_of_nonneg_left (le_of_lt hk) (mul_nonneg (by norm_num) (le_of_lt P))
... = 4 * (1/2) ^ e * ∥y - x∥ : by rw [real.norm_of_nonneg yzero.le],
calc ∥f y - f x - (y - x) • f'∥
= ∥(f y - f x - (y - x) • L e (n e) m) + (y - x) • (L e (n e) m - f')∥ :
by simp only [smul_sub, sub_add_sub_cancel]
... ≤ 4 * (1/2) ^ e * ∥y - x∥ + ∥y - x∥ * (12 * (1/2) ^ e) : norm_add_le_of_le J
(by { rw [norm_smul], exact mul_le_mul_of_nonneg_left (Lf' _ _ m_ge) (norm_nonneg _) })
... = 16 * ∥y - x∥ * (1/2) ^ e : by ring
... ≤ 16 * ∥y - x∥ * (ε / 16) :
mul_le_mul_of_nonneg_left he.le (mul_nonneg (by norm_num) (norm_nonneg _))
... = ε * ∥y - x∥ : by ring },
rw ← this.deriv_within (unique_diff_on_Ici x x le_rfl) at f'K,
exact ⟨this.differentiable_within_at, f'K⟩,
end
theorem differentiable_set_eq_D (hK : is_complete K) :
{x | differentiable_within_at ℝ f (Ici x) x ∧ deriv_within f (Ici x) x ∈ K} = D f K :=
subset.antisymm (differentiable_set_subset_D _) (D_subset_differentiable_set hK)
end right_deriv_measurable_aux
open right_deriv_measurable_aux
variables (f)
/-- The set of right differentiability points of a function, with derivative in a given complete
set, is Borel-measurable. -/
theorem measurable_set_of_differentiable_within_at_Ici_of_is_complete
{K : set F} (hK : is_complete K) :
measurable_set {x | differentiable_within_at ℝ f (Ici x) x ∧ deriv_within f (Ici x) x ∈ K} :=
by simp [differentiable_set_eq_D K hK, D, measurable_set_B, measurable_set.Inter_Prop,
measurable_set.Inter, measurable_set.Union]
variable [complete_space F]
/-- The set of right differentiability points of a function taking values in a complete space is
Borel-measurable. -/
theorem measurable_set_of_differentiable_within_at_Ici :
measurable_set {x | differentiable_within_at ℝ f (Ici x) x} :=
begin
have : is_complete (univ : set F) := complete_univ,
convert measurable_set_of_differentiable_within_at_Ici_of_is_complete f this,
simp
end
@[measurability] lemma measurable_deriv_within_Ici [measurable_space F] [borel_space F] :
measurable (λ x, deriv_within f (Ici x) x) :=
begin
refine measurable_of_is_closed (λ s hs, _),
have : (λ x, deriv_within f (Ici x) x) ⁻¹' s =
{x | differentiable_within_at ℝ f (Ici x) x ∧ deriv_within f (Ici x) x ∈ s} ∪
({x | ¬differentiable_within_at ℝ f (Ici x) x} ∩ {x | (0 : F) ∈ s}) :=
set.ext (λ x, mem_preimage.trans deriv_within_mem_iff),
rw this,
exact (measurable_set_of_differentiable_within_at_Ici_of_is_complete _ hs.is_complete).union
((measurable_set_of_differentiable_within_at_Ici _).compl.inter (measurable_set.const _))
end
lemma strongly_measurable_deriv_within_Ici [second_countable_topology F] :
strongly_measurable (λ x, deriv_within f (Ici x) x) :=
by { borelize F, exact (measurable_deriv_within_Ici f).strongly_measurable }
lemma ae_measurable_deriv_within_Ici [measurable_space F] [borel_space F]
(μ : measure ℝ) : ae_measurable (λ x, deriv_within f (Ici x) x) μ :=
(measurable_deriv_within_Ici f).ae_measurable
lemma ae_strongly_measurable_deriv_within_Ici [second_countable_topology F] (μ : measure ℝ) :
ae_strongly_measurable (λ x, deriv_within f (Ici x) x) μ :=
(strongly_measurable_deriv_within_Ici f).ae_strongly_measurable
/-- The set of right differentiability points of a function taking values in a complete space is
Borel-measurable. -/
theorem measurable_set_of_differentiable_within_at_Ioi :
measurable_set {x | differentiable_within_at ℝ f (Ioi x) x} :=
by simpa [differentiable_within_at_Ioi_iff_Ici]
using measurable_set_of_differentiable_within_at_Ici f
@[measurability] lemma measurable_deriv_within_Ioi [measurable_space F] [borel_space F] :
measurable (λ x, deriv_within f (Ioi x) x) :=
by simpa [deriv_within_Ioi_eq_Ici] using measurable_deriv_within_Ici f
lemma strongly_measurable_deriv_within_Ioi [second_countable_topology F] :
strongly_measurable (λ x, deriv_within f (Ioi x) x) :=
by { borelize F, exact (measurable_deriv_within_Ioi f).strongly_measurable }
lemma ae_measurable_deriv_within_Ioi [measurable_space F] [borel_space F]
(μ : measure ℝ) : ae_measurable (λ x, deriv_within f (Ioi x) x) μ :=
(measurable_deriv_within_Ioi f).ae_measurable
lemma ae_strongly_measurable_deriv_within_Ioi [second_countable_topology F] (μ : measure ℝ) :
ae_strongly_measurable (λ x, deriv_within f (Ioi x) x) μ :=
(strongly_measurable_deriv_within_Ioi f).ae_strongly_measurable
end right_deriv
|
e3babaf6140f43649eee2777ea9abb5d1199a80f | 3f7026ea8bef0825ca0339a275c03b911baef64d | /src/analysis/calculus/deriv.lean | b80f0e421b51d4fc65940409b8108e3631e75643 | [
"Apache-2.0"
] | permissive | rspencer01/mathlib | b1e3afa5c121362ef0881012cc116513ab09f18c | c7d36292c6b9234dc40143c16288932ae38fdc12 | refs/heads/master | 1,595,010,346,708 | 1,567,511,503,000 | 1,567,511,503,000 | 206,071,681 | 0 | 0 | Apache-2.0 | 1,567,513,643,000 | 1,567,513,643,000 | null | UTF-8 | Lean | false | false | 47,899 | lean | /-
Copyright (c) 2019 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Sébastien Gouëzel
The Fréchet derivative.
Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a
continuous 𝕜-linear map, where `𝕜` is a non-discrete normed field. Then
`has_fderiv_within_at f f' s x`
says that `f` has derivative `f'` at `x`, where the domain of interest
is restricted to `s`. We also have
`has_fderiv_at f f' x := has_fderiv_within_at f f' x univ`
The derivative is defined in terms of the `is_o` relation, but also
characterized in terms of the `tendsto` relation.
We also introduce predicates `differentiable_within_at 𝕜 f s x` (where `𝕜` is the base field,
`f` the function to be differentiated, `x` the point at which the derivative is asserted to exist,
and `s` the set along which the derivative is defined), as well as `differentiable_at 𝕜 f x`,
`differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative.
To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 f x`
for some choice of a derivative if it exists, and the zero function otherwise. This choice only
behaves well along sets for which the derivative is unique, i.e., those for which the tangent
directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and
`unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed
they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular
for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very
beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever.
In addition to the definition and basic properties of the derivative, this file contains the
usual formulas (and existence assertions) for the derivative of
* constants
* the identity
* bounded linear maps
* bounded bilinear maps
* sum of two functions
* multiplication of a function by a scalar constant
* negative of a function
* subtraction of two functions
* multiplication of a function by a scalar function
* multiplication of two scalar functions
* composition of functions (the chain rule)
-/
import analysis.asymptotics analysis.calculus.tangent_cone
open filter asymptotics continuous_linear_map set
noncomputable theory
local attribute [instance, priority 0] classical.decidable_inhabited classical.prop_decidable
set_option class.instance_max_depth 90
section
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E]
variables {F : Type*} [normed_group F] [normed_space 𝕜 F]
variables {G : Type*} [normed_group G] [normed_space 𝕜 G]
def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) :=
is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L
def has_fderiv_within_at (f : E → F) (f' : E →L[𝕜] F) (s : set E) (x : E) :=
has_fderiv_at_filter f f' x (nhds_within x s)
def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) :=
has_fderiv_at_filter f f' x (nhds x)
variables (𝕜)
def differentiable_within_at (f : E → F) (s : set E) (x : E) :=
∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x
def differentiable_at (f : E → F) (x : E) :=
∃f' : E →L[𝕜] F, has_fderiv_at f f' x
def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F :=
if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0
def fderiv (f : E → F) (x : E) : E →L[𝕜] F :=
if h : ∃f', has_fderiv_at f f' x then classical.some h else 0
def differentiable_on (f : E → F) (s : set E) :=
∀x ∈ s, differentiable_within_at 𝕜 f s x
def differentiable (f : E → F) :=
∀x, differentiable_at 𝕜 f x
variables {𝕜}
variables {f f₀ f₁ g : E → F}
variables {f' f₀' f₁' g' : E →L[𝕜] F}
variables {x : E}
variables {s t : set E}
variables {L L₁ L₂ : filter E}
section derivative_uniqueness
/- In this section, we discuss the uniqueness of the derivative.
We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the
uniqueness of the derivative. -/
/-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/
theorem unique_diff_within_at.eq (H : unique_diff_within_at 𝕜 s x)
(h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' :=
begin
have A : ∀y ∈ tangent_cone_at 𝕜 s x, f' y = f₁' y,
{ assume y hy,
rcases hy with ⟨c, d, hd, hc, ylim⟩,
have at_top_is_finer : at_top ≤ comap (λ (n : ℕ), x + d n) (nhds_within (x + 0) s),
{ rw [←tendsto_iff_comap, nhds_within, tendsto_inf],
split,
{ apply tendsto_add tendsto_const_nhds (tangent_cone_at.lim_zero hc ylim) },
{ rwa tendsto_principal } },
rw add_zero at at_top_is_finer,
have : is_o (λ y, f₁' (y - x) - f' (y - x)) (λ y, y - x) (nhds_within x s),
by simpa using h.sub h₁,
have : is_o (λ n:ℕ, f₁' ((x + d n) - x) - f' ((x + d n) - x)) (λ n, (x + d n) - x)
((nhds_within x s).comap (λn, x+ d n)) := is_o.comp this _,
have L1 : is_o (λ n:ℕ, f₁' (d n) - f' (d n)) d
((nhds_within x s).comap (λn, x + d n)) := by simpa using this,
have L2 : is_o (λn:ℕ, f₁' (d n) - f' (d n)) d at_top :=
is_o.mono at_top_is_finer L1,
have L3 : is_o (λn:ℕ, c n • (f₁' (d n) - f' (d n))) (λn, c n • d n) at_top :=
is_o_smul L2,
have L4 : is_o (λn:ℕ, c n • (f₁' (d n) - f' (d n))) (λn, (1:ℝ)) at_top :=
L3.trans_is_O (is_O_one_of_tendsto ylim),
have L : tendsto (λn:ℕ, c n • (f₁' (d n) - f' (d n))) at_top (nhds 0) :=
is_o_one_iff.1 L4,
have L' : tendsto (λ (n : ℕ), c n • (f₁' (d n) - f' (d n))) at_top (nhds (f₁' y - f' y)),
{ simp only [smul_sub, (continuous_linear_map.map_smul _ _ _).symm],
apply tendsto_sub ((f₁'.continuous.tendsto _).comp ylim) ((f'.continuous.tendsto _).comp ylim) },
have : f₁' y - f' y = 0 := tendsto_nhds_unique (by simp) L' L,
exact (sub_eq_zero_iff_eq.1 this).symm },
have B : ∀y ∈ submodule.span 𝕜 (tangent_cone_at 𝕜 s x), f' y = f₁' y,
{ assume y hy,
apply submodule.span_induction hy,
{ exact λy hy, A y hy },
{ simp only [continuous_linear_map.map_zero] },
{ simp {contextual := tt} },
{ simp {contextual := tt} } },
have C : ∀y ∈ closure ((submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) : set E), f' y = f₁' y,
{ assume y hy,
let K := {y | f' y = f₁' y},
have : (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ K := B,
have : closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ closure K :=
closure_mono this,
have : y ∈ closure K := this hy,
rwa closure_eq_of_is_closed (is_closed_eq f'.continuous f₁'.continuous) at this },
rw H.1 at C,
ext y,
exact C y (mem_univ _)
end
theorem unique_diff_on.eq (H : unique_diff_on 𝕜 s) (hx : x ∈ s)
(h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' :=
unique_diff_within_at.eq (H x hx) h h₁
end derivative_uniqueness
/- Basic properties of the derivative -/
section fderiv_properties
theorem has_fderiv_at_filter_iff_tendsto :
has_fderiv_at_filter f f' x L ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (nhds 0) :=
have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from λ x' hx',
by { rw [sub_eq_zero.1 ((norm_eq_zero (x' - x)).1 hx')], simp },
begin
unfold has_fderiv_at_filter,
rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h],
exact tendsto.congr'r (λ _, div_eq_inv_mul),
end
theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (nhds_within x s) (nhds 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (nhds x) (nhds 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) :
has_fderiv_at_filter f f' x L₁ :=
is_o.mono hst h
theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) :
has_fderiv_within_at f f' s x :=
h.mono (nhds_within_mono _ hst)
theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ nhds x) :
has_fderiv_at_filter f f' x L :=
h.mono hL
theorem has_fderiv_at.has_fderiv_within_at
(h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x :=
h.has_fderiv_at_filter lattice.inf_le_left
lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) :
differentiable_within_at 𝕜 f s x :=
⟨f', h⟩
lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x :=
⟨f', h⟩
@[simp] lemma has_fderiv_within_at_univ :
has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x :=
by { simp only [has_fderiv_within_at, nhds_within_univ], refl }
theorem has_fderiv_at_unique
(h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' :=
begin
rw ← has_fderiv_within_at_univ at h₀ h₁,
exact unique_diff_within_at_univ.eq h₀ h₁
end
lemma has_fderiv_within_at_inter' (h : t ∈ nhds_within x s) :
has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x :=
by simp [has_fderiv_within_at, nhds_within_restrict'' s h]
lemma has_fderiv_within_at_inter (h : t ∈ nhds x) :
has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x :=
by simp [has_fderiv_within_at, nhds_within_restrict' s h]
lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at 𝕜 f s x) :
has_fderiv_within_at f (fderiv_within 𝕜 f s x) s x :=
begin
dunfold fderiv_within,
dunfold differentiable_within_at at h,
rw dif_pos h,
exact classical.some_spec h
end
lemma differentiable_at.has_fderiv_at (h : differentiable_at 𝕜 f x) :
has_fderiv_at f (fderiv 𝕜 f x) x :=
begin
dunfold fderiv,
dunfold differentiable_at at h,
rw dif_pos h,
exact classical.some_spec h
end
lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' :=
by { ext, rw has_fderiv_at_unique h h.differentiable_at.has_fderiv_at }
lemma has_fderiv_within_at.fderiv_within
(h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 f s x = f' :=
by { ext, rw hxs.eq h h.differentiable_within_at.has_fderiv_within_at }
lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) :
differentiable_within_at 𝕜 f s x :=
begin
rcases h with ⟨f', hf'⟩,
exact ⟨f', hf'.mono st⟩
end
lemma differentiable_within_at_univ :
differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x :=
begin
simp [differentiable_within_at, has_fderiv_within_at, nhds_within_univ],
refl
end
lemma differentiable_within_at_inter (ht : t ∈ nhds x) :
differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x :=
by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter,
nhds_within_restrict' s ht]
lemma differentiable_at.differentiable_within_at
(h : differentiable_at 𝕜 f x) : differentiable_within_at 𝕜 f s x :=
(differentiable_within_at_univ.2 h).mono (subset_univ _)
lemma differentiable_within_at.differentiable_at
(h : differentiable_within_at 𝕜 f s x) (hs : s ∈ nhds x) : differentiable_at 𝕜 f x :=
begin
have : s = univ ∩ s, by rw univ_inter,
rwa [this, differentiable_within_at_inter hs, differentiable_within_at_univ] at h
end
lemma differentiable.fderiv_within
(h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 f s x = fderiv 𝕜 f x :=
begin
apply has_fderiv_within_at.fderiv_within _ hxs,
exact h.has_fderiv_at.has_fderiv_within_at
end
lemma differentiable_on.mono (h : differentiable_on 𝕜 f t) (st : s ⊆ t) :
differentiable_on 𝕜 f s :=
λx hx, (h x (st hx)).mono st
lemma differentiable_on_univ :
differentiable_on 𝕜 f univ ↔ differentiable 𝕜 f :=
by { simp [differentiable_on, differentiable_within_at_univ], refl }
lemma differentiable.differentiable_on (h : differentiable 𝕜 f) : differentiable_on 𝕜 f s :=
(differentiable_on_univ.2 h).mono (subset_univ _)
lemma differentiable_on_of_locally_differentiable_on
(h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on 𝕜 f (s ∩ u)) : differentiable_on 𝕜 f s :=
begin
assume x xs,
rcases h x xs with ⟨t, t_open, xt, ht⟩,
exact (differentiable_within_at_inter (mem_nhds_sets t_open xt)).1 (ht x ⟨xs, xt⟩)
end
lemma fderiv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x)
(h : differentiable_within_at 𝕜 f t x) :
fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x :=
((differentiable_within_at.has_fderiv_within_at h).mono st).fderiv_within ht
@[simp] lemma fderiv_within_univ : fderiv_within 𝕜 f univ = fderiv 𝕜 f :=
begin
ext x : 1,
by_cases h : differentiable_at 𝕜 f x,
{ apply has_fderiv_within_at.fderiv_within _ (is_open_univ.unique_diff_within_at (mem_univ _)),
rw has_fderiv_within_at_univ,
apply h.has_fderiv_at },
{ have : fderiv 𝕜 f x = 0,
by { unfold differentiable_at at h, simp [fderiv, h] },
rw this,
have : ¬(differentiable_within_at 𝕜 f univ x), by rwa differentiable_within_at_univ,
unfold differentiable_within_at at this,
simp [fderiv_within, this, -has_fderiv_within_at_univ] }
end
lemma fderiv_within_inter (ht : t ∈ nhds x) (hs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 f (s ∩ t) x = fderiv_within 𝕜 f s x :=
begin
by_cases h : differentiable_within_at 𝕜 f (s ∩ t) x,
{ apply fderiv_within_subset (inter_subset_left _ _) _ ((differentiable_within_at_inter ht).1 h),
apply hs.inter ht },
{ have : fderiv_within 𝕜 f (s ∩ t) x = 0,
by { unfold differentiable_within_at at h, simp [fderiv_within, h] },
rw this,
rw differentiable_within_at_inter ht at h,
have : fderiv_within 𝕜 f s x = 0,
by { unfold differentiable_within_at at h, simp [fderiv_within, h] },
rw this }
end
end fderiv_properties
/- Congr -/
section congr
theorem has_fderiv_at_filter_congr_of_mem_sets
(hx : f₀ x = f₁ x) (h₀ : {x | f₀ x = f₁ x} ∈ L) (h₁ : ∀ x, f₀' x = f₁' x) :
has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L :=
by { rw (ext h₁), exact is_o_congr
(by filter_upwards [h₀] λ x (h : _ = _), by simp [h, hx])
(univ_mem_sets' $ λ _, rfl) }
lemma has_fderiv_at_filter.congr_of_mem_sets (h : has_fderiv_at_filter f f' x L)
(hL : {x | f₁ x = f x} ∈ L) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L :=
begin
apply (has_fderiv_at_filter_congr_of_mem_sets hx hL _).2 h,
exact λx, rfl
end
lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x)
(hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x :=
has_fderiv_at_filter.congr_of_mem_sets (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx
lemma has_fderiv_within_at.congr_of_mem_nhds_within (h : has_fderiv_within_at f f' s x)
(h₁ : {y | f₁ y = f y} ∈ nhds_within x s) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x :=
has_fderiv_at_filter.congr_of_mem_sets h h₁ hx
lemma has_fderiv_at.congr_of_mem_nhds (h : has_fderiv_at f f' x)
(h₁ : {y | f₁ y = f y} ∈ nhds x) : has_fderiv_at f₁ f' x :=
has_fderiv_at_filter.congr_of_mem_sets h h₁ (mem_of_nhds h₁ : _)
lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x)
(ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x :=
(has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at
lemma differentiable_within_at.congr_of_mem_nhds_within
(h : differentiable_within_at 𝕜 f s x) (h₁ : {y | f₁ y = f y} ∈ nhds_within x s)
(hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x :=
(h.has_fderiv_within_at.congr_of_mem_nhds_within h₁ hx).differentiable_within_at
lemma differentiable_on.congr_mono (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ t, f₁ x = f x)
(h₁ : t ⊆ s) : differentiable_on 𝕜 f₁ t :=
λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁
lemma differentiable_at.congr_of_mem_nhds (h : differentiable_at 𝕜 f x)
(hL : {y | f₁ y = f y} ∈ nhds x) : differentiable_at 𝕜 f₁ x :=
has_fderiv_at.differentiable_at (has_fderiv_at_filter.congr_of_mem_sets h.has_fderiv_at hL (mem_of_nhds hL : _))
lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x)
(hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) :
fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x :=
(has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt
lemma fderiv_within_congr_of_mem_nhds_within (hs : unique_diff_within_at 𝕜 s x)
(hL : {y | f₁ y = f y} ∈ nhds_within x s) (hx : f₁ x = f x) :
fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x :=
begin
by_cases h : differentiable_within_at 𝕜 f s x ∨ differentiable_within_at 𝕜 f₁ s x,
{ cases h,
{ apply has_fderiv_within_at.fderiv_within _ hs,
exact has_fderiv_at_filter.congr_of_mem_sets h.has_fderiv_within_at hL hx },
{ symmetry,
apply has_fderiv_within_at.fderiv_within _ hs,
apply has_fderiv_at_filter.congr_of_mem_sets h.has_fderiv_within_at _ hx.symm,
convert hL,
ext y,
exact eq_comm } },
{ push_neg at h,
have A : fderiv_within 𝕜 f s x = 0,
by { unfold differentiable_within_at at h, simp [fderiv_within, h] },
have A₁ : fderiv_within 𝕜 f₁ s x = 0,
by { unfold differentiable_within_at at h, simp [fderiv_within, h] },
rw [A, A₁] }
end
lemma fderiv_within_congr (hs : unique_diff_within_at 𝕜 s x)
(hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) :
fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x :=
begin
apply fderiv_within_congr_of_mem_nhds_within hs _ hx,
apply mem_sets_of_superset self_mem_nhds_within,
exact hL
end
lemma fderiv_congr_of_mem_nhds (hL : {y | f₁ y = f y} ∈ nhds x) :
fderiv 𝕜 f₁ x = fderiv 𝕜 f x :=
begin
have A : f₁ x = f x := (mem_of_nhds hL : _),
rw [← fderiv_within_univ, ← fderiv_within_univ],
rw ← nhds_within_univ at hL,
exact fderiv_within_congr_of_mem_nhds_within unique_diff_within_at_univ hL A
end
end congr
/- id -/
section id
theorem has_fderiv_at_filter_id (x : E) (L : filter E) :
has_fderiv_at_filter id (id : E →L[𝕜] E) x L :=
(is_o_zero _ _).congr_left $ by simp
theorem has_fderiv_within_at_id (x : E) (s : set E) :
has_fderiv_within_at id (id : E →L[𝕜] E) s x :=
has_fderiv_at_filter_id _ _
theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id : E →L[𝕜] E) x :=
has_fderiv_at_filter_id _ _
lemma differentiable_at_id : differentiable_at 𝕜 id x :=
(has_fderiv_at_id x).differentiable_at
lemma differentiable_within_at_id : differentiable_within_at 𝕜 id s x :=
differentiable_at_id.differentiable_within_at
lemma differentiable_id : differentiable 𝕜 (id : E → E) :=
λx, differentiable_at_id
lemma differentiable_on_id : differentiable_on 𝕜 id s :=
differentiable_id.differentiable_on
lemma fderiv_id : fderiv 𝕜 id x = id :=
has_fderiv_at.fderiv (has_fderiv_at_id x)
lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 id s x = id :=
begin
rw differentiable.fderiv_within (differentiable_at_id) hxs,
exact fderiv_id
end
end id
/- constants -/
section const
theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) :
has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] F) x L :=
(is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self]
theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) :
has_fderiv_within_at (λ x, c) (0 : E →L[𝕜] F) s x :=
has_fderiv_at_filter_const _ _ _
theorem has_fderiv_at_const (c : F) (x : E) :
has_fderiv_at (λ x, c) (0 : E →L[𝕜] F) x :=
has_fderiv_at_filter_const _ _ _
lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x :=
⟨0, has_fderiv_at_const c x⟩
lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x :=
differentiable_at.differentiable_within_at (differentiable_at_const _)
lemma fderiv_const (c : F) : fderiv 𝕜 (λy, c) x = 0 :=
has_fderiv_at.fderiv (has_fderiv_at_const c x)
lemma fderiv_within_const (c : F) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λy, c) s x = 0 :=
begin
rw differentiable.fderiv_within (differentiable_at_const _) hxs,
exact fderiv_const _
end
lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) :=
λx, differentiable_at_const _
lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s :=
(differentiable_const _).differentiable_on
end const
/- Bounded linear maps -/
section is_bounded_linear_map
lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map 𝕜 f) :
has_fderiv_at_filter f h.to_continuous_linear_map x L :=
begin
have : (λ (x' : E), f x' - f x - h.to_continuous_linear_map (x' - x)) = λx', 0,
{ ext,
have : ∀a, h.to_continuous_linear_map a = f a := λa, rfl,
simp,
simp [this] },
rw [has_fderiv_at_filter, this],
exact asymptotics.is_o_zero _ _
end
lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map 𝕜 f) :
has_fderiv_within_at f h.to_continuous_linear_map s x :=
h.has_fderiv_at_filter
lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map 𝕜 f) :
has_fderiv_at f h.to_continuous_linear_map x :=
h.has_fderiv_at_filter
lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map 𝕜 f) :
differentiable_at 𝕜 f x :=
h.has_fderiv_at.differentiable_at
lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map 𝕜 f) :
differentiable_within_at 𝕜 f s x :=
h.differentiable_at.differentiable_within_at
lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map 𝕜 f) :
fderiv 𝕜 f x = h.to_continuous_linear_map :=
has_fderiv_at.fderiv (h.has_fderiv_at)
lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map 𝕜 f)
(hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = h.to_continuous_linear_map :=
begin
rw differentiable.fderiv_within h.differentiable_at hxs,
exact h.fderiv
end
lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map 𝕜 f) :
differentiable 𝕜 f :=
λx, h.differentiable_at
lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map 𝕜 f) :
differentiable_on 𝕜 f s :=
h.differentiable.differentiable_on
end is_bounded_linear_map
/- multiplication by a constant -/
section smul_const
theorem has_fderiv_at_filter.smul (h : has_fderiv_at_filter f f' x L) (c : 𝕜) :
has_fderiv_at_filter (λ x, c • f x) (c • f') x L :=
(is_o_const_smul_left h c).congr_left $ λ x, by simp [smul_neg, smul_add]
theorem has_fderiv_within_at.smul (h : has_fderiv_within_at f f' s x) (c : 𝕜) :
has_fderiv_within_at (λ x, c • f x) (c • f') s x :=
h.smul c
theorem has_fderiv_at.smul (h : has_fderiv_at f f' x) (c : 𝕜) :
has_fderiv_at (λ x, c • f x) (c • f') x :=
h.smul c
lemma differentiable_within_at.smul (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) :
differentiable_within_at 𝕜 (λy, c • f y) s x :=
(h.has_fderiv_within_at.smul c).differentiable_within_at
lemma differentiable_at.smul (h : differentiable_at 𝕜 f x) (c : 𝕜) :
differentiable_at 𝕜 (λy, c • f y) x :=
(h.has_fderiv_at.smul c).differentiable_at
lemma differentiable_on.smul (h : differentiable_on 𝕜 f s) (c : 𝕜) :
differentiable_on 𝕜 (λy, c • f y) s :=
λx hx, (h x hx).smul c
lemma differentiable.smul (h : differentiable 𝕜 f) (c : 𝕜) :
differentiable 𝕜 (λy, c • f y) :=
λx, (h x).smul c
lemma fderiv_within_smul (hxs : unique_diff_within_at 𝕜 s x)
(h : differentiable_within_at 𝕜 f s x) (c : 𝕜) :
fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x :=
(h.has_fderiv_within_at.smul c).fderiv_within hxs
lemma fderiv_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) :
fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x :=
(h.has_fderiv_at.smul c).fderiv
end smul_const
/- add -/
section add
theorem has_fderiv_at_filter.add
(hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) :
has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L :=
(hf.add hg).congr_left $ λ _, by simp
theorem has_fderiv_within_at.add
(hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) :
has_fderiv_within_at (λ y, f y + g y) (f' + g') s x :=
hf.add hg
theorem has_fderiv_at.add
(hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) :
has_fderiv_at (λ x, f x + g x) (f' + g') x :=
hf.add hg
lemma differentiable_within_at.add
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
differentiable_within_at 𝕜 (λ y, f y + g y) s x :=
(hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at
lemma differentiable_at.add
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
differentiable_at 𝕜 (λ y, f y + g y) x :=
(hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at
lemma differentiable_on.add
(hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) :
differentiable_on 𝕜 (λy, f y + g y) s :=
λx hx, (hf x hx).add (hg x hx)
lemma differentiable.add
(hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) :
differentiable 𝕜 (λy, f y + g y) :=
λx, (hf x).add (hg x)
lemma fderiv_within_add (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
fderiv_within 𝕜 (λy, f y + g y) s x = fderiv_within 𝕜 f s x + fderiv_within 𝕜 g s x :=
(hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_add
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
fderiv 𝕜 (λy, f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x :=
(hf.has_fderiv_at.add hg.has_fderiv_at).fderiv
end add
/- neg -/
section neg
theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) :
has_fderiv_at_filter (λ x, -f x) (-f') x L :=
(h.smul (-1:𝕜)).congr (by simp) (by simp)
theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, -f x) (-f') s x :=
h.neg
theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) :
has_fderiv_at (λ x, -f x) (-f') x :=
h.neg
lemma differentiable_within_at.neg (h : differentiable_within_at 𝕜 f s x) :
differentiable_within_at 𝕜 (λy, -f y) s x :=
h.has_fderiv_within_at.neg.differentiable_within_at
lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) :
differentiable_at 𝕜 (λy, -f y) x :=
h.has_fderiv_at.neg.differentiable_at
lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) :
differentiable_on 𝕜 (λy, -f y) s :=
λx hx, (h x hx).neg
lemma differentiable.neg (h : differentiable 𝕜 f) :
differentiable 𝕜 (λy, -f y) :=
λx, (h x).neg
lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x)
(h : differentiable_within_at 𝕜 f s x) :
fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x :=
h.has_fderiv_within_at.neg.fderiv_within hxs
lemma fderiv_neg (h : differentiable_at 𝕜 f x) :
fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x :=
h.has_fderiv_at.neg.fderiv
end neg
/- sub -/
section sub
theorem has_fderiv_at_filter.sub
(hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) :
has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L :=
hf.add hg.neg
theorem has_fderiv_within_at.sub
(hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) :
has_fderiv_within_at (λ x, f x - g x) (f' - g') s x :=
hf.sub hg
theorem has_fderiv_at.sub
(hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) :
has_fderiv_at (λ x, f x - g x) (f' - g') x :=
hf.sub hg
lemma differentiable_within_at.sub
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
differentiable_within_at 𝕜 (λ y, f y - g y) s x :=
(hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at
lemma differentiable_at.sub
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
differentiable_at 𝕜 (λ y, f y - g y) x :=
(hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at
lemma differentiable_on.sub
(hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) :
differentiable_on 𝕜 (λy, f y - g y) s :=
λx hx, (hf x hx).sub (hg x hx)
lemma differentiable.sub
(hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) :
differentiable 𝕜 (λy, f y - g y) :=
λx, (hf x).sub (hg x)
lemma fderiv_within_sub (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
fderiv_within 𝕜 (λy, f y - g y) s x = fderiv_within 𝕜 f s x - fderiv_within 𝕜 g s x :=
(hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_sub
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
fderiv 𝕜 (λy, f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x :=
(hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv
theorem has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) :
is_O (λ x', f x' - f x) (λ x', x' - x) L :=
h.to_is_O.congr_of_sub.2 (f'.is_O_sub _ _)
end sub
/- Continuity -/
section continuous
theorem has_fderiv_at_filter.tendsto_nhds
(hL : L ≤ nhds x) (h : has_fderiv_at_filter f f' x L) :
tendsto f L (nhds (f x)) :=
begin
have : tendsto (λ x', f x' - f x) L (nhds 0),
{ refine h.is_O_sub.trans_tendsto (tendsto_le_left hL _),
rw ← sub_self x, exact tendsto_sub tendsto_id tendsto_const_nhds },
have := tendsto_add this tendsto_const_nhds,
rw zero_add (f x) at this,
exact this.congr (by simp)
end
theorem has_fderiv_within_at.continuous_within_at
(h : has_fderiv_within_at f f' s x) : continuous_within_at f s x :=
has_fderiv_at_filter.tendsto_nhds lattice.inf_le_left h
theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) :
continuous_at f x :=
has_fderiv_at_filter.tendsto_nhds (le_refl _) h
lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at 𝕜 f s x) :
continuous_within_at f s x :=
let ⟨f', hf'⟩ := h in hf'.continuous_within_at
lemma differentiable_at.continuous_at (h : differentiable_at 𝕜 f x) : continuous_at f x :=
let ⟨f', hf'⟩ := h in hf'.continuous_at
lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s :=
λx hx, (h x hx).continuous_within_at
lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f :=
continuous_iff_continuous_at.2 $ λx, (h x).continuous_at
end continuous
/- Bounded bilinear maps -/
section bilinear_map
variables {b : E × F → G} {u : set (E × F) }
lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) :
has_fderiv_at b (h.deriv p) p :=
begin
have : (λ (x : E × F), b x - b p - (h.deriv p) (x - p)) = (λx, b (x.1 - p.1, x.2 - p.2)),
{ ext x,
delta is_bounded_bilinear_map.deriv,
change b x - b p - (b (p.1, x.2-p.2) + b (x.1-p.1, p.2))
= b (x.1 - p.1, x.2 - p.2),
have : b x = b (x.1, x.2), by { cases x, refl },
rw this,
have : b p = b (p.1, p.2), by { cases p, refl },
rw this,
simp only [h.map_sub_left, h.map_sub_right],
abel },
rw [has_fderiv_at, has_fderiv_at_filter, this],
rcases h.bound with ⟨C, Cpos, hC⟩,
have A : asymptotics.is_O (λx : E × F, b (x.1 - p.1, x.2 - p.2))
(λx, ∥x - p∥ * ∥x - p∥) (nhds p) :=
⟨C, Cpos, filter.univ_mem_sets' (λx, begin
simp only [mem_set_of_eq, norm_mul, norm_norm],
calc ∥b (x.1 - p.1, x.2 - p.2)∥ ≤ C * ∥x.1 - p.1∥ * ∥x.2 - p.2∥ : hC _ _
... ≤ C * ∥x-p∥ * ∥x-p∥ : by apply_rules [mul_le_mul, le_max_left, le_max_right, norm_nonneg,
le_of_lt Cpos, le_refl, mul_nonneg, norm_nonneg, norm_nonneg]
... = C * (∥x-p∥ * ∥x-p∥) : mul_assoc _ _ _ end)⟩,
have B : asymptotics.is_o (λ (x : E × F), ∥x - p∥ * ∥x - p∥)
(λx, 1 * ∥x - p∥) (nhds p),
{ apply asymptotics.is_o_mul_right _ (asymptotics.is_O_refl _ _),
rw [asymptotics.is_o_iff_tendsto],
{ simp only [div_one],
have : 0 = ∥p - p∥, by simp,
rw this,
have : continuous (λx, ∥x-p∥) :=
continuous_norm.comp (continuous_sub continuous_id continuous_const),
exact this.tendsto p },
simp only [forall_prop_of_false, not_false_iff, one_ne_zero, forall_true_iff] },
simp only [one_mul, asymptotics.is_o_norm_right] at B,
exact A.trans_is_o B
end
lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) :
has_fderiv_within_at b (h.deriv p) u p :=
(h.has_fderiv_at p).has_fderiv_within_at
lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) :
differentiable_at 𝕜 b p :=
(h.has_fderiv_at p).differentiable_at
lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) :
differentiable_within_at 𝕜 b u p :=
(h.differentiable_at p).differentiable_within_at
lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) :
fderiv 𝕜 b p = h.deriv p :=
has_fderiv_at.fderiv (h.has_fderiv_at p)
lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map 𝕜 b) (p : E × F)
(hxs : unique_diff_within_at 𝕜 u p) : fderiv_within 𝕜 b u p = h.deriv p :=
begin
rw differentiable.fderiv_within (h.differentiable_at p) hxs,
exact h.fderiv p
end
lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map 𝕜 b) :
differentiable 𝕜 b :=
λx, h.differentiable_at x
lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map 𝕜 b) :
differentiable_on 𝕜 b u :=
h.differentiable.differentiable_on
lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map 𝕜 b) :
continuous b :=
h.differentiable.continuous
end bilinear_map
/- Cartesian products -/
section cartesian_product
variables {f₂ : E → G} {f₂' : E →L[𝕜] G}
lemma has_fderiv_at_filter.prod
(hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) :
has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x L :=
begin
have : (λ (x' : E), (f₁ x', f₂ x') - (f₁ x, f₂ x) - (continuous_linear_map.prod f₁' f₂') (x' -x)) =
(λ (x' : E), (f₁ x' - f₁ x - f₁' (x' - x), f₂ x' - f₂ x - f₂' (x' - x))) := rfl,
rw [has_fderiv_at_filter, this],
rw [asymptotics.is_o_prod_left],
exact ⟨hf₁, hf₂⟩
end
lemma has_fderiv_within_at.prod
(hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) :
has_fderiv_within_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') s x :=
hf₁.prod hf₂
lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) :
has_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x :=
hf₁.prod hf₂
lemma differentiable_within_at.prod
(hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) :
differentiable_within_at 𝕜 (λx:E, (f₁ x, f₂ x)) s x :=
(hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at
lemma differentiable_at.prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) :
differentiable_at 𝕜 (λx:E, (f₁ x, f₂ x)) x :=
(hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at
lemma differentiable_on.prod (hf₁ : differentiable_on 𝕜 f₁ s) (hf₂ : differentiable_on 𝕜 f₂ s) :
differentiable_on 𝕜 (λx:E, (f₁ x, f₂ x)) s :=
λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx)
lemma differentiable.prod (hf₁ : differentiable 𝕜 f₁) (hf₂ : differentiable 𝕜 f₂) :
differentiable 𝕜 (λx:E, (f₁ x, f₂ x)) :=
λ x, differentiable_at.prod (hf₁ x) (hf₂ x)
lemma differentiable_at.fderiv_prod
(hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) :
fderiv 𝕜 (λx:E, (f₁ x, f₂ x)) x =
continuous_linear_map.prod (fderiv 𝕜 f₁ x) (fderiv 𝕜 f₂ x) :=
has_fderiv_at.fderiv (has_fderiv_at.prod hf₁.has_fderiv_at hf₂.has_fderiv_at)
lemma differentiable_at.fderiv_within_prod
(hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x)
(hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λx:E, (f₁ x, f₂ x)) s x =
continuous_linear_map.prod (fderiv_within 𝕜 f₁ s x) (fderiv_within 𝕜 f₂ s x) :=
begin
apply has_fderiv_within_at.fderiv_within _ hxs,
exact has_fderiv_within_at.prod hf₁.has_fderiv_within_at hf₂.has_fderiv_within_at
end
end cartesian_product
/- Composition -/
section composition
/- For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to
get confused since there are too many possibilities for composition -/
variable (x)
theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[𝕜] G}
(hg : has_fderiv_at_filter g g' (f x) (L.map f))
(hf : has_fderiv_at_filter f f' x L) :
has_fderiv_at_filter (g ∘ f) (g'.comp f') x L :=
let eq₁ := (g'.is_O_comp _ _).trans_is_o hf in
let eq₂ := ((hg.comp f).mono le_comap_map).trans_is_O hf.is_O_sub in
by { refine eq₂.tri (eq₁.congr_left (λ x', _)), simp }
/- A readable version of the previous theorem,
a general form of the chain rule. -/
example {g : F → G} {g' : F →L[𝕜] G}
(hg : has_fderiv_at_filter g g' (f x) (L.map f))
(hf : has_fderiv_at_filter f f' x L) :
has_fderiv_at_filter (g ∘ f) (g'.comp f') x L :=
begin
unfold has_fderiv_at_filter at hg,
have : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', f x' - f x) L,
from (hg.comp f).mono le_comap_map,
have eq₁ : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', x' - x) L,
from this.trans_is_O hf.is_O_sub,
have eq₂ : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L,
from hf,
have : is_O
(λ x', g' (f x' - f x - f' (x' - x))) (λ x', f x' - f x - f' (x' - x)) L,
from g'.is_O_comp _ _,
have : is_o (λ x', g' (f x' - f x - f' (x' - x))) (λ x', x' - x) L,
from this.trans_is_o eq₂,
have eq₃ : is_o (λ x', g' (f x' - f x) - (g' (f' (x' - x)))) (λ x', x' - x) L,
by { refine this.congr_left _, simp},
exact eq₁.tri eq₃
end
theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[𝕜] G}
(hg : has_fderiv_within_at g g' (f '' s) (f x))
(hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (g ∘ f) (g'.comp f') s x :=
(has_fderiv_at_filter.mono hg
hf.continuous_within_at.tendsto_nhds_within_image).comp x hf
/-- The chain rule. -/
theorem has_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G}
(hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) :
has_fderiv_at (g ∘ f) (g'.comp f') x :=
(hg.mono hf.continuous_at).comp x hf
theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[𝕜] G}
(hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (g ∘ f) (g'.comp f') s x :=
begin
rw ← has_fderiv_within_at_univ at hg,
exact has_fderiv_within_at.comp x (hg.mono (subset_univ _)) hf
end
lemma differentiable_within_at.comp {g : F → G} {t : set F}
(hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x)
(h : f '' s ⊆ t) : differentiable_within_at 𝕜 (g ∘ f) s x :=
begin
rcases hf with ⟨f', hf'⟩,
rcases hg with ⟨g', hg'⟩,
exact ⟨continuous_linear_map.comp g' f', (hg'.mono h).comp x hf'⟩
end
lemma differentiable_at.comp {g : F → G}
(hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) :
differentiable_at 𝕜 (g ∘ f) x :=
(hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at
lemma fderiv_within.comp {g : F → G} {t : set F}
(hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x)
(h : f '' s ⊆ t) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (g ∘ f) s x =
continuous_linear_map.comp (fderiv_within 𝕜 g t (f x)) (fderiv_within 𝕜 f s x) :=
begin
apply has_fderiv_within_at.fderiv_within _ hxs,
apply has_fderiv_within_at.comp x _ (hf.has_fderiv_within_at),
apply hg.has_fderiv_within_at.mono h
end
lemma fderiv.comp {g : F → G}
(hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) :
fderiv 𝕜 (g ∘ f) x = continuous_linear_map.comp (fderiv 𝕜 g (f x)) (fderiv 𝕜 f x) :=
begin
apply has_fderiv_at.fderiv,
exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at
end
lemma differentiable_on.comp {g : F → G} {t : set F}
(hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : f '' s ⊆ t) :
differentiable_on 𝕜 (g ∘ f) s :=
λx hx, differentiable_within_at.comp x (hg (f x) (st (mem_image_of_mem _ hx))) (hf x hx) st
lemma differentiable.comp {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable 𝕜 f) :
differentiable 𝕜 (g ∘ f) :=
λx, differentiable_at.comp x (hg (f x)) (hf x)
end composition
/- Multiplication by a scalar function -/
section smul
variables {c : E → 𝕜} {c' : E →L[𝕜] 𝕜}
theorem has_fderiv_within_at.smul'
(hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.scalar_prod_space_iso (f x)) s x :=
begin
have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × F), p.1 • p.2) := is_bounded_bilinear_map_smul,
exact has_fderiv_at.comp_has_fderiv_within_at x (this.has_fderiv_at (c x, f x)) (hc.prod hf)
end
theorem has_fderiv_at.smul' (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ y, c y • f y) (c x • f' + c'.scalar_prod_space_iso (f x)) x :=
begin
have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × F), p.1 • p.2) := is_bounded_bilinear_map_smul,
exact has_fderiv_at.comp x (this.has_fderiv_at (c x, f x)) (hc.prod hf)
end
lemma differentiable_within_at.smul'
(hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) :
differentiable_within_at 𝕜 (λ y, c y • f y) s x :=
(hc.has_fderiv_within_at.smul' hf.has_fderiv_within_at).differentiable_within_at
lemma differentiable_at.smul' (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) :
differentiable_at 𝕜 (λ y, c y • f y) x :=
(hc.has_fderiv_at.smul' hf.has_fderiv_at).differentiable_at
lemma differentiable_on.smul' (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) :
differentiable_on 𝕜 (λ y, c y • f y) s :=
λx hx, (hc x hx).smul' (hf x hx)
lemma differentiable.smul' (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) :
differentiable 𝕜 (λ y, c y • f y) :=
λx, (hc x).smul' (hf x)
lemma fderiv_within_smul' (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) :
fderiv_within 𝕜 (λ y, c y • f y) s x =
c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).scalar_prod_space_iso (f x) :=
(hc.has_fderiv_within_at.smul' hf.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_smul' (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) :
fderiv 𝕜 (λ y, c y • f y) x =
c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).scalar_prod_space_iso (f x) :=
(hc.has_fderiv_at.smul' hf.has_fderiv_at).fderiv
end smul
/- Multiplication of scalar functions -/
section mul
set_option class.instance_max_depth 120
variables {c d : E → 𝕜} {c' d' : E →L[𝕜] 𝕜}
theorem has_fderiv_within_at.mul
(hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) :
has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x :=
begin
have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × 𝕜), p.1 * p.2) := is_bounded_bilinear_map_mul,
convert has_fderiv_at.comp_has_fderiv_within_at x (this.has_fderiv_at (c x, d x)) (hc.prod hd),
ext z,
change c x * d' z + d x * c' z = c x * d' z + c' z * d x,
ring
end
theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) :
has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x :=
begin
have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × 𝕜), p.1 * p.2) := is_bounded_bilinear_map_mul,
convert has_fderiv_at.comp x (this.has_fderiv_at (c x, d x)) (hc.prod hd),
ext z,
change c x * d' z + d x * c' z = c x * d' z + c' z * d x,
ring
end
lemma differentiable_within_at.mul
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) :
differentiable_within_at 𝕜 (λ y, c y * d y) s x :=
(hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).differentiable_within_at
lemma differentiable_at.mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) :
differentiable_at 𝕜 (λ y, c y * d y) x :=
(hc.has_fderiv_at.mul hd.has_fderiv_at).differentiable_at
lemma differentiable_on.mul (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) :
differentiable_on 𝕜 (λ y, c y * d y) s :=
λx hx, (hc x hx).mul (hd x hx)
lemma differentiable.mul (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) :
differentiable 𝕜 (λ y, c y * d y) :=
λx, (hc x).mul (hd x)
lemma fderiv_within_mul (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) :
fderiv_within 𝕜 (λ y, c y * d y) s x =
c x • fderiv_within 𝕜 d s x + d x • fderiv_within 𝕜 c s x :=
(hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) :
fderiv 𝕜 (λ y, c y * d y) x =
c x • fderiv 𝕜 d x + d x • fderiv 𝕜 c x :=
(hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv
end mul
end
/-
In the special case of a normed space over the reals,
we can use scalar multiplication in the `tendsto` characterization
of the Fréchet derivative.
-/
section
variables {E : Type*} [normed_group E] [normed_space ℝ E]
variables {F : Type*} [normed_group F] [normed_space ℝ F]
variables {G : Type*} [normed_group G] [normed_space ℝ G]
theorem has_fderiv_at_filter_real_equiv {f : E → F} {f' : E →L[ℝ] F} {x : E} {L : filter E} :
tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (nhds 0) ↔
tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (nhds 0) :=
begin
symmetry,
rw [tendsto_iff_norm_tendsto_zero], refine tendsto.congr'r (λ x', _),
have : ∥x' + -x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _),
simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this]
end
end
|
a03822421e1a1ee5718472ac6cd55c6e2a51b776 | 33340b3a23ca62ef3c8a7f6a2d4e14c07c6d3354 | /dlo/remove_neg.lean | ea7f91484a4bc6f7177255e23c60af824e6e72ea | [] | no_license | lclem/cooper | 79554e72ced343c64fed24b2d892d24bf9447dfe | 812afc6b158821f2e7dac9c91d3b6123c7a19faf | refs/heads/master | 1,607,554,257,488 | 1,578,694,133,000 | 1,578,694,133,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,471 | lean | import .formula
open list
def remove_neg : atom_dlo → formula_dlo
| (t <' s) := (A' (t =' s) ∨' A' (s <' t))
| (t =' s) := (A' (t <' s) ∨' A' (s <' t))
lemma eval_remove_neg :
∀ (a : atom_dlo) (xs : list rat),
(remove_neg a).eval xs ↔ (¬ (a.eval xs))
| (t <' s) xs :=
begin
simp [formula_dlo.eval, atom_dlo.eval, remove_neg,
le_iff_lt_or_eq, or.comm, eq.symm']
end
| (t =' s) xs :=
begin
simp [formula_dlo.eval, atom_dlo.eval, remove_neg, le_antisymm_iff],
rw [imp_iff_not_or, not_le, or.comm],
end
#exit
simp only [remove_neg, atom_dlo.eval],
apply calc
(1 - i ≤ znum.dot_prod (map_neg ks) xs)
↔ (-(znum.dot_prod (map_neg ks) xs) ≤ -(1 - i)) :
begin apply iff.intro, apply (@neg_le_neg znum _), apply (@le_of_neg_le_neg znum _) end
... ↔ (znum.dot_prod ks xs ≤ -(1 - i)) :
begin rw [znum.map_neg_dot_prod], simp, end
... ↔ (znum.dot_prod ks xs ≤ i - 1) :
by rewrite neg_sub
... ↔ (znum.dot_prod ks xs < i) :
begin
apply iff.intro,
apply znum.lt_of_le_sub_one,
apply znum.le_sub_one_of_lt
end
... ↔ ¬i ≤ znum.dot_prod ks xs :
begin
apply iff.intro,
apply not_le_of_gt,
apply lt_of_not_ge
end
end
| (atom_dlo.dvd d i ks) xs := by refl
| (atom_dlo.ndvd d i ks) xs := by apply not_not_iff.symm
|
f5cd49833b521a2eb0bc55766eab151e1afcbb03 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/measure_theory/function/convergence_in_measure.lean | 0fcdd9622af264df2d9f41552ac3ebb7c3a2b055 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 16,856 | lean | /-
Copyright (c) 2022 Rémy Degenne, Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémy Degenne, Kexing Ying
-/
import measure_theory.function.egorov
/-!
# Convergence in measure
We define convergence in measure which is one of the many notions of convergence in probability.
A sequence of functions `f` is said to converge in measure to some function `g`
if for all `ε > 0`, the measure of the set `{x | ε ≤ dist (f i x) (g x)}` tends to 0 as `i`
converges along some given filter `l`.
Convergence in measure is most notably used in the formulation of the weak law of large numbers
and is also useful in theorems such as the Vitali convergence theorem. This file provides some
basic lemmas for working with convergence in measure and establishes some relations between
convergence in measure and other notions of convergence.
## Main definitions
* `measure_theory.tendsto_in_measure (μ : measure α) (f : ι → α → E) (g : α → E)`: `f` converges
in `μ`-measure to `g`.
## Main results
* `measure_theory.tendsto_in_measure_of_tendsto_ae`: convergence almost everywhere in a finite
measure space implies convergence in measure.
* `measure_theory.tendsto_in_measure.exists_seq_tendsto_ae`: if `f` is a sequence of functions
which converges in measure to `g`, then `f` has a subsequence which convergence almost
everywhere to `g`.
* `measure_theory.tendsto_in_measure_of_tendsto_snorm`: convergence in Lp implies convergence
in measure.
-/
open topological_space filter
open_locale nnreal ennreal measure_theory topological_space
namespace measure_theory
variables {α ι E : Type*} {m : measurable_space α} {μ : measure α}
/-- A sequence of functions `f` is said to converge in measure to some function `g` if for all
`ε > 0`, the measure of the set `{x | ε ≤ dist (f i x) (g x)}` tends to 0 as `i` converges along
some given filter `l`. -/
def tendsto_in_measure [has_dist E] {m : measurable_space α}
(μ : measure α) (f : ι → α → E) (l : filter ι) (g : α → E) : Prop :=
∀ ε (hε : 0 < ε), tendsto (λ i, μ {x | ε ≤ dist (f i x) (g x)}) l (𝓝 0)
lemma tendsto_in_measure_iff_norm [semi_normed_group E] {l : filter ι}
{f : ι → α → E} {g : α → E} :
tendsto_in_measure μ f l g
↔ ∀ ε (hε : 0 < ε), tendsto (λ i, μ {x | ε ≤ ∥f i x - g x∥}) l (𝓝 0) :=
by simp_rw [tendsto_in_measure, dist_eq_norm]
namespace tendsto_in_measure
variables [has_dist E] {l : filter ι} {f f' : ι → α → E} {g g' : α → E}
protected lemma congr' (h_left : ∀ᶠ i in l, f i =ᵐ[μ] f' i) (h_right : g =ᵐ[μ] g')
(h_tendsto : tendsto_in_measure μ f l g) :
tendsto_in_measure μ f' l g' :=
begin
intros ε hε,
suffices : (λ i, μ {x | ε ≤ dist (f' i x) (g' x)})
=ᶠ[l] (λ i, μ {x | ε ≤ dist (f i x) (g x)}),
{ rw tendsto_congr' this,
exact h_tendsto ε hε, },
filter_upwards [h_left] with i h_ae_eq,
refine measure_congr _,
filter_upwards [h_ae_eq, h_right] with x hxf hxg,
rw eq_iff_iff,
change ε ≤ dist (f' i x) (g' x) ↔ ε ≤ dist (f i x) (g x),
rw [hxg, hxf],
end
protected lemma congr (h_left : ∀ i, f i =ᵐ[μ] f' i) (h_right : g =ᵐ[μ] g')
(h_tendsto : tendsto_in_measure μ f l g) :
tendsto_in_measure μ f' l g' :=
tendsto_in_measure.congr' (eventually_of_forall h_left) h_right h_tendsto
lemma congr_left (h : ∀ i, f i =ᵐ[μ] f' i) (h_tendsto : tendsto_in_measure μ f l g) :
tendsto_in_measure μ f' l g :=
h_tendsto.congr h (eventually_eq.rfl)
lemma congr_right (h : g =ᵐ[μ] g') (h_tendsto : tendsto_in_measure μ f l g) :
tendsto_in_measure μ f l g' :=
h_tendsto.congr (λ i, eventually_eq.rfl) h
end tendsto_in_measure
section exists_seq_tendsto_ae
variables [metric_space E]
variables {f : ℕ → α → E} {g : α → E}
/-- Auxiliary lemma for `tendsto_in_measure_of_tendsto_ae`. -/
lemma tendsto_in_measure_of_tendsto_ae_of_strongly_measurable [is_finite_measure μ]
(hf : ∀ n, strongly_measurable (f n)) (hg : strongly_measurable g)
(hfg : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x))) :
tendsto_in_measure μ f at_top g :=
begin
refine λ ε hε, ennreal.tendsto_at_top_zero.mpr (λ δ hδ, _),
by_cases hδi : δ = ∞,
{ simp only [hδi, implies_true_iff, le_top, exists_const], },
lift δ to ℝ≥0 using hδi,
rw [gt_iff_lt, ennreal.coe_pos, ← nnreal.coe_pos] at hδ,
obtain ⟨t, htm, ht, hunif⟩ := tendsto_uniformly_on_of_ae_tendsto' hf hg hfg hδ,
rw ennreal.of_real_coe_nnreal at ht,
rw metric.tendsto_uniformly_on_iff at hunif,
obtain ⟨N, hN⟩ := eventually_at_top.1 (hunif ε hε),
refine ⟨N, λ n hn, _⟩,
suffices : {x : α | ε ≤ dist (f n x) (g x)} ⊆ t, from (measure_mono this).trans ht,
rw ← set.compl_subset_compl,
intros x hx,
rw [set.mem_compl_eq, set.nmem_set_of_eq, dist_comm, not_le],
exact hN n hn x hx,
end
/-- Convergence a.e. implies convergence in measure in a finite measure space. -/
lemma tendsto_in_measure_of_tendsto_ae [is_finite_measure μ]
(hf : ∀ n, ae_strongly_measurable (f n) μ)
(hfg : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x))) :
tendsto_in_measure μ f at_top g :=
begin
have hg : ae_strongly_measurable g μ, from ae_strongly_measurable_of_tendsto_ae _ hf hfg,
refine tendsto_in_measure.congr (λ i, (hf i).ae_eq_mk.symm) hg.ae_eq_mk.symm _,
refine tendsto_in_measure_of_tendsto_ae_of_strongly_measurable
(λ i, (hf i).strongly_measurable_mk) hg.strongly_measurable_mk _,
have hf_eq_ae : ∀ᵐ x ∂μ, ∀ n, (hf n).mk (f n) x = f n x,
from ae_all_iff.mpr (λ n, (hf n).ae_eq_mk.symm),
filter_upwards [hf_eq_ae, hg.ae_eq_mk, hfg] with x hxf hxg hxfg,
rw [← hxg, funext (λ n, hxf n)],
exact hxfg,
end
namespace exists_seq_tendsto_ae
lemma exists_nat_measure_lt_two_inv (hfg : tendsto_in_measure μ f at_top g) (n : ℕ) :
∃ N, ∀ m ≥ N, μ {x | 2⁻¹ ^ n ≤ dist (f m x) (g x)} ≤ 2⁻¹ ^ n :=
begin
specialize hfg (2⁻¹ ^ n) (by simp only [zero_lt_bit0, pow_pos, zero_lt_one, inv_pos]),
rw ennreal.tendsto_at_top_zero at hfg,
exact hfg (2⁻¹ ^ n) (pos_iff_ne_zero.mpr (λ h_zero, by simpa using pow_eq_zero h_zero))
end
/-- Given a sequence of functions `f` which converges in measure to `g`,
`seq_tendsto_ae_seq_aux` is a sequence such that
`∀ m ≥ seq_tendsto_ae_seq_aux n, μ {x | 2⁻¹ ^ n ≤ dist (f m x) (g x)} ≤ 2⁻¹ ^ n`. -/
noncomputable
def seq_tendsto_ae_seq_aux (hfg : tendsto_in_measure μ f at_top g) (n : ℕ) :=
classical.some (exists_nat_measure_lt_two_inv hfg n)
/-- Transformation of `seq_tendsto_ae_seq_aux` to makes sure it is strictly monotone. -/
noncomputable
def seq_tendsto_ae_seq (hfg : tendsto_in_measure μ f at_top g) : ℕ → ℕ
| 0 := seq_tendsto_ae_seq_aux hfg 0
| (n + 1) := max (seq_tendsto_ae_seq_aux hfg (n + 1))
(seq_tendsto_ae_seq n + 1)
lemma seq_tendsto_ae_seq_succ (hfg : tendsto_in_measure μ f at_top g) {n : ℕ} :
seq_tendsto_ae_seq hfg (n + 1) =
max (seq_tendsto_ae_seq_aux hfg (n + 1)) (seq_tendsto_ae_seq hfg n + 1) :=
by rw seq_tendsto_ae_seq
lemma seq_tendsto_ae_seq_spec (hfg : tendsto_in_measure μ f at_top g)
(n k : ℕ) (hn : seq_tendsto_ae_seq hfg n ≤ k) :
μ {x | 2⁻¹ ^ n ≤ dist (f k x) (g x)} ≤ 2⁻¹ ^ n :=
begin
cases n,
{ exact classical.some_spec (exists_nat_measure_lt_two_inv hfg 0) k hn },
{ exact classical.some_spec (exists_nat_measure_lt_two_inv hfg _) _
(le_trans (le_max_left _ _) hn) }
end
lemma seq_tendsto_ae_seq_strict_mono (hfg : tendsto_in_measure μ f at_top g) :
strict_mono (seq_tendsto_ae_seq hfg) :=
begin
refine strict_mono_nat_of_lt_succ (λ n, _),
rw seq_tendsto_ae_seq_succ,
exact lt_of_lt_of_le (lt_add_one $ seq_tendsto_ae_seq hfg n) (le_max_right _ _),
end
end exists_seq_tendsto_ae
/-- If `f` is a sequence of functions which converges in measure to `g`, then there exists a
subsequence of `f` which converges a.e. to `g`. -/
lemma tendsto_in_measure.exists_seq_tendsto_ae
(hfg : tendsto_in_measure μ f at_top g) :
∃ ns : ℕ → ℕ, strict_mono ns ∧ ∀ᵐ x ∂μ, tendsto (λ i, f (ns i) x) at_top (𝓝 (g x)) :=
begin
/- Since `f` tends to `g` in measure, it has a subsequence `k ↦ f (ns k)` such that
`μ {|f (ns k) - g| ≥ 2⁻ᵏ} ≤ 2⁻ᵏ` for all `k`. Defining
`s := ⋂ k, ⋃ i ≥ k, {|f (ns k) - g| ≥ 2⁻ᵏ}`, we see that `μ s = 0` by the
first Borel-Cantelli lemma.
On the other hand, as `s` is precisely the set for which `f (ns k)`
doesn't converge to `g`, `f (ns k)` converges almost everywhere to `g` as required. -/
have h_lt_ε_real : ∀ (ε : ℝ) (hε : 0 < ε), ∃ k : ℕ, 2 * 2⁻¹ ^ k < ε,
{ intros ε hε,
obtain ⟨k, h_k⟩ : ∃ (k : ℕ), 2⁻¹ ^ k < ε := exists_pow_lt_of_lt_one hε (by norm_num),
refine ⟨k + 1, (le_of_eq _).trans_lt h_k⟩,
rw pow_add, ring },
set ns := exists_seq_tendsto_ae.seq_tendsto_ae_seq hfg,
use ns,
let S := λ k, {x | 2⁻¹ ^ k ≤ dist (f (ns k) x) (g x)},
have hμS_le : ∀ k, μ (S k) ≤ 2⁻¹ ^ k :=
λ k, exists_seq_tendsto_ae.seq_tendsto_ae_seq_spec hfg k (ns k) (le_rfl),
set s := filter.at_top.limsup S with hs,
have hμs : μ s = 0,
{ refine measure_limsup_eq_zero (ne_of_lt $ lt_of_le_of_lt (ennreal.tsum_le_tsum hμS_le) _),
simp only [ennreal.tsum_geometric, ennreal.one_sub_inv_two, inv_inv],
dec_trivial },
have h_tendsto : ∀ x ∈ sᶜ, tendsto (λ i, f (ns i) x) at_top (𝓝 (g x)),
{ refine λ x hx, metric.tendsto_at_top.mpr (λ ε hε, _),
rw [hs, limsup_eq_infi_supr_of_nat] at hx,
simp only [set.supr_eq_Union, set.infi_eq_Inter, set.compl_Inter, set.compl_Union,
set.mem_Union, set.mem_Inter, set.mem_compl_eq, set.mem_set_of_eq, not_le] at hx,
obtain ⟨N, hNx⟩ := hx,
obtain ⟨k, hk_lt_ε⟩ := h_lt_ε_real ε hε,
refine ⟨max N (k - 1), λ n hn_ge, lt_of_le_of_lt _ hk_lt_ε⟩,
specialize hNx n ((le_max_left _ _).trans hn_ge),
have h_inv_n_le_k : (2 : ℝ)⁻¹ ^ n ≤ 2 * 2⁻¹ ^ k,
{ rw [mul_comm, ← inv_mul_le_iff' (@two_pos ℝ _ _)],
conv_lhs { congr, rw ← pow_one (2 : ℝ)⁻¹ },
rw [← pow_add, add_comm],
exact pow_le_pow_of_le_one ((one_div (2 : ℝ)) ▸ one_half_pos.le) (inv_le_one one_le_two)
((le_tsub_add.trans (add_le_add_right (le_max_right _ _) 1)).trans
(add_le_add_right hn_ge 1)) },
exact le_trans hNx.le h_inv_n_le_k },
rw ae_iff,
refine ⟨exists_seq_tendsto_ae.seq_tendsto_ae_seq_strict_mono hfg, measure_mono_null (λ x, _) hμs⟩,
rw [set.mem_set_of_eq, ← @not_not (x ∈ s), not_imp_not],
exact h_tendsto x,
end
lemma tendsto_in_measure.exists_seq_tendsto_in_measure_at_top
{u : filter ι} [ne_bot u] [is_countably_generated u] {f : ι → α → E} {g : α → E}
(hfg : tendsto_in_measure μ f u g) :
∃ ns : ℕ → ι, tendsto_in_measure μ (λ n, f (ns n)) at_top g :=
begin
obtain ⟨ns, h_tendsto_ns⟩ : ∃ (ns : ℕ → ι), tendsto ns at_top u := exists_seq_tendsto u,
exact ⟨ns, λ ε hε, (hfg ε hε).comp h_tendsto_ns⟩,
end
lemma tendsto_in_measure.exists_seq_tendsto_ae'
{u : filter ι} [ne_bot u] [is_countably_generated u] {f : ι → α → E} {g : α → E}
(hfg : tendsto_in_measure μ f u g) :
∃ ns : ℕ → ι, ∀ᵐ x ∂μ, tendsto (λ i, f (ns i) x) at_top (𝓝 (g x)) :=
begin
obtain ⟨ms, hms⟩ := hfg.exists_seq_tendsto_in_measure_at_top,
obtain ⟨ns, -, hns⟩ := hms.exists_seq_tendsto_ae,
exact ⟨ms ∘ ns, hns⟩,
end
end exists_seq_tendsto_ae
section ae_measurable_of
variables [measurable_space E] [normed_group E] [borel_space E]
lemma tendsto_in_measure.ae_measurable
{u : filter ι} [ne_bot u] [is_countably_generated u]
{f : ι → α → E} {g : α → E} (hf : ∀ n, ae_measurable (f n) μ)
(h_tendsto : tendsto_in_measure μ f u g) :
ae_measurable g μ :=
begin
obtain ⟨ns, hns⟩ := h_tendsto.exists_seq_tendsto_ae',
exact ae_measurable_of_tendsto_metrizable_ae at_top (λ n, hf (ns n)) hns,
end
end ae_measurable_of
section tendsto_in_measure_of
variables [normed_group E] {p : ℝ≥0∞}
variables {f : ι → α → E} {g : α → E}
/-- This lemma is superceded by `measure_theory.tendsto_in_measure_of_tendsto_snorm` where we
allow `p = ∞` and only require `ae_strongly_measurable`. -/
lemma tendsto_in_measure_of_tendsto_snorm_of_strongly_measurable
(hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞)
(hf : ∀ n, strongly_measurable (f n)) (hg : strongly_measurable g) {l : filter ι}
(hfg : tendsto (λ n, snorm (f n - g) p μ) l (𝓝 0)) :
tendsto_in_measure μ f l g :=
begin
intros ε hε,
replace hfg := ennreal.tendsto.const_mul (tendsto.ennrpow_const p.to_real hfg)
(or.inr $ @ennreal.of_real_ne_top (1 / ε ^ (p.to_real))),
simp only [mul_zero, ennreal.zero_rpow_of_pos (ennreal.to_real_pos hp_ne_zero hp_ne_top)] at hfg,
rw ennreal.tendsto_nhds_zero at hfg ⊢,
intros δ hδ,
refine (hfg δ hδ).mono (λ n hn, _),
refine le_trans _ hn,
rw [ennreal.of_real_div_of_pos (real.rpow_pos_of_pos hε _), ennreal.of_real_one, mul_comm,
mul_one_div, ennreal.le_div_iff_mul_le _ (or.inl (ennreal.of_real_ne_top)), mul_comm],
{ convert mul_meas_ge_le_pow_snorm' μ hp_ne_zero hp_ne_top ((hf n).sub hg).ae_strongly_measurable
(ennreal.of_real ε),
{ exact (ennreal.of_real_rpow_of_pos hε).symm },
{ ext x,
rw [dist_eq_norm, ← ennreal.of_real_le_of_real_iff (norm_nonneg _),
of_real_norm_eq_coe_nnnorm],
exact iff.rfl } },
{ rw [ne, ennreal.of_real_eq_zero, not_le],
exact or.inl (real.rpow_pos_of_pos hε _) },
end
/-- This lemma is superceded by `measure_theory.tendsto_in_measure_of_tendsto_snorm` where we
allow `p = ∞`. -/
lemma tendsto_in_measure_of_tendsto_snorm_of_ne_top
(hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞)
(hf : ∀ n, ae_strongly_measurable (f n) μ) (hg : ae_strongly_measurable g μ) {l : filter ι}
(hfg : tendsto (λ n, snorm (f n - g) p μ) l (𝓝 0)) :
tendsto_in_measure μ f l g :=
begin
refine tendsto_in_measure.congr (λ i, (hf i).ae_eq_mk.symm) hg.ae_eq_mk.symm _,
refine tendsto_in_measure_of_tendsto_snorm_of_strongly_measurable hp_ne_zero hp_ne_top
(λ i, (hf i).strongly_measurable_mk) hg.strongly_measurable_mk _,
have : (λ n, snorm ((hf n).mk (f n) - hg.mk g) p μ) = (λ n, snorm (f n - g) p μ),
{ ext1 n, refine snorm_congr_ae (eventually_eq.sub (hf n).ae_eq_mk.symm hg.ae_eq_mk.symm), },
rw this,
exact hfg,
end
/-- See also `measure_theory.tendsto_in_measure_of_tendsto_snorm` which work for general
Lp-convergence for all `p ≠ 0`. -/
lemma tendsto_in_measure_of_tendsto_snorm_top {E} [normed_group E] {f : ι → α → E} {g : α → E}
{l : filter ι} (hfg : tendsto (λ n, snorm (f n - g) ∞ μ) l (𝓝 0)) :
tendsto_in_measure μ f l g :=
begin
intros δ hδ,
simp only [snorm_exponent_top, snorm_ess_sup] at hfg,
rw ennreal.tendsto_nhds_zero at hfg ⊢,
intros ε hε,
specialize hfg ((ennreal.of_real δ) / 2) (ennreal.div_pos_iff.2
⟨(ennreal.of_real_pos.2 hδ).ne.symm, ennreal.two_ne_top⟩),
refine hfg.mono (λ n hn, _),
simp only [true_and, gt_iff_lt, ge_iff_le, zero_tsub, zero_le, zero_add, set.mem_Icc,
pi.sub_apply] at *,
have : ess_sup (λ (x : α), (∥f n x - g x∥₊ : ℝ≥0∞)) μ < ennreal.of_real δ :=
lt_of_le_of_lt hn (ennreal.half_lt_self (ennreal.of_real_pos.2 hδ).ne.symm
ennreal.of_real_lt_top.ne),
refine ((le_of_eq _).trans (ae_lt_of_ess_sup_lt this).le).trans hε.le,
congr' with x,
simp only [ennreal.of_real_le_iff_le_to_real ennreal.coe_lt_top.ne, ennreal.coe_to_real,
not_lt, coe_nnnorm, set.mem_set_of_eq, set.mem_compl_eq],
rw ← dist_eq_norm (f n x) (g x),
refl
end
/-- Convergence in Lp implies convergence in measure. -/
lemma tendsto_in_measure_of_tendsto_snorm {l : filter ι}
(hp_ne_zero : p ≠ 0) (hf : ∀ n, ae_strongly_measurable (f n) μ) (hg : ae_strongly_measurable g μ)
(hfg : tendsto (λ n, snorm (f n - g) p μ) l (𝓝 0)) :
tendsto_in_measure μ f l g :=
begin
by_cases hp_ne_top : p = ∞,
{ subst hp_ne_top,
exact tendsto_in_measure_of_tendsto_snorm_top hfg },
{ exact tendsto_in_measure_of_tendsto_snorm_of_ne_top hp_ne_zero hp_ne_top hf hg hfg }
end
/-- Convergence in Lp implies convergence in measure. -/
lemma tendsto_in_measure_of_tendsto_Lp [hp : fact (1 ≤ p)]
{f : ι → Lp E p μ} {g : Lp E p μ} {l : filter ι} (hfg : tendsto f l (𝓝 g)) :
tendsto_in_measure μ (λ n, f n) l g :=
tendsto_in_measure_of_tendsto_snorm (ennreal.zero_lt_one.trans_le hp.elim).ne.symm
(λ n, Lp.ae_strongly_measurable _) (Lp.ae_strongly_measurable _)
((Lp.tendsto_Lp_iff_tendsto_ℒp' _ _).mp hfg)
end tendsto_in_measure_of
end measure_theory
|
37fa1995bd0342183b75d362f632908ead326840 | 9b9a16fa2cb737daee6b2785474678b6fa91d6d4 | /test/linarith.lean | edd083294c2492e462b3033c7c313f197c305935 | [
"Apache-2.0"
] | permissive | johoelzl/mathlib | 253f46daa30b644d011e8e119025b01ad69735c4 | 592e3c7a2dfbd5826919b4605559d35d4d75938f | refs/heads/master | 1,625,657,216,488 | 1,551,374,946,000 | 1,551,374,946,000 | 98,915,829 | 0 | 0 | Apache-2.0 | 1,522,917,267,000 | 1,501,524,499,000 | Lean | UTF-8 | Lean | false | false | 3,811 | lean | import tactic.linarith
example (e b c a v0 v1 : ℚ) (h1 : v0 = 5*a) (h2 : v1 = 3*b) (h3 : v0 + v1 + c = 10) :
v0 + 5 + (v1 - 3) + (c - 2) = 10 :=
by linarith
example (ε : ℚ) (h1 : ε > 0) : ε / 2 + ε / 3 + ε / 7 < ε :=
by linarith
example (x y z : ℚ) (h1 : 2*x < 3*y) (h2 : -4*x + z/2 < 0)
(h3 : 12*y - z < 0) : false :=
by linarith
example (ε : ℚ) (h1 : ε > 0) : ε / 2 < ε :=
by linarith
example (ε : ℚ) (h1 : ε > 0) : ε / 3 + ε / 3 + ε / 3 = ε :=
by linarith
example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false :=
by linarith {discharger := `[ring SOP]}
example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false :=
by linarith
example (a b c : ℚ) (x y : ℤ) (h1 : x ≤ 3*y) (h2 : b + 2 > 3 + b) : false :=
by linarith {restrict_type := ℚ}
example (g v V c h : ℚ) (h1 : h = 0) (h2 : v = V) (h3 : V > 0) (h4 : g > 0)
(h5 : 0 ≤ c) (h6 : c < 1) :
v ≤ V :=
by linarith
example (x y z : ℚ) (h1 : 2*x + ((-3)*y) < 0) (h2 : (-4)*x + 2*z < 0)
(h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false :=
by linarith
example (x y z : ℚ) (h1 : 2*1*x + (3)*(y*(-1)) < 0) (h2 : (-2)*x*2 < -(z + z))
(h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false :=
by linarith
example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0)
(h3 : 12*y - 4* z < 0) : false :=
by linarith
example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5)
(h3 : 12*y - 4* z < 0) : false :=
by linarith
example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) :
¬ 12*y - 4* z < 0 :=
by linarith
example (w x y z : ℤ) (h1 : 4*x + (-3)*y + 6*w ≤ 0) (h2 : (-1)*x < 0)
(h3 : y < 0) (h4 : w ≥ 0) (h5 : nat.prime x.nat_abs) : false :=
by linarith
example (a b c : ℚ) (h1 : a > 0) (h2 : b > 5) (h3 : c < -10)
(h4 : a + b - c < 3) : false :=
by linarith
example (a b c : ℚ) (h2 : b > 0) (h3 : ¬ b ≥ 0) : false :=
by linarith
example (a b c : ℚ) (h2 : (2 : ℚ) > 3) : a + b - c ≥ 3 :=
by linarith {exfalso := ff}
example (x : ℚ) (hx : x > 0) (h : x.num < 0) : false :=
by linarith using [rat.num_pos_iff_pos.mpr hx]
example (x y z : ℚ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y :=
by linarith
example (x y z : ℕ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y :=
by linarith
example (x y z : ℚ) (hx : ¬ x > 3*y) (h2 : ¬ y > 2*z) (h3 : x ≥ 6*z) : x = 3*y :=
by linarith
example (h1 : (1 : ℕ) < 1) : false :=
by linarith
example (a b c : ℚ) (h2 : b > 0) (h3 : b < 0) : nat.prime 10 :=
by linarith
example (a b c : ℕ) : a + b ≥ a :=
by linarith
example (a b c : ℕ) : ¬ a + b < a :=
by linarith
example (x y : ℚ) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3) (h' : (x + 4) * x ≥ 0)
(h'' : (6 + 3 * y) * y ≥ 0) : false :=
by linarith
example (x y : ℕ) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3) : false :=
by linarith
example (a b i : ℕ) (h1 : ¬ a < i) (h2 : b < i) (h3 : a ≤ b) : false :=
by linarith
example (n : ℕ) (h1 : n ≤ 3) (h2 : n > 2) : n = 3 := by linarith
example (z : ℕ) (hz : ¬ z ≥ 2) (h2 : ¬ z + 1 ≤ 2) : false :=
by linarith
example (z : ℕ) (hz : ¬ z ≥ 2) : z + 1 ≤ 2 :=
by linarith
example (a b c : ℚ) (h1 : 1 / a < b) (h2 : b < c) : 1 / a < c :=
by linarith
example
(N : ℕ) (n : ℕ) (Hirrelevant : n > N)
(A : ℚ) (l : ℚ) (h : A - l ≤ -(A - l)) (h_1 : ¬A ≤ -A) (h_2 : ¬l ≤ -l)
(h_3 : -(A - l) < 1) : A < l + 1 := by linarith
example (d : ℚ) (q n : ℕ) (h1 : ((q : ℚ) - 1)*n ≥ 0) (h2 : d = 2/3*(((q : ℚ) - 1)*n)) : d ≤ ((q : ℚ) - 1)*n :=
by linarith
example (d : ℚ) (q n : ℕ) (h1 : ((q : ℚ) - 1)*n ≥ 0) (h2 : d = 2/3*(((q : ℚ) - 1)*n)) :
((q : ℚ) - 1)*n - d = 1/3 * (((q : ℚ) - 1)*n) :=
by linarith
|
ebd55e063549dddd058853262802498acc82ac28 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/group_theory/group_action/sub_mul_action.lean | 81abf2bde26e581db0b5b59244868475395b96bd | [
"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 | 5,156 | lean | /-
Copyright (c) 2020 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import algebra.group_action_hom
import algebra.module.basic
import data.set_like
import group_theory.group_action.basic
/-!
# Sets invariant to a `mul_action`
In this file we define `sub_mul_action R M`; a subset of a `mul_action R M` which is closed with
respect to scalar multiplication.
For most uses, typically `submodule R M` is more powerful.
## Main definitions
* `sub_mul_action.mul_action` - the `mul_action R M` transferred to the subtype.
* `sub_mul_action.mul_action'` - the `mul_action S M` transferred to the subtype when
`is_scalar_tower S R M`.
* `sub_mul_action.is_scalar_tower` - the `is_scalar_tower S R M` transferred to the subtype.
## Tags
submodule, mul_action
-/
open function
universes u u' v
variables {S : Type u'} {R : Type u} {M : Type v}
set_option old_structure_cmd true
/-- A sub_mul_action is a set which is closed under scalar multiplication. -/
structure sub_mul_action (R : Type u) (M : Type v) [has_scalar R M] : Type v :=
(carrier : set M)
(smul_mem' : ∀ (c : R) {x : M}, x ∈ carrier → c • x ∈ carrier)
namespace sub_mul_action
variables [has_scalar R M]
instance : set_like (sub_mul_action R M) M :=
⟨sub_mul_action.carrier, λ p q h, by cases p; cases q; congr'⟩
@[simp] lemma mem_carrier {p : sub_mul_action R M} {x : M} : x ∈ p.carrier ↔ x ∈ (p : set M) :=
iff.rfl
@[ext] theorem ext {p q : sub_mul_action R M} (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := set_like.ext h
instance : has_bot (sub_mul_action R M) :=
⟨{ carrier := ∅, smul_mem' := λ c, set.not_mem_empty}⟩
instance : inhabited (sub_mul_action R M) := ⟨⊥⟩
end sub_mul_action
namespace sub_mul_action
section has_scalar
variables [has_scalar R M]
variables (p : sub_mul_action R M)
variables {r : R} {x : M}
lemma smul_mem (r : R) (h : x ∈ p) : r • x ∈ p := p.smul_mem' r h
instance : has_scalar R p :=
{ smul := λ c x, ⟨c • x.1, smul_mem _ c x.2⟩ }
variables {p}
@[simp, norm_cast] lemma coe_smul (r : R) (x : p) : ((r • x : p) : M) = r • ↑x := rfl
@[simp, norm_cast] lemma coe_mk (x : M) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : M) = x := rfl
variables (p)
/-- Embedding of a submodule `p` to the ambient space `M`. -/
protected def subtype : p →[R] M :=
by refine {to_fun := coe, ..}; simp [coe_smul]
@[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl
lemma subtype_eq_val : ((sub_mul_action.subtype p) : p → M) = subtype.val := rfl
end has_scalar
section mul_action
variables [monoid S] [monoid R]
variables [mul_action R M]
variables [has_scalar S R] [mul_action S M] [is_scalar_tower S R M]
variables (p : sub_mul_action R M)
variables {r : R} {x : M}
lemma smul_of_tower_mem (s : S) (h : x ∈ p) : s • x ∈ p :=
by { rw [←one_smul R x, ←smul_assoc], exact p.smul_mem _ h }
instance has_scalar' : has_scalar S p :=
{ smul := λ c x, ⟨c • x.1, smul_of_tower_mem _ c x.2⟩ }
instance : is_scalar_tower S R p :=
{ smul_assoc := λ s r x, subtype.ext $ smul_assoc s r ↑x }
@[simp, norm_cast] lemma coe_smul_of_tower (s : S) (x : p) : ((s • x : p) : M) = s • ↑x := rfl
@[simp] lemma smul_mem_iff' (u : units S) : (u : S) • x ∈ p ↔ x ∈ p :=
⟨λ h, by simpa only [smul_smul, u.inv_mul, one_smul] using p.smul_of_tower_mem (↑u⁻¹ : S) h,
p.smul_of_tower_mem u⟩
/-- If the scalar product forms a `mul_action`, then the subset inherits this action -/
instance mul_action' : mul_action S p :=
{ smul := (•),
one_smul := λ x, subtype.ext $ one_smul _ x,
mul_smul := λ c₁ c₂ x, subtype.ext $ mul_smul c₁ c₂ x }
instance : mul_action R p := p.mul_action'
end mul_action
section semimodule
variables [semiring R] [add_comm_monoid M]
variables [semimodule R M]
variables (p : sub_mul_action R M)
lemma zero_mem (h : (p : set M).nonempty) : (0 : M) ∈ p :=
let ⟨x, hx⟩ := h in zero_smul R (x : M) ▸ p.smul_mem 0 hx
/-- If the scalar product forms a `semimodule`, and the `sub_mul_action` is not `⊥`, then the
subset inherits the zero. -/
instance [n_empty : nonempty p] : has_zero p :=
{ zero := ⟨0, n_empty.elim $ λ x, p.zero_mem ⟨x, x.prop⟩⟩ }
end semimodule
section add_comm_group
variables [ring R] [add_comm_group M]
variables [semimodule R M]
variables (p p' : sub_mul_action R M)
variables {r : R} {x y : M}
lemma neg_mem (hx : x ∈ p) : -x ∈ p := by { rw ← neg_one_smul R, exact p.smul_mem _ hx }
@[simp] lemma neg_mem_iff : -x ∈ p ↔ x ∈ p :=
⟨λ h, by { rw ←neg_neg x, exact neg_mem _ h}, neg_mem _⟩
instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩
@[simp, norm_cast] lemma coe_neg (x : p) : ((-x : p) : M) = -x := rfl
end add_comm_group
end sub_mul_action
namespace sub_mul_action
variables [division_ring S] [semiring R] [mul_action R M]
variables [has_scalar S R] [mul_action S M] [is_scalar_tower S R M]
variables (p : sub_mul_action R M) {s : S} {x y : M}
theorem smul_mem_iff (s0 : s ≠ 0) : s • x ∈ p ↔ x ∈ p :=
p.smul_mem_iff' (units.mk0 s s0)
end sub_mul_action
|
18d6be498f06f189631e627f7af85f1cc5665602 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/abelian/non_preadditive_auto.lean | a025280fdd2e8086e3dd1d40b687e5a6527154ec | [] | 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 | 21,946 | lean | /-
Copyright (c) 2020 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.limits.shapes.finite_products
import Mathlib.category_theory.limits.shapes.kernels
import Mathlib.category_theory.limits.shapes.normal_mono
import Mathlib.category_theory.preadditive.default
import Mathlib.PostPort
universes v u l
namespace Mathlib
/-!
# Every non_preadditive_abelian category is preadditive
In mathlib, we define an abelian category as a preadditive category with a zero object,
kernels and cokernels, products and coproducts and in which every monomorphism and epimorphis is
normal.
While virtually every interesting abelian category has a natural preadditive structure (which is why
it is included in the definition), preadditivity is not actually needed: Every category that has
all of the other properties appearing in the definition of an abelian category admits a preadditive
structure. This is the construction we carry out in this file.
The proof proceeds in roughly five steps:
1. Prove some results (for example that all equalizers exist) that would be trivial if we already
had the preadditive structure but are a bit of work without it.
2. Develop images and coimages to show that every monomorphism is the kernel of its cokernel.
The results of the first two steps are also useful for the "normal" development of abelian
categories, and will be used there.
3. For every object `A`, define a "subtraction" morphism `σ : A ⨯ A ⟶ A` and use it to define
subtraction on morphisms as `f - g := prod.lift f g ≫ σ`.
4. Prove a small number of identities about this subtraction from the definition of `σ`.
5. From these identities, prove a large number of other identities that imply that defining
`f + g := f - (0 - g)` indeed gives an abelian group structure on morphisms such that composition
is bilinear.
The construction is non-trivial and it is quite remarkable that this abelian group structure can
be constructed purely from the existence of a few limits and colimits. What's even more impressive
is that all additive structures on a category are in some sense isomorphic, so for abelian
categories with a natural preadditive structure, this construction manages to "almost" reconstruct
this natural structure. However, we have not formalized this isomorphism.
## References
* [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2]
-/
namespace category_theory
/-- We call a category `non_preadditive_abelian` if it has a zero object, kernels, cokernels, binary
products and coproducts, and every monomorphism and every epimorphism is normal. -/
class non_preadditive_abelian (C : Type u) [category C] where
has_zero_object : limits.has_zero_object C
has_zero_morphisms : limits.has_zero_morphisms C
has_kernels : limits.has_kernels C
has_cokernels : limits.has_cokernels C
has_finite_products : limits.has_finite_products C
has_finite_coproducts : limits.has_finite_coproducts C
normal_mono : {X Y : C} → (f : X ⟶ Y) → [_inst_2 : mono f] → normal_mono f
normal_epi : {X Y : C} → (f : X ⟶ Y) → [_inst_2 : epi f] → normal_epi f
end category_theory
namespace category_theory.non_preadditive_abelian
/-- In a `non_preadditive_abelian` category, every epimorphism is strong. -/
theorem strong_epi_of_epi {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C}
(f : P ⟶ Q) [epi f] : strong_epi f :=
category_theory.strong_epi_of_regular_epi f
/-- In a `non_preadditive_abelian` category, a monomorphism which is also an epimorphism is an
isomorphism. -/
def is_iso_of_mono_of_epi {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C}
(f : X ⟶ Y) [mono f] [epi f] : is_iso f :=
is_iso_of_mono_of_strong_epi f
/-- The pullback of two monomorphisms exists. -/
theorem pullback_of_mono {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C}
{Z : C} (a : X ⟶ Z) (b : Y ⟶ Z) [mono a] [mono b] : limits.has_limit (limits.cospan a b) :=
sorry
/-- The pushout of two epimorphisms exists. -/
theorem pushout_of_epi {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} {Z : C}
(a : X ⟶ Y) (b : X ⟶ Z) [epi a] [epi b] : limits.has_colimit (limits.span a b) :=
sorry
/-- The pullback of `(𝟙 X, f)` and `(𝟙 X, g)` -/
/-- The equalizer of `f` and `g` exists. -/
theorem has_limit_parallel_pair {C : Type u} [category C] [non_preadditive_abelian C] {X : C}
{Y : C} (f : X ⟶ Y) (g : X ⟶ Y) : limits.has_limit (limits.parallel_pair f g) :=
sorry
/-- The pushout of `(𝟙 Y, f)` and `(𝟙 Y, g)`. -/
/-- The coequalizer of `f` and `g` exists. -/
theorem has_colimit_parallel_pair {C : Type u} [category C] [non_preadditive_abelian C] {X : C}
{Y : C} (f : X ⟶ Y) (g : X ⟶ Y) : limits.has_colimit (limits.parallel_pair f g) :=
sorry
/-- A `non_preadditive_abelian` category has all equalizers. -/
protected instance has_equalizers {C : Type u} [category C] [non_preadditive_abelian C] :
limits.has_equalizers C :=
limits.has_equalizers_of_has_limit_parallel_pair C
/-- A `non_preadditive_abelian` category has all coequalizers. -/
protected instance has_coequalizers {C : Type u} [category C] [non_preadditive_abelian C] :
limits.has_coequalizers C :=
limits.has_coequalizers_of_has_colimit_parallel_pair C
/-- If a zero morphism is a kernel of `f`, then `f` is a monomorphism. -/
theorem mono_of_zero_kernel {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C}
(f : X ⟶ Y) (Z : C)
(l :
limits.is_limit
(limits.kernel_fork.of_ι 0
((fun (this : 0 ≫ f = 0) => this)
(eq.mpr
(id
(Eq.trans
((fun (a a_1 : Z ⟶ Y) (e_1 : a = a_1) (ᾰ ᾰ_1 : Z ⟶ Y) (e_2 : ᾰ = ᾰ_1) =>
congr (congr_arg Eq e_1) e_2)
(0 ≫ f) 0 limits.zero_comp 0 0 (Eq.refl 0))
(propext (eq_self_iff_true 0))))
trivial)))) :
mono f :=
sorry
/-- If a zero morphism is a cokernel of `f`, then `f` is an epimorphism. -/
theorem epi_of_zero_cokernel {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C}
(f : X ⟶ Y) (Z : C)
(l :
limits.is_colimit
(limits.cokernel_cofork.of_π 0
((fun (this : f ≫ 0 = 0) => this)
(eq.mpr
(id
(Eq.trans
((fun (a a_1 : X ⟶ Z) (e_1 : a = a_1) (ᾰ ᾰ_1 : X ⟶ Z) (e_2 : ᾰ = ᾰ_1) =>
congr (congr_arg Eq e_1) e_2)
(f ≫ 0) 0 limits.comp_zero 0 0 (Eq.refl 0))
(propext (eq_self_iff_true 0))))
trivial)))) :
epi f :=
sorry
/-- If `g ≫ f = 0` implies `g = 0` for all `g`, then `0 : 0 ⟶ X` is a kernel of `f`. -/
def zero_kernel_of_cancel_zero {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C}
(f : X ⟶ Y) (hf : ∀ (Z : C) (g : Z ⟶ X), g ≫ f = 0 → g = 0) :
limits.is_limit (limits.kernel_fork.of_ι 0 (zero_kernel_of_cancel_zero._proof_1 f)) :=
limits.fork.is_limit.mk (limits.kernel_fork.of_ι 0 sorry) (fun (s : limits.fork f 0) => 0) sorry
sorry
/-- If `f ≫ g = 0` implies `g = 0` for all `g`, then `0 : Y ⟶ 0` is a cokernel of `f`. -/
def zero_cokernel_of_zero_cancel {C : Type u} [category C] [non_preadditive_abelian C] {X : C}
{Y : C} (f : X ⟶ Y) (hf : ∀ (Z : C) (g : Y ⟶ Z), f ≫ g = 0 → g = 0) :
limits.is_colimit (limits.cokernel_cofork.of_π 0 (zero_cokernel_of_zero_cancel._proof_1 f)) :=
limits.cofork.is_colimit.mk (limits.cokernel_cofork.of_π 0 sorry)
(fun (s : limits.cofork f 0) => 0) sorry sorry
/-- If `g ≫ f = 0` implies `g = 0` for all `g`, then `f` is a monomorphism. -/
theorem mono_of_cancel_zero {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C}
(f : X ⟶ Y) (hf : ∀ (Z : C) (g : Z ⟶ X), g ≫ f = 0 → g = 0) : mono f :=
mono_of_zero_kernel f 0 (zero_kernel_of_cancel_zero f hf)
/-- If `f ≫ g = 0` implies `g = 0` for all `g`, then `g` is a monomorphism. -/
theorem epi_of_zero_cancel {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C}
(f : X ⟶ Y) (hf : ∀ (Z : C) (g : Y ⟶ Z), f ≫ g = 0 → g = 0) : epi f :=
epi_of_zero_cokernel f 0 (zero_cokernel_of_zero_cancel f hf)
/-- The kernel of the cokernel of `f` is called the image of `f`. -/
protected def image {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C}
(f : P ⟶ Q) : C :=
limits.kernel (limits.cokernel.π f)
/-- The inclusion of the image into the codomain. -/
protected def image.ι {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C}
(f : P ⟶ Q) : non_preadditive_abelian.image f ⟶ Q :=
limits.kernel.ι (limits.cokernel.π f)
/-- There is a canonical epimorphism `p : P ⟶ image f` for every `f`. -/
protected def factor_thru_image {C : Type u} [category C] [non_preadditive_abelian C] {P : C}
{Q : C} (f : P ⟶ Q) : P ⟶ non_preadditive_abelian.image f :=
limits.kernel.lift (limits.cokernel.π f) f sorry
/-- `f` factors through its image via the canonical morphism `p`. -/
@[simp] theorem image.fac_assoc {C : Type u} [category C] [non_preadditive_abelian C] {P : C}
{Q : C} (f : P ⟶ Q) {X' : C} (f' : Q ⟶ X') :
non_preadditive_abelian.factor_thru_image f ≫ image.ι f ≫ f' = f ≫ f' :=
sorry
/-- The map `p : P ⟶ image f` is an epimorphism -/
protected instance factor_thru_image.category_theory.epi {C : Type u} [category C]
[non_preadditive_abelian C] {P : C} {Q : C} (f : P ⟶ Q) :
epi (non_preadditive_abelian.factor_thru_image f) :=
sorry
-- It will suffice to consider some g : I ⟶ R such that p ≫ g = 0 and show that g = 0.
protected instance mono_factor_thru_image {C : Type u} [category C] [non_preadditive_abelian C]
{P : C} {Q : C} (f : P ⟶ Q) [mono f] : mono (non_preadditive_abelian.factor_thru_image f) :=
mono_of_mono_fac (image.fac f)
protected instance is_iso_factor_thru_image {C : Type u} [category C] [non_preadditive_abelian C]
{P : C} {Q : C} (f : P ⟶ Q) [mono f] : is_iso (non_preadditive_abelian.factor_thru_image f) :=
is_iso_of_mono_of_epi (non_preadditive_abelian.factor_thru_image f)
/-- The cokernel of the kernel of `f` is called the coimage of `f`. -/
protected def coimage {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C}
(f : P ⟶ Q) : C :=
limits.cokernel (limits.kernel.ι f)
/-- The projection onto the coimage. -/
protected def coimage.π {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C}
(f : P ⟶ Q) : P ⟶ non_preadditive_abelian.coimage f :=
limits.cokernel.π (limits.kernel.ι f)
/-- There is a canonical monomorphism `i : coimage f ⟶ Q`. -/
protected def factor_thru_coimage {C : Type u} [category C] [non_preadditive_abelian C] {P : C}
{Q : C} (f : P ⟶ Q) : non_preadditive_abelian.coimage f ⟶ Q :=
limits.cokernel.desc (limits.kernel.ι f) f sorry
/-- `f` factors through its coimage via the canonical morphism `p`. -/
protected theorem coimage.fac {C : Type u} [category C] [non_preadditive_abelian C] {P : C} {Q : C}
(f : P ⟶ Q) : coimage.π f ≫ non_preadditive_abelian.factor_thru_coimage f = f :=
limits.cokernel.π_desc (limits.kernel.ι f) f (factor_thru_coimage._proof_1 f)
/-- The canonical morphism `i : coimage f ⟶ Q` is a monomorphism -/
protected instance factor_thru_coimage.category_theory.mono {C : Type u} [category C]
[non_preadditive_abelian C] {P : C} {Q : C} (f : P ⟶ Q) :
mono (non_preadditive_abelian.factor_thru_coimage f) :=
sorry
protected instance epi_factor_thru_coimage {C : Type u} [category C] [non_preadditive_abelian C]
{P : C} {Q : C} (f : P ⟶ Q) [epi f] : epi (non_preadditive_abelian.factor_thru_coimage f) :=
epi_of_epi_fac (coimage.fac f)
protected instance is_iso_factor_thru_coimage {C : Type u} [category C] [non_preadditive_abelian C]
{P : C} {Q : C} (f : P ⟶ Q) [epi f] : is_iso (non_preadditive_abelian.factor_thru_coimage f) :=
is_iso_of_mono_of_epi (non_preadditive_abelian.factor_thru_coimage f)
/-- In a `non_preadditive_abelian` category, an epi is the cokernel of its kernel. More precisely:
If `f` is an epimorphism and `s` is some limit kernel cone on `f`, then `f` is a cokernel
of `fork.ι s`. -/
def epi_is_cokernel_of_kernel {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C}
{f : X ⟶ Y} [epi f] (s : limits.fork f 0) (h : limits.is_limit s) :
limits.is_colimit (limits.cokernel_cofork.of_π f (epi_is_cokernel_of_kernel._proof_1 s)) :=
limits.is_cokernel.cokernel_iso (limits.fork.ι s) f
(limits.cokernel.of_iso_comp
(nat_trans.app (limits.cone.π (limits.limit.cone (limits.parallel_pair f 0)))
limits.walking_parallel_pair.zero)
(limits.fork.ι s)
(limits.is_limit.cone_point_unique_up_to_iso
(limits.limit.is_limit (limits.parallel_pair f 0)) h)
sorry)
(as_iso (non_preadditive_abelian.factor_thru_coimage f)) sorry
/-- In a `non_preadditive_abelian` category, a mono is the kernel of its cokernel. More precisely:
If `f` is a monomorphism and `s` is some colimit cokernel cocone on `f`, then `f` is a kernel
of `cofork.π s`. -/
def mono_is_kernel_of_cokernel {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C}
{f : X ⟶ Y} [mono f] (s : limits.cofork f 0) (h : limits.is_colimit s) :
limits.is_limit (limits.kernel_fork.of_ι f (mono_is_kernel_of_cokernel._proof_1 s)) :=
limits.is_kernel.iso_kernel (limits.cofork.π s) f
(limits.kernel.of_comp_iso
(nat_trans.app (limits.cocone.ι (limits.colimit.cocone (limits.parallel_pair f 0)))
limits.walking_parallel_pair.one)
(limits.cofork.π s)
(limits.is_colimit.cocone_point_unique_up_to_iso h
(limits.colimit.is_colimit (limits.parallel_pair f 0)))
sorry)
(as_iso (non_preadditive_abelian.factor_thru_image f)) sorry
/-- The composite `A ⟶ A ⨯ A ⟶ cokernel (Δ A)`, where the first map is `(𝟙 A, 0)` and the second map
is the canonical projection into the cokernel. -/
def r {C : Type u} [category C] [non_preadditive_abelian C] (A : C) :
A ⟶ limits.cokernel (limits.diag A) :=
limits.prod.lift 𝟙 0 ≫ limits.cokernel.π (limits.diag A)
protected instance mono_Δ {C : Type u} [category C] [non_preadditive_abelian C] {A : C} :
mono (limits.diag A) :=
mono_of_mono_fac (limits.prod.lift_fst 𝟙 𝟙)
protected instance mono_r {C : Type u} [category C] [non_preadditive_abelian C] {A : C} :
mono (r A) :=
sorry
protected instance epi_r {C : Type u} [category C] [non_preadditive_abelian C] {A : C} :
epi (r A) :=
sorry
protected instance is_iso_r {C : Type u} [category C] [non_preadditive_abelian C] {A : C} :
is_iso (r A) :=
is_iso_of_mono_of_epi (r A)
/-- The composite `A ⨯ A ⟶ cokernel (diag A) ⟶ A` given by the natural projection into the cokernel
followed by the inverse of `r`. In the category of modules, using the normal kernels and
cokernels, this map is equal to the map `(a, b) ↦ a - b`, hence the name `σ` for
"subtraction". -/
def σ {C : Type u} [category C] [non_preadditive_abelian C] {A : C} : A ⨯ A ⟶ A :=
limits.cokernel.π (limits.diag A) ≫ inv (r A)
@[simp] theorem diag_σ {C : Type u} [category C] [non_preadditive_abelian C] {X : C} :
limits.diag X ≫ σ = 0 :=
eq.mpr
(id
(Eq._oldrec (Eq.refl (limits.diag X ≫ σ = 0))
(limits.cokernel.condition_assoc (limits.diag X) (inv (r X)))))
(eq.mpr (id (Eq._oldrec (Eq.refl (0 ≫ inv (r X) = 0)) limits.zero_comp)) (Eq.refl 0))
@[simp] theorem lift_σ_assoc {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {X' : C}
(f' : X ⟶ X') :
limits.prod.lift 𝟙 0 ≫ limits.cokernel.π (limits.diag X) ≫ inv (r X) ≫ f' = f' :=
sorry
theorem lift_map {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (f : X ⟶ Y) :
limits.prod.lift 𝟙 0 ≫ limits.prod.map f f = f ≫ limits.prod.lift 𝟙 0 :=
sorry
/-- σ is a cokernel of Δ X. -/
def is_colimit_σ {C : Type u} [category C] [non_preadditive_abelian C] {X : C} :
limits.is_colimit (limits.cokernel_cofork.of_π σ diag_σ) :=
limits.cokernel.cokernel_iso (limits.diag X) σ (iso.symm (as_iso (r X))) sorry
/-- This is the key identity satisfied by `σ`. -/
theorem σ_comp {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (f : X ⟶ Y) :
σ ≫ f = limits.prod.map f f ≫ σ :=
sorry
/- We write `f - g` for `prod.lift f g ≫ σ`. -/
/-- Subtraction of morphisms in a `non_preadditive_abelian` category. -/
def has_sub {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} : Sub (X ⟶ Y) :=
{ sub := fun (f g : X ⟶ Y) => limits.prod.lift f g ≫ σ }
/- We write `-f` for `0 - f`. -/
/-- Negation of morphisms in a `non_preadditive_abelian` category. -/
def has_neg {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} : Neg (X ⟶ Y) :=
{ neg := fun (f : X ⟶ Y) => 0 - f }
/- We write `f + g` for `f - (-g)`. -/
/-- Addition of morphisms in a `non_preadditive_abelian` category. -/
def has_add {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} : Add (X ⟶ Y) :=
{ add := fun (f g : X ⟶ Y) => f - -g }
theorem sub_def {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y)
(b : X ⟶ Y) : a - b = limits.prod.lift a b ≫ σ :=
rfl
theorem add_def {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y)
(b : X ⟶ Y) : a + b = a - -b :=
rfl
theorem neg_def {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) :
-a = 0 - a :=
rfl
theorem sub_zero {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) :
a - 0 = a :=
sorry
theorem sub_self {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) :
a - a = 0 :=
sorry
theorem lift_sub_lift {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C}
(a : X ⟶ Y) (b : X ⟶ Y) (c : X ⟶ Y) (d : X ⟶ Y) :
limits.prod.lift a b - limits.prod.lift c d = limits.prod.lift (a - c) (b - d) :=
sorry
theorem sub_sub_sub {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C}
(a : X ⟶ Y) (b : X ⟶ Y) (c : X ⟶ Y) (d : X ⟶ Y) : a - c - (b - d) = a - b - (c - d) :=
sorry
theorem neg_sub {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y)
(b : X ⟶ Y) : -a - b = -b - a :=
sorry
theorem neg_neg {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) :
--a = a :=
sorry
theorem add_comm {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y)
(b : X ⟶ Y) : a + b = b + a :=
sorry
theorem add_neg {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y)
(b : X ⟶ Y) : a + -b = a - b :=
eq.mpr (id (Eq._oldrec (Eq.refl (a + -b = a - b)) (add_def a (-b))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a - --b = a - b)) (neg_neg b))) (Eq.refl (a - b)))
theorem add_neg_self {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C}
(a : X ⟶ Y) : a + -a = 0 :=
eq.mpr (id (Eq._oldrec (Eq.refl (a + -a = 0)) (add_neg a a)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a - a = 0)) (sub_self a))) (Eq.refl 0))
theorem neg_add_self {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C}
(a : X ⟶ Y) : -a + a = 0 :=
eq.mpr (id (Eq._oldrec (Eq.refl (-a + a = 0)) (add_comm (-a) a)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a + -a = 0)) (add_neg_self a))) (Eq.refl 0))
theorem neg_sub' {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y)
(b : X ⟶ Y) : -(a - b) = -a + b :=
sorry
theorem neg_add {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y)
(b : X ⟶ Y) : -(a + b) = -a - b :=
eq.mpr (id (Eq._oldrec (Eq.refl (-(a + b) = -a - b)) (add_def a b)))
(eq.mpr (id (Eq._oldrec (Eq.refl (-(a - -b) = -a - b)) (neg_sub' a (-b))))
(eq.mpr (id (Eq._oldrec (Eq.refl (-a + -b = -a - b)) (add_neg (-a) b))) (Eq.refl (-a - b))))
theorem sub_add {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y)
(b : X ⟶ Y) (c : X ⟶ Y) : a - b + c = a - (b - c) :=
sorry
theorem add_assoc {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y)
(b : X ⟶ Y) (c : X ⟶ Y) : a + b + c = a + (b + c) :=
sorry
theorem add_zero {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} (a : X ⟶ Y) :
a + 0 = a :=
sorry
theorem comp_sub {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} {Z : C}
(f : X ⟶ Y) (g : Y ⟶ Z) (h : Y ⟶ Z) : f ≫ (g - h) = f ≫ g - f ≫ h :=
sorry
theorem sub_comp {C : Type u} [category C] [non_preadditive_abelian C] {X : C} {Y : C} {Z : C}
(f : X ⟶ Y) (g : X ⟶ Y) (h : Y ⟶ Z) : (f - g) ≫ h = f ≫ h - g ≫ h :=
sorry
theorem comp_add {C : Type u} [category C] [non_preadditive_abelian C] (X : C) (Y : C) (Z : C)
(f : X ⟶ Y) (g : Y ⟶ Z) (h : Y ⟶ Z) : f ≫ (g + h) = f ≫ g + f ≫ h :=
sorry
theorem add_comp {C : Type u} [category C] [non_preadditive_abelian C] (X : C) (Y : C) (Z : C)
(f : X ⟶ Y) (g : X ⟶ Y) (h : Y ⟶ Z) : (f + g) ≫ h = f ≫ h + g ≫ h :=
sorry
/-- Every `non_preadditive_abelian` category is preadditive. -/
def preadditive {C : Type u} [category C] [non_preadditive_abelian C] : preadditive C :=
preadditive.mk
end Mathlib |
ab54c63e5a464086faaa9ec8eb10daa278232930 | 592ee40978ac7604005a4e0d35bbc4b467389241 | /Library/generated/mathscheme-lean/InvolutiveRingoidWithAntiDistrib.lean | b108b6cd17d72d37edfe079ce937eb962626393d | [] | no_license | ysharoda/Deriving-Definitions | 3e149e6641fae440badd35ac110a0bd705a49ad2 | dfecb27572022de3d4aa702cae8db19957523a59 | refs/heads/master | 1,679,127,857,700 | 1,615,939,007,000 | 1,615,939,007,000 | 229,785,731 | 4 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,971 | lean | import init.data.nat.basic
import init.data.fin.basic
import data.vector
import .Prelude
open Staged
open nat
open fin
open vector
section InvolutiveRingoidWithAntiDistrib
structure InvolutiveRingoidWithAntiDistrib (A : Type) : Type :=
(times : (A → (A → A)))
(plus : (A → (A → A)))
(leftDistributive_times_plus : (∀ {x y z : A} , (times x (plus y z)) = (plus (times x y) (times x z))))
(rightDistributive_times_plus : (∀ {x y z : A} , (times (plus y z) x) = (plus (times y x) (times z x))))
(prim : (A → A))
(antidis_prim_plus : (∀ {x y : A} , (prim (plus x y)) = (plus (prim y) (prim x))))
(antidis_prim_times : (∀ {x y : A} , (prim (times x y)) = (times (prim y) (prim x))))
open InvolutiveRingoidWithAntiDistrib
structure Sig (AS : Type) : Type :=
(timesS : (AS → (AS → AS)))
(plusS : (AS → (AS → AS)))
(primS : (AS → AS))
structure Product (A : Type) : Type :=
(timesP : ((Prod A A) → ((Prod A A) → (Prod A A))))
(plusP : ((Prod A A) → ((Prod A A) → (Prod A A))))
(primP : ((Prod A A) → (Prod A A)))
(leftDistributive_times_plusP : (∀ {xP yP zP : (Prod A A)} , (timesP xP (plusP yP zP)) = (plusP (timesP xP yP) (timesP xP zP))))
(rightDistributive_times_plusP : (∀ {xP yP zP : (Prod A A)} , (timesP (plusP yP zP) xP) = (plusP (timesP yP xP) (timesP zP xP))))
(antidis_prim_plusP : (∀ {xP yP : (Prod A A)} , (primP (plusP xP yP)) = (plusP (primP yP) (primP xP))))
(antidis_prim_timesP : (∀ {xP yP : (Prod A A)} , (primP (timesP xP yP)) = (timesP (primP yP) (primP xP))))
structure Hom {A1 : Type} {A2 : Type} (In1 : (InvolutiveRingoidWithAntiDistrib A1)) (In2 : (InvolutiveRingoidWithAntiDistrib A2)) : Type :=
(hom : (A1 → A2))
(pres_times : (∀ {x1 x2 : A1} , (hom ((times In1) x1 x2)) = ((times In2) (hom x1) (hom x2))))
(pres_plus : (∀ {x1 x2 : A1} , (hom ((plus In1) x1 x2)) = ((plus In2) (hom x1) (hom x2))))
(pres_prim : (∀ {x1 : A1} , (hom ((prim In1) x1)) = ((prim In2) (hom x1))))
structure RelInterp {A1 : Type} {A2 : Type} (In1 : (InvolutiveRingoidWithAntiDistrib A1)) (In2 : (InvolutiveRingoidWithAntiDistrib A2)) : Type 1 :=
(interp : (A1 → (A2 → Type)))
(interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times In1) x1 x2) ((times In2) y1 y2))))))
(interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus In1) x1 x2) ((plus In2) y1 y2))))))
(interp_prim : (∀ {x1 : A1} {y1 : A2} , ((interp x1 y1) → (interp ((prim In1) x1) ((prim In2) y1)))))
inductive InvolutiveRingoidWithAntiDistribTerm : Type
| timesL : (InvolutiveRingoidWithAntiDistribTerm → (InvolutiveRingoidWithAntiDistribTerm → InvolutiveRingoidWithAntiDistribTerm))
| plusL : (InvolutiveRingoidWithAntiDistribTerm → (InvolutiveRingoidWithAntiDistribTerm → InvolutiveRingoidWithAntiDistribTerm))
| primL : (InvolutiveRingoidWithAntiDistribTerm → InvolutiveRingoidWithAntiDistribTerm)
open InvolutiveRingoidWithAntiDistribTerm
inductive ClInvolutiveRingoidWithAntiDistribTerm (A : Type) : Type
| sing : (A → ClInvolutiveRingoidWithAntiDistribTerm)
| timesCl : (ClInvolutiveRingoidWithAntiDistribTerm → (ClInvolutiveRingoidWithAntiDistribTerm → ClInvolutiveRingoidWithAntiDistribTerm))
| plusCl : (ClInvolutiveRingoidWithAntiDistribTerm → (ClInvolutiveRingoidWithAntiDistribTerm → ClInvolutiveRingoidWithAntiDistribTerm))
| primCl : (ClInvolutiveRingoidWithAntiDistribTerm → ClInvolutiveRingoidWithAntiDistribTerm)
open ClInvolutiveRingoidWithAntiDistribTerm
inductive OpInvolutiveRingoidWithAntiDistribTerm (n : ℕ) : Type
| v : ((fin n) → OpInvolutiveRingoidWithAntiDistribTerm)
| timesOL : (OpInvolutiveRingoidWithAntiDistribTerm → (OpInvolutiveRingoidWithAntiDistribTerm → OpInvolutiveRingoidWithAntiDistribTerm))
| plusOL : (OpInvolutiveRingoidWithAntiDistribTerm → (OpInvolutiveRingoidWithAntiDistribTerm → OpInvolutiveRingoidWithAntiDistribTerm))
| primOL : (OpInvolutiveRingoidWithAntiDistribTerm → OpInvolutiveRingoidWithAntiDistribTerm)
open OpInvolutiveRingoidWithAntiDistribTerm
inductive OpInvolutiveRingoidWithAntiDistribTerm2 (n : ℕ) (A : Type) : Type
| v2 : ((fin n) → OpInvolutiveRingoidWithAntiDistribTerm2)
| sing2 : (A → OpInvolutiveRingoidWithAntiDistribTerm2)
| timesOL2 : (OpInvolutiveRingoidWithAntiDistribTerm2 → (OpInvolutiveRingoidWithAntiDistribTerm2 → OpInvolutiveRingoidWithAntiDistribTerm2))
| plusOL2 : (OpInvolutiveRingoidWithAntiDistribTerm2 → (OpInvolutiveRingoidWithAntiDistribTerm2 → OpInvolutiveRingoidWithAntiDistribTerm2))
| primOL2 : (OpInvolutiveRingoidWithAntiDistribTerm2 → OpInvolutiveRingoidWithAntiDistribTerm2)
open OpInvolutiveRingoidWithAntiDistribTerm2
def simplifyCl {A : Type} : ((ClInvolutiveRingoidWithAntiDistribTerm A) → (ClInvolutiveRingoidWithAntiDistribTerm A))
| (plusCl (primCl y) (primCl x)) := (primCl (plusCl x y))
| (timesCl (primCl y) (primCl x)) := (primCl (timesCl x y))
| (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2))
| (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2))
| (primCl x1) := (primCl (simplifyCl x1))
| (sing x1) := (sing x1)
def simplifyOpB {n : ℕ} : ((OpInvolutiveRingoidWithAntiDistribTerm n) → (OpInvolutiveRingoidWithAntiDistribTerm n))
| (plusOL (primOL y) (primOL x)) := (primOL (plusOL x y))
| (timesOL (primOL y) (primOL x)) := (primOL (timesOL x y))
| (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2))
| (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2))
| (primOL x1) := (primOL (simplifyOpB x1))
| (v x1) := (v x1)
def simplifyOp {n : ℕ} {A : Type} : ((OpInvolutiveRingoidWithAntiDistribTerm2 n A) → (OpInvolutiveRingoidWithAntiDistribTerm2 n A))
| (plusOL2 (primOL2 y) (primOL2 x)) := (primOL2 (plusOL2 x y))
| (timesOL2 (primOL2 y) (primOL2 x)) := (primOL2 (timesOL2 x y))
| (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2))
| (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2))
| (primOL2 x1) := (primOL2 (simplifyOp x1))
| (v2 x1) := (v2 x1)
| (sing2 x1) := (sing2 x1)
def evalB {A : Type} : ((InvolutiveRingoidWithAntiDistrib A) → (InvolutiveRingoidWithAntiDistribTerm → A))
| In (timesL x1 x2) := ((times In) (evalB In x1) (evalB In x2))
| In (plusL x1 x2) := ((plus In) (evalB In x1) (evalB In x2))
| In (primL x1) := ((prim In) (evalB In x1))
def evalCl {A : Type} : ((InvolutiveRingoidWithAntiDistrib A) → ((ClInvolutiveRingoidWithAntiDistribTerm A) → A))
| In (sing x1) := x1
| In (timesCl x1 x2) := ((times In) (evalCl In x1) (evalCl In x2))
| In (plusCl x1 x2) := ((plus In) (evalCl In x1) (evalCl In x2))
| In (primCl x1) := ((prim In) (evalCl In x1))
def evalOpB {A : Type} {n : ℕ} : ((InvolutiveRingoidWithAntiDistrib A) → ((vector A n) → ((OpInvolutiveRingoidWithAntiDistribTerm n) → A)))
| In vars (v x1) := (nth vars x1)
| In vars (timesOL x1 x2) := ((times In) (evalOpB In vars x1) (evalOpB In vars x2))
| In vars (plusOL x1 x2) := ((plus In) (evalOpB In vars x1) (evalOpB In vars x2))
| In vars (primOL x1) := ((prim In) (evalOpB In vars x1))
def evalOp {A : Type} {n : ℕ} : ((InvolutiveRingoidWithAntiDistrib A) → ((vector A n) → ((OpInvolutiveRingoidWithAntiDistribTerm2 n A) → A)))
| In vars (v2 x1) := (nth vars x1)
| In vars (sing2 x1) := x1
| In vars (timesOL2 x1 x2) := ((times In) (evalOp In vars x1) (evalOp In vars x2))
| In vars (plusOL2 x1 x2) := ((plus In) (evalOp In vars x1) (evalOp In vars x2))
| In vars (primOL2 x1) := ((prim In) (evalOp In vars x1))
def inductionB {P : (InvolutiveRingoidWithAntiDistribTerm → Type)} : ((∀ (x1 x2 : InvolutiveRingoidWithAntiDistribTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → ((∀ (x1 x2 : InvolutiveRingoidWithAntiDistribTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → ((∀ (x1 : InvolutiveRingoidWithAntiDistribTerm) , ((P x1) → (P (primL x1)))) → (∀ (x : InvolutiveRingoidWithAntiDistribTerm) , (P x)))))
| ptimesl pplusl ppriml (timesL x1 x2) := (ptimesl _ _ (inductionB ptimesl pplusl ppriml x1) (inductionB ptimesl pplusl ppriml x2))
| ptimesl pplusl ppriml (plusL x1 x2) := (pplusl _ _ (inductionB ptimesl pplusl ppriml x1) (inductionB ptimesl pplusl ppriml x2))
| ptimesl pplusl ppriml (primL x1) := (ppriml _ (inductionB ptimesl pplusl ppriml x1))
def inductionCl {A : Type} {P : ((ClInvolutiveRingoidWithAntiDistribTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClInvolutiveRingoidWithAntiDistribTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → ((∀ (x1 x2 : (ClInvolutiveRingoidWithAntiDistribTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → ((∀ (x1 : (ClInvolutiveRingoidWithAntiDistribTerm A)) , ((P x1) → (P (primCl x1)))) → (∀ (x : (ClInvolutiveRingoidWithAntiDistribTerm A)) , (P x))))))
| psing ptimescl ppluscl pprimcl (sing x1) := (psing x1)
| psing ptimescl ppluscl pprimcl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing ptimescl ppluscl pprimcl x1) (inductionCl psing ptimescl ppluscl pprimcl x2))
| psing ptimescl ppluscl pprimcl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing ptimescl ppluscl pprimcl x1) (inductionCl psing ptimescl ppluscl pprimcl x2))
| psing ptimescl ppluscl pprimcl (primCl x1) := (pprimcl _ (inductionCl psing ptimescl ppluscl pprimcl x1))
def inductionOpB {n : ℕ} {P : ((OpInvolutiveRingoidWithAntiDistribTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpInvolutiveRingoidWithAntiDistribTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → ((∀ (x1 x2 : (OpInvolutiveRingoidWithAntiDistribTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → ((∀ (x1 : (OpInvolutiveRingoidWithAntiDistribTerm n)) , ((P x1) → (P (primOL x1)))) → (∀ (x : (OpInvolutiveRingoidWithAntiDistribTerm n)) , (P x))))))
| pv ptimesol pplusol pprimol (v x1) := (pv x1)
| pv ptimesol pplusol pprimol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv ptimesol pplusol pprimol x1) (inductionOpB pv ptimesol pplusol pprimol x2))
| pv ptimesol pplusol pprimol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv ptimesol pplusol pprimol x1) (inductionOpB pv ptimesol pplusol pprimol x2))
| pv ptimesol pplusol pprimol (primOL x1) := (pprimol _ (inductionOpB pv ptimesol pplusol pprimol x1))
def inductionOp {n : ℕ} {A : Type} {P : ((OpInvolutiveRingoidWithAntiDistribTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpInvolutiveRingoidWithAntiDistribTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → ((∀ (x1 x2 : (OpInvolutiveRingoidWithAntiDistribTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → ((∀ (x1 : (OpInvolutiveRingoidWithAntiDistribTerm2 n A)) , ((P x1) → (P (primOL2 x1)))) → (∀ (x : (OpInvolutiveRingoidWithAntiDistribTerm2 n A)) , (P x)))))))
| pv2 psing2 ptimesol2 pplusol2 pprimol2 (v2 x1) := (pv2 x1)
| pv2 psing2 ptimesol2 pplusol2 pprimol2 (sing2 x1) := (psing2 x1)
| pv2 psing2 ptimesol2 pplusol2 pprimol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 pprimol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 pprimol2 x2))
| pv2 psing2 ptimesol2 pplusol2 pprimol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 pprimol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 pprimol2 x2))
| pv2 psing2 ptimesol2 pplusol2 pprimol2 (primOL2 x1) := (pprimol2 _ (inductionOp pv2 psing2 ptimesol2 pplusol2 pprimol2 x1))
def stageB : (InvolutiveRingoidWithAntiDistribTerm → (Staged InvolutiveRingoidWithAntiDistribTerm))
| (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2))
| (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2))
| (primL x1) := (stage1 primL (codeLift1 primL) (stageB x1))
def stageCl {A : Type} : ((ClInvolutiveRingoidWithAntiDistribTerm A) → (Staged (ClInvolutiveRingoidWithAntiDistribTerm A)))
| (sing x1) := (Now (sing x1))
| (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2))
| (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2))
| (primCl x1) := (stage1 primCl (codeLift1 primCl) (stageCl x1))
def stageOpB {n : ℕ} : ((OpInvolutiveRingoidWithAntiDistribTerm n) → (Staged (OpInvolutiveRingoidWithAntiDistribTerm n)))
| (v x1) := (const (code (v x1)))
| (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2))
| (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2))
| (primOL x1) := (stage1 primOL (codeLift1 primOL) (stageOpB x1))
def stageOp {n : ℕ} {A : Type} : ((OpInvolutiveRingoidWithAntiDistribTerm2 n A) → (Staged (OpInvolutiveRingoidWithAntiDistribTerm2 n A)))
| (sing2 x1) := (Now (sing2 x1))
| (v2 x1) := (const (code (v2 x1)))
| (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2))
| (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2))
| (primOL2 x1) := (stage1 primOL2 (codeLift1 primOL2) (stageOp x1))
structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type :=
(timesT : ((Repr A) → ((Repr A) → (Repr A))))
(plusT : ((Repr A) → ((Repr A) → (Repr A))))
(primT : ((Repr A) → (Repr A)))
end InvolutiveRingoidWithAntiDistrib |
db5ea86f8410765a31279db22f3fe302668dc4ef | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Compiler/IR/ExpandResetReuse.lean | aab8af752ca874015893c7d12f5ae2533c153f76 | [
"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 | 9,851 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Compiler.IR.CompilerM
import Lean.Compiler.IR.NormIds
import Lean.Compiler.IR.FreeVars
namespace Lean.IR.ExpandResetReuse
/-- Mapping from variable to projections -/
abbrev ProjMap := HashMap VarId Expr
namespace CollectProjMap
abbrev Collector := ProjMap → ProjMap
@[inline] def collectVDecl (x : VarId) (v : Expr) : Collector := fun m =>
match v with
| .proj .. => m.insert x v
| .sproj .. => m.insert x v
| .uproj .. => m.insert x v
| _ => m
partial def collectFnBody : FnBody → Collector
| .vdecl x _ v b => collectVDecl x v ∘ collectFnBody b
| .jdecl _ _ v b => collectFnBody v ∘ collectFnBody b
| .case _ _ _ alts => fun s => alts.foldl (fun s alt => collectFnBody alt.body s) s
| e => if e.isTerminal then id else collectFnBody e.body
end CollectProjMap
/-- Create a mapping from variables to projections.
This function assumes variable ids have been normalized -/
def mkProjMap (d : Decl) : ProjMap :=
match d with
| .fdecl (body := b) .. => CollectProjMap.collectFnBody b {}
| _ => {}
structure Context where
projMap : ProjMap
/-- Return true iff `x` is consumed in all branches of the current block.
Here consumption means the block contains a `dec x` or `reuse x ...`. -/
partial def consumed (x : VarId) : FnBody → Bool
| .vdecl _ _ v b =>
match v with
| Expr.reuse y _ _ _ => x == y || consumed x b
| _ => consumed x b
| .dec y _ _ _ b => x == y || consumed x b
| .case _ _ _ alts => alts.all fun alt => consumed x alt.body
| e => !e.isTerminal && consumed x e.body
abbrev Mask := Array (Option VarId)
/-- Auxiliary function for eraseProjIncFor -/
partial def eraseProjIncForAux (y : VarId) (bs : Array FnBody) (mask : Mask) (keep : Array FnBody) : Array FnBody × Mask :=
let done (_ : Unit) := (bs ++ keep.reverse, mask)
let keepInstr (b : FnBody) := eraseProjIncForAux y bs.pop mask (keep.push b)
if bs.size < 2 then done ()
else
let b := bs.back
match b with
| .vdecl _ _ (.sproj _ _ _) _ => keepInstr b
| .vdecl _ _ (.uproj _ _) _ => keepInstr b
| .inc z n c p _ =>
if n == 0 then done () else
let b' := bs[bs.size - 2]!
match b' with
| .vdecl w _ (.proj i x) _ =>
if w == z && y == x then
/- Found
```
let z := proj[i] y
inc z n c
```
We keep `proj`, and `inc` when `n > 1`
-/
let bs := bs.pop.pop
let mask := mask.set! i (some z)
let keep := keep.push b'
let keep := if n == 1 then keep else keep.push (FnBody.inc z (n-1) c p FnBody.nil)
eraseProjIncForAux y bs mask keep
else done ()
| _ => done ()
| _ => done ()
/-- Try to erase `inc` instructions on projections of `y` occurring in the tail of `bs`.
Return the updated `bs` and a bit mask specifying which `inc`s have been removed. -/
def eraseProjIncFor (n : Nat) (y : VarId) (bs : Array FnBody) : Array FnBody × Mask :=
eraseProjIncForAux y bs (mkArray n none) #[]
/-- Replace `reuse x ctor ...` with `ctor ...`, and remoce `dec x` -/
partial def reuseToCtor (x : VarId) : FnBody → FnBody
| FnBody.dec y n c p b =>
if x == y then b -- n must be 1 since `x := reset ...`
else FnBody.dec y n c p (reuseToCtor x b)
| FnBody.vdecl z t v b =>
match v with
| Expr.reuse y c _ xs =>
if x == y then FnBody.vdecl z t (Expr.ctor c xs) b
else FnBody.vdecl z t v (reuseToCtor x b)
| _ =>
FnBody.vdecl z t v (reuseToCtor x b)
| FnBody.case tid y yType alts =>
let alts := alts.map fun alt => alt.modifyBody (reuseToCtor x)
FnBody.case tid y yType alts
| e =>
if e.isTerminal then
e
else
let (instr, b) := e.split
let b := reuseToCtor x b
instr.setBody b
/--
replace
```
x := reset y; b
```
with
```
inc z_1; ...; inc z_i; dec y; b'
```
where `z_i`'s are the variables in `mask`,
and `b'` is `b` where we removed `dec x` and replaced `reuse x ctor_i ...` with `ctor_i ...`.
-/
def mkSlowPath (x y : VarId) (mask : Mask) (b : FnBody) : FnBody :=
let b := reuseToCtor x b
let b := FnBody.dec y 1 true false b
mask.foldl (init := b) fun b m => match m with
| some z => FnBody.inc z 1 true false b
| none => b
abbrev M := ReaderT Context (StateM Nat)
def mkFresh : M VarId :=
modifyGet fun n => ({ idx := n }, n + 1)
def releaseUnreadFields (y : VarId) (mask : Mask) (b : FnBody) : M FnBody :=
mask.size.foldM (init := b) fun i b =>
match mask.get! i with
| some _ => pure b -- code took ownership of this field
| none => do
let fld ← mkFresh
pure (FnBody.vdecl fld IRType.object (Expr.proj i y) (FnBody.dec fld 1 true false b))
def setFields (y : VarId) (zs : Array Arg) (b : FnBody) : FnBody :=
zs.size.fold (init := b) fun i b => FnBody.set y i (zs.get! i) b
/-- Given `set x[i] := y`, return true iff `y := proj[i] x` -/
def isSelfSet (ctx : Context) (x : VarId) (i : Nat) (y : Arg) : Bool :=
match y with
| Arg.var y =>
match ctx.projMap.find? y with
| some (Expr.proj j w) => j == i && w == x
| _ => false
| _ => false
/-- Given `uset x[i] := y`, return true iff `y := uproj[i] x` -/
def isSelfUSet (ctx : Context) (x : VarId) (i : Nat) (y : VarId) : Bool :=
match ctx.projMap.find? y with
| some (Expr.uproj j w) => j == i && w == x
| _ => false
/-- Given `sset x[n, i] := y`, return true iff `y := sproj[n, i] x` -/
def isSelfSSet (ctx : Context) (x : VarId) (n : Nat) (i : Nat) (y : VarId) : Bool :=
match ctx.projMap.find? y with
| some (Expr.sproj m j w) => n == m && j == i && w == x
| _ => false
/-- Remove unnecessary `set/uset/sset` operations -/
partial def removeSelfSet (ctx : Context) : FnBody → FnBody
| FnBody.set x i y b =>
if isSelfSet ctx x i y then removeSelfSet ctx b
else FnBody.set x i y (removeSelfSet ctx b)
| FnBody.uset x i y b =>
if isSelfUSet ctx x i y then removeSelfSet ctx b
else FnBody.uset x i y (removeSelfSet ctx b)
| FnBody.sset x n i y t b =>
if isSelfSSet ctx x n i y then removeSelfSet ctx b
else FnBody.sset x n i y t (removeSelfSet ctx b)
| FnBody.case tid y yType alts =>
let alts := alts.map fun alt => alt.modifyBody (removeSelfSet ctx)
FnBody.case tid y yType alts
| e =>
if e.isTerminal then e
else
let (instr, b) := e.split
let b := removeSelfSet ctx b
instr.setBody b
partial def reuseToSet (ctx : Context) (x y : VarId) : FnBody → FnBody
| FnBody.dec z n c p b =>
if x == z then FnBody.del y b
else FnBody.dec z n c p (reuseToSet ctx x y b)
| FnBody.vdecl z t v b =>
match v with
| Expr.reuse w c u zs =>
if x == w then
let b := setFields y zs (b.replaceVar z y)
let b := if u then FnBody.setTag y c.cidx b else b
removeSelfSet ctx b
else FnBody.vdecl z t v (reuseToSet ctx x y b)
| _ => FnBody.vdecl z t v (reuseToSet ctx x y b)
| FnBody.case tid z zType alts =>
let alts := alts.map fun alt => alt.modifyBody (reuseToSet ctx x y)
FnBody.case tid z zType alts
| e =>
if e.isTerminal then e
else
let (instr, b) := e.split
let b := reuseToSet ctx x y b
instr.setBody b
/--
replace
```
x := reset y; b
```
with
```
let f_i_1 := proj[i_1] y;
...
let f_i_k := proj[i_k] y;
b'
```
where `i_j`s are the field indexes
that the code did not touch immediately before the reset.
That is `mask[j] == none`.
`b'` is `b` where `y` `dec x` is replaced with `del y`,
and `z := reuse x ctor_i ws; F` is replaced with
`set x i ws[i]` operations, and we replace `z` with `x` in `F`
-/
def mkFastPath (x y : VarId) (mask : Mask) (b : FnBody) : M FnBody := do
let ctx ← read
let b := reuseToSet ctx x y b
releaseUnreadFields y mask b
-- Expand `bs; x := reset[n] y; b`
partial def expand (mainFn : FnBody → Array FnBody → M FnBody)
(bs : Array FnBody) (x : VarId) (n : Nat) (y : VarId) (b : FnBody) : M FnBody := do
let (bs, mask) := eraseProjIncFor n y bs
/- Remark: we may be duplicting variable/JP indices. That is, `bSlow` and `bFast` may
have duplicate indices. We run `normalizeIds` to fix the ids after we have expand them. -/
let bSlow := mkSlowPath x y mask b
let bFast ← mkFastPath x y mask b
/- We only optimize recursively the fast. -/
let bFast ← mainFn bFast #[]
let c ← mkFresh
let b := FnBody.vdecl c IRType.uint8 (Expr.isShared y) (mkIf c bSlow bFast)
return reshape bs b
partial def searchAndExpand : FnBody → Array FnBody → M FnBody
| d@(FnBody.vdecl x _ (Expr.reset n y) b), bs =>
if consumed x b then do
expand searchAndExpand bs x n y b
else
searchAndExpand b (push bs d)
| FnBody.jdecl j xs v b, bs => do
let v ← searchAndExpand v #[]
searchAndExpand b (push bs (FnBody.jdecl j xs v FnBody.nil))
| FnBody.case tid x xType alts, bs => do
let alts ← alts.mapM fun alt => alt.mmodifyBody fun b => searchAndExpand b #[]
return reshape bs (FnBody.case tid x xType alts)
| b, bs =>
if b.isTerminal then return reshape bs b
else searchAndExpand b.body (push bs b)
def main (d : Decl) : Decl :=
match d with
| .fdecl (body := b) .. =>
let m := mkProjMap d
let nextIdx := d.maxIndex + 1
let bNew := (searchAndExpand b #[] { projMap := m }).run' nextIdx
d.updateBody! bNew
| d => d
end ExpandResetReuse
/-- (Try to) expand `reset` and `reuse` instructions. -/
def Decl.expandResetReuse (d : Decl) : Decl :=
(ExpandResetReuse.main d).normalizeIds
end Lean.IR
|
8feca753bd5af95943d18f59e52a470ec7602f73 | d642a6b1261b2cbe691e53561ac777b924751b63 | /src/topology/subset_properties.lean | f02b47111ad37781ea59ffc23d3d63e10c0d8405 | [
"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 | 31,139 | 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
Properties of subsets of topological spaces: compact, clopen, irreducible,
connected, totally disconnected, totally separated.
-/
import topology.constructions
open set filter lattice classical
open_locale classical
universes u v
variables {α : Type u} {β : Type v} [topological_space α]
/- compact sets -/
section compact
/-- A set `s` is compact if for every filter `f` that contains `s`,
every set of `f` also meets every neighborhood of some `a ∈ s`. -/
def compact (s : set α) := ∀f, f ≠ ⊥ → f ≤ principal s → ∃a∈s, f ⊓ nhds a ≠ ⊥
lemma compact_inter {s t : set α} (hs : compact s) (ht : is_closed t) : compact (s ∩ t) :=
assume f hnf hstf,
let ⟨a, hsa, (ha : f ⊓ nhds a ≠ ⊥)⟩ := hs f hnf (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))) in
have ∀a, principal t ⊓ nhds a ≠ ⊥ → a ∈ t,
by intro a; rw [inf_comm]; rw [is_closed_iff_nhds] at ht; exact ht a,
have a ∈ t,
from this a $ neq_bot_of_le_neq_bot ha $ inf_le_inf (le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))) (le_refl _),
⟨a, ⟨hsa, this⟩, ha⟩
lemma compact_diff {s t : set α} (hs : compact s) (ht : is_open t) : compact (s \ t) :=
compact_inter hs (is_closed_compl_iff.mpr ht)
lemma compact_of_is_closed_subset {s t : set α}
(hs : compact s) (ht : is_closed t) (h : t ⊆ s) : compact t :=
by convert ← compact_inter hs ht; exact inter_eq_self_of_subset_right h
lemma compact_adherence_nhdset {s t : set α} {f : filter α}
(hs : compact s) (hf₂ : f ≤ principal s) (ht₁ : is_open t) (ht₂ : ∀a∈s, nhds a ⊓ f ≠ ⊥ → a ∈ t) :
t ∈ f :=
classical.by_cases mem_sets_of_neq_bot $
assume : f ⊓ principal (- t) ≠ ⊥,
let ⟨a, ha, (hfa : f ⊓ principal (-t) ⊓ nhds a ≠ ⊥)⟩ := hs _ this $ inf_le_left_of_le hf₂ in
have a ∈ t,
from ht₂ a ha $ neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_left,
have nhds a ⊓ principal (-t) ≠ ⊥,
from neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_right,
have ∀s∈(nhds a ⊓ principal (-t)).sets, s ≠ ∅,
from forall_sets_neq_empty_iff_neq_bot.mpr this,
have false,
from this _ ⟨t, mem_nhds_sets ht₁ ‹a ∈ t›, -t, subset.refl _, subset.refl _⟩ (inter_compl_self _),
by contradiction
lemma compact_iff_ultrafilter_le_nhds {s : set α} :
compact s ↔ (∀f, is_ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ nhds a) :=
⟨assume hs : compact s, assume f hf hfs,
let ⟨a, ha, h⟩ := hs _ hf.left hfs in
⟨a, ha, le_of_ultrafilter hf h⟩,
assume hs : (∀f, is_ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ nhds a),
assume f hf hfs,
let ⟨a, ha, (h : ultrafilter_of f ≤ nhds a)⟩ :=
hs (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs) in
have ultrafilter_of f ⊓ nhds a ≠ ⊥,
by simp only [inf_of_le_left, h]; exact (ultrafilter_ultrafilter_of hf).left,
⟨a, ha, neq_bot_of_le_neq_bot this (inf_le_inf ultrafilter_of_le (le_refl _))⟩⟩
lemma compact_elim_finite_subcover {s : set α} {c : set (set α)}
(hs : compact s) (hc₁ : ∀t∈c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c' :=
classical.by_contradiction $ assume h,
have h : ∀{c'}, c' ⊆ c → finite c' → ¬ s ⊆ ⋃₀ c',
from assume c' h₁ h₂ h₃, h ⟨c', h₁, h₂, h₃⟩,
let
f : filter α := (⨅c':{c' : set (set α) // c' ⊆ c ∧ finite c'}, principal (s - ⋃₀ c')),
⟨a, ha⟩ := @exists_mem_of_ne_empty α s
(assume h', h (empty_subset _) finite_empty $ h'.symm ▸ empty_subset _)
in
have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩
(assume ⟨c₁, hc₁, hc'₁⟩ ⟨c₂, hc₂, hc'₂⟩, ⟨⟨c₁ ∪ c₂, union_subset hc₁ hc₂, finite_union hc'₁ hc'₂⟩,
principal_mono.mpr $ diff_subset_diff_right $ sUnion_mono $ subset_union_left _ _,
principal_mono.mpr $ diff_subset_diff_right $ sUnion_mono $ subset_union_right _ _⟩)
(assume ⟨c', hc'₁, hc'₂⟩, show principal (s \ _) ≠ ⊥, by simp only [ne.def, principal_eq_bot_iff, diff_eq_empty]; exact h hc'₁ hc'₂),
have f ≤ principal s, from infi_le_of_le ⟨∅, empty_subset _, finite_empty⟩ $
show principal (s \ ⋃₀∅) ≤ principal s, from le_principal_iff.2 (diff_subset _ _),
let
⟨a, ha, (h : f ⊓ nhds a ≠ ⊥)⟩ := hs f ‹f ≠ ⊥› this,
⟨t, ht₁, (ht₂ : a ∈ t)⟩ := hc₂ ha
in
have f ≤ principal (-t),
from infi_le_of_le ⟨{t}, by rwa singleton_subset_iff, finite_insert _ finite_empty⟩ $
principal_mono.mpr $
show s - ⋃₀{t} ⊆ - t, begin rw sUnion_singleton; exact assume x ⟨_, hnt⟩, hnt end,
have is_closed (- t), from is_open_compl_iff.mp $ by rw lattice.neg_neg; exact hc₁ t ht₁,
have a ∈ - t, from is_closed_iff_nhds.mp this _ $ neq_bot_of_le_neq_bot h $
le_inf inf_le_right (inf_le_left_of_le ‹f ≤ principal (- t)›),
this ‹a ∈ t›
lemma compact_elim_finite_subcover_image {s : set α} {b : set β} {c : β → set α}
(hs : compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) :
∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i :=
if h : b = ∅ then ⟨∅, empty_subset _, finite_empty, h ▸ hc₂⟩ else
let ⟨i, hi⟩ := exists_mem_of_ne_empty h in
have hc'₁ : ∀i∈c '' b, is_open i, from assume i ⟨j, hj, h⟩, h ▸ hc₁ _ hj,
have hc'₂ : s ⊆ ⋃₀ (c '' b), by rwa set.sUnion_image,
let ⟨d, hd₁, hd₂, hd₃⟩ := compact_elim_finite_subcover hs hc'₁ hc'₂ in
have ∀x : d, ∃i, i ∈ b ∧ c i = x, from assume ⟨x, hx⟩, hd₁ hx,
let ⟨f', hf⟩ := axiom_of_choice this,
f := λx:set α, (if h : x ∈ d then f' ⟨x, h⟩ else i : β) in
have ∀(x : α) (i : set α), i ∈ d → x ∈ i → (∃ (i : β), i ∈ f '' d ∧ x ∈ c i),
from assume x i hid hxi, ⟨f i, mem_image_of_mem f hid,
by simpa only [f, dif_pos hid, (hf ⟨_, hid⟩).2] using hxi⟩,
⟨f '' d,
assume i ⟨j, hj, h⟩,
h ▸ by simpa only [f, dif_pos hj] using (hf ⟨_, hj⟩).1,
finite_image f hd₂,
subset.trans hd₃ $ by simpa only [subset_def, mem_sUnion, exists_imp_distrib, mem_Union, exists_prop, and_imp]⟩
section
-- this proof times out without this
local attribute [instance, priority 1000] classical.prop_decidable
lemma compact_of_finite_subcover {s : set α}
(h : ∀c, (∀t∈c, is_open t) → s ⊆ ⋃₀ c → ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c') : compact s :=
assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, f ⊓ nhds x ≠ ⊥),
have hf : ∀x∈s, nhds x ⊓ f = ⊥,
by simpa only [not_exists, not_not, inf_comm],
have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t,
from assume ⟨x, hxs, hx⟩,
have ∅ ∈ nhds x ⊓ f, by rw [empty_in_sets_eq_bot, hf x hxs],
let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in
have ∅ ∈ nhds x ⊓ principal t₂,
from (nhds x ⊓ principal t₂).sets_of_superset (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht,
have nhds x ⊓ principal t₂ = ⊥,
by rwa [empty_in_sets_eq_bot] at this,
by simp only [closure_eq_nhds] at hx; exact hx t₂ ht₂ this,
have ∀x∈s, ∃t∈f.sets, x ∉ closure t, by simpa only [not_exists, not_forall],
let c := (λt, - closure t) '' f.sets, ⟨c', hcc', hcf, hsc'⟩ := h c
(assume t ⟨s, hs, h⟩, h ▸ is_closed_closure) (by simpa only [subset_def, sUnion_image, mem_Union]) in
let ⟨b, hb⟩ := axiom_of_choice $
show ∀s:c', ∃t, t ∈ f ∧ - closure t = s,
from assume ⟨x, hx⟩, hcc' hx in
have (⋂s∈c', if h : s ∈ c' then b ⟨s, h⟩ else univ) ∈ f,
from Inter_mem_sets hcf $ assume t ht, by rw [dif_pos ht]; exact (hb ⟨t, ht⟩).left,
have s ∩ (⋂s∈c', if h : s ∈ c' then b ⟨s, h⟩ else univ) ∈ f,
from inter_mem_sets (le_principal_iff.1 hfs) this,
have ∅ ∈ f,
from mem_sets_of_superset this $ assume x ⟨hxs, hxi⟩,
let ⟨t, htc', hxt⟩ := (show ∃t ∈ c', x ∈ t, from hsc' hxs) in
have -closure (b ⟨t, htc'⟩) = t, from (hb _).right,
have x ∈ - t,
from this ▸ (calc x ∈ b ⟨t, htc'⟩ : by rw mem_bInter_iff at hxi; have h := hxi t htc'; rwa [dif_pos htc'] at h
... ⊆ closure (b ⟨t, htc'⟩) : subset_closure
... ⊆ - - closure (b ⟨t, htc'⟩) : by rw lattice.neg_neg; exact subset.refl _),
show false, from this hxt,
hfn $ by rwa [empty_in_sets_eq_bot] at this
end
lemma compact_iff_finite_subcover {s : set α} :
compact s ↔ (∀c, (∀t∈c, is_open t) → s ⊆ ⋃₀ c → ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c') :=
⟨assume hc c, compact_elim_finite_subcover hc, compact_of_finite_subcover⟩
lemma compact_empty : compact (∅ : set α) :=
assume f hnf hsf, not.elim hnf $
empty_in_sets_eq_bot.1 $ le_principal_iff.1 hsf
lemma compact_singleton {a : α} : compact ({a} : set α) :=
compact_of_finite_subcover $ assume c hc₁ hc₂,
let ⟨i, hic, hai⟩ := (show ∃i ∈ c, a ∈ i, from mem_sUnion.1 $ singleton_subset_iff.1 hc₂) in
⟨{i}, singleton_subset_iff.2 hic, finite_singleton _, by rwa [sUnion_singleton, singleton_subset_iff]⟩
lemma compact_bUnion_of_compact {s : set β} {f : β → set α} (hs : finite s) :
(∀i ∈ s, compact (f i)) → compact (⋃i ∈ s, f i) :=
assume hf, compact_of_finite_subcover $ assume c c_open c_cover,
have ∀i : subtype s, ∃c' ⊆ c, finite c' ∧ f i ⊆ ⋃₀ c', from
assume ⟨i, hi⟩, compact_elim_finite_subcover (hf i hi) c_open
(calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi
... ⊆ ⋃₀ c : c_cover),
let ⟨finite_subcovers, h⟩ := axiom_of_choice this in
let c' := ⋃i, finite_subcovers i in
have c' ⊆ c, from Union_subset (λi, (h i).fst),
have finite c', from @finite_Union _ _ hs.fintype _ (λi, (h i).snd.1),
have (⋃i ∈ s, f i) ⊆ ⋃₀ c', from bUnion_subset $ λi hi, calc
f i ⊆ ⋃₀ finite_subcovers ⟨i,hi⟩ : (h ⟨i,hi⟩).snd.2
... ⊆ ⋃₀ c' : sUnion_mono (subset_Union _ _),
⟨c', ‹c' ⊆ c›, ‹finite c'›, this⟩
lemma compact_Union_of_compact {f : β → set α} [fintype β]
(h : ∀i, compact (f i)) : compact (⋃i, f i) :=
by rw ← bUnion_univ; exact compact_bUnion_of_compact finite_univ (λ i _, h i)
lemma compact_of_finite {s : set α} (hs : finite s) : compact s :=
bUnion_of_singleton s ▸ compact_bUnion_of_compact hs (λ _ _, compact_singleton)
lemma compact_union_of_compact {s t : set α} (hs : compact s) (ht : compact t) : compact (s ∪ t) :=
by rw union_eq_Union; exact compact_Union_of_compact (λ b, by cases b; assumption)
section tube_lemma
variables [topological_space β]
def nhds_contain_boxes (s : set α) (t : set β) : Prop :=
∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n),
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n
lemma nhds_contain_boxes.symm {s : set α} {t : set β} :
nhds_contain_boxes s t → nhds_contain_boxes t s :=
assume H n hn hp,
let ⟨u, v, uo, vo, su, tv, p⟩ :=
H (prod.swap ⁻¹' n)
(continuous_swap n hn)
(by rwa [←image_subset_iff, prod.swap, image_swap_prod]) in
⟨v, u, vo, uo, tv, su,
by rwa [←image_subset_iff, prod.swap, image_swap_prod] at p⟩
lemma nhds_contain_boxes.comm {s : set α} {t : set β} :
nhds_contain_boxes s t ↔ nhds_contain_boxes t s :=
iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm
lemma nhds_contain_boxes_of_singleton {x : α} {y : β} :
nhds_contain_boxes ({x} : set α) ({y} : set β) :=
assume n hn hp,
let ⟨u, v, uo, vo, xu, yv, hp'⟩ :=
is_open_prod_iff.mp hn x y (hp $ by simp) in
⟨u, v, uo, vo, by simpa, by simpa, hp'⟩
lemma nhds_contain_boxes_of_compact {s : set α} (hs : compact s) (t : set β)
(H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t :=
assume n hn hp,
have ∀x : subtype s, ∃uv : set α × set β,
is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n,
from assume ⟨x, hx⟩,
have set.prod {x} t ⊆ n, from
subset.trans (prod_mono (by simpa) (subset.refl _)) hp,
let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩,
let ⟨uvs, h⟩ := classical.axiom_of_choice this in
have us_cover : s ⊆ ⋃i, (uvs i).1, from
assume x hx, set.subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1),
let ⟨s0, _, s0_fin, s0_cover⟩ :=
compact_elim_finite_subcover_image hs (λi _, (h i).1) $
by rw bUnion_univ; exact us_cover in
let u := ⋃(i ∈ s0), (uvs i).1 in
let v := ⋂(i ∈ s0), (uvs i).2 in
have is_open u, from is_open_bUnion (λi _, (h i).1),
have is_open v, from is_open_bInter s0_fin (λi _, (h i).2.1),
have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1),
have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩,
have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx',
let ⟨i,is0,hi⟩ := this in
(h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩,
⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩
lemma generalized_tube_lemma {s : set α} (hs : compact s) {t : set β} (ht : compact t)
{n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) :
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n :=
have _, from
nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $
nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton,
this n hn hp
end tube_lemma
/-- Type class for compact spaces. Separation is sometimes included in the definition, especially
in the French literature, but we do not include it here. -/
class compact_space (α : Type*) [topological_space α] : Prop :=
(compact_univ : compact (univ : set α))
lemma compact_univ [h : compact_space α] : compact (univ : set α) := h.compact_univ
lemma compact_of_closed [compact_space α] {s : set α} (h : is_closed s) :
compact s :=
compact_of_is_closed_subset compact_univ h (subset_univ _)
variables [topological_space β]
lemma compact_image {s : set α} {f : α → β} (hs : compact s) (hf : continuous f) :
compact (f '' s) :=
compact_of_finite_subcover $ assume c hco hcs,
have hdo : ∀t∈c, is_open (f ⁻¹' t), from assume t' ht, hf _ $ hco _ ht,
have hds : s ⊆ ⋃i∈c, f ⁻¹' i,
by simpa [subset_def, -mem_image] using hcs,
let ⟨d', hcd', hfd', hd'⟩ := compact_elim_finite_subcover_image hs hdo hds in
⟨d', hcd', hfd', by simpa [subset_def, -mem_image, image_subset_iff] using hd'⟩
lemma compact_range [compact_space α] {f : α → β} (hf : continuous f) :
compact (range f) :=
by rw ← image_univ; exact compact_image compact_univ hf
lemma compact_iff_compact_image_of_embedding {s : set α} {f : α → β} (hf : embedding f) :
compact s ↔ compact (f '' s) :=
iff.intro (assume h, compact_image h hf.continuous) $ assume h, begin
rw compact_iff_ultrafilter_le_nhds at ⊢ h,
intros u hu us',
let u' : filter β := map f u,
have : u' ≤ principal (f '' s), begin
rw [map_le_iff_le_comap, comap_principal], convert us',
exact preimage_image_eq _ hf.inj
end,
rcases h u' (ultrafilter_map hu) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩,
refine ⟨a, ha, _⟩,
rwa [hf.induced, nhds_induced, ←map_le_iff_le_comap]
end
lemma compact_iff_compact_in_subtype {p : α → Prop} {s : set {a // p a}} :
compact s ↔ compact (subtype.val '' s) :=
compact_iff_compact_image_of_embedding embedding_subtype_val
lemma compact_iff_compact_univ {s : set α} : compact s ↔ compact (univ : set (subtype s)) :=
by rw [compact_iff_compact_in_subtype, image_univ, subtype.val_range]; refl
lemma compact_iff_compact_space {s : set α} : compact s ↔ compact_space s :=
compact_iff_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩
lemma compact_prod (s : set α) (t : set β) (ha : compact s) (hb : compact t) : compact (set.prod s t) :=
begin
rw compact_iff_ultrafilter_le_nhds at ha hb ⊢,
intros f hf hfs,
rw le_principal_iff at hfs,
rcases ha (map prod.fst f) (ultrafilter_map hf)
(le_principal_iff.2 (mem_map_sets_iff.2
⟨_, hfs, image_subset_iff.2 (λ s h, h.1)⟩)) with ⟨a, sa, ha⟩,
rcases hb (map prod.snd f) (ultrafilter_map hf)
(le_principal_iff.2 (mem_map_sets_iff.2
⟨_, hfs, image_subset_iff.2 (λ s h, h.2)⟩)) with ⟨b, tb, hb⟩,
rw map_le_iff_le_comap at ha hb,
refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩,
rw nhds_prod_eq, exact le_inf ha hb
end
instance [compact_space α] [compact_space β] : compact_space (α × β) :=
⟨begin
have A : compact (set.prod (univ : set α) (univ : set β)) :=
compact_prod univ univ compact_univ compact_univ,
have : set.prod (univ : set α) (univ : set β) = (univ : set (α × β)) := by simp,
rwa this at A,
end⟩
instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) :=
⟨begin
have A : compact (@sum.inl α β '' univ) := compact_image compact_univ continuous_inl,
have B : compact (@sum.inr α β '' univ) := compact_image compact_univ continuous_inr,
have C := compact_union_of_compact A B,
have : (@sum.inl α β '' univ) ∪ (@sum.inr α β '' univ) = univ := by ext; cases x; simp,
rwa this at C,
end⟩
section tychonoff
variables {ι : Type*} {π : ι → Type*} [∀i, topological_space (π i)]
/-- Tychonoff's theorem -/
lemma compact_pi_infinite {s : Πi:ι, set (π i)} :
(∀i, compact (s i)) → compact {x : Πi:ι, π i | ∀i, x i ∈ s i} :=
begin
simp [compact_iff_ultrafilter_le_nhds, nhds_pi],
exact assume h f hf hfs,
let p : Πi:ι, filter (π i) := λi, map (λx:Πi:ι, π i, x i) f in
have ∀i:ι, ∃a, a∈s i ∧ p i ≤ nhds a,
from assume i, h i (p i) (ultrafilter_map hf) $
show (λx:Πi:ι, π i, x i) ⁻¹' s i ∈ f.sets,
from mem_sets_of_superset hfs $ assume x (hx : ∀i, x i ∈ s i), hx i,
let ⟨a, ha⟩ := classical.axiom_of_choice this in
⟨a, assume i, (ha i).left, assume i, map_le_iff_le_comap.mp $ (ha i).right⟩
end
instance pi.compact [∀i:ι, compact_space (π i)] : compact_space (Πi, π i) :=
⟨begin
have A : compact {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} :=
compact_pi_infinite (λi, compact_univ),
have : {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} = univ := by ext; simp,
rwa this at A,
end⟩
end tychonoff
instance quot.compact_space {r : α → α → Prop} [compact_space α] :
compact_space (quot r) :=
⟨begin
have : quot.mk r '' univ = univ,
by rw [image_univ, range_iff_surjective]; exact quot.exists_rep,
rw ←this,
exact compact_image compact_univ continuous_quot_mk
end⟩
instance quotient.compact_space {s : setoid α} [compact_space α] :
compact_space (quotient s) :=
quot.compact_space
/-- There are various definitions of "locally compact space" in the literature, which agree for
Hausdorff spaces but not in general. This one is the precise condition on X needed for the
evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the
compact-open topology. -/
class locally_compact_space (α : Type*) [topological_space α] : Prop :=
(local_compact_nhds : ∀ (x : α) (n ∈ nhds x), ∃ s ∈ nhds x, s ⊆ n ∧ compact s)
end compact
section clopen
def is_clopen (s : set α) : Prop :=
is_open s ∧ is_closed s
theorem is_clopen_union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) :=
⟨is_open_union hs.1 ht.1, is_closed_union hs.2 ht.2⟩
theorem is_clopen_inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) :=
⟨is_open_inter hs.1 ht.1, is_closed_inter hs.2 ht.2⟩
@[simp] theorem is_clopen_empty : is_clopen (∅ : set α) :=
⟨is_open_empty, is_closed_empty⟩
@[simp] theorem is_clopen_univ : is_clopen (univ : set α) :=
⟨is_open_univ, is_closed_univ⟩
theorem is_clopen_compl {s : set α} (hs : is_clopen s) : is_clopen (-s) :=
⟨hs.2, is_closed_compl_iff.2 hs.1⟩
@[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen (-s) ↔ is_clopen s :=
⟨λ h, compl_compl s ▸ is_clopen_compl h, is_clopen_compl⟩
theorem is_clopen_diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s-t) :=
is_clopen_inter hs (is_clopen_compl ht)
end clopen
section irreducible
/-- A irreducible set is one where there is no non-trivial pair of disjoint opens. -/
def is_irreducible (s : set α) : Prop :=
∀ (u v : set α), is_open u → is_open v →
(∃ x, x ∈ s ∩ u) → (∃ x, x ∈ s ∩ v) → ∃ x, x ∈ s ∩ (u ∩ v)
theorem is_irreducible_empty : is_irreducible (∅ : set α) :=
λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim
theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) :=
λ u v _ _ ⟨y, h1, h2⟩ ⟨z, h3, h4⟩, by rw mem_singleton_iff at h1 h3;
substs y z; exact ⟨x, or.inl rfl, h2, h4⟩
theorem is_irreducible_closure {s : set α} (H : is_irreducible s) :
is_irreducible (closure s) :=
λ u v hu hv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩,
let ⟨p, hpu, hps⟩ := exists_mem_of_ne_empty (mem_closure_iff.1 hycs u hu hyu) in
let ⟨q, hqv, hqs⟩ := exists_mem_of_ne_empty (mem_closure_iff.1 hzcs v hv hzv) in
let ⟨r, hrs, hruv⟩ := H u v hu hv ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in
⟨r, subset_closure hrs, hruv⟩
theorem exists_irreducible (s : set α) (H : is_irreducible s) :
∃ t : set α, is_irreducible t ∧ s ⊆ t ∧ ∀ u, is_irreducible u → t ⊆ u → u = t :=
let ⟨m, hm, hsm, hmm⟩ := zorn.zorn_subset₀ { t : set α | is_irreducible t }
(λ c hc hcc hcn, let ⟨t, htc⟩ := exists_mem_of_ne_empty hcn in
⟨⋃₀ c, λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩,
let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy,
⟨q, hqc, hzq⟩ := mem_sUnion.1 hz in
or.cases_on (zorn.chain.total hcc hpc hqc)
(assume hpq : p ⊆ q, let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv
⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in
⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩)
(assume hqp : q ⊆ p, let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv
⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in
⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩),
λ x hxc, set.subset_sUnion_of_mem hxc⟩) s H in
⟨m, hm, hsm, λ u hu hmu, hmm _ hu hmu⟩
def irreducible_component (x : α) : set α :=
classical.some (exists_irreducible {x} is_irreducible_singleton)
theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) :=
(classical.some_spec (exists_irreducible {x} is_irreducible_singleton)).1
theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x :=
singleton_subset_iff.1
(classical.some_spec (exists_irreducible {x} is_irreducible_singleton)).2.1
theorem eq_irreducible_component {x : α} :
∀ {s : set α}, is_irreducible s → irreducible_component x ⊆ s → s = irreducible_component x :=
(classical.some_spec (exists_irreducible {x} is_irreducible_singleton)).2.2
theorem is_closed_irreducible_component {x : α} :
is_closed (irreducible_component x) :=
closure_eq_iff_is_closed.1 $ eq_irreducible_component
(is_irreducible_closure is_irreducible_irreducible_component)
subset_closure
/-- A irreducible space is one where there is no non-trivial pair of disjoint opens. -/
class irreducible_space (α : Type u) [topological_space α] : Prop :=
(is_irreducible_univ : is_irreducible (univ : set α))
theorem irreducible_exists_mem_inter [irreducible_space α] {s t : set α} :
is_open s → is_open t → (∃ x, x ∈ s) → (∃ x, x ∈ t) → ∃ x, x ∈ s ∩ t :=
by simpa only [univ_inter, univ_subset_iff] using
@irreducible_space.is_irreducible_univ α _ _ s t
end irreducible
section connected
/-- A connected set is one where there is no non-trivial open partition. -/
def is_connected (s : set α) : Prop :=
∀ (u v : set α), is_open u → is_open v → s ⊆ u ∪ v →
(∃ x, x ∈ s ∩ u) → (∃ x, x ∈ s ∩ v) → ∃ x, x ∈ s ∩ (u ∩ v)
theorem is_connected_of_is_irreducible {s : set α} (H : is_irreducible s) : is_connected s :=
λ _ _ hu hv _, H _ _ hu hv
theorem is_connected_empty : is_connected (∅ : set α) :=
is_connected_of_is_irreducible is_irreducible_empty
theorem is_connected_singleton {x} : is_connected ({x} : set α) :=
is_connected_of_is_irreducible is_irreducible_singleton
theorem is_connected_sUnion (x : α) (c : set (set α)) (H1 : ∀ s ∈ c, x ∈ s)
(H2 : ∀ s ∈ c, is_connected s) : is_connected (⋃₀ c) :=
begin
rintro u v hu hv hUcuv ⟨y, hyUc, hyu⟩ ⟨z, hzUc, hzv⟩,
cases classical.em (c = ∅) with hc hc,
{ rw [hc, sUnion_empty] at hyUc, exact hyUc.elim },
cases ne_empty_iff_exists_mem.1 hc with s hs,
cases hUcuv (mem_sUnion_of_mem (H1 s hs) hs) with hxu hxv,
{ rcases hzUc with ⟨t, htc, hzt⟩,
specialize H2 t htc u v hu hv (subset.trans (subset_sUnion_of_mem htc) hUcuv),
cases H2 ⟨x, H1 t htc, hxu⟩ ⟨z, hzt, hzv⟩ with r hr,
exact ⟨r, mem_sUnion_of_mem hr.1 htc, hr.2⟩ },
{ rcases hyUc with ⟨t, htc, hyt⟩,
specialize H2 t htc u v hu hv (subset.trans (subset_sUnion_of_mem htc) hUcuv),
cases H2 ⟨y, hyt, hyu⟩ ⟨x, H1 t htc, hxv⟩ with r hr,
exact ⟨r, mem_sUnion_of_mem hr.1 htc, hr.2⟩ }
end
theorem is_connected_union (x : α) {s t : set α} (H1 : x ∈ s) (H2 : x ∈ t)
(H3 : is_connected s) (H4 : is_connected t) : is_connected (s ∪ t) :=
have _ := is_connected_sUnion x {t,s}
(by rintro r (rfl | rfl | h); [exact H1, exact H2, exact h.elim])
(by rintro r (rfl | rfl | h); [exact H3, exact H4, exact h.elim]),
have h2 : ⋃₀ {t, s} = s ∪ t, from (sUnion_insert _ _).trans (by rw sUnion_singleton),
by rwa h2 at this
theorem is_connected_closure {s : set α} (H : is_connected s) :
is_connected (closure s) :=
λ u v hu hv hcsuv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩,
let ⟨p, hpu, hps⟩ := exists_mem_of_ne_empty (mem_closure_iff.1 hycs u hu hyu) in
let ⟨q, hqv, hqs⟩ := exists_mem_of_ne_empty (mem_closure_iff.1 hzcs v hv hzv) in
let ⟨r, hrs, hruv⟩ := H u v hu hv (subset.trans subset_closure hcsuv) ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in
⟨r, subset_closure hrs, hruv⟩
def connected_component (x : α) : set α :=
⋃₀ { s : set α | is_connected s ∧ x ∈ s }
theorem is_connected_connected_component {x : α} : is_connected (connected_component x) :=
is_connected_sUnion x _ (λ _, and.right) (λ _, and.left)
theorem mem_connected_component {x : α} : x ∈ connected_component x :=
mem_sUnion_of_mem (mem_singleton x) ⟨is_connected_singleton, mem_singleton x⟩
theorem subset_connected_component {x : α} {s : set α} (H1 : is_connected s) (H2 : x ∈ s) :
s ⊆ connected_component x :=
λ z hz, mem_sUnion_of_mem hz ⟨H1, H2⟩
theorem is_closed_connected_component {x : α} :
is_closed (connected_component x) :=
closure_eq_iff_is_closed.1 $ subset.antisymm
(subset_connected_component
(is_connected_closure is_connected_connected_component)
(subset_closure mem_connected_component))
subset_closure
theorem irreducible_component_subset_connected_component {x : α} :
irreducible_component x ⊆ connected_component x :=
subset_connected_component
(is_connected_of_is_irreducible is_irreducible_irreducible_component)
mem_irreducible_component
/-- A connected space is one where there is no non-trivial open partition. -/
class connected_space (α : Type u) [topological_space α] : Prop :=
(is_connected_univ : is_connected (univ : set α))
instance irreducible_space.connected_space (α : Type u) [topological_space α]
[irreducible_space α] : connected_space α :=
⟨is_connected_of_is_irreducible $ irreducible_space.is_irreducible_univ α⟩
theorem exists_mem_inter [connected_space α] {s t : set α} :
is_open s → is_open t → s ∪ t = univ →
(∃ x, x ∈ s) → (∃ x, x ∈ t) → ∃ x, x ∈ s ∩ t :=
by simpa only [univ_inter, univ_subset_iff] using
@connected_space.is_connected_univ α _ _ s t
theorem is_clopen_iff [connected_space α] {s : set α} : is_clopen s ↔ s = ∅ ∨ s = univ :=
⟨λ hs, classical.by_contradiction $ λ h,
have h1 : s ≠ ∅ ∧ -s ≠ ∅, from ⟨mt or.inl h,
mt (λ h2, or.inr $ (by rw [← compl_compl s, h2, compl_empty] : s = univ)) h⟩,
let ⟨_, h2, h3⟩ := exists_mem_inter hs.1 hs.2 (union_compl_self s)
(ne_empty_iff_exists_mem.1 h1.1) (ne_empty_iff_exists_mem.1 h1.2) in
h3 h2,
by rintro (rfl | rfl); [exact is_clopen_empty, exact is_clopen_univ]⟩
end connected
section totally_disconnected
def is_totally_disconnected (s : set α) : Prop :=
∀ t, t ⊆ s → is_connected t → subsingleton t
theorem is_totally_disconnected_empty : is_totally_disconnected (∅ : set α) :=
λ t ht _, ⟨λ ⟨_, h⟩, (ht h).elim⟩
theorem is_totally_disconnected_singleton {x} : is_totally_disconnected ({x} : set α) :=
λ t ht _, ⟨λ ⟨p, hp⟩ ⟨q, hq⟩, subtype.eq $ show p = q,
from (eq_of_mem_singleton (ht hp)).symm ▸ (eq_of_mem_singleton (ht hq)).symm⟩
class totally_disconnected_space (α : Type u) [topological_space α] : Prop :=
(is_totally_disconnected_univ : is_totally_disconnected (univ : set α))
end totally_disconnected
section totally_separated
def is_totally_separated (s : set α) : Prop :=
∀ x ∈ s, ∀ y ∈ s, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧
x ∈ u ∧ y ∈ v ∧ s ⊆ u ∪ v ∧ u ∩ v = ∅
theorem is_totally_separated_empty : is_totally_separated (∅ : set α) :=
λ x, false.elim
theorem is_totally_separated_singleton {x} : is_totally_separated ({x} : set α) :=
λ p hp q hq hpq, (hpq $ (eq_of_mem_singleton hp).symm ▸ (eq_of_mem_singleton hq).symm).elim
theorem is_totally_disconnected_of_is_totally_separated {s : set α}
(H : is_totally_separated s) : is_totally_disconnected s :=
λ t hts ht, ⟨λ ⟨x, hxt⟩ ⟨y, hyt⟩, subtype.eq $ classical.by_contradiction $
assume hxy : x ≠ y, let ⟨u, v, hu, hv, hxu, hyv, hsuv, huv⟩ := H x (hts hxt) y (hts hyt) hxy in
let ⟨r, hrt, hruv⟩ := ht u v hu hv (subset.trans hts hsuv) ⟨x, hxt, hxu⟩ ⟨y, hyt, hyv⟩ in
((ext_iff _ _).1 huv r).1 hruv⟩
class totally_separated_space (α : Type u) [topological_space α] : Prop :=
(is_totally_separated_univ : is_totally_separated (univ : set α))
instance totally_separated_space.totally_disconnected_space (α : Type u) [topological_space α]
[totally_separated_space α] : totally_disconnected_space α :=
⟨is_totally_disconnected_of_is_totally_separated $ totally_separated_space.is_totally_separated_univ α⟩
end totally_separated
|
73cf931c0961542ff67d4bc8b2de1b9021976912 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/linear_algebra/affine_space/affine_subspace.lean | f29f4999e542ba62916bd5c44da6ee0c54447905 | [
"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 | 45,463 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import linear_algebra.affine_space.basic
import linear_algebra.tensor_product
import data.set.intervals.unordered_interval
/-!
# Affine spaces
This file defines affine subspaces (over modules) and the affine span of a set of points.
## Main definitions
* `affine_subspace k P` is the type of affine subspaces. Unlike
affine spaces, affine subspaces are allowed to be empty, and lemmas
that do not apply to empty affine subspaces have `nonempty`
hypotheses. There is a `complete_lattice` structure on affine
subspaces.
* `affine_subspace.direction` gives the `submodule` spanned by the
pairwise differences of points in an `affine_subspace`. There are
various lemmas relating to the set of vectors in the `direction`,
and relating the lattice structure on affine subspaces to that on
their directions.
* `affine_span` gives the affine subspace spanned by a set of points,
with `vector_span` giving its direction. `affine_span` is defined
in terms of `span_points`, which gives an explicit description of
the points contained in the affine span; `span_points` itself should
generally only be used when that description is required, with
`affine_span` being the main definition for other purposes. Two
other descriptions of the affine span are proved equivalent: it is
the `Inf` of affine subspaces containing the points, and (if
`[nontrivial k]`) it contains exactly those points that are affine
combinations of points in the given set.
## Implementation notes
`out_param` is used in the definiton of `add_torsor V P` to make `V` an implicit argument (deduced
from `P`) in most cases; `include V` is needed in many cases for `V`, and type classes using it, to
be added as implicit arguments to individual lemmas. As for modules, `k` is an explicit argument
rather than implied by `P` or `V`.
This file only provides purely algebraic definitions and results.
Those depending on analysis or topology are defined elsewhere; see
`analysis.normed_space.add_torsor` and `topology.algebra.affine`.
## References
* https://en.wikipedia.org/wiki/Affine_space
* https://en.wikipedia.org/wiki/Principal_homogeneous_space
-/
noncomputable theory
open_locale big_operators classical affine
open set
section
variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V]
variables [affine_space V P]
include V
/-- The submodule spanning the differences of a (possibly empty) set
of points. -/
def vector_span (s : set P) : submodule k V := submodule.span k (s -ᵥ s)
/-- The definition of `vector_span`, for rewriting. -/
lemma vector_span_def (s : set P) : vector_span k s = submodule.span k (s -ᵥ s) :=
rfl
/-- `vector_span` is monotone. -/
lemma vector_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : vector_span k s₁ ≤ vector_span k s₂ :=
submodule.span_mono (vsub_self_mono h)
variables (P)
/-- The `vector_span` of the empty set is `⊥`. -/
@[simp] lemma vector_span_empty : vector_span k (∅ : set P) = (⊥ : submodule k V) :=
by rw [vector_span_def, vsub_empty, submodule.span_empty]
variables {P}
/-- The `vector_span` of a single point is `⊥`. -/
@[simp] lemma vector_span_singleton (p : P) : vector_span k ({p} : set P) = ⊥ :=
by simp [vector_span_def]
/-- The `s -ᵥ s` lies within the `vector_span k s`. -/
lemma vsub_set_subset_vector_span (s : set P) : s -ᵥ s ⊆ ↑(vector_span k s) :=
submodule.subset_span
/-- Each pairwise difference is in the `vector_span`. -/
lemma vsub_mem_vector_span {s : set P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) :
p1 -ᵥ p2 ∈ vector_span k s :=
vsub_set_subset_vector_span k s (vsub_mem_vsub hp1 hp2)
/-- The points in the affine span of a (possibly empty) set of
points. Use `affine_span` instead to get an `affine_subspace k P`. -/
def span_points (s : set P) : set P :=
{p | ∃ p1 ∈ s, ∃ v ∈ (vector_span k s), p = v +ᵥ p1}
/-- A point in a set is in its affine span. -/
lemma mem_span_points (p : P) (s : set P) : p ∈ s → p ∈ span_points k s
| hp := ⟨p, hp, 0, submodule.zero_mem _, (zero_vadd V p).symm⟩
/-- A set is contained in its `span_points`. -/
lemma subset_span_points (s : set P) : s ⊆ span_points k s :=
λ p, mem_span_points k p s
/-- The `span_points` of a set is nonempty if and only if that set
is. -/
@[simp] lemma span_points_nonempty (s : set P) :
(span_points k s).nonempty ↔ s.nonempty :=
begin
split,
{ contrapose,
rw [set.not_nonempty_iff_eq_empty, set.not_nonempty_iff_eq_empty],
intro h,
simp [h, span_points] },
{ exact λ h, h.mono (subset_span_points _ _) }
end
/-- Adding a point in the affine span and a vector in the spanning
submodule produces a point in the affine span. -/
lemma vadd_mem_span_points_of_mem_span_points_of_mem_vector_span {s : set P} {p : P} {v : V}
(hp : p ∈ span_points k s) (hv : v ∈ vector_span k s) : v +ᵥ p ∈ span_points k s :=
begin
rcases hp with ⟨p2, ⟨hp2, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩,
rw [hv2p, vadd_vadd],
use [p2, hp2, v + v2, (vector_span k s).add_mem hv hv2, rfl]
end
/-- Subtracting two points in the affine span produces a vector in the
spanning submodule. -/
lemma vsub_mem_vector_span_of_mem_span_points_of_mem_span_points {s : set P} {p1 p2 : P}
(hp1 : p1 ∈ span_points k s) (hp2 : p2 ∈ span_points k s) :
p1 -ᵥ p2 ∈ vector_span k s :=
begin
rcases hp1 with ⟨p1a, ⟨hp1a, ⟨v1, ⟨hv1, hv1p⟩⟩⟩⟩,
rcases hp2 with ⟨p2a, ⟨hp2a, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩,
rw [hv1p, hv2p, vsub_vadd_eq_vsub_sub (v1 +ᵥ p1a), vadd_vsub_assoc, add_comm, add_sub_assoc],
have hv1v2 : v1 - v2 ∈ vector_span k s,
{ rw sub_eq_add_neg,
apply (vector_span k s).add_mem hv1,
rw ←neg_one_smul k v2,
exact (vector_span k s).smul_mem (-1 : k) hv2 },
refine (vector_span k s).add_mem _ hv1v2,
exact vsub_mem_vector_span k hp1a hp2a
end
end
/-- An `affine_subspace k P` is a subset of an `affine_space V P`
that, if not empty, has an affine space structure induced by a
corresponding subspace of the `module k V`. -/
structure affine_subspace (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V]
[module k V] [affine_space V P] :=
(carrier : set P)
(smul_vsub_vadd_mem : ∀ (c : k) {p1 p2 p3 : P}, p1 ∈ carrier → p2 ∈ carrier → p3 ∈ carrier →
c • (p1 -ᵥ p2 : V) +ᵥ p3 ∈ carrier)
namespace submodule
variables {k V : Type*} [ring k] [add_comm_group V] [module k V]
/-- Reinterpret `p : submodule k V` as an `affine_subspace k V`. -/
def to_affine_subspace (p : submodule k V) : affine_subspace k V :=
{ carrier := p,
smul_vsub_vadd_mem := λ c p₁ p₂ p₃ h₁ h₂ h₃, p.add_mem (p.smul_mem _ (p.sub_mem h₁ h₂)) h₃ }
end submodule
namespace affine_subspace
variables (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V]
[affine_space V P]
include V
instance : has_coe (affine_subspace k P) (set P) := ⟨carrier⟩
instance : has_mem P (affine_subspace k P) := ⟨λ p s, p ∈ (s : set P)⟩
/-- A point is in an affine subspace coerced to a set if and only if
it is in that affine subspace. -/
@[simp] lemma mem_coe (p : P) (s : affine_subspace k P) :
p ∈ (s : set P) ↔ p ∈ s :=
iff.rfl
variables {k P}
/-- The direction of an affine subspace is the submodule spanned by
the pairwise differences of points. (Except in the case of an empty
affine subspace, where the direction is the zero submodule, every
vector in the direction is the difference of two points in the affine
subspace.) -/
def direction (s : affine_subspace k P) : submodule k V := vector_span k (s : set P)
/-- The direction equals the `vector_span`. -/
lemma direction_eq_vector_span (s : affine_subspace k P) :
s.direction = vector_span k (s : set P) :=
rfl
/-- Alternative definition of the direction when the affine subspace
is nonempty. This is defined so that the order on submodules (as used
in the definition of `submodule.span`) can be used in the proof of
`coe_direction_eq_vsub_set`, and is not intended to be used beyond
that proof. -/
def direction_of_nonempty {s : affine_subspace k P} (h : (s : set P).nonempty) :
submodule k V :=
{ carrier := (s : set P) -ᵥ s,
zero_mem' := begin
cases h with p hp,
exact (vsub_self p) ▸ vsub_mem_vsub hp hp
end,
add_mem' := begin
intros a b ha hb,
rcases ha with ⟨p1, p2, hp1, hp2, rfl⟩,
rcases hb with ⟨p3, p4, hp3, hp4, rfl⟩,
rw [←vadd_vsub_assoc],
refine vsub_mem_vsub _ hp4,
convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp3,
rw one_smul
end,
smul_mem' := begin
intros c v hv,
rcases hv with ⟨p1, p2, hp1, hp2, rfl⟩,
rw [←vadd_vsub (c • (p1 -ᵥ p2)) p2],
refine vsub_mem_vsub _ hp2,
exact s.smul_vsub_vadd_mem c hp1 hp2 hp2
end }
/-- `direction_of_nonempty` gives the same submodule as
`direction`. -/
lemma direction_of_nonempty_eq_direction {s : affine_subspace k P} (h : (s : set P).nonempty) :
direction_of_nonempty h = s.direction :=
le_antisymm (vsub_set_subset_vector_span k s) (submodule.span_le.2 set.subset.rfl)
/-- The set of vectors in the direction of a nonempty affine subspace
is given by `vsub_set`. -/
lemma coe_direction_eq_vsub_set {s : affine_subspace k P} (h : (s : set P).nonempty) :
(s.direction : set V) = (s : set P) -ᵥ s :=
direction_of_nonempty_eq_direction h ▸ rfl
/-- A vector is in the direction of a nonempty affine subspace if and
only if it is the subtraction of two vectors in the subspace. -/
lemma mem_direction_iff_eq_vsub {s : affine_subspace k P} (h : (s : set P).nonempty) (v : V) :
v ∈ s.direction ↔ ∃ p1 ∈ s, ∃ p2 ∈ s, v = p1 -ᵥ p2 :=
begin
rw [←set_like.mem_coe, coe_direction_eq_vsub_set h],
exact ⟨λ ⟨p1, p2, hp1, hp2, hv⟩, ⟨p1, hp1, p2, hp2, hv.symm⟩,
λ ⟨p1, hp1, p2, hp2, hv⟩, ⟨p1, p2, hp1, hp2, hv.symm⟩⟩
end
/-- Adding a vector in the direction to a point in the subspace
produces a point in the subspace. -/
lemma vadd_mem_of_mem_direction {s : affine_subspace k P} {v : V} (hv : v ∈ s.direction) {p : P}
(hp : p ∈ s) : v +ᵥ p ∈ s :=
begin
rw mem_direction_iff_eq_vsub ⟨p, hp⟩ at hv,
rcases hv with ⟨p1, hp1, p2, hp2, hv⟩,
rw hv,
convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp,
rw one_smul
end
/-- Subtracting two points in the subspace produces a vector in the
direction. -/
lemma vsub_mem_direction {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) :
(p1 -ᵥ p2) ∈ s.direction :=
vsub_mem_vector_span k hp1 hp2
/-- Adding a vector to a point in a subspace produces a point in the
subspace if and only if the vector is in the direction. -/
lemma vadd_mem_iff_mem_direction {s : affine_subspace k P} (v : V) {p : P} (hp : p ∈ s) :
v +ᵥ p ∈ s ↔ v ∈ s.direction :=
⟨λ h, by simpa using vsub_mem_direction h hp, λ h, vadd_mem_of_mem_direction h hp⟩
/-- Given a point in an affine subspace, the set of vectors in its
direction equals the set of vectors subtracting that point on the
right. -/
lemma coe_direction_eq_vsub_set_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) :
(s.direction : set V) = (-ᵥ p) '' s :=
begin
rw coe_direction_eq_vsub_set ⟨p, hp⟩,
refine le_antisymm _ _,
{ rintros v ⟨p1, p2, hp1, hp2, rfl⟩,
exact ⟨p1 -ᵥ p2 +ᵥ p,
vadd_mem_of_mem_direction (vsub_mem_direction hp1 hp2) hp,
(vadd_vsub _ _)⟩ },
{ rintros v ⟨p2, hp2, rfl⟩,
exact ⟨p2, p, hp2, hp, rfl⟩ }
end
/-- Given a point in an affine subspace, the set of vectors in its
direction equals the set of vectors subtracting that point on the
left. -/
lemma coe_direction_eq_vsub_set_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) :
(s.direction : set V) = (-ᵥ) p '' s :=
begin
ext v,
rw [set_like.mem_coe, ←submodule.neg_mem_iff, ←set_like.mem_coe,
coe_direction_eq_vsub_set_right hp, set.mem_image_iff_bex, set.mem_image_iff_bex],
conv_lhs { congr, funext, rw [←neg_vsub_eq_vsub_rev, neg_inj] }
end
/-- Given a point in an affine subspace, a vector is in its direction
if and only if it results from subtracting that point on the right. -/
lemma mem_direction_iff_eq_vsub_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) :
v ∈ s.direction ↔ ∃ p2 ∈ s, v = p2 -ᵥ p :=
begin
rw [←set_like.mem_coe, coe_direction_eq_vsub_set_right hp],
exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩
end
/-- Given a point in an affine subspace, a vector is in its direction
if and only if it results from subtracting that point on the left. -/
lemma mem_direction_iff_eq_vsub_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) :
v ∈ s.direction ↔ ∃ p2 ∈ s, v = p -ᵥ p2 :=
begin
rw [←set_like.mem_coe, coe_direction_eq_vsub_set_left hp],
exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩
end
/-- Given a point in an affine subspace, a result of subtracting that
point on the right is in the direction if and only if the other point
is in the subspace. -/
lemma vsub_right_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) :
p2 -ᵥ p ∈ s.direction ↔ p2 ∈ s :=
begin
rw mem_direction_iff_eq_vsub_right hp,
simp
end
/-- Given a point in an affine subspace, a result of subtracting that
point on the left is in the direction if and only if the other point
is in the subspace. -/
lemma vsub_left_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) :
p -ᵥ p2 ∈ s.direction ↔ p2 ∈ s :=
begin
rw mem_direction_iff_eq_vsub_left hp,
simp
end
/-- Two affine subspaces are equal if they have the same points. -/
@[ext] lemma ext {s1 s2 : affine_subspace k P} (h : (s1 : set P) = s2) : s1 = s2 :=
begin
cases s1,
cases s2,
congr,
exact h
end
/-- Two affine subspaces with the same direction and nonempty
intersection are equal. -/
lemma ext_of_direction_eq {s1 s2 : affine_subspace k P} (hd : s1.direction = s2.direction)
(hn : ((s1 : set P) ∩ s2).nonempty) : s1 = s2 :=
begin
ext p,
have hq1 := set.mem_of_mem_inter_left hn.some_mem,
have hq2 := set.mem_of_mem_inter_right hn.some_mem,
split,
{ intro hp,
rw ←vsub_vadd p hn.some,
refine vadd_mem_of_mem_direction _ hq2,
rw ←hd,
exact vsub_mem_direction hp hq1 },
{ intro hp,
rw ←vsub_vadd p hn.some,
refine vadd_mem_of_mem_direction _ hq1,
rw hd,
exact vsub_mem_direction hp hq2 }
end
instance to_add_torsor (s : affine_subspace k P) [nonempty s] : add_torsor s.direction s :=
{ vadd := λ a b, ⟨(a:V) +ᵥ (b:P), vadd_mem_of_mem_direction a.2 b.2⟩,
zero_vadd := by simp,
add_vadd := λ a b c, by { ext, apply add_vadd },
vsub := λ a b, ⟨(a:P) -ᵥ (b:P), (vsub_left_mem_direction_iff_mem a.2 _).mpr b.2 ⟩,
nonempty := by apply_instance,
vsub_vadd' := λ a b, by { ext, apply add_torsor.vsub_vadd' },
vadd_vsub' := λ a b, by { ext, apply add_torsor.vadd_vsub' } }
@[simp, norm_cast] lemma coe_vsub (s : affine_subspace k P) [nonempty s] (a b : s) :
↑(a -ᵥ b) = (a:P) -ᵥ (b:P) :=
rfl
@[simp, norm_cast] lemma coe_vadd (s : affine_subspace k P) [nonempty s] (a : s.direction) (b : s) :
↑(a +ᵥ b) = (a:V) +ᵥ (b:P) :=
rfl
/-- Two affine subspaces with nonempty intersection are equal if and
only if their directions are equal. -/
lemma eq_iff_direction_eq_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁)
(h₂ : p ∈ s₂) : s₁ = s₂ ↔ s₁.direction = s₂.direction :=
⟨λ h, h ▸ rfl, λ h, ext_of_direction_eq h ⟨p, h₁, h₂⟩⟩
/-- Construct an affine subspace from a point and a direction. -/
def mk' (p : P) (direction : submodule k V) : affine_subspace k P :=
{ carrier := {q | ∃ v ∈ direction, q = v +ᵥ p},
smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, begin
rcases hp1 with ⟨v1, hv1, hp1⟩,
rcases hp2 with ⟨v2, hv2, hp2⟩,
rcases hp3 with ⟨v3, hv3, hp3⟩,
use [c • (v1 - v2) + v3,
direction.add_mem (direction.smul_mem c (direction.sub_mem hv1 hv2)) hv3],
simp [hp1, hp2, hp3, vadd_vadd]
end }
/-- An affine subspace constructed from a point and a direction contains
that point. -/
lemma self_mem_mk' (p : P) (direction : submodule k V) :
p ∈ mk' p direction :=
⟨0, ⟨direction.zero_mem, (zero_vadd _ _).symm⟩⟩
/-- An affine subspace constructed from a point and a direction contains
the result of adding a vector in that direction to that point. -/
lemma vadd_mem_mk' {v : V} (p : P) {direction : submodule k V} (hv : v ∈ direction) :
v +ᵥ p ∈ mk' p direction :=
⟨v, hv, rfl⟩
/-- An affine subspace constructed from a point and a direction is
nonempty. -/
lemma mk'_nonempty (p : P) (direction : submodule k V) : (mk' p direction : set P).nonempty :=
⟨p, self_mem_mk' p direction⟩
/-- The direction of an affine subspace constructed from a point and a
direction. -/
@[simp] lemma direction_mk' (p : P) (direction : submodule k V) :
(mk' p direction).direction = direction :=
begin
ext v,
rw mem_direction_iff_eq_vsub (mk'_nonempty _ _),
split,
{ rintros ⟨p1, ⟨v1, hv1, hp1⟩, p2, ⟨v2, hv2, hp2⟩, hv⟩,
rw [hv, hp1, hp2, vadd_vsub_vadd_cancel_right],
exact direction.sub_mem hv1 hv2 },
{ exact λ hv, ⟨v +ᵥ p, vadd_mem_mk' _ hv, p,
self_mem_mk' _ _, (vadd_vsub _ _).symm⟩ }
end
/-- Constructing an affine subspace from a point in a subspace and
that subspace's direction yields the original subspace. -/
@[simp] lemma mk'_eq {s : affine_subspace k P} {p : P} (hp : p ∈ s) : mk' p s.direction = s :=
ext_of_direction_eq (direction_mk' p s.direction)
⟨p, set.mem_inter (self_mem_mk' _ _) hp⟩
/-- If an affine subspace contains a set of points, it contains the
`span_points` of that set. -/
lemma span_points_subset_coe_of_subset_coe {s : set P} {s1 : affine_subspace k P} (h : s ⊆ s1) :
span_points k s ⊆ s1 :=
begin
rintros p ⟨p1, hp1, v, hv, hp⟩,
rw hp,
have hp1s1 : p1 ∈ (s1 : set P) := set.mem_of_mem_of_subset hp1 h,
refine vadd_mem_of_mem_direction _ hp1s1,
have hs : vector_span k s ≤ s1.direction := vector_span_mono k h,
rw set_like.le_def at hs,
rw ←set_like.mem_coe,
exact set.mem_of_mem_of_subset hv hs
end
end affine_subspace
section affine_span
variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V]
[affine_space V P]
include V
/-- The affine span of a set of points is the smallest affine subspace
containing those points. (Actually defined here in terms of spans in
modules.) -/
def affine_span (s : set P) : affine_subspace k P :=
{ carrier := span_points k s,
smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3,
vadd_mem_span_points_of_mem_span_points_of_mem_vector_span k hp3
((vector_span k s).smul_mem c
(vsub_mem_vector_span_of_mem_span_points_of_mem_span_points k hp1 hp2)) }
/-- The affine span, converted to a set, is `span_points`. -/
@[simp] lemma coe_affine_span (s : set P) :
(affine_span k s : set P) = span_points k s :=
rfl
/-- A set is contained in its affine span. -/
lemma subset_affine_span (s : set P) : s ⊆ affine_span k s :=
subset_span_points k s
/-- The direction of the affine span is the `vector_span`. -/
lemma direction_affine_span (s : set P) : (affine_span k s).direction = vector_span k s :=
begin
apply le_antisymm,
{ refine submodule.span_le.2 _,
rintros v ⟨p1, p3, ⟨p2, hp2, v1, hv1, hp1⟩, ⟨p4, hp4, v2, hv2, hp3⟩, rfl⟩,
rw [hp1, hp3, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, set_like.mem_coe],
exact (vector_span k s).sub_mem ((vector_span k s).add_mem hv1
(vsub_mem_vector_span k hp2 hp4)) hv2 },
{ exact vector_span_mono k (subset_span_points k s) }
end
/-- A point in a set is in its affine span. -/
lemma mem_affine_span {p : P} {s : set P} (hp : p ∈ s) : p ∈ affine_span k s :=
mem_span_points k p s hp
end affine_span
namespace affine_subspace
variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V]
[S : affine_space V P]
include S
instance : complete_lattice (affine_subspace k P) :=
{ sup := λ s1 s2, affine_span k (s1 ∪ s2),
le_sup_left := λ s1 s2, set.subset.trans (set.subset_union_left s1 s2)
(subset_span_points k _),
le_sup_right := λ s1 s2, set.subset.trans (set.subset_union_right s1 s2)
(subset_span_points k _),
sup_le := λ s1 s2 s3 hs1 hs2, span_points_subset_coe_of_subset_coe (set.union_subset hs1 hs2),
inf := λ s1 s2, mk (s1 ∩ s2)
(λ c p1 p2 p3 hp1 hp2 hp3,
⟨s1.smul_vsub_vadd_mem c hp1.1 hp2.1 hp3.1,
s2.smul_vsub_vadd_mem c hp1.2 hp2.2 hp3.2⟩),
inf_le_left := λ _ _, set.inter_subset_left _ _,
inf_le_right := λ _ _, set.inter_subset_right _ _,
le_inf := λ _ _ _, set.subset_inter,
top := { carrier := set.univ,
smul_vsub_vadd_mem := λ _ _ _ _ _ _ _, set.mem_univ _ },
le_top := λ _ _ _, set.mem_univ _,
bot := { carrier := ∅,
smul_vsub_vadd_mem := λ _ _ _ _, false.elim },
bot_le := λ _ _, false.elim,
Sup := λ s, affine_span k (⋃ s' ∈ s, (s' : set P)),
Inf := λ s, mk (⋂ s' ∈ s, (s' : set P))
(λ c p1 p2 p3 hp1 hp2 hp3, set.mem_bInter_iff.2 $ λ s2 hs2,
s2.smul_vsub_vadd_mem c (set.mem_bInter_iff.1 hp1 s2 hs2)
(set.mem_bInter_iff.1 hp2 s2 hs2)
(set.mem_bInter_iff.1 hp3 s2 hs2)),
le_Sup := λ _ _ h, set.subset.trans (set.subset_bUnion_of_mem h) (subset_span_points k _),
Sup_le := λ _ _ h, span_points_subset_coe_of_subset_coe (set.bUnion_subset h),
Inf_le := λ _ _, set.bInter_subset_of_mem,
le_Inf := λ _ _, set.subset_bInter,
.. partial_order.lift (coe : affine_subspace k P → set P) (λ _ _, ext) }
instance : inhabited (affine_subspace k P) := ⟨⊤⟩
/-- The `≤` order on subspaces is the same as that on the corresponding
sets. -/
lemma le_def (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ (s1 : set P) ⊆ s2 :=
iff.rfl
/-- One subspace is less than or equal to another if and only if all
its points are in the second subspace. -/
lemma le_def' (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ ∀ p ∈ s1, p ∈ s2 :=
iff.rfl
/-- The `<` order on subspaces is the same as that on the corresponding
sets. -/
lemma lt_def (s1 s2 : affine_subspace k P) : s1 < s2 ↔ (s1 : set P) ⊂ s2 :=
iff.rfl
/-- One subspace is not less than or equal to another if and only if
it has a point not in the second subspace. -/
lemma not_le_iff_exists (s1 s2 : affine_subspace k P) : ¬ s1 ≤ s2 ↔ ∃ p ∈ s1, p ∉ s2 :=
set.not_subset
/-- If a subspace is less than another, there is a point only in the
second. -/
lemma exists_of_lt {s1 s2 : affine_subspace k P} (h : s1 < s2) : ∃ p ∈ s2, p ∉ s1 :=
set.exists_of_ssubset h
/-- A subspace is less than another if and only if it is less than or
equal to the second subspace and there is a point only in the
second. -/
lemma lt_iff_le_and_exists (s1 s2 : affine_subspace k P) : s1 < s2 ↔ s1 ≤ s2 ∧ ∃ p ∈ s2, p ∉ s1 :=
by rw [lt_iff_le_not_le, not_le_iff_exists]
/-- If an affine subspace is nonempty and contained in another with
the same direction, they are equal. -/
lemma eq_of_direction_eq_of_nonempty_of_le {s₁ s₂ : affine_subspace k P}
(hd : s₁.direction = s₂.direction) (hn : (s₁ : set P).nonempty) (hle : s₁ ≤ s₂) :
s₁ = s₂ :=
let ⟨p, hp⟩ := hn in ext_of_direction_eq hd ⟨p, hp, hle hp⟩
variables (k V)
/-- The affine span is the `Inf` of subspaces containing the given
points. -/
lemma affine_span_eq_Inf (s : set P) : affine_span k s = Inf {s' | s ⊆ s'} :=
le_antisymm (span_points_subset_coe_of_subset_coe (set.subset_bInter (λ _ h, h)))
(Inf_le (subset_span_points k _))
variables (P)
/-- The Galois insertion formed by `affine_span` and coercion back to
a set. -/
protected def gi : galois_insertion (affine_span k) (coe : affine_subspace k P → set P) :=
{ choice := λ s _, affine_span k s,
gc := λ s1 s2, ⟨λ h, set.subset.trans (subset_span_points k s1) h,
span_points_subset_coe_of_subset_coe⟩,
le_l_u := λ _, subset_span_points k _,
choice_eq := λ _ _, rfl }
/-- The span of the empty set is `⊥`. -/
@[simp] lemma span_empty : affine_span k (∅ : set P) = ⊥ :=
(affine_subspace.gi k V P).gc.l_bot
/-- The span of `univ` is `⊤`. -/
@[simp] lemma span_univ : affine_span k (set.univ : set P) = ⊤ :=
eq_top_iff.2 $ subset_span_points k _
variables {P}
/-- The affine span of a single point, coerced to a set, contains just
that point. -/
@[simp] lemma coe_affine_span_singleton (p : P) : (affine_span k ({p} : set P) : set P) = {p} :=
begin
ext x,
rw [mem_coe, ←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_singleton p)) _,
direction_affine_span],
simp
end
/-- A point is in the affine span of a single point if and only if
they are equal. -/
@[simp] lemma mem_affine_span_singleton (p1 p2 : P) :
p1 ∈ affine_span k ({p2} : set P) ↔ p1 = p2 :=
by simp [←mem_coe]
/-- The span of a union of sets is the sup of their spans. -/
lemma span_union (s t : set P) : affine_span k (s ∪ t) = affine_span k s ⊔ affine_span k t :=
(affine_subspace.gi k V P).gc.l_sup
/-- The span of a union of an indexed family of sets is the sup of
their spans. -/
lemma span_Union {ι : Type*} (s : ι → set P) :
affine_span k (⋃ i, s i) = ⨆ i, affine_span k (s i) :=
(affine_subspace.gi k V P).gc.l_supr
variables (P)
/-- `⊤`, coerced to a set, is the whole set of points. -/
@[simp] lemma top_coe : ((⊤ : affine_subspace k P) : set P) = set.univ :=
rfl
variables {P}
/-- All points are in `⊤`. -/
lemma mem_top (p : P) : p ∈ (⊤ : affine_subspace k P) :=
set.mem_univ p
variables (P)
/-- The direction of `⊤` is the whole module as a submodule. -/
@[simp] lemma direction_top : (⊤ : affine_subspace k P).direction = ⊤ :=
begin
cases S.nonempty with p,
ext v,
refine ⟨imp_intro submodule.mem_top, λ hv, _⟩,
have hpv : (v +ᵥ p -ᵥ p : V) ∈ (⊤ : affine_subspace k P).direction :=
vsub_mem_direction (mem_top k V _) (mem_top k V _),
rwa vadd_vsub at hpv
end
/-- `⊥`, coerced to a set, is the empty set. -/
@[simp] lemma bot_coe : ((⊥ : affine_subspace k P) : set P) = ∅ :=
rfl
variables {P}
/-- No points are in `⊥`. -/
lemma not_mem_bot (p : P) : p ∉ (⊥ : affine_subspace k P) :=
set.not_mem_empty p
variables (P)
/-- The direction of `⊥` is the submodule `⊥`. -/
@[simp] lemma direction_bot : (⊥ : affine_subspace k P).direction = ⊥ :=
by rw [direction_eq_vector_span, bot_coe, vector_span_def, vsub_empty, submodule.span_empty]
variables {k V P}
/-- A nonempty affine subspace is `⊤` if and only if its direction is
`⊤`. -/
@[simp] lemma direction_eq_top_iff_of_nonempty {s : affine_subspace k P}
(h : (s : set P).nonempty) : s.direction = ⊤ ↔ s = ⊤ :=
begin
split,
{ intro hd,
rw ←direction_top k V P at hd,
refine ext_of_direction_eq hd _,
simp [h] },
{ rintro rfl,
simp }
end
/-- The inf of two affine subspaces, coerced to a set, is the
intersection of the two sets of points. -/
@[simp] lemma inf_coe (s1 s2 : affine_subspace k P) : ((s1 ⊓ s2) : set P) = s1 ∩ s2 :=
rfl
/-- A point is in the inf of two affine subspaces if and only if it is
in both of them. -/
lemma mem_inf_iff (p : P) (s1 s2 : affine_subspace k P) : p ∈ s1 ⊓ s2 ↔ p ∈ s1 ∧ p ∈ s2 :=
iff.rfl
/-- The direction of the inf of two affine subspaces is less than or
equal to the inf of their directions. -/
lemma direction_inf (s1 s2 : affine_subspace k P) :
(s1 ⊓ s2).direction ≤ s1.direction ⊓ s2.direction :=
begin
repeat { rw [direction_eq_vector_span, vector_span_def] },
exact le_inf
(Inf_le_Inf (λ p hp, trans (vsub_self_mono (inter_subset_left _ _)) hp))
(Inf_le_Inf (λ p hp, trans (vsub_self_mono (inter_subset_right _ _)) hp))
end
/-- If two affine subspaces have a point in common, the direction of
their inf equals the inf of their directions. -/
lemma direction_inf_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁) (h₂ : p ∈ s₂) :
(s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction :=
begin
ext v,
rw [submodule.mem_inf, ←vadd_mem_iff_mem_direction v h₁, ←vadd_mem_iff_mem_direction v h₂,
←vadd_mem_iff_mem_direction v ((mem_inf_iff p s₁ s₂).2 ⟨h₁, h₂⟩), mem_inf_iff]
end
/-- If two affine subspaces have a point in their inf, the direction
of their inf equals the inf of their directions. -/
lemma direction_inf_of_mem_inf {s₁ s₂ : affine_subspace k P} {p : P} (h : p ∈ s₁ ⊓ s₂) :
(s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction :=
direction_inf_of_mem ((mem_inf_iff p s₁ s₂).1 h).1 ((mem_inf_iff p s₁ s₂).1 h).2
/-- If one affine subspace is less than or equal to another, the same
applies to their directions. -/
lemma direction_le {s1 s2 : affine_subspace k P} (h : s1 ≤ s2) : s1.direction ≤ s2.direction :=
begin
repeat { rw [direction_eq_vector_span, vector_span_def] },
exact vector_span_mono k h
end
/-- If one nonempty affine subspace is less than another, the same
applies to their directions -/
lemma direction_lt_of_nonempty {s1 s2 : affine_subspace k P} (h : s1 < s2)
(hn : (s1 : set P).nonempty) : s1.direction < s2.direction :=
begin
cases hn with p hp,
rw lt_iff_le_and_exists at h,
rcases h with ⟨hle, p2, hp2, hp2s1⟩,
rw set_like.lt_iff_le_and_exists,
use [direction_le hle, p2 -ᵥ p, vsub_mem_direction hp2 (hle hp)],
intro hm,
rw vsub_right_mem_direction_iff_mem hp p2 at hm,
exact hp2s1 hm
end
/-- The sup of the directions of two affine subspaces is less than or
equal to the direction of their sup. -/
lemma sup_direction_le (s1 s2 : affine_subspace k P) :
s1.direction ⊔ s2.direction ≤ (s1 ⊔ s2).direction :=
begin
repeat { rw [direction_eq_vector_span, vector_span_def] },
exact sup_le
(Inf_le_Inf (λ p hp, set.subset.trans (vsub_self_mono (le_sup_left : s1 ≤ s1 ⊔ s2)) hp))
(Inf_le_Inf (λ p hp, set.subset.trans (vsub_self_mono (le_sup_right : s2 ≤ s1 ⊔ s2)) hp))
end
/-- The sup of the directions of two nonempty affine subspaces with
empty intersection is less than the direction of their sup. -/
lemma sup_direction_lt_of_nonempty_of_inter_empty {s1 s2 : affine_subspace k P}
(h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (he : (s1 ∩ s2 : set P) = ∅) :
s1.direction ⊔ s2.direction < (s1 ⊔ s2).direction :=
begin
cases h1 with p1 hp1,
cases h2 with p2 hp2,
rw set_like.lt_iff_le_and_exists,
use [sup_direction_le s1 s2, p2 -ᵥ p1,
vsub_mem_direction ((le_sup_right : s2 ≤ s1 ⊔ s2) hp2) ((le_sup_left : s1 ≤ s1 ⊔ s2) hp1)],
intro h,
rw submodule.mem_sup at h,
rcases h with ⟨v1, hv1, v2, hv2, hv1v2⟩,
rw [←sub_eq_zero, sub_eq_add_neg, neg_vsub_eq_vsub_rev, add_comm v1, add_assoc,
←vadd_vsub_assoc, ←neg_neg v2, add_comm, ←sub_eq_add_neg, ←vsub_vadd_eq_vsub_sub,
vsub_eq_zero_iff_eq] at hv1v2,
refine set.nonempty.ne_empty _ he,
use [v1 +ᵥ p1, vadd_mem_of_mem_direction hv1 hp1],
rw hv1v2,
exact vadd_mem_of_mem_direction (submodule.neg_mem _ hv2) hp2
end
/-- If the directions of two nonempty affine subspaces span the whole
module, they have nonempty intersection. -/
lemma inter_nonempty_of_nonempty_of_sup_direction_eq_top {s1 s2 : affine_subspace k P}
(h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty)
(hd : s1.direction ⊔ s2.direction = ⊤) : ((s1 : set P) ∩ s2).nonempty :=
begin
by_contradiction h,
rw set.not_nonempty_iff_eq_empty at h,
have hlt := sup_direction_lt_of_nonempty_of_inter_empty h1 h2 h,
rw hd at hlt,
exact not_top_lt hlt
end
/-- If the directions of two nonempty affine subspaces are complements
of each other, they intersect in exactly one point. -/
lemma inter_eq_singleton_of_nonempty_of_is_compl {s1 s2 : affine_subspace k P}
(h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty)
(hd : is_compl s1.direction s2.direction) : ∃ p, (s1 : set P) ∩ s2 = {p} :=
begin
cases inter_nonempty_of_nonempty_of_sup_direction_eq_top h1 h2 hd.sup_eq_top with p hp,
use p,
ext q,
rw set.mem_singleton_iff,
split,
{ rintros ⟨hq1, hq2⟩,
have hqp : q -ᵥ p ∈ s1.direction ⊓ s2.direction :=
⟨vsub_mem_direction hq1 hp.1, vsub_mem_direction hq2 hp.2⟩,
rwa [hd.inf_eq_bot, submodule.mem_bot, vsub_eq_zero_iff_eq] at hqp },
{ exact λ h, h.symm ▸ hp }
end
/-- Coercing a subspace to a set then taking the affine span produces
the original subspace. -/
@[simp] lemma affine_span_coe (s : affine_subspace k P) : affine_span k (s : set P) = s :=
begin
refine le_antisymm _ (subset_span_points _ _),
rintros p ⟨p1, hp1, v, hv, rfl⟩,
exact vadd_mem_of_mem_direction hv hp1
end
end affine_subspace
section affine_space'
variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V]
[affine_space V P]
variables {ι : Type*}
include V
open affine_subspace set
/-- The `vector_span` is the span of the pairwise subtractions with a
given point on the left. -/
lemma vector_span_eq_span_vsub_set_left {s : set P} {p : P} (hp : p ∈ s) :
vector_span k s = submodule.span k ((-ᵥ) p '' s) :=
begin
rw vector_span_def,
refine le_antisymm _ (submodule.span_mono _),
{ rw submodule.span_le,
rintros v ⟨p1, p2, hp1, hp2, hv⟩,
rw ←vsub_sub_vsub_cancel_left p1 p2 p at hv,
rw [←hv, set_like.mem_coe, submodule.mem_span],
exact λ m hm, submodule.sub_mem _ (hm ⟨p2, hp2, rfl⟩) (hm ⟨p1, hp1, rfl⟩) },
{ rintros v ⟨p2, hp2, hv⟩,
exact ⟨p, p2, hp, hp2, hv⟩ }
end
/-- The `vector_span` is the span of the pairwise subtractions with a
given point on the right. -/
lemma vector_span_eq_span_vsub_set_right {s : set P} {p : P} (hp : p ∈ s) :
vector_span k s = submodule.span k ((-ᵥ p) '' s) :=
begin
rw vector_span_def,
refine le_antisymm _ (submodule.span_mono _),
{ rw submodule.span_le,
rintros v ⟨p1, p2, hp1, hp2, hv⟩,
rw ←vsub_sub_vsub_cancel_right p1 p2 p at hv,
rw [←hv, set_like.mem_coe, submodule.mem_span],
exact λ m hm, submodule.sub_mem _ (hm ⟨p1, hp1, rfl⟩) (hm ⟨p2, hp2, rfl⟩) },
{ rintros v ⟨p2, hp2, hv⟩,
exact ⟨p2, p, hp2, hp, hv⟩ }
end
/-- The `vector_span` is the span of the pairwise subtractions with a
given point on the left, excluding the subtraction of that point from
itself. -/
lemma vector_span_eq_span_vsub_set_left_ne {s : set P} {p : P} (hp : p ∈ s) :
vector_span k s = submodule.span k ((-ᵥ) p '' (s \ {p})) :=
begin
conv_lhs { rw [vector_span_eq_span_vsub_set_left k hp, ←set.insert_eq_of_mem hp,
←set.insert_diff_singleton, set.image_insert_eq] },
simp [submodule.span_insert_eq_span]
end
/-- The `vector_span` is the span of the pairwise subtractions with a
given point on the right, excluding the subtraction of that point from
itself. -/
lemma vector_span_eq_span_vsub_set_right_ne {s : set P} {p : P} (hp : p ∈ s) :
vector_span k s = submodule.span k ((-ᵥ p) '' (s \ {p})) :=
begin
conv_lhs { rw [vector_span_eq_span_vsub_set_right k hp, ←set.insert_eq_of_mem hp,
←set.insert_diff_singleton, set.image_insert_eq] },
simp [submodule.span_insert_eq_span]
end
/-- The `vector_span` is the span of the pairwise subtractions with a
given point on the right, excluding the subtraction of that point from
itself. -/
lemma vector_span_eq_span_vsub_finset_right_ne {s : finset P} {p : P} (hp : p ∈ s) :
vector_span k (s : set P) = submodule.span k ((s.erase p).image (-ᵥ p)) :=
by simp [vector_span_eq_span_vsub_set_right_ne _ (finset.mem_coe.mpr hp)]
/-- The `vector_span` of the image of a function is the span of the
pairwise subtractions with a given point on the left, excluding the
subtraction of that point from itself. -/
lemma vector_span_image_eq_span_vsub_set_left_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) :
vector_span k (p '' s) = submodule.span k ((-ᵥ) (p i) '' (p '' (s \ {i}))) :=
begin
conv_lhs { rw [vector_span_eq_span_vsub_set_left k (set.mem_image_of_mem p hi),
←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq,
set.image_insert_eq] },
simp [submodule.span_insert_eq_span]
end
/-- The `vector_span` of the image of a function is the span of the
pairwise subtractions with a given point on the right, excluding the
subtraction of that point from itself. -/
lemma vector_span_image_eq_span_vsub_set_right_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) :
vector_span k (p '' s) = submodule.span k ((-ᵥ (p i)) '' (p '' (s \ {i}))) :=
begin
conv_lhs { rw [vector_span_eq_span_vsub_set_right k (set.mem_image_of_mem p hi),
←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq,
set.image_insert_eq] },
simp [submodule.span_insert_eq_span]
end
/-- The `vector_span` of an indexed family is the span of the pairwise
subtractions with a given point on the left. -/
lemma vector_span_range_eq_span_range_vsub_left (p : ι → P) (i0 : ι) :
vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i0 -ᵥ p i)) :=
by rw [vector_span_eq_span_vsub_set_left k (set.mem_range_self i0), ←set.range_comp]
/-- The `vector_span` of an indexed family is the span of the pairwise
subtractions with a given point on the right. -/
lemma vector_span_range_eq_span_range_vsub_right (p : ι → P) (i0 : ι) :
vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i -ᵥ p i0)) :=
by rw [vector_span_eq_span_vsub_set_right k (set.mem_range_self i0), ←set.range_comp]
/-- The `vector_span` of an indexed family is the span of the pairwise
subtractions with a given point on the left, excluding the subtraction
of that point from itself. -/
lemma vector_span_range_eq_span_range_vsub_left_ne (p : ι → P) (i₀ : ι) :
vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i₀ -ᵥ p i)) :=
begin
rw [←set.image_univ, vector_span_image_eq_span_vsub_set_left_ne k _ (set.mem_univ i₀)],
congr' with v,
simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists,
subtype.coe_mk],
split,
{ rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩,
exact ⟨i₁, hi₁, hv⟩ },
{ exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ }
end
/-- The `vector_span` of an indexed family is the span of the pairwise
subtractions with a given point on the right, excluding the subtraction
of that point from itself. -/
lemma vector_span_range_eq_span_range_vsub_right_ne (p : ι → P) (i₀ : ι) :
vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i -ᵥ p i₀)) :=
begin
rw [←set.image_univ, vector_span_image_eq_span_vsub_set_right_ne k _ (set.mem_univ i₀)],
congr' with v,
simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists,
subtype.coe_mk],
split,
{ rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩,
exact ⟨i₁, hi₁, hv⟩ },
{ exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ }
end
/-- The affine span of a set is nonempty if and only if that set
is. -/
lemma affine_span_nonempty (s : set P) :
(affine_span k s : set P).nonempty ↔ s.nonempty :=
span_points_nonempty k s
/-- The affine span of a nonempty set is nonempty. -/
instance {s : set P} [nonempty s] : nonempty (affine_span k s) :=
((affine_span_nonempty k s).mpr (nonempty_subtype.mp ‹_›)).to_subtype
variables {k}
/-- Suppose a set of vectors spans `V`. Then a point `p`, together
with those vectors added to `p`, spans `P`. -/
lemma affine_span_singleton_union_vadd_eq_top_of_span_eq_top {s : set V} (p : P)
(h : submodule.span k (set.range (coe : s → V)) = ⊤) :
affine_span k ({p} ∪ (λ v, v +ᵥ p) '' s) = ⊤ :=
begin
convert ext_of_direction_eq _
⟨p,
mem_affine_span k (set.mem_union_left _ (set.mem_singleton _)),
mem_top k V p⟩,
rw [direction_affine_span, direction_top,
vector_span_eq_span_vsub_set_right k
((set.mem_union_left _ (set.mem_singleton _)) : p ∈ _), eq_top_iff, ←h],
apply submodule.span_mono,
rintros v ⟨v', rfl⟩,
use (v' : V) +ᵥ p,
simp
end
variables (k)
/-- `affine_span` is monotone. -/
lemma affine_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : affine_span k s₁ ≤ affine_span k s₂ :=
span_points_subset_coe_of_subset_coe (set.subset.trans h (subset_affine_span k _))
/-- Taking the affine span of a set, adding a point and taking the
span again produces the same results as adding the point to the set
and taking the span. -/
lemma affine_span_insert_affine_span (p : P) (ps : set P) :
affine_span k (insert p (affine_span k ps : set P)) = affine_span k (insert p ps) :=
by rw [set.insert_eq, set.insert_eq, span_union, span_union, affine_span_coe]
/-- If a point is in the affine span of a set, adding it to that set
does not change the affine span. -/
lemma affine_span_insert_eq_affine_span {p : P} {ps : set P} (h : p ∈ affine_span k ps) :
affine_span k (insert p ps) = affine_span k ps :=
begin
rw ←mem_coe at h,
rw [←affine_span_insert_affine_span, set.insert_eq_of_mem h, affine_span_coe]
end
end affine_space'
namespace affine_subspace
variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V]
[affine_space V P]
include V
/-- The direction of the sup of two nonempty affine subspaces is the
sup of the two directions and of any one difference between points in
the two subspaces. -/
lemma direction_sup {s1 s2 : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s1) (hp2 : p2 ∈ s2) :
(s1 ⊔ s2).direction = s1.direction ⊔ s2.direction ⊔ k ∙ (p2 -ᵥ p1) :=
begin
refine le_antisymm _ _,
{ change (affine_span k ((s1 : set P) ∪ s2)).direction ≤ _,
rw ←mem_coe at hp1,
rw [direction_affine_span, vector_span_eq_span_vsub_set_right k (set.mem_union_left _ hp1),
submodule.span_le],
rintros v ⟨p3, hp3, rfl⟩,
cases hp3,
{ rw [sup_assoc, sup_comm, set_like.mem_coe, submodule.mem_sup],
use [0, submodule.zero_mem _, p3 -ᵥ p1, vsub_mem_direction hp3 hp1],
rw zero_add },
{ rw [sup_assoc, set_like.mem_coe, submodule.mem_sup],
use [0, submodule.zero_mem _, p3 -ᵥ p1],
rw [and_comm, zero_add],
use rfl,
rw [←vsub_add_vsub_cancel p3 p2 p1, submodule.mem_sup],
use [p3 -ᵥ p2, vsub_mem_direction hp3 hp2, p2 -ᵥ p1,
submodule.mem_span_singleton_self _] } },
{ refine sup_le (sup_direction_le _ _) _,
rw [direction_eq_vector_span, vector_span_def],
exact Inf_le_Inf (λ p hp, set.subset.trans
(set.singleton_subset_iff.2
(vsub_mem_vsub (mem_span_points k p2 _ (set.mem_union_right _ hp2))
(mem_span_points k p1 _ (set.mem_union_left _ hp1))))
hp) }
end
/-- The direction of the span of the result of adding a point to a
nonempty affine subspace is the sup of the direction of that subspace
and of any one difference between that point and a point in the
subspace. -/
lemma direction_affine_span_insert {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) :
(affine_span k (insert p2 (s : set P))).direction = submodule.span k {p2 -ᵥ p1} ⊔ s.direction :=
begin
rw [sup_comm, ←set.union_singleton, ←coe_affine_span_singleton k V p2],
change (s ⊔ affine_span k {p2}).direction = _,
rw [direction_sup hp1 (mem_affine_span k (set.mem_singleton _)), direction_affine_span],
simp
end
/-- Given a point `p1` in an affine subspace `s`, and a point `p2`, a
point `p` is in the span of `s` with `p2` added if and only if it is a
multiple of `p2 -ᵥ p1` added to a point in `s`. -/
lemma mem_affine_span_insert_iff {s : affine_subspace k P} {p1 : P} (hp1 : p1 ∈ s) (p2 p : P) :
p ∈ affine_span k (insert p2 (s : set P)) ↔
∃ (r : k) (p0 : P) (hp0 : p0 ∈ s), p = r • (p2 -ᵥ p1 : V) +ᵥ p0 :=
begin
rw ←mem_coe at hp1,
rw [←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_insert_of_mem _ hp1)),
direction_affine_span_insert hp1, submodule.mem_sup],
split,
{ rintros ⟨v1, hv1, v2, hv2, hp⟩,
rw submodule.mem_span_singleton at hv1,
rcases hv1 with ⟨r, rfl⟩,
use [r, v2 +ᵥ p1, vadd_mem_of_mem_direction hv2 hp1],
symmetry' at hp,
rw [←sub_eq_zero, ←vsub_vadd_eq_vsub_sub, vsub_eq_zero_iff_eq] at hp,
rw [hp, vadd_vadd] },
{ rintros ⟨r, p3, hp3, rfl⟩,
use [r • (p2 -ᵥ p1), submodule.mem_span_singleton.2 ⟨r, rfl⟩, p3 -ᵥ p1,
vsub_mem_direction hp3 hp1],
rw [vadd_vsub_assoc, add_comm] }
end
end affine_subspace
|
b1f63d5a322745120b62710a4b80fb02649f0600 | 83c8119e3298c0bfc53fc195c41a6afb63d01513 | /library/init/meta/interactive.lean | 477563d433bdd8e1b14b2884fcd79b6f69f73b42 | [
"Apache-2.0"
] | permissive | anfelor/lean | 584b91c4e87a6d95f7630c2a93fb082a87319ed0 | 31cfc2b6bf7d674f3d0f73848b842c9c9869c9f1 | refs/heads/master | 1,610,067,141,310 | 1,585,992,232,000 | 1,585,992,232,000 | 251,683,543 | 0 | 0 | Apache-2.0 | 1,585,676,570,000 | 1,585,676,569,000 | null | UTF-8 | Lean | false | false | 70,943 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.tactic init.meta.rewrite_tactic init.meta.simp_tactic
import init.meta.smt.congruence_closure init.category.combinators
import init.meta.interactive_base init.meta.derive init.meta.match_tactic
import init.meta.congr_tactic
open lean
open lean.parser
local postfix `?`:9001 := optional
local postfix *:9001 := many
namespace tactic
/- allows metavars -/
meta def i_to_expr (q : pexpr) : tactic expr :=
to_expr q tt
/- allow metavars and no subgoals -/
meta def i_to_expr_no_subgoals (q : pexpr) : tactic expr :=
to_expr q tt ff
/- doesn't allows metavars -/
meta def i_to_expr_strict (q : pexpr) : tactic expr :=
to_expr q ff
/- Auxiliary version of i_to_expr for apply-like tactics.
This is a workaround for comment
https://github.com/leanprover/lean/issues/1342#issuecomment-307912291
at issue #1342.
In interactive mode, given a tactic
apply f
we want the apply tactic to create all metavariables. The following
definition will return `@f` for `f`. That is, it will **not** create
metavariables for implicit arguments.
Before we added `i_to_expr_for_apply`, the tactic
apply le_antisymm
would first elaborate `le_antisymm`, and create
@le_antisymm ?m_1 ?m_2 ?m_3 ?m_4
The type class resolution problem
?m_2 : weak_order ?m_1
by the elaborator since ?m_1 is not assigned yet, and the problem is
discarded.
Then, we would invoke `apply_core`, which would create two
new metavariables for the explicit arguments, and try to unify the resulting
type with the current target. After the unification,
the metavariables ?m_1, ?m_3 and ?m_4 are assigned, but we lost
the information about the pending type class resolution problem.
With `i_to_expr_for_apply`, `le_antisymm` is elaborate into `@le_antisymm`,
the apply_core tactic creates all metavariables, and solves the ones that
can be solved by type class resolution.
Another possible fix: we modify the elaborator to return pending
type class resolution problems, and store them in the tactic_state.
-/
meta def i_to_expr_for_apply (q : pexpr) : tactic expr :=
let aux (n : name) : tactic expr := do
p ← resolve_name n,
match p with
| (expr.const c []) := do r ← mk_const c, save_type_info r q, return r
| _ := i_to_expr p
end
in match q with
| (expr.const c []) := aux c
| (expr.local_const c _ _ _) := aux c
| _ := i_to_expr q
end
namespace interactive
open interactive interactive.types expr
/--
itactic: parse a nested "interactive" tactic. That is, parse
`{` tactic `}`
-/
meta def itactic : Type :=
tactic unit
meta def propagate_tags (tac : tactic unit) : tactic unit :=
do tag ← get_main_tag,
if tag = [] then tac
else focus1 $ do
tac,
gs ← get_goals,
when (bnot gs.empty) $ do
new_tag ← get_main_tag,
when new_tag.empty $ with_enable_tags (set_main_tag tag)
meta def concat_tags (tac : tactic (list (name × expr))) : tactic unit :=
mcond tags_enabled
(do in_tag ← get_main_tag,
r ← tac,
/- remove assigned metavars -/
r ← r.mfilter $ λ ⟨n, m⟩, bnot <$> is_assigned m,
match r with
| [(_, m)] := set_tag m in_tag /- if there is only new subgoal, we just propagate `in_tag` -/
| _ := r.mmap' (λ ⟨n, m⟩, set_tag m (n::in_tag))
end)
(tac >> skip)
/--
If the current goal is a Pi/forall `∀ x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`.
If the goal is an arrow `t → u`, then it puts `h : t` in the local context and the new goal target is `u`.
If the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails.
-/
meta def intro : parse ident_? → tactic unit
| none := propagate_tags (intro1 >> skip)
| (some h) := propagate_tags (tactic.intro h >> skip)
/--
Similar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder.
The variant `intros h₁ ... hₙ` introduces `n` new hypotheses using the given identifiers to name them.
-/
meta def intros : parse ident_* → tactic unit
| [] := propagate_tags (tactic.intros >> skip)
| hs := propagate_tags (intro_lst hs >> skip)
/--
The tactic `introv` allows the user to automatically introduce the variables of a theorem and explicitly name the hypotheses involved. The given names are used to name non-dependent hypotheses.
Examples:
```
example : ∀ a b : nat, a = b → b = a :=
begin
introv h,
exact h.symm
end
```
The state after `introv h` is
```
a b : ℕ,
h : a = b
⊢ b = a
```
```
example : ∀ a b : nat, a = b → ∀ c, b = c → a = c :=
begin
introv h₁ h₂,
exact h₁.trans h₂
end
```
The state after `introv h₁ h₂` is
```
a b : ℕ,
h₁ : a = b,
c : ℕ,
h₂ : b = c
⊢ a = c
```
-/
meta def introv (ns : parse ident_*) : tactic unit :=
propagate_tags (tactic.introv ns >> return ())
/--
The tactic `rename h₁ h₂` renames hypothesis `h₁` to `h₂` in the current local context.
-/
meta def rename (h₁ h₂ : parse ident) : tactic unit :=
propagate_tags (tactic.rename h₁ h₂)
/--
The `apply` tactic tries to match the current goal against the conclusion of the type of term. The argument term should be a term well-formed in the local context of the main goal. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non-dependent premises are added before dependent ones.
The `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types.
-/
meta def apply (q : parse texpr) : tactic unit :=
concat_tags (do h ← i_to_expr_for_apply q, tactic.apply h)
/--
Similar to the `apply` tactic, but does not reorder goals.
-/
meta def fapply (q : parse texpr) : tactic unit :=
concat_tags (i_to_expr_for_apply q >>= tactic.fapply)
/--
Similar to the `apply` tactic, but only creates subgoals for non-dependent premises that have not been fixed by type inference or type class resolution.
-/
meta def eapply (q : parse texpr) : tactic unit :=
concat_tags (i_to_expr_for_apply q >>= tactic.eapply)
/--
Similar to the `apply` tactic, but allows the user to provide a `apply_cfg` configuration object.
-/
meta def apply_with (q : parse parser.pexpr) (cfg : apply_cfg) : tactic unit :=
concat_tags (do e ← i_to_expr_for_apply q, tactic.apply e cfg)
/--
Similar to the `apply` tactic, but uses matching instead of unification.
`apply_match t` is equivalent to `apply_with t {unify := ff}`
-/
meta def mapply (q : parse texpr) : tactic unit :=
concat_tags (do e ← i_to_expr_for_apply q, tactic.apply e {unify := ff})
/--
This tactic tries to close the main goal `... ⊢ t` by generating a term of type `t` using type class resolution.
-/
meta def apply_instance : tactic unit :=
tactic.apply_instance
/--
This tactic behaves like `exact`, but with a big difference: the user can put underscores `_` in the expression as placeholders for holes that need to be filled, and `refine` will generate as many subgoals as there are holes.
Note that some holes may be implicit. The type of each hole must either be synthesized by the system or declared by an explicit type ascription like `(_ : nat → Prop)`.
-/
meta def refine (q : parse texpr) : tactic unit :=
tactic.refine q
/--
This tactic looks in the local context for a hypothesis whose type is equal to the goal target. If it finds one, it uses it to prove the goal, and otherwise it fails.
-/
meta def assumption : tactic unit :=
tactic.assumption
/-- Try to apply `assumption` to all goals. -/
meta def assumption' : tactic unit :=
tactic.any_goals tactic.assumption
private meta def change_core (e : expr) : option expr → tactic unit
| none := tactic.change e
| (some h) :=
do num_reverted : ℕ ← revert h,
expr.pi n bi d b ← target,
tactic.change $ expr.pi n bi e b,
intron num_reverted
/--
`change u` replaces the target `t` of the main goal to `u` provided that `t` is well formed with respect to the local context of the main goal and `t` and `u` are definitionally equal.
`change u at h` will change a local hypothesis to `u`.
`change t with u at h1 h2 ...` will replace `t` with `u` in all the supplied hypotheses (or `*`), or in the goal if no `at` clause is specified, provided that `t` and `u` are definitionally equal.
-/
meta def change (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit
| none (loc.ns [none]) := do e ← i_to_expr q, change_core e none
| none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh)
| none _ := fail "change-at does not support multiple locations"
| (some w) l :=
do u ← mk_meta_univ,
ty ← mk_meta_var (sort u),
eq ← i_to_expr ``(%%q : %%ty),
ew ← i_to_expr ``(%%w : %%ty),
let repl := λe : expr, e.replace (λ a n, if a = eq then some ew else none),
l.try_apply
(λh, do e ← infer_type h, change_core (repl e) (some h))
(do g ← target, change_core (repl g) none)
/--
This tactic provides an exact proof term to solve the main goal. If `t` is the goal and `p` is a term of type `u` then `exact p` succeeds if and only if `t` and `u` can be unified.
-/
meta def exact (q : parse texpr) : tactic unit :=
do tgt : expr ← target,
i_to_expr_strict ``(%%q : %%tgt) >>= tactic.exact
/--
Like `exact`, but takes a list of terms and checks that all goals are discharged after the tactic.
-/
meta def exacts : parse pexpr_list_or_texpr → tactic unit
| [] := done
| (t :: ts) := exact t >> exacts ts
/--
A synonym for `exact` that allows writing `have/suffices/show ..., from ...` in tactic mode.
-/
meta def «from» := exact
/--
`revert h₁ ... hₙ` applies to any goal with hypotheses `h₁` ... `hₙ`. It moves the hypotheses and their dependencies to the target of the goal. This tactic is the inverse of `intro`.
-/
meta def revert (ids : parse ident*) : tactic unit :=
propagate_tags (do hs ← mmap tactic.get_local ids, revert_lst hs, skip)
private meta def resolve_name' (n : name) : tactic expr :=
do {
p ← resolve_name n,
match p with
| expr.const n _ := mk_const n -- create metavars for universe levels
| _ := i_to_expr p
end
}
/- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant.
This is not an optimization, by skipping the elaborator we make sure that no unwanted resolution is used.
Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat.
Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/
meta def to_expr' (p : pexpr) : tactic expr :=
match p with
| (const c []) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e
| (local_const c _ _ _) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e
| _ := i_to_expr p
end
@[derive has_reflect]
meta structure rw_rule :=
(pos : pos)
(symm : bool)
(rule : pexpr)
meta def get_rule_eqn_lemmas (r : rw_rule) : tactic (list name) :=
let aux (n : name) : tactic (list name) := do {
p ← resolve_name n,
-- unpack local refs
let e := p.erase_annotations.get_app_fn.erase_annotations,
match e with
| const n _ := get_eqn_lemmas_for tt n
| _ := return []
end } <|> return [] in
match r.rule with
| const n _ := aux n
| local_const n _ _ _ := aux n
| _ := return []
end
private meta def rw_goal (cfg : rewrite_cfg) (rs : list rw_rule) : tactic unit :=
rs.mmap' $ λ r, do
save_info r.pos,
eq_lemmas ← get_rule_eqn_lemmas r,
orelse'
(do e ← to_expr' r.rule, rewrite_target e {symm := r.symm, ..cfg})
(eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_target e {symm := r.symm, ..cfg})
(eq_lemmas.empty)
private meta def uses_hyp (e : expr) (h : expr) : bool :=
e.fold ff $ λ t _ r, r || to_bool (t = h)
private meta def rw_hyp (cfg : rewrite_cfg) : list rw_rule → expr → tactic unit
| [] hyp := skip
| (r::rs) hyp := do
save_info r.pos,
eq_lemmas ← get_rule_eqn_lemmas r,
orelse'
(do e ← to_expr' r.rule, when (not (uses_hyp e hyp)) $ rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs)
(eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs)
(eq_lemmas.empty)
meta def rw_rule_p (ep : parser pexpr) : parser rw_rule :=
rw_rule.mk <$> cur_pos <*> (option.is_some <$> (with_desc "←" (tk "←" <|> tk "<-"))?) <*> ep
@[derive has_reflect]
meta structure rw_rules_t :=
(rules : list rw_rule)
(end_pos : option pos)
-- accepts the same content as `pexpr_list_or_texpr`, but with correct goal info pos annotations
meta def rw_rules : parser rw_rules_t :=
(tk "[" *>
rw_rules_t.mk <$> sep_by (skip_info (tk ",")) (set_goal_info_pos $ rw_rule_p (parser.pexpr 0))
<*> (some <$> cur_pos <* set_goal_info_pos (tk "]")))
<|> rw_rules_t.mk <$> (list.ret <$> rw_rule_p texpr) <*> return none
private meta def rw_core (rs : parse rw_rules) (loca : parse location) (cfg : rewrite_cfg) : tactic unit :=
match loca with
| loc.wildcard := loca.try_apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules)
| _ := loca.apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules)
end >> try (reflexivity reducible)
>> (returnopt rs.end_pos >>= save_info <|> skip)
/--
`rewrite e` applies identity `e` as a rewrite rule to the target of the main goal. If `e` is preceded by left arrow (`←` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined constant, then the equational lemmas associated with `e` are used. This provides a convenient way to unfold `e`.
`rewrite [e₁, ..., eₙ]` applies the given rules sequentially.
`rewrite e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `⊢` or `|-` can also be used, to signify the target of the goal.
-/
meta def rewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit :=
propagate_tags (rw_core q l cfg)
/--
An abbreviation for `rewrite`.
-/
meta def rw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit :=
propagate_tags (rw_core q l cfg)
/--
`rewrite` followed by `assumption`.
-/
meta def rwa (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit :=
rewrite q l cfg >> try assumption
/--
A variant of `rewrite` that uses the unifier more aggressively, unfolding semireducible definitions.
-/
meta def erewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit :=
propagate_tags (rw_core q l cfg)
/--
An abbreviation for `erewrite`.
-/
meta def erw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit :=
propagate_tags (rw_core q l cfg)
precedence `generalizing` : 0
private meta def collect_hyps_uids : tactic name_set :=
do ctx ← local_context,
return $ ctx.foldl (λ r h, r.insert h.local_uniq_name) mk_name_set
private meta def revert_new_hyps (input_hyp_uids : name_set) : tactic unit :=
do ctx ← local_context,
let to_revert := ctx.foldr (λ h r, if input_hyp_uids.contains h.local_uniq_name then r else h::r) [],
tag ← get_main_tag,
m ← revert_lst to_revert,
set_main_tag (mk_num_name `_case m :: tag)
/--
Apply `t` to main goal, and revert any new hypothesis in the generated goals,
and tag generated goals when using supported tactics such as: `induction`, `apply`, `cases`, `constructor`, ...
This tactic is useful for writing robust proof scripts that are not sensitive
to the name generation strategy used by `t`.
```
example (n : ℕ) : n = n :=
begin
with_cases { induction n },
case nat.zero { reflexivity },
case nat.succ : n' ih { reflexivity }
end
```
TODO(Leo): improve docstring
-/
meta def with_cases (t : itactic) : tactic unit :=
with_enable_tags $ focus1 $ do
input_hyp_uids ← collect_hyps_uids,
t,
all_goals (revert_new_hyps input_hyp_uids)
private meta def get_type_name (e : expr) : tactic name :=
do e_type ← infer_type e >>= whnf,
(const I ls) ← return $ get_app_fn e_type,
return I
private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name)
| (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x)
| _ := fail "parse error"
private meta def generalize_arg_p : parser (pexpr × name) :=
with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux
/--
`generalize : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type.
`generalize h : e = x` in addition registers the hypothesis `h : e = x`.
-/
meta def generalize (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) : tactic unit :=
propagate_tags $
do let (p, x) := p,
e ← i_to_expr p,
some h ← pure h | tactic.generalize e x >> intro1 >> skip,
tgt ← target,
-- if generalizing fails, fall back to not replacing anything
tgt' ← do {
⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize e x >> target),
to_expr ``(Π x, %%e = x → %%(tgt'.binding_body.lift_vars 0 1))
} <|> to_expr ``(Π x, %%e = x → %%tgt),
t ← assert h tgt',
swap,
exact ``(%%t %%e rfl),
intro x,
intro h
meta def cases_arg_p : parser (option name × pexpr) :=
with_desc "(id :)? expr" $ do
t ← texpr,
match t with
| (local_const x _ _ _) :=
(tk ":" *> do t ← texpr, pure (some x, t)) <|> pure (none, t)
| _ := pure (none, t)
end
/--
Given the initial tag `in_tag` and the cases names produced by `induction` or `cases` tactic,
update the tag of the new subgoals.
-/
private meta def set_cases_tags (in_tag : tag) (rs : list name) : tactic unit :=
do te ← tags_enabled,
gs ← get_goals,
match gs with
| [g] := when te (set_tag g in_tag) -- if only one goal was produced, we should not make the tag longer
| _ := do
let tgs : list (name × expr) := rs.map₂ (λ n g, (n, g)) gs,
if te
then tgs.mmap' (λ ⟨n, g⟩, set_tag g (n::in_tag))
/- If `induction/cases` is not in a `with_cases` block, we still set tags using `_case_simple` to make
sure we can use the `case` notation.
```
induction h,
case c { ... }
```
-/
else tgs.mmap' (λ ⟨n, g⟩, with_enable_tags (set_tag g (`_case_simple::n::[])))
end
private meta def set_induction_tags (in_tag : tag) (rs : list (name × list expr × list (name × expr))) : tactic unit :=
set_cases_tags in_tag (rs.map (λ e, e.1))
/--
Assuming `x` is a variable in the local context with an inductive type, `induction x` applies induction on `x` to the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor and an inductive hypothesis is added for each recursive argument to the constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the inductive hypothesis incorporates that hypothesis as well.
For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `induction n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypotheses `h : P (nat.succ a)` and `ih₁ : P a → Q a` and target `Q (nat.succ a)`. Here the names `a` and `ih₁` ire chosen automatically.
`induction e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then performs induction on the resulting variable.
`induction e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors and inductive hypotheses, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. Note that for long sequences of names, the `case` tactic provides a more convenient naming mechanism.
`induction e using r` allows the user to specify the principle of induction that should be used. Here `r` should be a theorem whose result type must be of the form `C t`, where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables
`induction e generalizing z₁ ... zₙ`, where `z₁ ... zₙ` are variables in the local context, generalizes over `z₁ ... zₙ` before applying the induction but then introduces them in each goal. In other words, the net effect is that each inductive hypothesis is generalized.
`induction h : t` will introduce an equality of the form `h : t = C x y`, asserting that the input term is equal to the current constructor case, to the context.
-/
meta def induction (hp : parse cases_arg_p) (rec_name : parse using_ident) (ids : parse with_ident_list)
(revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit :=
do in_tag ← get_main_tag,
focus1 $ do {
-- process `h : t` case
e ← match hp with
| (some h, p) := do
x ← get_unused_name,
generalize h () (p, x),
get_local x
| (none, p) := i_to_expr p
end,
-- generalize major premise
e ← if e.is_local_constant then pure e
else tactic.generalize e >> intro1,
-- generalize major premise args
(e, newvars, locals) ← do {
none ← pure rec_name | pure (e, [], []),
t ← infer_type e,
t ← whnf_ginductive t,
const n _ ← pure t.get_app_fn | pure (e, [], []),
env ← get_env,
tt ← pure $ env.is_inductive n | pure (e, [], []),
let (locals, nonlocals) := (t.get_app_args.drop $ env.inductive_num_params n).partition
(λ arg : expr, arg.is_local_constant),
_ :: _ ← pure nonlocals | pure (e, [], []),
n ← tactic.revert e,
newvars ← nonlocals.mmap $ λ arg, do {
n ← revert_kdeps arg,
tactic.generalize arg,
h ← intro1,
intron n,
-- now try to clear hypotheses that may have been abstracted away
let locals := arg.fold [] (λ e _ acc, if e.is_local_constant then e::acc else acc),
locals.mmap' (try ∘ clear),
pure h
},
intron (n-1),
e ← intro1,
pure (e, newvars, locals)
},
-- revert `generalizing` params
n ← mmap tactic.get_local (revert.get_or_else []) >>= revert_lst,
rs ← tactic.induction e ids rec_name,
all_goals $ do {
intron n,
clear_lst (newvars.map local_pp_name),
(e::locals).mmap' (try ∘ clear) },
set_induction_tags in_tag rs }
private meta def is_case_simple_tag : tag → bool
| (`_case_simple :: _) := tt
| _ := ff
private meta def is_case_tag : tag → option nat
| (name.mk_numeral n `_case :: _) := some n.val
| _ := none
private meta def tag_match (t : tag) (pre : list name) : bool :=
pre.is_prefix_of t.reverse &&
((is_case_tag t).is_some || is_case_simple_tag t)
private meta def collect_tagged_goals (pre : list name) : tactic (list expr) :=
do gs ← get_goals,
gs.mfoldr (λ g r, do
t ← get_tag g,
if tag_match t pre then return (g::r) else return r)
[]
private meta def find_tagged_goal_aux (pre : list name) : tactic expr :=
do gs ← collect_tagged_goals pre,
match gs with
| [] := fail ("invalid `case`, there is no goal tagged with prefix " ++ to_string pre)
| [g] := return g
| gs := do
tags : list (list name) ← gs.mmap get_tag,
fail ("invalid `case`, there is more than one goal tagged with prefix " ++ to_string pre ++ ", matching tags: " ++ to_string tags)
end
private meta def find_tagged_goal (pre : list name) : tactic expr :=
match pre with
| [] := do g::gs ← get_goals, return g
| _ :=
find_tagged_goal_aux pre
<|>
-- try to resolve constructor names, and try again
do env ← get_env,
pre ← pre.mmap (λ id,
(do r_id ← resolve_constant id,
if (env.inductive_type_of r_id).is_none then return id
else return r_id)
<|> return id),
find_tagged_goal_aux pre
end
private meta def find_case (goals : list expr) (ty : name) (idx : nat) (num_indices : nat) : option expr → expr → option (expr × expr)
| case e := if e.has_meta_var then match e with
| (mvar _ _ _) :=
do case ← case,
guard $ e ∈ goals,
pure (case, e)
| (app _ _) :=
let idx :=
match e.get_app_fn with
| const (name.mk_string rec ty') _ :=
guard (ty' = ty) >>
match mk_simple_name rec with
| `drec := some idx | `rec := some idx
-- indices + major premise
| `dcases_on := some (idx + num_indices + 1) | `cases_on := some (idx + num_indices + 1)
| _ := none
end
| _ := none
end in
match idx with
| none := list.foldl (<|>) (find_case case e.get_app_fn) $ e.get_app_args.map (find_case case)
| some idx :=
let args := e.get_app_args in
do arg ← args.nth idx,
args.enum.foldl
(λ acc ⟨i, arg⟩, match acc with
| some _ := acc
| _ := if i ≠ idx then find_case none arg else none
end)
-- start recursion with likely case
(find_case (some arg) arg)
end
| (lam _ _ _ e) := find_case case e
| (elet _ _ _ e) := find_case case e
| (macro n args) := list.foldl (<|>) none $ args.map (find_case case)
| _ := none
end else none
private meta def rename_lams : expr → list name → tactic unit
| (lam n _ _ e) (n'::ns) := (rename n n' >> rename_lams e ns) <|> rename_lams e (n'::ns)
| _ _ := skip
/--
Focuses on the `induction`/`cases`/`with_cases` subgoal corresponding to the given tag prefix, optionally renaming introduced locals.
```
example (n : ℕ) : n = n :=
begin
induction n,
case nat.zero { reflexivity },
case nat.succ : a ih { reflexivity }
end
```
-/
meta def case (pre : parse ident_*) (ids : parse $ (tk ":" *> ident_*)?) (tac : itactic) : tactic unit :=
do g ← find_tagged_goal pre,
tag ← get_tag g,
let ids := ids.get_or_else [],
match is_case_tag tag with
| some n := do
let m := ids.length,
gs ← get_goals,
set_goals $ g :: gs.filter (≠ g),
intro_lst ids,
when (m < n) $ intron (n - m),
solve1 tac
| none :=
match is_case_simple_tag tag with
| tt :=
/- Use the old `case` implementation -/
do r ← result,
env ← get_env,
[ctor_id] ← return pre,
ctor ← resolve_constant ctor_id
<|> fail ("'" ++ to_string ctor_id ++ "' is not a constructor"),
ty ← (env.inductive_type_of ctor).to_monad
<|> fail ("'" ++ to_string ctor ++ "' is not a constructor"),
let ctors := env.constructors_of ty,
let idx := env.inductive_num_params ty + /- motive -/ 1 +
list.index_of ctor ctors,
/- Remark: we now use `find_case` just to locate the `lambda` used in `rename_lams`.
The goal is now located using tags. -/
(case, _) ← (find_case [g] ty idx (env.inductive_num_indices ty) none r ).to_monad
<|> fail "could not find open goal of given case",
gs ← get_goals,
set_goals $ g :: gs.filter (≠ g),
rename_lams case ids,
solve1 tac
| ff := failed
end
end
/--
Assuming `x` is a variable in the local context with an inductive type, `destruct x` splits the main goal, producing one goal for each constructor of the inductive type, in which `x` is assumed to be a general instance of that constructor. In contrast to `cases`, the local context is unchanged, i.e. no elements are reverted or introduced.
For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `destruct n` produces one goal with target `n = 0 → Q n`, and one goal with target `∀ (a : ℕ), (λ (w : ℕ), n = w → Q n) (nat.succ a)`. Here the name `a` is chosen automatically.
-/
meta def destruct (p : parse texpr) : tactic unit :=
i_to_expr p >>= tactic.destruct
meta def cases_core (e : expr) (ids : list name := []) : tactic unit :=
do in_tag ← get_main_tag,
focus1 $ do
rs ← tactic.cases e ids,
set_cases_tags in_tag rs
/--
Assuming `x` is a variable in the local context with an inductive type, `cases x` splits the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the case split affects that hypothesis as well.
For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypothesis `h : P (nat.succ a)` and target `Q (nat.succ a)`. Here the name `a` is chosen automatically.
`cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then cases on the resulting variable.
`cases e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically.
`cases h : e`, where `e` is a variable or an expression, performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis, where `...` is the constructor instance for that particular case.
-/
meta def cases : parse cases_arg_p → parse with_ident_list → tactic unit
| (none, p) ids := do
e ← i_to_expr p,
cases_core e ids
| (some h, p) ids := do
x ← get_unused_name,
generalize h () (p, x),
hx ← get_local x,
cases_core hx ids
private meta def find_matching_hyp (ps : list pattern) : tactic expr :=
any_hyp $ λ h, do
type ← infer_type h,
ps.mfirst $ λ p, do
match_pattern p type,
return h
/--
`cases_matching p` applies the `cases` tactic to a hypothesis `h : type` if `type` matches the pattern `p`.
`cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type` if `type` matches one of the given patterns.
`cases_matching* p` more efficient and compact version of `focus1 { repeat { cases_matching p } }`. It is more efficient because the pattern is compiled once.
Example: The following tactic destructs all conjunctions and disjunctions in the current goal.
```
cases_matching* [_ ∨ _, _ ∧ _]
```
-/
meta def cases_matching (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit :=
do ps ← ps.mmap pexpr_to_pattern,
if rec.is_none
then find_matching_hyp ps >>= cases_core
else tactic.focus1 $ tactic.repeat $ find_matching_hyp ps >>= cases_core
/-- Shorthand for `cases_matching` -/
meta def casesm (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit :=
cases_matching rec ps
private meta def try_cases_for_types (type_names : list name) (at_most_one : bool) : tactic unit :=
any_hyp $ λ h, do
I ← expr.get_app_fn <$> (infer_type h >>= head_beta),
guard I.is_constant,
guard (I.const_name ∈ type_names),
tactic.focus1 (cases_core h >> if at_most_one then do n ← num_goals, guard (n <= 1) else skip)
/--
`cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)`
`cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)`
`cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }`
`cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1.
Example: The following tactic destructs all conjunctions and disjunctions in the current goal.
```
cases_type* or and
```
-/
meta def cases_type (one : parse $ (tk "!")?) (rec : parse $ (tk "*")?) (type_names : parse ident*) : tactic unit :=
do type_names ← type_names.mmap resolve_constant,
if rec.is_none
then try_cases_for_types type_names (bnot one.is_none)
else tactic.focus1 $ tactic.repeat $ try_cases_for_types type_names (bnot one.is_none)
/--
Tries to solve the current goal using a canonical proof of `true`, or the `reflexivity` tactic, or the `contradiction` tactic.
-/
meta def trivial : tactic unit :=
tactic.triv <|> tactic.reflexivity <|> tactic.contradiction <|> fail "trivial tactic failed"
/--
Closes the main goal using `sorry`.
-/
meta def admit : tactic unit := tactic.admit
/--
Closes the main goal using `sorry`.
-/
meta def «sorry» : tactic unit := tactic.admit
/--
The contradiction tactic attempts to find in the current local context a hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses.
-/
meta def contradiction : tactic unit :=
tactic.contradiction
/--
`iterate { t }` repeatedly applies tactic `t` until `t` fails. `iterate { t }` always succeeds.
`iterate n { t }` applies `t` `n` times.
-/
meta def iterate (n : parse small_nat?) (t : itactic) : tactic unit :=
match n with
| none := tactic.iterate t
| some n := iterate_exactly n t
end
/--
`repeat { t }` applies `t` to each goal. If the application succeeds,
the tactic is applied recursively to all the generated subgoals until it eventually fails.
The recursion stops in a subgoal when the tactic has failed to make progress.
The tactic `repeat { t }` never fails.
-/
meta def repeat : itactic → tactic unit :=
tactic.repeat
/--
`try { t }` tries to apply tactic `t`, but succeeds whether or not `t` succeeds.
-/
meta def try : itactic → tactic unit :=
tactic.try
/--
A do-nothing tactic that always succeeds.
-/
meta def skip : tactic unit :=
tactic.skip
/--
`solve1 { t }` applies the tactic `t` to the main goal and fails if it is not solved.
-/
meta def solve1 : itactic → tactic unit :=
tactic.solve1
/--
`abstract id { t }` tries to use tactic `t` to solve the main goal. If it succeeds, it abstracts the goal as an independent definition or theorem with name `id`. If `id` is omitted, a name is generated automatically.
-/
meta def abstract (id : parse ident?) (tac : itactic) : tactic unit :=
tactic.abstract tac id
/--
`all_goals { t }` applies the tactic `t` to every goal, and succeeds if each application succeeds.
-/
meta def all_goals : itactic → tactic unit :=
tactic.all_goals
/--
`any_goals { t }` applies the tactic `t` to every goal, and succeeds if at least one application succeeds.
-/
meta def any_goals : itactic → tactic unit :=
tactic.any_goals
/--
`focus { t }` temporarily hides all goals other than the first, applies `t`, and then restores the other goals. It fails if there are no goals.
-/
meta def focus (tac : itactic) : tactic unit :=
tactic.focus1 tac
private meta def assume_core (n : name) (ty : pexpr) :=
do t ← target,
when (not $ t.is_pi ∨ t.is_let) whnf_target,
t ← target,
when (not $ t.is_pi ∨ t.is_let) $
fail "assume tactic failed, Pi/let expression expected",
ty ← i_to_expr ty,
unify ty t.binding_domain,
intro_core n >> skip
/--
Assuming the target of the goal is a Pi or a let, `assume h : t` unifies the type of the binder with `t` and introduces it with name `h`, just like `intro h`. If `h` is absent, the tactic uses the name `this`. If `t` is omitted, it will be inferred.
`assume (h₁ : t₁) ... (hₙ : tₙ)` introduces multiple hypotheses. Any of the types may be omitted, but the names must be present.
-/
meta def «assume» : parse (sum.inl <$> (tk ":" *> texpr) <|> sum.inr <$> parse_binders tac_rbp) → tactic unit
| (sum.inl ty) := assume_core `this ty
| (sum.inr binders) :=
binders.mmap' $ λ b, assume_core b.local_pp_name b.local_type
/--
`have h : t := p` adds the hypothesis `h : t` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred.
`have h : t` adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable.
If `h` is omitted, the name `this` is used.
-/
meta def «have» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit :=
let h := h.get_or_else `this in
match q₁, q₂ with
| some e, some p := do
t ← i_to_expr e,
v ← i_to_expr ``(%%p : %%t),
tactic.assertv h t v
| none, some p := do
p ← i_to_expr p,
tactic.note h none p
| some e, none := i_to_expr e >>= tactic.assert h
| none, none := do
u ← mk_meta_univ,
e ← mk_meta_var (sort u),
tactic.assert h e
end >> skip
/--
`let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred.
`let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable.
If `h` is omitted, the name `this` is used.
-/
meta def «let» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit :=
let h := h.get_or_else `this in
match q₁, q₂ with
| some e, some p := do
t ← i_to_expr e,
v ← i_to_expr ``(%%p : %%t),
tactic.definev h t v
| none, some p := do
p ← i_to_expr p,
tactic.pose h none p
| some e, none := i_to_expr e >>= tactic.define h
| none, none := do
u ← mk_meta_univ,
e ← mk_meta_var (sort u),
tactic.define h e
end >> skip
/--
`suffices h : t` is the same as `have h : t, tactic.swap`. In other words, it adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`.
-/
meta def «suffices» (h : parse ident?) (t : parse (tk ":" *> texpr)?) : tactic unit :=
«have» h t none >> tactic.swap
/--
This tactic displays the current state in the tracing buffer.
-/
meta def trace_state : tactic unit :=
tactic.trace_state
/--
`trace a` displays `a` in the tracing buffer.
-/
meta def trace {α : Type} [has_to_tactic_format α] (a : α) : tactic unit :=
tactic.trace a
/--
`existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals.
`existsi [e₁, ..., eₙ]` iteratively does the same for each expression in the list.
-/
meta def existsi : parse pexpr_list_or_texpr → tactic unit
| [] := return ()
| (p::ps) := i_to_expr p >>= tactic.existsi >> existsi ps
/--
This tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds.
-/
meta def constructor : tactic unit :=
concat_tags tactic.constructor
/--
Similar to `constructor`, but only non-dependent premises are added as new goals.
-/
meta def econstructor : tactic unit :=
concat_tags tactic.econstructor
/--
Applies the first constructor when the type of the target is an inductive data type with two constructors.
-/
meta def left : tactic unit :=
concat_tags tactic.left
/--
Applies the second constructor when the type of the target is an inductive data type with two constructors.
-/
meta def right : tactic unit :=
concat_tags tactic.right
/--
Applies the constructor when the type of the target is an inductive data type with one constructor.
-/
meta def split : tactic unit :=
concat_tags tactic.split
private meta def constructor_matching_aux (ps : list pattern) : tactic unit :=
do t ← target, ps.mfirst (λ p, match_pattern p t), constructor
meta def constructor_matching (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit :=
do ps ← ps.mmap pexpr_to_pattern,
if rec.is_none then constructor_matching_aux ps
else tactic.focus1 $ tactic.repeat $ constructor_matching_aux ps
/--
Replaces the target of the main goal by `false`.
-/
meta def exfalso : tactic unit :=
tactic.exfalso
/--
The `injection` tactic is based on the fact that constructors of inductive data types are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t₁)` and `(c t₂)` are two terms that are equal then `t₁` and `t₂` are equal too.
If `q` is a proof of a statement of conclusion `t₁ = t₂`, then injection applies injectivity to derive the equality of all arguments of `t₁` and `t₂` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t₁` and `t₂` should be constructor applications of the same constructor.
Given `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h₁ h₂` uses the names `h₁` and `h₂` to name the new hypotheses.
-/
meta def injection (q : parse texpr) (hs : parse with_ident_list) : tactic unit :=
do e ← i_to_expr q, tactic.injection_with e hs, try assumption
/--
`injections with h₁ ... hₙ` iteratively applies `injection` to hypotheses using the names `h₁ ... hₙ`.
-/
meta def injections (hs : parse with_ident_list) : tactic unit :=
do tactic.injections_with hs, try assumption
end interactive
meta structure simp_config_ext extends simp_config :=
(discharger : tactic unit := failed)
section mk_simp_set
open expr interactive.types
@[derive has_reflect]
meta inductive simp_arg_type : Type
| all_hyps : simp_arg_type
| except : name → simp_arg_type
| expr : pexpr → simp_arg_type
| symm_expr : pexpr → simp_arg_type
meta instance simp_arg_type_to_tactic_format : has_to_tactic_format simp_arg_type :=
⟨λ a, match a with
| simp_arg_type.all_hyps := pure "*"
| (simp_arg_type.except n) := pure format!"-{n}"
| (simp_arg_type.expr e) := i_to_expr_no_subgoals e >>= pp
| (simp_arg_type.symm_expr e) := ((++) "←") <$> (i_to_expr_no_subgoals e >>= pp)
end⟩
meta def simp_arg : parser simp_arg_type :=
(tk "*" *> return simp_arg_type.all_hyps) <|>
(tk "-" *> simp_arg_type.except <$> ident) <|>
(tk "<-" *> simp_arg_type.symm_expr <$> texpr) <|>
(simp_arg_type.expr <$> texpr)
meta def simp_arg_list : parser (list simp_arg_type) :=
(tk "*" *> return [simp_arg_type.all_hyps]) <|> list_of simp_arg <|> return []
private meta def resolve_exception_ids (all_hyps : bool) : list name → list name → list name → tactic (list name × list name)
| [] gex hex := return (gex.reverse, hex.reverse)
| (id::ids) gex hex := do
p ← resolve_name id,
let e := p.erase_annotations.get_app_fn.erase_annotations,
match e with
| const n _ := resolve_exception_ids ids (n::gex) hex
| local_const n _ _ _ := when (not all_hyps) (fail $ sformat! "invalid local exception {id}, '*' was not used") >>
resolve_exception_ids ids gex (n::hex)
| _ := fail $ sformat! "invalid exception {id}, unknown identifier"
end
/-- Decode a list of `simp_arg_type` into lists for each type.
This is a backwards-compatibility version of `decode_simp_arg_list_with_symm`.
This version fails when an argument of the form `simp_arg_type.symm_expr`
is included, so that `simp`-like tactics that do not (yet) support backwards rewriting
should properly report an error but function normally on other inputs.
-/
meta def decode_simp_arg_list (hs : list simp_arg_type) : tactic $ list pexpr × list name × list name × bool :=
do
(hs, ex, all) ← hs.mfoldl
(λ (r : (list pexpr × list name × bool)) h, do
let (es, ex, all) := r,
match h with
| simp_arg_type.all_hyps := pure (es, ex, tt)
| simp_arg_type.except id := pure (es, id::ex, all)
| simp_arg_type.expr e := pure (e::es, ex, all)
| simp_arg_type.symm_expr _ := fail "arguments of the form '←...' are not supported"
end)
([], [], ff),
(gex, hex) ← resolve_exception_ids all ex [] [],
return (hs.reverse, gex, hex, all)
/-- Decode a list of `simp_arg_type` into lists for each type.
This is the newer version of `decode_simp_arg_list`,
and has a new name for backwards compatibility.
This version indicates the direction of a `simp` lemma by including a `bool` with the `pexpr`.
-/
meta def decode_simp_arg_list_with_symm (hs : list simp_arg_type) : tactic $ list (pexpr × bool) × list name × list name × bool :=
do
let (hs, ex, all) := hs.foldl
(λ r h,
match r, h with
| (es, ex, all), simp_arg_type.all_hyps := (es, ex, tt)
| (es, ex, all), simp_arg_type.except id := (es, id::ex, all)
| (es, ex, all), simp_arg_type.expr e := ((e, ff)::es, ex, all)
| (es, ex, all), simp_arg_type.symm_expr e := ((e, tt)::es, ex, all)
end)
([], [], ff),
(gex, hex) ← resolve_exception_ids all ex [] [],
return (hs.reverse, gex, hex, all)
private meta def add_simps : simp_lemmas → list (name × bool) → tactic simp_lemmas
| s [] := return s
| s (n::ns) := do s' ← s.add_simp n.fst n.snd, add_simps s' ns
private meta def report_invalid_simp_lemma {α : Type} (n : name): tactic α :=
fail format!"invalid simplification lemma '{n}' (use command 'set_option trace.simp_lemmas true' for more details)"
private meta def check_no_overload (p : pexpr) : tactic unit :=
when p.is_choice_macro $
match p with
| macro _ ps :=
fail $ to_fmt "ambiguous overload, possible interpretations" ++
format.join (ps.map (λ p, (to_fmt p).indent 4))
| _ := failed
end
private meta def simp_lemmas.resolve_and_add (s : simp_lemmas) (u : list name) (n : name) (ref : pexpr) (symm : bool) :
tactic (simp_lemmas × list name) :=
do
p ← resolve_name n,
check_no_overload p,
-- unpack local refs
let e := p.erase_annotations.get_app_fn.erase_annotations,
match e with
| const n _ :=
(do b ← is_valid_simp_lemma_cnst n, guard b, save_const_type_info n ref, s ← s.add_simp n symm, return (s, u))
<|>
(do eqns ← get_eqn_lemmas_for tt n,
guard (eqns.length > 0),
save_const_type_info n ref,
s ← add_simps s (eqns.map (λ e, (e, ff))),
return (s, u))
<|>
(do env ← get_env, guard (env.is_projection n).is_some, return (s, n::u))
<|>
report_invalid_simp_lemma n
| _ :=
(do e ← i_to_expr_no_subgoals p, b ← is_valid_simp_lemma e, guard b, try (save_type_info e ref), s ← s.add e symm, return (s, u))
<|>
report_invalid_simp_lemma n
end
private meta def simp_lemmas.add_pexpr (s : simp_lemmas) (u : list name) (p : pexpr) (symm : bool) :
tactic (simp_lemmas × list name) :=
match p with
| (const c []) := simp_lemmas.resolve_and_add s u c p symm
| (local_const c _ _ _) := simp_lemmas.resolve_and_add s u c p symm
| _ := do new_e ← i_to_expr_no_subgoals p,
s ← s.add new_e symm,
return (s, u)
end
private meta def simp_lemmas.append_pexprs :
simp_lemmas → list name → list (pexpr × bool) → tactic (simp_lemmas × list name)
| s u [] := return (s, u)
| s u (l::ls) := do
(s, u) ← simp_lemmas.add_pexpr s u l.fst l.snd,
simp_lemmas.append_pexprs s u ls
meta def mk_simp_set_core (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) (at_star : bool)
: tactic (bool × simp_lemmas × list name) :=
do (hs, gex, hex, all_hyps) ← decode_simp_arg_list_with_symm hs,
when (all_hyps ∧ at_star ∧ not hex.empty) $ fail "A tactic of the form `simp [*, -h] at *` is currently not supported",
s ← join_user_simp_lemmas no_dflt attr_names,
-- Erase `h` from the default simp set for calls of the form `simp [←h]`.
let to_erase := hs.foldl (λ l h, match h with
| (const id _, tt) := id :: l
| _ := l
end ) [],
let s := s.erase to_erase,
(s, u) ← simp_lemmas.append_pexprs s [] hs,
s ← if not at_star ∧ all_hyps then do
ctx ← collect_ctx_simps,
let ctx := ctx.filter (λ h, h.local_uniq_name ∉ hex), -- remove local exceptions
s.append ctx
else return s,
-- add equational lemmas, if any
gex ← gex.mmap (λ n, list.cons n <$> get_eqn_lemmas_for tt n),
return (all_hyps, simp_lemmas.erase s $ gex.join, u)
meta def mk_simp_set (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) : tactic (simp_lemmas × list name) :=
prod.snd <$> (mk_simp_set_core no_dflt attr_names hs ff)
end mk_simp_set
namespace interactive
open interactive interactive.types expr
meta def simp_core_aux (cfg : simp_config) (discharger : tactic unit) (s : simp_lemmas) (u : list name) (hs : list expr) (tgt : bool) : tactic unit :=
do to_remove ← hs.mfilter $ λ h, do {
h_type ← infer_type h,
(do (new_h_type, pr) ← simplify s u h_type cfg `eq discharger,
assert h.local_pp_name new_h_type,
mk_eq_mp pr h >>= tactic.exact >> return tt)
<|>
(return ff) },
goal_simplified ← if tgt then (simp_target s u cfg discharger >> return tt) <|> (return ff) else return ff,
guard (cfg.fail_if_unchanged = ff ∨ to_remove.length > 0 ∨ goal_simplified) <|> fail "simplify tactic failed to simplify",
to_remove.mmap' (λ h, try (clear h))
meta def simp_core (cfg : simp_config) (discharger : tactic unit)
(no_dflt : bool) (hs : list simp_arg_type) (attr_names : list name)
(locat : loc) : tactic unit :=
match locat with
| loc.wildcard := do (all_hyps, s, u) ← mk_simp_set_core no_dflt attr_names hs tt,
if all_hyps then tactic.simp_all s u cfg discharger
else do hyps ← non_dep_prop_hyps, simp_core_aux cfg discharger s u hyps tt
| _ := do (s, u) ← mk_simp_set no_dflt attr_names hs,
ns ← locat.get_locals,
simp_core_aux cfg discharger s u ns locat.include_goal
end
>> try tactic.triv >> try (tactic.reflexivity reducible)
/--
The `simp` tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants.
`simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`.
`simp [h₁ h₂ ... hₙ]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `hᵢ`'s, where the `hᵢ`'s are expressions. If `hᵢ` is preceded by left arrow (`←` or `<-`), the simplification is performed in the reverse direction. If an `hᵢ` is a defined constant `f`, then the equational lemmas associated with `f` are used. This provides a convenient way to unfold `f`.
`simp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and all hypotheses.
`simp *` is a shorthand for `simp [*]`.
`simp only [h₁ h₂ ... hₙ]` is like `simp [h₁ h₂ ... hₙ]` but does not use `[simp]` lemmas
`simp [-id_1, ... -id_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `idᵢ`.
`simp at h₁ h₂ ... hₙ` simplifies the non-dependent hypotheses `h₁ : T₁` ... `hₙ : Tₙ`. The tactic fails if the target or another hypothesis depends on one of them. The token `⊢` or `|-` can be added to the list to include the target.
`simp at *` simplifies all the hypotheses and the target.
`simp * at *` simplifies target and all (non-dependent propositional) hypotheses using the other hypotheses.
`simp with attr₁ ... attrₙ` simplifies the main goal target using the lemmas tagged with any of the attributes `[attr₁]`, ..., `[attrₙ]` or `[simp]`.
-/
meta def simp (use_iota_eqn : parse $ (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list)
(locat : parse location) (cfg : simp_config_ext := {}) : tactic unit :=
let cfg := if use_iota_eqn.is_none then cfg else {iota_eqn := tt, ..cfg} in
propagate_tags (simp_core cfg.to_simp_config cfg.discharger no_dflt hs attr_names locat)
/--
Just construct the simp set and trace it. Used for debugging.
-/
meta def trace_simp_set (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) : tactic unit :=
do (s, _) ← mk_simp_set no_dflt attr_names hs,
s.pp >>= trace
/--
`simp_intros h₁ h₂ ... hₙ` is similar to `intros h₁ h₂ ... hₙ` except that each hypothesis is simplified as it is introduced, and each introduced hypothesis is used to simplify later ones and the final target.
As with `simp`, a list of simplification lemmas can be provided. The modifiers `only` and `with` behave as with `simp`.
-/
meta def simp_intros (ids : parse ident_*) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list)
(cfg : simp_intros_config := {}) : tactic unit :=
do (s, u) ← mk_simp_set no_dflt attr_names hs,
when (¬u.empty) (fail (sformat! "simp_intros tactic does not support {u}")),
tactic.simp_intros s u ids cfg,
try triv >> try (reflexivity reducible)
private meta def to_simp_arg_list (symms : list bool) (es : list pexpr) : list simp_arg_type :=
(symms.zip es).map (λ ⟨s, e⟩, if s then simp_arg_type.symm_expr e else simp_arg_type.expr e)
/--
`dsimp` is similar to `simp`, except that it only uses definitional equalities.
-/
meta def dsimp (no_dflt : parse only_flag) (es : parse simp_arg_list) (attr_names : parse with_ident_list)
(l : parse location) (cfg : dsimp_config := {}) : tactic unit :=
do (s, u) ← mk_simp_set no_dflt attr_names es,
match l with
| loc.wildcard :=
/- Remark: we cannot revert frozen local instances.
We disable zeta expansion because to prevent `intron n` from failing.
Another option is to put a "marker" at the current target, and
implement `intro_upto_marker`. -/
do n ← revert_all,
dsimp_target s u {zeta := ff ..cfg},
intron n
| _ := l.apply (λ h, dsimp_hyp h s u cfg) (dsimp_target s u cfg)
end
/--
This tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation, that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal.
-/
meta def reflexivity : tactic unit :=
tactic.reflexivity
/--
Shorter name for the tactic `reflexivity`.
-/
meta def refl : tactic unit :=
tactic.reflexivity
/--
This tactic applies to a goal whose target has the form `t ~ u` where `~` is a symmetric relation, that is, a relation which has a symmetry lemma tagged with the attribute `[symm]`. It replaces the target with `u ~ t`.
-/
meta def symmetry : tactic unit :=
tactic.symmetry
/--
This tactic applies to a goal whose target has the form `t ~ u` where `~` is a transitive relation, that is, a relation which has a transitivity lemma tagged with the attribute `[trans]`.
`transitivity s` replaces the goal with the two subgoals `t ~ s` and `s ~ u`. If `s` is omitted, then a metavariable is used instead.
-/
meta def transitivity (q : parse texpr?) : tactic unit :=
tactic.transitivity >> match q with
| none := skip
| some q :=
do (r, lhs, rhs) ← target_lhs_rhs,
i_to_expr q >>= unify rhs
end
/--
Proves a goal with target `s = t` when `s` and `t` are equal up to the associativity and commutativity of their binary operations.
-/
meta def ac_reflexivity : tactic unit :=
tactic.ac_refl
/--
An abbreviation for `ac_reflexivity`.
-/
meta def ac_refl : tactic unit :=
tactic.ac_refl
/--
Tries to prove the main goal using congruence closure.
-/
meta def cc : tactic unit :=
tactic.cc
/--
Given hypothesis `h : x = t` or `h : t = x`, where `x` is a local constant, `subst h` substitutes `x` by `t` everywhere in the main goal and then clears `h`.
-/
meta def subst (q : parse texpr) : tactic unit :=
i_to_expr q >>= tactic.subst >> try (tactic.reflexivity reducible)
/--
Apply `subst` to all hypotheses of the form `h : x = t` or `h : t = x`.
-/
meta def subst_vars : tactic unit :=
tactic.subst_vars
/--
`clear h₁ ... hₙ` tries to clear each hypothesis `hᵢ` from the local context.
-/
meta def clear : parse ident* → tactic unit :=
tactic.clear_lst
private meta def to_qualified_name_core : name → list name → tactic name
| n [] := fail $ "unknown declaration '" ++ to_string n ++ "'"
| n (ns::nss) := do
curr ← return $ ns ++ n,
env ← get_env,
if env.contains curr then return curr
else to_qualified_name_core n nss
private meta def to_qualified_name (n : name) : tactic name :=
do env ← get_env,
if env.contains n then return n
else do
ns ← open_namespaces,
to_qualified_name_core n ns
private meta def to_qualified_names : list name → tactic (list name)
| [] := return []
| (c::cs) := do new_c ← to_qualified_name c, new_cs ← to_qualified_names cs, return (new_c::new_cs)
/--
Similar to `unfold`, but only uses definitional equalities.
-/
meta def dunfold (cs : parse ident*) (l : parse location) (cfg : dunfold_config := {}) : tactic unit :=
match l with
| (loc.wildcard) := do ls ← tactic.local_context,
n ← revert_lst ls,
new_cs ← to_qualified_names cs,
dunfold_target new_cs cfg,
intron n
| _ := do new_cs ← to_qualified_names cs, l.apply (λ h, dunfold_hyp cs h cfg) (dunfold_target new_cs cfg)
end
private meta def delta_hyps : list name → list name → tactic unit
| cs [] := skip
| cs (h::hs) := get_local h >>= delta_hyp cs >> delta_hyps cs hs
/--
Similar to `dunfold`, but performs a raw delta reduction, rather than using an equation associated with the defined constants.
-/
meta def delta : parse ident* → parse location → tactic unit
| cs (loc.wildcard) := do ls ← tactic.local_context,
n ← revert_lst ls,
new_cs ← to_qualified_names cs,
delta_target new_cs,
intron n
| cs l := do new_cs ← to_qualified_names cs, l.apply (delta_hyp new_cs) (delta_target new_cs)
private meta def unfold_projs_hyps (cfg : unfold_proj_config := {}) (hs : list name) : tactic bool :=
hs.mfoldl (λ r h, do h ← get_local h, (unfold_projs_hyp h cfg >> return tt) <|> return r) ff
/--
This tactic unfolds all structure projections.
-/
meta def unfold_projs (l : parse location) (cfg : unfold_proj_config := {}) : tactic unit :=
match l with
| loc.wildcard := do ls ← local_context,
b₁ ← unfold_projs_hyps cfg (ls.map expr.local_pp_name),
b₂ ← (tactic.unfold_projs_target cfg >> return tt) <|> return ff,
when (not b₁ ∧ not b₂) (fail "unfold_projs failed to simplify")
| _ :=
l.try_apply (λ h, unfold_projs_hyp h cfg)
(tactic.unfold_projs_target cfg) <|> fail "unfold_projs failed to simplify"
end
end interactive
meta def ids_to_simp_arg_list (tac_name : name) (cs : list name) : tactic (list simp_arg_type) :=
cs.mmap $ λ c, do
n ← resolve_name c,
hs ← get_eqn_lemmas_for ff n.const_name,
env ← get_env,
let p := env.is_projection n.const_name,
when (hs.empty ∧ p.is_none) (fail (sformat! "{tac_name} tactic failed, {c} does not have equational lemmas nor is a projection")),
return $ simp_arg_type.expr (expr.const c [])
structure unfold_config extends simp_config :=
(zeta := ff)
(proj := ff)
(eta := ff)
(canonize_instances := ff)
(constructor_eq := ff)
namespace interactive
open interactive interactive.types expr
/--
Given defined constants `e₁ ... eₙ`, `unfold e₁ ... eₙ` iteratively unfolds all occurrences in the target of the main goal, using equational lemmas associated with the definitions.
As with `simp`, the `at` modifier can be used to specify locations for the unfolding.
-/
meta def unfold (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {}) : tactic unit :=
do es ← ids_to_simp_arg_list "unfold" cs,
let no_dflt := tt,
simp_core cfg.to_simp_config failed no_dflt es [] locat
/--
Similar to `unfold`, but does not iterate the unfolding.
-/
meta def unfold1 (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {single_pass := tt}) : tactic unit :=
unfold cs locat cfg
/--
If the target of the main goal is an `opt_param`, assigns the default value.
-/
meta def apply_opt_param : tactic unit :=
tactic.apply_opt_param
/--
If the target of the main goal is an `auto_param`, executes the associated tactic.
-/
meta def apply_auto_param : tactic unit :=
tactic.apply_auto_param
/--
Fails if the given tactic succeeds.
-/
meta def fail_if_success (tac : itactic) : tactic unit :=
tactic.fail_if_success tac
/--
Succeeds if the given tactic fails.
-/
meta def success_if_fail (tac : itactic) : tactic unit :=
tactic.success_if_fail tac
meta def guard_expr_eq (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit :=
do e ← to_expr p, guard (alpha_eqv t e)
/--
`guard_target t` fails if the target of the main goal is not `t`.
We use this tactic for writing tests.
-/
meta def guard_target (p : parse texpr) : tactic unit :=
do t ← target, guard_expr_eq t p
/--
`guard_hyp h := t` fails if the hypothesis `h` does not have type `t`.
We use this tactic for writing tests.
-/
meta def guard_hyp (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit :=
do h ← get_local n >>= infer_type, guard_expr_eq h p
/--
`match_target t` fails if target does not match pattern `t`.
-/
meta def match_target (t : parse texpr) (m := reducible) : tactic unit :=
tactic.match_target t m >> skip
/--
`by_cases (h :)? p` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch.
This tactic requires that `p` is decidable. To ensure that all propositions are decidable via classical reasoning, use `local attribute [instance] classical.prop_decidable`.
-/
meta def by_cases : parse cases_arg_p → tactic unit
| (n, q) := concat_tags $ do
p ← tactic.to_expr_strict q,
tactic.by_cases p (n.get_or_else `h),
pos_g :: neg_g :: rest ← get_goals,
return [(`pos, pos_g), (`neg, neg_g)]
/--
Apply function extensionality and introduce new hypotheses.
The tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to
```
|- ((fun x, ...) = (fun x, ...))
```
The variant `funext h₁ ... hₙ` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses.
-/
meta def funext : parse ident_* → tactic unit
| [] := tactic.funext >> skip
| hs := funext_lst hs >> skip
/--
If the target of the main goal is a proposition `p`, `by_contradiction h` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. If `h` is omitted, a name is generated automatically.
This tactic requires that `p` is decidable. To ensure that all propositions are decidable via classical reasoning, use `local attribute [instance] classical.prop_decidable`.
-/
meta def by_contradiction (n : parse ident?) : tactic unit :=
tactic.by_contradiction n >> return ()
/--
An abbreviation for `by_contradiction`.
-/
meta def by_contra (n : parse ident?) : tactic unit :=
by_contradiction n
/--
Type check the given expression, and trace its type.
-/
meta def type_check (p : parse texpr) : tactic unit :=
do e ← to_expr p, tactic.type_check e, infer_type e >>= trace
/--
Fail if there are unsolved goals.
-/
meta def done : tactic unit :=
tactic.done
private meta def show_aux (p : pexpr) : list expr → list expr → tactic unit
| [] r := fail "show tactic failed"
| (g::gs) r := do
do {set_goals [g], g_ty ← target, ty ← i_to_expr p, unify g_ty ty, set_goals (g :: r.reverse ++ gs), tactic.change ty}
<|>
show_aux gs (g::r)
/--
`show t` finds the first goal whose target unifies with `t`. It makes that the main goal, performs the unification, and replaces the target with the unified version of `t`.
-/
meta def «show» (q : parse texpr) : tactic unit :=
do gs ← get_goals,
show_aux q gs []
/--
The tactic `specialize h a₁ ... aₙ` works on local hypothesis `h`. The premises of this hypothesis, either universal quantifications or non-dependent implications, are instantiated by concrete terms coming either from arguments `a₁` ... `aₙ`. The tactic adds a new hypothesis with the same name `h := h a₁ ... aₙ` and tries to clear the previous one.
-/
meta def specialize (p : parse texpr) : tactic unit :=
do e ← i_to_expr p,
let h := expr.get_app_fn e,
if h.is_local_constant
then tactic.note h.local_pp_name none e >> try (tactic.clear h)
else tactic.fail "specialize requires a term of the form `h x_1 .. x_n` where `h` appears in the local context"
meta def congr := tactic.congr
end interactive
end tactic
section add_interactive
open tactic
/- See add_interactive -/
private meta def add_interactive_aux (new_namespace : name) : list name → command
| [] := return ()
| (n::ns) := do
env ← get_env,
d_name ← resolve_constant n,
(declaration.defn _ ls ty val hints trusted) ← env.get d_name,
(name.mk_string h _) ← return d_name,
let new_name := new_namespace <.> h,
add_decl (declaration.defn new_name ls ty (expr.const d_name (ls.map level.param)) hints trusted),
do {
doc ← doc_string d_name,
add_doc_string new_name doc
} <|> skip,
add_interactive_aux ns
/--
Copy a list of meta definitions in the current namespace to tactic.interactive.
This command is useful when we want to update tactic.interactive without closing the current namespace.
-/
meta def add_interactive (ns : list name) (p : name := `tactic.interactive) : command :=
add_interactive_aux p ns
meta def has_dup : tactic bool :=
do ctx ← local_context,
let p : name_set × bool :=
ctx.foldl (λ ⟨s, r⟩ h,
if r then (s, r)
else if s.contains h.local_pp_name then (s, tt)
else (s.insert h.local_pp_name, ff))
(mk_name_set, ff),
return p.2
/--
Renames hypotheses with the same name.
-/
meta def dedup : tactic unit :=
mwhen has_dup $ do
ctx ← local_context,
n ← revert_lst ctx,
intron n
end add_interactive
namespace tactic
/- Helper tactic for `mk_inj_eq -/
protected meta def apply_inj_lemma : tactic unit :=
do h ← intro `h,
some (lhs, rhs) ← expr.is_eq <$> infer_type h,
(expr.const C _) ← return lhs.get_app_fn,
-- We disable auto_param and opt_param support to address issue #1943
applyc (name.mk_string "inj" C) {auto_param := ff, opt_param := ff},
assumption
/- Auxiliary tactic for proving `I.C.inj_eq` lemmas.
These lemmas are automatically generated by the equation compiler.
Example:
```
list.cons.inj_eq : forall h1 h2 t1 t2, (h1::t1 = h2::t2) = (h1 = h2 ∧ t1 = t2) :=
by mk_inj_eq
```
-/
meta def mk_inj_eq : tactic unit :=
`[
intros,
/-
We use `_root_.*` in the following tactics because
names are resolved at tactic execution time in interactive mode.
See PR #1913
TODO(Leo): This is probably not the only instance of this problem.
`[ ... ] blocks are convenient to use because they allow us to use the interactive
mode to write non interactive tactics.
One potential fix for this issue is to resolve names in `[ ... ] at tactic
compilation time.
After this issue is fixed, we should remove the `_root_.*` workaround.
-/
apply _root_.propext,
apply _root_.iff.intro,
{ tactic.apply_inj_lemma },
{ intro _, try { cases_matching* _ ∧ _ }, refl <|> { congr; { assumption <|> subst_vars } } }
]
end tactic
/- Define inj_eq lemmas for inductive datatypes that were declared before `mk_inj_eq` -/
universes u v
lemma sum.inl.inj_eq {α : Type u} (β : Type v) (a₁ a₂ : α) : (@sum.inl α β a₁ = sum.inl a₂) = (a₁ = a₂) :=
by tactic.mk_inj_eq
lemma sum.inr.inj_eq (α : Type u) {β : Type v} (b₁ b₂ : β) : (@sum.inr α β b₁ = sum.inr b₂) = (b₁ = b₂) :=
by tactic.mk_inj_eq
lemma psum.inl.inj_eq {α : Sort u} (β : Sort v) (a₁ a₂ : α) : (@psum.inl α β a₁ = psum.inl a₂) = (a₁ = a₂) :=
by tactic.mk_inj_eq
lemma psum.inr.inj_eq (α : Sort u) {β : Sort v} (b₁ b₂ : β) : (@psum.inr α β b₁ = psum.inr b₂) = (b₁ = b₂) :=
by tactic.mk_inj_eq
lemma sigma.mk.inj_eq {α : Type u} {β : α → Type v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : (sigma.mk a₁ b₁ = sigma.mk a₂ b₂) = (a₁ = a₂ ∧ b₁ == b₂) :=
by tactic.mk_inj_eq
lemma psigma.mk.inj_eq {α : Sort u} {β : α → Sort v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : (psigma.mk a₁ b₁ = psigma.mk a₂ b₂) = (a₁ = a₂ ∧ b₁ == b₂) :=
by tactic.mk_inj_eq
lemma subtype.mk.inj_eq {α : Sort u} {p : α → Prop} (a₁ : α) (h₁ : p a₁) (a₂ : α) (h₂ : p a₂) : (subtype.mk a₁ h₁ = subtype.mk a₂ h₂) = (a₁ = a₂) :=
by tactic.mk_inj_eq
lemma option.some.inj_eq {α : Type u} (a₁ a₂ : α) : (some a₁ = some a₂) = (a₁ = a₂) :=
by tactic.mk_inj_eq
lemma list.cons.inj_eq {α : Type u} (h₁ : α) (t₁ : list α) (h₂ : α) (t₂ : list α) : (list.cons h₁ t₁ = list.cons h₂ t₂) = (h₁ = h₂ ∧ t₁ = t₂) :=
by tactic.mk_inj_eq
lemma nat.succ.inj_eq (n₁ n₂ : nat) : (nat.succ n₁ = nat.succ n₂) = (n₁ = n₂) :=
by tactic.mk_inj_eq
|
1cec6e1441f6bceb81baa50e4c6c717c4065e53f | 574dac3bf276ecf173ecf82fca6c3b0c96bfe477 | /library/init/meta/converter/interactive.lean | e9bfb723b191cb5cf71aca50c6bf558698d0e9bb | [
"Apache-2.0"
] | permissive | thormikkel2/lean | 511050dcaa22894e0520ec6d1ff7352afed66590 | 201f6cdc5986f2cf2dcef9f6645dfa6840a93f0f | refs/heads/master | 1,672,552,832,086 | 1,602,781,965,000 | 1,602,781,965,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,872 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
Converter monad for building simplifiers.
-/
prelude
import init.meta.interactive
import init.meta.converter.conv
namespace conv
meta def save_info (p : pos) : conv unit :=
do s ← tactic.read,
tactic.save_info_thunk p (λ _, s.to_format tt)
meta def step {α : Type} (c : conv α) : conv unit :=
c >> return ()
meta def istep {α : Type} (line0 col0 line col : nat) (c : conv α) : conv unit :=
tactic.istep line0 col0 line col c
meta def execute (c : conv unit) : tactic unit :=
c
meta def solve1 (c : conv unit) : conv unit :=
tactic.solve1 $ c >> tactic.try (tactic.any_goals tactic.reflexivity)
namespace interactive
open lean
open lean.parser
open interactive
open interactive.types
open tactic_result
meta def itactic : Type :=
conv unit
meta def skip : conv unit :=
conv.skip
meta def whnf : conv unit :=
conv.whnf
meta def dsimp (no_dflt : parse only_flag) (es : parse tactic.simp_arg_list) (attr_names : parse with_ident_list)
(cfg : tactic.dsimp_config := {}) : conv unit :=
do (s, u) ← tactic.mk_simp_set no_dflt attr_names es,
conv.dsimp (some s) u cfg
meta def trace_lhs : conv unit :=
lhs >>= tactic.trace
meta def change (p : parse texpr) : conv unit :=
tactic.i_to_expr p >>= conv.change
meta def congr : conv unit :=
conv.congr
meta def funext : conv unit :=
conv.funext
private meta def is_relation : conv unit :=
(lhs >>= tactic.relation_lhs_rhs >> return ())
<|>
tactic.fail "current expression is not a relation"
meta def to_lhs : conv unit :=
is_relation >> congr >> tactic.swap >> skip
meta def to_rhs : conv unit :=
is_relation >> congr >> skip
meta def done : conv unit :=
tactic.done
meta def find (p : parse parser.pexpr) (c : itactic) : conv unit :=
do (r, lhs, _) ← tactic.target_lhs_rhs,
pat ← tactic.pexpr_to_pattern p,
s ← simp_lemmas.mk_default, -- to be able to use congruence lemmas @[congr]
-- we have to thread the tactic state through `ext_simplify_core` manually
st ← tactic.read,
(found_result, new_lhs, pr) ← tactic.ext_simplify_core
(success ff st) -- loop counter
{zeta := ff, beta := ff, single_pass := tt, eta := ff, proj := ff,
fail_if_unchanged := ff, memoize := ff}
s
(λ u, return u)
(λ found_result s r p e, do
found ← tactic.resume found_result,
guard (not found),
matched ← (tactic.match_pattern pat e >> return tt) <|> return ff,
guard matched,
res ← tactic.capture (c.convert e r),
-- If an error occurs in conversion, capture it; `ext_simplify_core` will not
-- propagate it.
match res with
| (success r s') := return (success tt s', r.fst, some r.snd, ff)
| (exception f p s') := return (exception f p s', e, none, ff)
end)
(λ a s r p e, tactic.failed)
r lhs,
found ← tactic.resume found_result,
when (not found) $ tactic.fail "find converter failed, pattern was not found",
update_lhs new_lhs pr
meta def for (p : parse parser.pexpr) (occs : parse (list_of small_nat)) (c : itactic) : conv unit :=
do (r, lhs, _) ← tactic.target_lhs_rhs,
pat ← tactic.pexpr_to_pattern p,
s ← simp_lemmas.mk_default, -- to be able to use congruence lemmas @[congr]
-- we have to thread the tactic state through `ext_simplify_core` manually
st ← tactic.read,
(found_result, new_lhs, pr) ← tactic.ext_simplify_core
(success 1 st) -- loop counter, and whether the conversion tactic failed
{zeta := ff, beta := ff, single_pass := tt, eta := ff, proj := ff,
fail_if_unchanged := ff, memoize := ff}
s
(λ u, return u)
(λ found_result s r p e, do
i ← tactic.resume found_result,
matched ← (tactic.match_pattern pat e >> return tt) <|> return ff,
guard matched,
if i ∈ occs then do
res ← tactic.capture (c.convert e r),
-- If an error occurs in conversion, capture it; `ext_simplify_core` will not
-- propagate it.
match res with
| (success r s') := return (success (i+1) s', r.fst, some r.snd, tt)
| (exception f p s') := return (exception f p s', e, none, tt)
end
else do
st ← tactic.read,
return (success (i+1) st, e, none, tt))
(λ a s r p e, tactic.failed)
r lhs,
tactic.resume found_result,
update_lhs new_lhs pr
meta def simp (no_dflt : parse only_flag) (hs : parse tactic.simp_arg_list) (attr_names : parse with_ident_list)
(cfg : tactic.simp_config_ext := {})
: conv unit :=
do (s, u) ← tactic.mk_simp_set no_dflt attr_names hs,
(r, lhs, rhs) ← tactic.target_lhs_rhs,
(new_lhs, pr) ← tactic.simplify s u lhs cfg.to_simp_config r cfg.discharger,
update_lhs new_lhs pr,
return ()
meta def guard_lhs (p : parse texpr) : tactic unit :=
do t ← lhs, tactic.interactive.guard_expr_eq t p
section rw
open tactic.interactive (rw_rules rw_rule get_rule_eqn_lemmas to_expr')
open tactic (rewrite_cfg)
private meta def rw_lhs (h : expr) (cfg : rewrite_cfg) : conv unit :=
do l ← conv.lhs,
(new_lhs, prf, _) ← tactic.rewrite h l cfg,
update_lhs new_lhs prf
private meta def rw_core (rs : list rw_rule) (cfg : rewrite_cfg) : conv unit :=
rs.mmap' $ λ r, do
save_info r.pos,
eq_lemmas ← get_rule_eqn_lemmas r,
orelse'
(do h ← to_expr' r.rule, rw_lhs h {symm := r.symm, ..cfg})
(eq_lemmas.mfirst $ λ n, do e ← tactic.mk_const n, rw_lhs e {symm := r.symm, ..cfg})
(eq_lemmas.empty)
meta def rewrite (q : parse rw_rules) (cfg : rewrite_cfg := {}) : conv unit :=
rw_core q.rules cfg
meta def rw (q : parse rw_rules) (cfg : rewrite_cfg := {}) : conv unit :=
rw_core q.rules cfg
end rw
end interactive
end conv
namespace tactic
namespace interactive
open lean
open lean.parser
open interactive
open interactive.types
open tactic
local postfix `?`:9001 := optional
private meta def conv_at (h_name : name) (c : conv unit) : tactic unit :=
do h ← get_local h_name,
h_type ← infer_type h,
(new_h_type, pr) ← c.convert h_type,
replace_hyp h new_h_type pr,
return ()
private meta def conv_target (c : conv unit) : tactic unit :=
do t ← target,
(new_t, pr) ← c.convert t,
replace_target new_t pr,
try tactic.triv, try (tactic.reflexivity reducible)
meta def conv (loc : parse (tk "at" *> ident)?)
(p : parse (tk "in" *> parser.pexpr)?)
(c : conv.interactive.itactic) : tactic unit :=
do let c :=
match p with
| some p := _root_.conv.interactive.find p c
| none := c
end,
match loc with
| some h := conv_at h c
| none := conv_target c
end
end interactive
end tactic
|
3add82fb22406fe5b1367e562c69e9969ed3168a | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebra/continued_fractions/basic.lean | 2e61569c0d012b946b4850fa40f01bc122bb64a8 | [
"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 | 13,778 | lean | /-
Copyright (c) 2019 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann
-/
import data.seq.seq
import algebra.field.basic
/-!
# Basic Definitions/Theorems for Continued Fractions
## Summary
We define generalised, simple, and regular continued fractions and functions to evaluate their
convergents. We follow the naming conventions from Wikipedia and [wall2018analytic], Chapter 1.
## Main definitions
1. Generalised continued fractions (gcfs)
2. Simple continued fractions (scfs)
3. (Regular) continued fractions ((r)cfs)
4. Computation of convergents using the recurrence relation in `convergents`.
5. Computation of convergents by directly evaluating the fraction described by the gcf in
`convergents'`.
## Implementation notes
1. The most commonly used kind of continued fractions in the literature are regular continued
fractions. We hence just call them `continued_fractions` in the library.
2. We use sequences from `data.seq` to encode potentially infinite sequences.
## References
- <https://en.wikipedia.org/wiki/Generalized_continued_fraction>
- [Wall, H.S., *Analytic Theory of Continued Fractions*][wall2018analytic]
## Tags
numerics, number theory, approximations, fractions
-/
-- Fix a carrier `α`.
variable (α : Type*)
/-!### Definitions-/
/-- We collect a partial numerator `aᵢ` and partial denominator `bᵢ` in a pair `⟨aᵢ,bᵢ⟩`. -/
@[derive inhabited]
protected structure generalized_continued_fraction.pair := (a : α) (b : α)
open generalized_continued_fraction
/-! Interlude: define some expected coercions and instances. -/
namespace generalized_continued_fraction.pair
variable {α}
/-- Make a `gcf.pair` printable. -/
instance [has_repr α] : has_repr (pair α) :=
⟨λ p, "(a : " ++ (repr p.a) ++ ", b : " ++ (repr p.b) ++ ")"⟩
/-- Maps a function `f` on both components of a given pair. -/
def map {β : Type*} (f : α → β) (gp : pair α) : pair β :=
⟨f gp.a, f gp.b⟩
section coe
/- Fix another type `β` which we will convert to. -/
variables {β : Type*} [has_coe α β]
/-- Coerce a pair by elementwise coercion. -/
instance has_coe_to_generalized_continued_fraction_pair : has_coe (pair α) (pair β) :=
⟨map coe⟩
@[simp, norm_cast]
lemma coe_to_generalized_continued_fraction_pair {a b : α} :
(↑(pair.mk a b) : pair β) = pair.mk (a : β) (b : β) := rfl
end coe
end generalized_continued_fraction.pair
variable (α)
/--
A *generalised continued fraction* (gcf) is a potentially infinite expression of the form
a₀
h + ---------------------------
a₁
b₀ + --------------------
a₂
b₁ + --------------
a₃
b₂ + --------
b₃ + ...
where `h` is called the *head term* or *integer part*, the `aᵢ` are called the
*partial numerators* and the `bᵢ` the *partial denominators* of the gcf.
We store the sequence of partial numerators and denominators in a sequence of
generalized_continued_fraction.pairs `s`.
For convenience, one often writes `[h; (a₀, b₀), (a₁, b₁), (a₂, b₂),...]`.
-/
structure generalized_continued_fraction :=
(h : α) (s : seq $ pair α)
variable {α}
namespace generalized_continued_fraction
/-- Constructs a generalized continued fraction without fractional part. -/
def of_integer (a : α) : generalized_continued_fraction α :=
⟨a, seq.nil⟩
instance [inhabited α] : inhabited (generalized_continued_fraction α) := ⟨of_integer default⟩
/-- Returns the sequence of partial numerators `aᵢ` of `g`. -/
def partial_numerators (g : generalized_continued_fraction α) : seq α :=
g.s.map pair.a
/-- Returns the sequence of partial denominators `bᵢ` of `g`. -/
def partial_denominators (g : generalized_continued_fraction α) : seq α :=
g.s.map pair.b
/-- A gcf terminated at position `n` if its sequence terminates at position `n`. -/
def terminated_at (g : generalized_continued_fraction α) (n : ℕ) : Prop := g.s.terminated_at n
/-- It is decidable whether a gcf terminated at a given position. -/
instance terminated_at_decidable (g : generalized_continued_fraction α) (n : ℕ) :
decidable (g.terminated_at n) :=
by { unfold terminated_at, apply_instance }
/-- A gcf terminates if its sequence terminates. -/
def terminates (g : generalized_continued_fraction α) : Prop := g.s.terminates
section coe
/-! Interlude: define some expected coercions. -/
/- Fix another type `β` which we will convert to. -/
variables {β : Type*} [has_coe α β]
/-- Coerce a gcf by elementwise coercion. -/
instance has_coe_to_generalized_continued_fraction :
has_coe (generalized_continued_fraction α) (generalized_continued_fraction β) :=
⟨λ g, ⟨(g.h : β), (g.s.map coe : seq $ pair β)⟩⟩
@[simp, norm_cast]
lemma coe_to_generalized_continued_fraction {g : generalized_continued_fraction α} :
(↑(g : generalized_continued_fraction α) : generalized_continued_fraction β) =
⟨(g.h : β), (g.s.map coe : seq $ pair β)⟩ :=
rfl
end coe
end generalized_continued_fraction
/--
A generalized continued fraction is a *simple continued fraction* if all partial numerators are
equal to one.
1
h + ---------------------------
1
b₀ + --------------------
1
b₁ + --------------
1
b₂ + --------
b₃ + ...
-/
def generalized_continued_fraction.is_simple_continued_fraction
(g : generalized_continued_fraction α) [has_one α] : Prop :=
∀ (n : ℕ) (aₙ : α), g.partial_numerators.nth n = some aₙ → aₙ = 1
variable (α)
/--
A *simple continued fraction* (scf) is a generalized continued fraction (gcf) whose partial
numerators are equal to one.
1
h + ---------------------------
1
b₀ + --------------------
1
b₁ + --------------
1
b₂ + --------
b₃ + ...
For convenience, one often writes `[h; b₀, b₁, b₂,...]`.
It is encoded as the subtype of gcfs that satisfy
`generalized_continued_fraction.is_simple_continued_fraction`.
-/
def simple_continued_fraction [has_one α] :=
{g : generalized_continued_fraction α // g.is_simple_continued_fraction}
variable {α}
/- Interlude: define some expected coercions. -/
namespace simple_continued_fraction
variable [has_one α]
/-- Constructs a simple continued fraction without fractional part. -/
def of_integer (a : α) : simple_continued_fraction α :=
⟨generalized_continued_fraction.of_integer a, λ n aₙ h, by cases h⟩
instance : inhabited (simple_continued_fraction α) := ⟨of_integer 1⟩
/-- Lift a scf to a gcf using the inclusion map. -/
instance has_coe_to_generalized_continued_fraction :
has_coe (simple_continued_fraction α) (generalized_continued_fraction α) :=
by {unfold simple_continued_fraction, apply_instance}
lemma coe_to_generalized_continued_fraction {s : simple_continued_fraction α} :
(↑s : generalized_continued_fraction α) = s.val := rfl
end simple_continued_fraction
/--
A simple continued fraction is a *(regular) continued fraction* ((r)cf) if all partial denominators
`bᵢ` are positive, i.e. `0 < bᵢ`.
-/
def simple_continued_fraction.is_continued_fraction [has_one α] [has_zero α] [has_lt α]
(s : simple_continued_fraction α) : Prop :=
∀ (n : ℕ) (bₙ : α),
(↑s : generalized_continued_fraction α).partial_denominators.nth n = some bₙ → 0 < bₙ
variable (α)
/--
A *(regular) continued fraction* ((r)cf) is a simple continued fraction (scf) whose partial
denominators are all positive. It is the subtype of scfs that satisfy
`simple_continued_fraction.is_continued_fraction`.
-/
def continued_fraction [has_one α] [has_zero α] [has_lt α] :=
{s : simple_continued_fraction α // s.is_continued_fraction}
variable {α}
/-! Interlude: define some expected coercions. -/
namespace continued_fraction
variables [has_one α] [has_zero α] [has_lt α]
/-- Constructs a continued fraction without fractional part. -/
def of_integer (a : α) : continued_fraction α :=
⟨simple_continued_fraction.of_integer a, λ n bₙ h, by cases h⟩
instance : inhabited (continued_fraction α) := ⟨of_integer 0⟩
/-- Lift a cf to a scf using the inclusion map. -/
instance has_coe_to_simple_continued_fraction :
has_coe (continued_fraction α) (simple_continued_fraction α) :=
by {unfold continued_fraction, apply_instance}
lemma coe_to_simple_continued_fraction {c : continued_fraction α} :
(↑c : simple_continued_fraction α) = c.val := rfl
/-- Lift a cf to a scf using the inclusion map. -/
instance has_coe_to_generalized_continued_fraction :
has_coe (continued_fraction α) (generalized_continued_fraction α) :=
⟨λ c, ↑(↑c : simple_continued_fraction α)⟩
lemma coe_to_generalized_continued_fraction {c : continued_fraction α} :
(↑c : generalized_continued_fraction α) = c.val := rfl
end continued_fraction
namespace generalized_continued_fraction
/-!
### Computation of Convergents
We now define how to compute the convergents of a gcf. There are two standard ways to do this:
directly evaluating the (infinite) fraction described by the gcf or using a recurrence relation.
For (r)cfs, these computations are equivalent as shown in
`algebra.continued_fractions.convergents_equiv`.
-/
-- Fix a division ring for the computations.
variables {K : Type*} [division_ring K]
/-!
We start with the definition of the recurrence relation. Given a gcf `g`, for all `n ≥ 1`, we define
- `A₋₁ = 1, A₀ = h, Aₙ = bₙ₋₁ * Aₙ₋₁ + aₙ₋₁ * Aₙ₋₂`, and
- `B₋₁ = 0, B₀ = 1, Bₙ = bₙ₋₁ * Bₙ₋₁ + aₙ₋₁ * Bₙ₋₂`.
`Aₙ, `Bₙ` are called the *nth continuants*, Aₙ the *nth numerator*, and `Bₙ` the
*nth denominator* of `g`. The *nth convergent* of `g` is given by `Aₙ / Bₙ`.
-/
/--
Returns the next numerator `Aₙ = bₙ₋₁ * Aₙ₋₁ + aₙ₋₁ * Aₙ₋₂`, where `predA` is `Aₙ₋₁`,
`ppredA` is `Aₙ₋₂`, `a` is `aₙ₋₁`, and `b` is `bₙ₋₁`.
-/
def next_numerator (a b ppredA predA : K) : K := b * predA + a * ppredA
/--
Returns the next denominator `Bₙ = bₙ₋₁ * Bₙ₋₁ + aₙ₋₁ * Bₙ₋₂``, where `predB` is `Bₙ₋₁` and
`ppredB` is `Bₙ₋₂`, `a` is `aₙ₋₁`, and `b` is `bₙ₋₁`.
-/
def next_denominator (aₙ bₙ ppredB predB : K) : K := bₙ * predB + aₙ * ppredB
/--
Returns the next continuants `⟨Aₙ, Bₙ⟩` using `next_numerator` and `next_denominator`, where `pred`
is `⟨Aₙ₋₁, Bₙ₋₁⟩`, `ppred` is `⟨Aₙ₋₂, Bₙ₋₂⟩`, `a` is `aₙ₋₁`, and `b` is `bₙ₋₁`.
-/
def next_continuants (a b : K) (ppred pred : pair K) : pair K :=
⟨next_numerator a b ppred.a pred.a, next_denominator a b ppred.b pred.b⟩
/-- Returns the continuants `⟨Aₙ₋₁, Bₙ₋₁⟩` of `g`. -/
def continuants_aux (g : generalized_continued_fraction K) : stream (pair K)
| 0 := ⟨1, 0⟩
| 1 := ⟨g.h, 1⟩
| (n + 2) :=
match g.s.nth n with
| none := continuants_aux (n + 1)
| some gp := next_continuants gp.a gp.b (continuants_aux n) (continuants_aux $ n + 1)
end
/-- Returns the continuants `⟨Aₙ, Bₙ⟩` of `g`. -/
def continuants (g : generalized_continued_fraction K) : stream (pair K) :=
g.continuants_aux.tail
/-- Returns the numerators `Aₙ` of `g`. -/
def numerators (g : generalized_continued_fraction K) : stream K :=
g.continuants.map pair.a
/-- Returns the denominators `Bₙ` of `g`. -/
def denominators (g : generalized_continued_fraction K) : stream K :=
g.continuants.map pair.b
/-- Returns the convergents `Aₙ / Bₙ` of `g`, where `Aₙ, Bₙ` are the nth continuants of `g`. -/
def convergents (g : generalized_continued_fraction K) : stream K :=
λ (n : ℕ), (g.numerators n) / (g.denominators n)
/--
Returns the approximation of the fraction described by the given sequence up to a given position n.
For example, `convergents'_aux [(1, 2), (3, 4), (5, 6)] 2 = 1 / (2 + 3 / 4)` and
`convergents'_aux [(1, 2), (3, 4), (5, 6)] 0 = 0`.
-/
def convergents'_aux : seq (pair K) → ℕ → K
| s 0 := 0
| s (n + 1) := match s.head with
| none := 0
| some gp := gp.a / (gp.b + convergents'_aux s.tail n)
end
/--
Returns the convergents of `g` by evaluating the fraction described by `g` up to a given
position `n`. For example, `convergents' [9; (1, 2), (3, 4), (5, 6)] 2 = 9 + 1 / (2 + 3 / 4)` and
`convergents' [9; (1, 2), (3, 4), (5, 6)] 0 = 9`
-/
def convergents' (g : generalized_continued_fraction K) (n : ℕ) : K := g.h + convergents'_aux g.s n
end generalized_continued_fraction
-- Now, some basic, general theorems
namespace generalized_continued_fraction
/-- Two gcfs `g` and `g'` are equal if and only if their components are equal. -/
protected lemma ext_iff {g g' : generalized_continued_fraction α} :
g = g' ↔ g.h = g'.h ∧ g.s = g'.s :=
by { cases g, cases g', simp }
@[ext]
protected lemma ext {g g' : generalized_continued_fraction α} (hyp : g.h = g'.h ∧ g.s = g'.s) :
g = g' :=
generalized_continued_fraction.ext_iff.elim_right hyp
end generalized_continued_fraction
|
0ab2b8bc90fd822b044282c9396a1212495ba63c | ecdf4e083eb363cd3a0d6880399f86e2cd7f5adb | /src/category_theory/group_object.lean | 66318f5ae2e8a9741b824eb71d94553af76ffe03 | [] | no_license | fpvandoorn/formalabstracts | 29aa71772da418f18994c38379e2192a6ef361f7 | cea2f9f96d89ee1187d1b01e33f22305cdfe4d59 | refs/heads/master | 1,609,476,761,601 | 1,558,130,287,000 | 1,558,130,287,000 | 97,261,457 | 0 | 2 | null | 1,550,879,230,000 | 1,500,056,313,000 | Lean | UTF-8 | Lean | false | false | 4,173 | lean | -- Copyright (c) 2019 Jesse Han. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Jesse Han
import .finite_limits
open category_theory category_theory.limits category_theory.limits.binary_product
category_theory.limits.finite_limits
universes v u
local infix ` × `:60 := binary_product
local infix ` ×.map `:90 := binary_product.map
local infix ` ×.iso `:90 := binary_product.iso
/-- A group object in a category with finite products is an object `G` equipped with morphisms
`μ : G × G ⟶ G`, `e : 1 ⟶ G` and `i : G ⟶ G` such that the axioms for a group hold
(which is expressed in terms of commuting diagrams) -/
structure group_object (C : Type u) [𝓒 : category.{v+1} C] [H : has_binary_products.{v} C]
[H' : has_terminal_object.{v} C] : Type (max u v) :=
(obj : C)
(mul : obj × obj ⟶ obj)
(mul_assoc : assoc_hom ≫ 𝟙 obj ×.map mul ≫ mul = mul ×.map 𝟙 obj ≫ mul)
(one : term ⟶ obj)
(one_mul : 𝟙 obj = one_mul_inv ≫ one ×.map 𝟙 obj ≫ mul)
(mul_one : 𝟙 obj = mul_one_inv ≫ 𝟙 obj ×.map one ≫ mul)
(inv : obj ⟶ obj)
(mul_left_inv : terminal_map _ ≫ one = map_to_product.mk inv (𝟙 obj) ≫ mul)
/-- A morphism between group objects is a morphism between the objects that commute with
multiplication -/
structure group_hom {C : Type u} [category.{v+1} C] [has_binary_products C]
[has_terminal_object C] (G G' : group_object C) : Type (max u v) :=
(map : G.obj ⟶ G'.obj)
(map_mul : G.mul ≫ map = map ×.map map ≫ G'.mul)
variables {C : Type u} [𝓒 : category.{v+1} C] [p𝓒 : has_binary_products.{v} C]
[t𝓒 : has_terminal_object.{v} C] {X Y : C} {G G' G₁ G₂ G₃ H : group_object C}
include 𝓒 p𝓒 t𝓒
namespace group_hom
/-- The identity morphism between group objects -/
def id (G : group_object C) : group_hom G G :=
⟨𝟙 G.obj, omitted⟩
/-- Composition of morphisms between group objects -/
def comp (f : group_hom G₁ G₂) (g : group_hom G₂ G₃) : group_hom G₁ G₃ :=
⟨f.map ≫ g.map, omitted⟩
lemma map_one (f : group_hom G G') : G.one ≫ f.map = G'.one := omitted
lemma map_inv (f : group_hom G G') : G.inv ≫ f.map = f.map ≫ G'.inv := omitted
end group_hom
namespace group_object
/-- The category of group objects -/
instance category : category (group_object C) :=
{ hom := group_hom,
id := group_hom.id,
comp := λ X Y Z, group_hom.comp }
/-- The terminal group object -/
def terminal_group : group_object C :=
{ obj := term,
mul := terminal_map _,
mul_assoc := terminal_map_eq _ _,
one := terminal_map _,
one_mul := terminal_map_eq _ _,
mul_one := terminal_map_eq _ _,
inv := terminal_map _,
mul_left_inv := terminal_map_eq _ _ }
/-- The morphism into the terminal group object -/
def hom_terminal_group (G : group_object C) : G ⟶ terminal_group :=
by exact ⟨terminal_map G.obj, omitted⟩
/-- The category of group objects has a terminal object -/
def has_terminal_object : has_terminal_object (group_object C) :=
has_terminal_object.mk terminal_group hom_terminal_group omitted
/-- The binary product of group objects -/
protected def prod (G G' : group_object C) : group_object C :=
{ obj := G.obj × G'.obj,
mul := product_assoc4.hom ≫ G.mul ×.map G'.mul,
mul_assoc := omitted,
one := map_to_product.mk G.one G'.one,
one_mul := omitted,
mul_one := omitted,
inv := G.inv ×.map G'.inv,
mul_left_inv := omitted }
protected def pr1 : G.prod G' ⟶ G := by exact ⟨π₁, omitted⟩
protected def pr2 : G.prod G' ⟶ G' := by exact ⟨π₂, omitted⟩
protected def lift (f : H ⟶ G) (g : H ⟶ G') : H ⟶ G.prod G' :=
by exact ⟨map_to_product.mk f.map g.map, omitted⟩
/-- The category of group objects has binary products -/
def has_binary_products : has_binary_products (group_object C) :=
begin
apply has_binary_products.mk group_object.prod (λ G G', group_object.pr1)
(λ G G', group_object.pr2) (λ G G' H, group_object.lift),
omit_proofs
end
/-- A group object is abelian if multiplication is commutative -/
def is_abelian (G : group_object C) : Prop := product_comm.hom ≫ G.mul = G.mul
end group_object
|
76894bc0f3be35b109b41bba13ba094bf2152430 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/autoBoundImplicits2.lean | e87d79922dd94a97c5ed63d617e262f6a4e0a54b | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 1,084 | lean | def f [Add α] (a : α) : α :=
a + a
set_option relaxedAutoImplicit false
def BV (n : Nat) := { a : Array Bool // a.size = n }
def allZero (bv : BV n) : Prop :=
∀ i, i < n → bv.val[i]! = false
def foo (b : BV n) (h : allZero b) : BV n :=
b
def optbind (x : Option α) (f : α → Option β) : Option β :=
match x with
| none => none
| some a => f a
instance : Monad Option where
bind := optbind
pure := some
inductive Mem : α → List α → Prop
| head (a : α) (as : List α) : Mem a (a::as)
def g1 {α : Type u} (a : α) : α :=
a
#check g1
set_option autoImplicit false in
def g2 {α : Type u /- Error -/} (a : α) : α :=
a
def g3 {α : Type β /- Error greek letters are not valid auto names for universe -/} (a : α) : α :=
a
def g4 {α : Type v} (a : α) : α :=
a
def g5 {α : Type (v+1)} (a : α) : α :=
a
def g6 {α : Type u} (a : α) :=
let β : Type u := α
let x : β := a
x
inductive M (m : Type v → Type w) where
| f (β : Type v) : M m
variable {m : Type u → Type u}
def h1 (a : m α) := a
#print h1
|
35ad6e482d7b9ce7639dd6816c01ee720da6f4ac | b00eb947a9c4141624aa8919e94ce6dcd249ed70 | /src/Lean/KeyedDeclsAttribute.lean | fa22052dc813dfaca7723be243848f6bccb17a35 | [
"Apache-2.0"
] | permissive | gebner/lean4-old | a4129a041af2d4d12afb3a8d4deedabde727719b | ee51cdfaf63ee313c914d83264f91f414a0e3b6e | refs/heads/master | 1,683,628,606,745 | 1,622,651,300,000 | 1,622,654,405,000 | 142,608,821 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,307 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Attributes
import Lean.Compiler.InitAttr
import Lean.ToExpr
import Lean.ScopedEnvExtension
import Lean.Compiler.IR.CompilerM
/-!
A builder for attributes that are applied to declarations of a common type and
group them by the given attribute argument (an arbitrary `Name`, currently).
Also creates a second "builtin" attribute used for bootstrapping, which saves
the applied declarations in an `IO.Ref` instead of an environment extension.
Used to register elaborators, macros, tactics, and delaborators.
-/
namespace Lean
namespace KeyedDeclsAttribute
-- could be a parameter as well, but right now it's all names
abbrev Key := Name
/--
`KeyedDeclsAttribute` definition.
Important: `mkConst valueTypeName` and `γ` must be definitionally equal. -/
structure Def (γ : Type) where
builtinName : Name := Name.anonymous -- Builtin attribute name, if any (e.g., `builtinTermElab)
name : Name -- Attribute name (e.g., `termElab)
descr : String -- Attribute description
valueTypeName : Name
-- Convert `Syntax` into a `Key`, the default implementation expects an identifier.
evalKey : Bool → Syntax → AttrM Key := fun builtin stx => Attribute.Builtin.getId stx
deriving Inhabited
structure OLeanEntry where
key : Key
decl : Name -- Name of a declaration stored in the environment which has type `mkConst Def.valueTypeName`.
deriving Inhabited
structure AttributeEntry (γ : Type) extends OLeanEntry where
/- Recall that we cannot store `γ` into .olean files because it is a closure.
Given `OLeanEntry.decl`, we convert it into a `γ` by using the unsafe function `evalConstCheck`. -/
value : γ
abbrev Table (γ : Type) := SMap Key (List γ)
structure ExtensionState (γ : Type) where
newEntries : List OLeanEntry := []
table : Table γ := {}
deriving Inhabited
abbrev Extension (γ : Type) := ScopedEnvExtension OLeanEntry (AttributeEntry γ) (ExtensionState γ)
end KeyedDeclsAttribute
structure KeyedDeclsAttribute (γ : Type) where
defn : KeyedDeclsAttribute.Def γ
-- imported/builtin instances
tableRef : IO.Ref (KeyedDeclsAttribute.Table γ)
-- instances from current module
ext : KeyedDeclsAttribute.Extension γ
deriving Inhabited
namespace KeyedDeclsAttribute
def Table.insert {γ : Type} (table : Table γ) (k : Key) (v : γ) : Table γ :=
match table.find? k with
| some vs => SMap.insert table k (v::vs)
| none => SMap.insert table k [v]
def addBuiltin {γ} (attr : KeyedDeclsAttribute γ) (key : Key) (val : γ) : IO Unit :=
attr.tableRef.modify fun m => m.insert key val
/--
def _regBuiltin$(declName) : IO Unit :=
@addBuiltin $(mkConst valueTypeName) $(mkConst attrDeclName) $(key) $(mkConst declName)
-/
def declareBuiltin {γ} (df : Def γ) (attrDeclName : Name) (env : Environment) (key : Key) (declName : Name) : IO Environment :=
let name := `_regBuiltin ++ declName
let type := mkApp (mkConst `IO) (mkConst `Unit)
let val := mkAppN (mkConst `Lean.KeyedDeclsAttribute.addBuiltin) #[mkConst df.valueTypeName, mkConst attrDeclName, toExpr key, mkConst declName]
let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := val, hints := ReducibilityHints.opaque,
safety := DefinitionSafety.safe }
match env.addAndCompile {} decl with
-- TODO: pretty print error
| Except.error e => do
let msg ← (e.toMessageData {}).toString
throw (IO.userError s!"failed to emit registration code for builtin '{declName}': {msg}")
| Except.ok env => IO.ofExcept (setBuiltinInitAttr env name)
protected unsafe def init {γ} (df : Def γ) (attrDeclName : Name) : IO (KeyedDeclsAttribute γ) := do
let tableRef ← IO.mkRef ({} : Table γ)
let ext : Extension γ ← registerScopedEnvExtension {
name := df.name
mkInitial := do return { table := (← tableRef.get) }
ofOLeanEntry := fun s entry => do
let ctx ← read
match ctx.env.evalConstCheck γ ctx.opts df.valueTypeName entry.decl with
| Except.ok f => return { toOLeanEntry := entry, value := f }
| Except.error ex => throw (IO.userError ex)
addEntry := fun s e =>
{ table := s.table.insert e.key e.value, newEntries := e.toOLeanEntry :: s.newEntries }
toOLeanEntry := (·.toOLeanEntry)
}
unless df.builtinName.isAnonymous do
registerBuiltinAttribute {
name := df.builtinName,
descr := "(builtin) " ++ df.descr,
add := fun declName stx kind => do
unless kind == AttributeKind.global do throwError "invalid attribute '{df.builtinName}', must be global"
let key ← df.evalKey true stx
let decl ← getConstInfo declName
match decl.type with
| Expr.const c _ _ =>
if c != df.valueTypeName then throwError "unexpected type at '{declName}', '{df.valueTypeName}' expected"
else
let env ← getEnv
let env ← declareBuiltin df attrDeclName env key declName
setEnv env
| _ => throwError "unexpected type at '{declName}', '{df.valueTypeName}' expected",
applicationTime := AttributeApplicationTime.afterCompilation
}
registerBuiltinAttribute {
name := df.name
descr := df.descr
add := fun constName stx attrKind => do
let key ← df.evalKey false stx
match IR.getSorryDep (← getEnv) constName with
| none =>
let val ← evalConstCheck γ df.valueTypeName constName
ext.add { key := key, decl := constName, value := val } attrKind
| _ =>
-- If the declaration contains `sorry`, we skip `evalConstCheck` to avoid unnecessary bizarre error message
pure ()
applicationTime := AttributeApplicationTime.afterCompilation
}
pure { defn := df, tableRef := tableRef, ext := ext }
/-- Retrieve values tagged with `[attr key]` or `[builtinAttr key]`. -/
def getValues {γ} (attr : KeyedDeclsAttribute γ) (env : Environment) (key : Name) : List γ :=
(attr.ext.getState env).table.findD key []
end KeyedDeclsAttribute
end Lean
|
6501282c0f4a938733c8b9b77b433bf8fcc8714a | 94e33a31faa76775069b071adea97e86e218a8ee | /src/algebra/monoid_algebra/basic.lean | 0ad604262a1a7f5df17a6791201872a18bd5bd67 | [
"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 | 67,025 | 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 G. Kudryashov, Scott Morrison
-/
import algebra.big_operators.finsupp
import algebra.hom.non_unital_alg
import linear_algebra.finsupp
/-!
# Monoid algebras
When the domain of a `finsupp` has a multiplicative or additive structure, we can define
a convolution product. To mathematicians this structure is known as the "monoid algebra",
i.e. the finite formal linear combinations over a given semiring of elements of the monoid.
The "group ring" ℤ[G] or the "group algebra" k[G] are typical uses.
In fact the construction of the "monoid algebra" makes sense when `G` is not even a monoid, but
merely a magma, i.e., when `G` carries a multiplication which is not required to satisfy any
conditions at all. In this case the construction yields a not-necessarily-unital,
not-necessarily-associative algebra but it is still adjoint to the forgetful functor from such
algebras to magmas, and we prove this as `monoid_algebra.lift_magma`.
In this file we define `monoid_algebra k G := G →₀ k`, and `add_monoid_algebra k G`
in the same way, and then define the convolution product on these.
When the domain is additive, this is used to define polynomials:
```
polynomial α := add_monoid_algebra ℕ α
mv_polynomial σ α := add_monoid_algebra (σ →₀ ℕ) α
```
When the domain is multiplicative, e.g. a group, this will be used to define the group ring.
## Implementation note
Unfortunately because additive and multiplicative structures both appear in both cases,
it doesn't appear to be possible to make much use of `to_additive`, and we just settle for
saying everything twice.
Similarly, I attempted to just define
`add_monoid_algebra k G := monoid_algebra k (multiplicative G)`, but the definitional equality
`multiplicative G = G` leaks through everywhere, and seems impossible to use.
-/
noncomputable theory
open_locale big_operators
open finset finsupp
universes u₁ u₂ u₃
variables (k : Type u₁) (G : Type u₂) {R : Type*}
/-! ### Multiplicative monoids -/
section
variables [semiring k]
/--
The monoid algebra over a semiring `k` generated by the monoid `G`.
It is the type of finite formal `k`-linear combinations of terms of `G`,
endowed with the convolution product.
-/
@[derive [inhabited, add_comm_monoid]]
def monoid_algebra : Type (max u₁ u₂) := G →₀ k
instance : has_coe_to_fun (monoid_algebra k G) (λ _, G → k) :=
finsupp.has_coe_to_fun
end
namespace monoid_algebra
variables {k G}
section
variables [semiring k] [non_unital_non_assoc_semiring R]
/-- A non-commutative version of `monoid_algebra.lift`: given a additive homomorphism `f : k →+ R`
and a homomorphism `g : G → R`, returns the additive homomorphism from
`monoid_algebra k G` such that `lift_nc f g (single a b) = f b * g a`. If `f` is a ring homomorphism
and the range of either `f` or `g` is in center of `R`, then the result is a ring homomorphism. If
`R` is a `k`-algebra and `f = algebra_map k R`, then the result is an algebra homomorphism called
`monoid_algebra.lift`. -/
def lift_nc (f : k →+ R) (g : G → R) : monoid_algebra k G →+ R :=
lift_add_hom (λ x : G, (add_monoid_hom.mul_right (g x)).comp f)
@[simp] lemma lift_nc_single (f : k →+ R) (g : G → R) (a : G) (b : k) :
lift_nc f g (single a b) = f b * g a :=
lift_add_hom_apply_single _ _ _
end
section has_mul
variables [semiring k] [has_mul G]
/-- The product of `f g : monoid_algebra k G` is the finitely supported function
whose value at `a` is the sum of `f x * g y` over all pairs `x, y`
such that `x * y = a`. (Think of the group ring of a group.) -/
instance : has_mul (monoid_algebra k G) :=
⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)⟩
lemma mul_def {f g : monoid_algebra k G} :
f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)) :=
rfl
instance : non_unital_non_assoc_semiring (monoid_algebra k G) :=
{ zero := 0,
mul := (*),
add := (+),
left_distrib := assume f g h, by simp only [mul_def, sum_add_index, mul_add, mul_zero,
single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add],
right_distrib := assume f g h, by simp only [mul_def, sum_add_index, add_mul, zero_mul,
single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero,
sum_add],
zero_mul := assume f, by simp only [mul_def, sum_zero_index],
mul_zero := assume f, by simp only [mul_def, sum_zero_index, sum_zero],
.. finsupp.add_comm_monoid }
variables [semiring R]
lemma lift_nc_mul {g_hom : Type*} [mul_hom_class g_hom G R] (f : k →+* R) (g : g_hom)
(a b : monoid_algebra k G) (h_comm : ∀ {x y}, y ∈ a.support → commute (f (b x)) (g y)) :
lift_nc (f : k →+ R) g (a * b) = lift_nc (f : k →+ R) g a * lift_nc (f : k →+ R) g b :=
begin
conv_rhs { rw [← sum_single a, ← sum_single b] },
simp_rw [mul_def, (lift_nc _ g).map_finsupp_sum, lift_nc_single, finsupp.sum_mul,
finsupp.mul_sum],
refine finset.sum_congr rfl (λ y hy, finset.sum_congr rfl (λ x hx, _)),
simp [mul_assoc, (h_comm hy).left_comm]
end
end has_mul
section semigroup
variables [semiring k] [semigroup G] [semiring R]
instance : non_unital_semiring (monoid_algebra k G) :=
{ zero := 0,
mul := (*),
add := (+),
mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff,
add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add],
.. monoid_algebra.non_unital_non_assoc_semiring}
end semigroup
section has_one
variables [non_assoc_semiring R] [semiring k] [has_one G]
/-- The unit of the multiplication is `single 1 1`, i.e. the function
that is `1` at `1` and zero elsewhere. -/
instance : has_one (monoid_algebra k G) :=
⟨single 1 1⟩
lemma one_def : (1 : monoid_algebra k G) = single 1 1 :=
rfl
@[simp] lemma lift_nc_one {g_hom : Type*} [one_hom_class g_hom G R] (f : k →+* R) (g : g_hom) :
lift_nc (f : k →+ R) g 1 = 1 :=
by simp [one_def]
end has_one
section mul_one_class
variables [semiring k] [mul_one_class G]
instance : non_assoc_semiring (monoid_algebra k G) :=
{ one := 1,
mul := (*),
zero := 0,
add := (+),
nat_cast := λ n, single 1 n,
nat_cast_zero := by simp [nat.cast],
nat_cast_succ := λ _, by simp [nat.cast]; refl,
one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul,
single_zero, sum_zero, zero_add, one_mul, sum_single],
mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero,
single_zero, sum_zero, add_zero, mul_one, sum_single],
..monoid_algebra.non_unital_non_assoc_semiring }
end mul_one_class
/-! #### Semiring structure -/
section semiring
variables [semiring k] [monoid G]
instance : semiring (monoid_algebra k G) :=
{ one := 1,
mul := (*),
zero := 0,
add := (+),
.. monoid_algebra.non_unital_semiring,
.. monoid_algebra.non_assoc_semiring }
variables [semiring R]
/-- `lift_nc` as a `ring_hom`, for when `f x` and `g y` commute -/
def lift_nc_ring_hom (f : k →+* R) (g : G →* R) (h_comm : ∀ x y, commute (f x) (g y)) :
monoid_algebra k G →+* R :=
{ to_fun := lift_nc (f : k →+ R) g,
map_one' := lift_nc_one _ _,
map_mul' := λ a b, lift_nc_mul _ _ _ _ $ λ _ _ _, h_comm _ _,
..(lift_nc (f : k →+ R) g)}
end semiring
instance [comm_semiring k] [comm_semigroup G] : non_unital_comm_semiring (monoid_algebra k G) :=
{ mul_comm := assume f g,
begin
simp only [mul_def, finsupp.sum, mul_comm],
rw [finset.sum_comm],
simp only [mul_comm]
end,
.. monoid_algebra.non_unital_semiring }
instance [semiring k] [nontrivial k] [nonempty G]: nontrivial (monoid_algebra k G) :=
finsupp.nontrivial
/-! #### Derived instances -/
section derived_instances
instance [comm_semiring k] [comm_monoid G] : comm_semiring (monoid_algebra k G) :=
{ .. monoid_algebra.non_unital_comm_semiring,
.. monoid_algebra.semiring }
instance [semiring k] [subsingleton k] : unique (monoid_algebra k G) :=
finsupp.unique_of_right
instance [ring k] : add_comm_group (monoid_algebra k G) :=
finsupp.add_comm_group
instance [ring k] [has_mul G] : non_unital_non_assoc_ring (monoid_algebra k G) :=
{ .. monoid_algebra.add_comm_group,
.. monoid_algebra.non_unital_non_assoc_semiring }
instance [ring k] [semigroup G] : non_unital_ring (monoid_algebra k G) :=
{ .. monoid_algebra.add_comm_group,
.. monoid_algebra.non_unital_semiring }
instance [ring k] [mul_one_class G] : non_assoc_ring (monoid_algebra k G) :=
{ .. monoid_algebra.add_comm_group,
.. monoid_algebra.non_assoc_semiring }
instance [ring k] [monoid G] : ring (monoid_algebra k G) :=
{ .. monoid_algebra.non_unital_non_assoc_ring,
.. monoid_algebra.semiring }
instance [comm_ring k] [comm_semigroup G] : non_unital_comm_ring (monoid_algebra k G) :=
{ .. monoid_algebra.non_unital_comm_semiring,
.. monoid_algebra.non_unital_ring }
instance [comm_ring k] [comm_monoid G] : comm_ring (monoid_algebra k G) :=
{ .. monoid_algebra.non_unital_comm_ring,
.. monoid_algebra.ring }
variables {S : Type*}
instance [monoid R] [semiring k] [distrib_mul_action R k] :
has_smul R (monoid_algebra k G) :=
finsupp.has_smul
instance [monoid R] [semiring k] [distrib_mul_action R k] :
distrib_mul_action R (monoid_algebra k G) :=
finsupp.distrib_mul_action G k
instance [semiring R] [semiring k] [module R k] :
module R (monoid_algebra k G) :=
finsupp.module G k
instance [monoid R] [semiring k] [distrib_mul_action R k] [has_faithful_smul R k] [nonempty G] :
has_faithful_smul R (monoid_algebra k G) :=
finsupp.has_faithful_smul
instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k]
[has_smul R S] [is_scalar_tower R S k] :
is_scalar_tower R S (monoid_algebra k G) :=
finsupp.is_scalar_tower G k
instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k]
[smul_comm_class R S k] :
smul_comm_class R S (monoid_algebra k G) :=
finsupp.smul_comm_class G k
instance [monoid R] [semiring k] [distrib_mul_action R k] [distrib_mul_action Rᵐᵒᵖ k]
[is_central_scalar R k] :
is_central_scalar R (monoid_algebra k G) :=
finsupp.is_central_scalar G k
/-- This is not an instance as it conflicts with `monoid_algebra.distrib_mul_action` when `G = kˣ`.
-/
def comap_distrib_mul_action_self [group G] [semiring k] :
distrib_mul_action G (monoid_algebra k G) :=
finsupp.comap_distrib_mul_action
end derived_instances
section misc_theorems
variables [semiring k]
local attribute [reducible] monoid_algebra
lemma mul_apply [decidable_eq G] [has_mul G] (f g : monoid_algebra k G) (x : G) :
(f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ * a₂ = x then b₁ * b₂ else 0) :=
begin
rw [mul_def],
simp only [finsupp.sum_apply, single_apply],
end
lemma mul_apply_antidiagonal [has_mul G] (f g : monoid_algebra k G) (x : G) (s : finset (G × G))
(hs : ∀ {p : G × G}, p ∈ s ↔ p.1 * p.2 = x) :
(f * g) x = ∑ p in s, (f p.1 * g p.2) :=
let F : G × G → k := λ p, by classical; exact if p.1 * p.2 = x then f p.1 * g p.2 else 0 in
calc (f * g) x = (∑ a₁ in f.support, ∑ a₂ in g.support, F (a₁, a₂)) :
mul_apply f g x
... = ∑ p in f.support.product g.support, F p : finset.sum_product.symm
... = ∑ p in (f.support.product g.support).filter (λ p : G × G, p.1 * p.2 = x), f p.1 * g p.2 :
(finset.sum_filter _ _).symm
... = ∑ p in s.filter (λ p : G × G, p.1 ∈ f.support ∧ p.2 ∈ g.support), f p.1 * g p.2 :
sum_congr (by { ext, simp only [mem_filter, mem_product, hs, and_comm] }) (λ _ _, rfl)
... = ∑ p in s, f p.1 * g p.2 : sum_subset (filter_subset _ _) $ λ p hps hp,
begin
simp only [mem_filter, mem_support_iff, not_and, not_not] at hp ⊢,
by_cases h1 : f p.1 = 0,
{ rw [h1, zero_mul] },
{ rw [hp hps h1, mul_zero] }
end
lemma support_mul [has_mul G] [decidable_eq G] (a b : monoid_algebra k G) :
(a * b).support ⊆ a.support.bUnion (λa₁, b.support.bUnion $ λa₂, {a₁ * a₂}) :=
subset.trans support_sum $ bUnion_mono $ assume a₁ _,
subset.trans support_sum $ bUnion_mono $ assume a₂ _, support_single_subset
@[simp] lemma single_mul_single [has_mul G] {a₁ a₂ : G} {b₁ b₂ : k} :
(single a₁ b₁ : monoid_algebra k G) * single a₂ b₂ = single (a₁ * a₂) (b₁ * b₂) :=
(sum_single_index (by simp only [zero_mul, single_zero, sum_zero])).trans
(sum_single_index (by rw [mul_zero, single_zero]))
@[simp] lemma single_pow [monoid G] {a : G} {b : k} :
∀ n : ℕ, (single a b : monoid_algebra k G)^n = single (a^n) (b ^ n)
| 0 := by { simp only [pow_zero], refl }
| (n+1) := by simp only [pow_succ, single_pow n, single_mul_single]
section
/-- Like `finsupp.map_domain_zero`, but for the `1` we define in this file -/
@[simp] lemma map_domain_one {α : Type*} {β : Type*} {α₂ : Type*}
[semiring β] [has_one α] [has_one α₂] {F : Type*} [one_hom_class F α α₂] (f : F) :
(map_domain f (1 : monoid_algebra β α) : monoid_algebra β α₂) = (1 : monoid_algebra β α₂) :=
by simp_rw [one_def, map_domain_single, map_one]
/-- Like `finsupp.map_domain_add`, but for the convolutive multiplication we define in this file -/
lemma map_domain_mul {α : Type*} {β : Type*} {α₂ : Type*} [semiring β] [has_mul α] [has_mul α₂]
{F : Type*} [mul_hom_class F α α₂] (f : F) (x y : monoid_algebra β α) :
(map_domain f (x * y : monoid_algebra β α) : monoid_algebra β α₂) =
(map_domain f x * map_domain f y : monoid_algebra β α₂) :=
begin
simp_rw [mul_def, map_domain_sum, map_domain_single, map_mul],
rw finsupp.sum_map_domain_index,
{ congr,
ext a b,
rw finsupp.sum_map_domain_index,
{ simp },
{ simp [mul_add] } },
{ simp },
{ simp [add_mul] }
end
variables (k G)
/-- The embedding of a magma into its magma algebra. -/
@[simps] def of_magma [has_mul G] : G →ₙ* (monoid_algebra k G) :=
{ to_fun := λ a, single a 1,
map_mul' := λ a b, by simp only [mul_def, mul_one, sum_single_index, single_eq_zero, mul_zero], }
/-- The embedding of a unital magma into its magma algebra. -/
@[simps] def of [mul_one_class G] : G →* monoid_algebra k G :=
{ to_fun := λ a, single a 1,
map_one' := rfl,
.. of_magma k G }
end
lemma smul_of [mul_one_class G] (g : G) (r : k) :
r • (of k G g) = single g r := by simp
lemma of_injective [mul_one_class G] [nontrivial k] : function.injective (of k G) :=
λ a b h, by simpa using (single_eq_single_iff _ _ _ _).mp h
/--
`finsupp.single` as a `monoid_hom` from the product type into the monoid algebra.
Note the order of the elements of the product are reversed compared to the arguments of
`finsupp.single`.
-/
@[simps] def single_hom [mul_one_class G] : k × G →* monoid_algebra k G :=
{ to_fun := λ a, single a.2 a.1,
map_one' := rfl,
map_mul' := λ a b, single_mul_single.symm }
lemma mul_single_apply_aux [has_mul G] (f : monoid_algebra k G) {r : k}
{x y z : G} (H : ∀ a, a * x = z ↔ a = y) :
(f * single x r) z = f y * r :=
by classical; exact
have A : ∀ a₁ b₁, (single x r).sum (λ a₂ b₂, ite (a₁ * a₂ = z) (b₁ * b₂) 0) =
ite (a₁ * x = z) (b₁ * r) 0,
from λ a₁ b₁, sum_single_index $ by simp,
calc (f * single x r) z = sum f (λ a b, if (a = y) then (b * r) else 0) :
by simp only [mul_apply, A, H]
... = if y ∈ f.support then f y * r else 0 : f.support.sum_ite_eq' _ _
... = f y * r : by split_ifs with h; simp at h; simp [h]
lemma mul_single_one_apply [mul_one_class G] (f : monoid_algebra k G) (r : k) (x : G) :
(f * single 1 r) x = f x * r :=
f.mul_single_apply_aux $ λ a, by rw [mul_one]
lemma support_mul_single [right_cancel_semigroup G]
(f : monoid_algebra k G) (r : k) (hr : ∀ y, y * r = 0 ↔ y = 0) (x : G) :
(f * single x r).support = f.support.map (mul_right_embedding x) :=
begin
ext y, simp only [mem_support_iff, mem_map, exists_prop, mul_right_embedding_apply],
by_cases H : ∃ a, a * x = y,
{ rcases H with ⟨a, rfl⟩,
rw [mul_single_apply_aux f (λ _, mul_left_inj x)],
simp [hr] },
{ push_neg at H,
classical,
simp [mul_apply, H] }
end
lemma single_mul_apply_aux [has_mul G] (f : monoid_algebra k G) {r : k} {x y z : G}
(H : ∀ a, x * a = y ↔ a = z) :
(single x r * f) y = r * f z :=
by classical; exact (
have f.sum (λ a b, ite (x * a = y) (0 * b) 0) = 0, by simp,
calc (single x r * f) y = sum f (λ a b, ite (x * a = y) (r * b) 0) :
(mul_apply _ _ _).trans $ sum_single_index (by exact this)
... = f.sum (λ a b, ite (a = z) (r * b) 0) : by simp only [H]
... = if z ∈ f.support then (r * f z) else 0 : f.support.sum_ite_eq' _ _
... = _ : by split_ifs with h; simp at h; simp [h])
lemma single_one_mul_apply [mul_one_class G] (f : monoid_algebra k G) (r : k) (x : G) :
(single 1 r * f) x = r * f x :=
f.single_mul_apply_aux $ λ a, by rw [one_mul]
lemma support_single_mul [left_cancel_semigroup G]
(f : monoid_algebra k G) (r : k) (hr : ∀ y, r * y = 0 ↔ y = 0) (x : G) :
(single x r * f).support = f.support.map (mul_left_embedding x) :=
begin
ext y, simp only [mem_support_iff, mem_map, exists_prop, mul_left_embedding_apply],
by_cases H : ∃ a, x * a = y,
{ rcases H with ⟨a, rfl⟩,
rw [single_mul_apply_aux f (λ _, mul_right_inj x)],
simp [hr] },
{ push_neg at H,
classical,
simp [mul_apply, H] }
end
lemma lift_nc_smul [mul_one_class G] {R : Type*} [semiring R] (f : k →+* R) (g : G →* R) (c : k)
(φ : monoid_algebra k G) :
lift_nc (f : k →+ R) g (c • φ) = f c * lift_nc (f : k →+ R) g φ :=
begin
suffices : (lift_nc ↑f g).comp (smul_add_hom k (monoid_algebra k G) c) =
(add_monoid_hom.mul_left (f c)).comp (lift_nc ↑f g),
from add_monoid_hom.congr_fun this φ,
ext a b, simp [mul_assoc]
end
end misc_theorems
/-! #### Non-unital, non-associative algebra structure -/
section non_unital_non_assoc_algebra
variables (k) [monoid R] [semiring k] [distrib_mul_action R k] [has_mul G]
instance is_scalar_tower_self [is_scalar_tower R k k] :
is_scalar_tower R (monoid_algebra k G) (monoid_algebra k G) :=
⟨λ t a b,
begin
ext m,
classical,
simp only [mul_apply, finsupp.smul_sum, smul_ite, smul_mul_assoc, sum_smul_index', zero_mul,
if_t_t, implies_true_iff, eq_self_iff_true, sum_zero, coe_smul, smul_eq_mul, pi.smul_apply,
smul_zero],
end⟩
/-- Note that if `k` is a `comm_semiring` then we have `smul_comm_class k k k` and so we can take
`R = k` in the below. In other words, if the coefficients are commutative amongst themselves, they
also commute with the algebra multiplication. -/
instance smul_comm_class_self [smul_comm_class R k k] :
smul_comm_class R (monoid_algebra k G) (monoid_algebra k G) :=
⟨λ t a b,
begin
ext m,
simp only [mul_apply, finsupp.sum, finset.smul_sum, smul_ite, mul_smul_comm, sum_smul_index',
implies_true_iff, eq_self_iff_true, coe_smul, ite_eq_right_iff, smul_eq_mul, pi.smul_apply,
mul_zero, smul_zero],
end⟩
instance smul_comm_class_symm_self [smul_comm_class k R k] :
smul_comm_class (monoid_algebra k G) R (monoid_algebra k G) :=
⟨λ t a b, by { haveI := smul_comm_class.symm k R k, rw ← smul_comm, } ⟩
variables {A : Type u₃} [non_unital_non_assoc_semiring A]
/-- A non_unital `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its
values on the functions `single a 1`. -/
lemma non_unital_alg_hom_ext [distrib_mul_action k A]
{φ₁ φ₂ : monoid_algebra k G →ₙₐ[k] A}
(h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ :=
non_unital_alg_hom.to_distrib_mul_action_hom_injective $
finsupp.distrib_mul_action_hom_ext' $
λ a, distrib_mul_action_hom.ext_ring (h a)
/-- See note [partially-applied ext lemmas]. -/
@[ext] lemma non_unital_alg_hom_ext' [distrib_mul_action k A]
{φ₁ φ₂ : monoid_algebra k G →ₙₐ[k] A}
(h : φ₁.to_mul_hom.comp (of_magma k G) = φ₂.to_mul_hom.comp (of_magma k G)) : φ₁ = φ₂ :=
non_unital_alg_hom_ext k $ mul_hom.congr_fun h
/-- The functor `G ↦ monoid_algebra k G`, from the category of magmas to the category of non-unital,
non-associative algebras over `k` is adjoint to the forgetful functor in the other direction. -/
@[simps] def lift_magma [module k A] [is_scalar_tower k A A] [smul_comm_class k A A] :
(G →ₙ* A) ≃ (monoid_algebra k G →ₙₐ[k] A) :=
{ to_fun := λ f,
{ to_fun := λ a, a.sum (λ m t, t • f m),
map_smul' := λ t' a,
begin
rw [finsupp.smul_sum, sum_smul_index'],
{ simp_rw smul_assoc, },
{ intros m, exact zero_smul k (f m), },
end,
map_mul' := λ a₁ a₂,
begin
let g : G → k → A := λ m t, t • f m,
have h₁ : ∀ m, g m 0 = 0, { intros, exact zero_smul k (f m), },
have h₂ : ∀ m (t₁ t₂ : k), g m (t₁ + t₂) = g m t₁ + g m t₂, { intros, rw ← add_smul, },
simp_rw [finsupp.mul_sum, finsupp.sum_mul, smul_mul_smul, ← f.map_mul, mul_def,
sum_comm a₂ a₁, sum_sum_index h₁ h₂, sum_single_index (h₁ _)],
end,
.. lift_add_hom (λ x, (smul_add_hom k A).flip (f x)) },
inv_fun := λ F, F.to_mul_hom.comp (of_magma k G),
left_inv := λ f, by { ext m, simp only [non_unital_alg_hom.coe_mk, of_magma_apply,
non_unital_alg_hom.to_mul_hom_eq_coe, sum_single_index, function.comp_app, one_smul, zero_smul,
mul_hom.coe_comp, non_unital_alg_hom.coe_to_mul_hom], },
right_inv := λ F, by { ext m, simp only [non_unital_alg_hom.coe_mk, of_magma_apply,
non_unital_alg_hom.to_mul_hom_eq_coe, sum_single_index, function.comp_app, one_smul, zero_smul,
mul_hom.coe_comp, non_unital_alg_hom.coe_to_mul_hom], }, }
end non_unital_non_assoc_algebra
/-! #### Algebra structure -/
section algebra
local attribute [reducible] monoid_algebra
lemma single_one_comm [comm_semiring k] [mul_one_class G] (r : k) (f : monoid_algebra k G) :
single 1 r * f = f * single 1 r :=
by { ext, rw [single_one_mul_apply, mul_single_one_apply, mul_comm] }
/-- `finsupp.single 1` as a `ring_hom` -/
@[simps] def single_one_ring_hom [semiring k] [mul_one_class G] : k →+* monoid_algebra k G :=
{ map_one' := rfl,
map_mul' := λ x y, by rw [single_add_hom, single_mul_single, one_mul],
..finsupp.single_add_hom 1}
/-- If `f : G → H` is a multiplicative homomorphism between two monoids, then
`finsupp.map_domain f` is a ring homomorphism between their monoid algebras. -/
@[simps]
def map_domain_ring_hom (k : Type*) {H F : Type*} [semiring k] [monoid G] [monoid H]
[monoid_hom_class F G H] (f : F) :
monoid_algebra k G →+* monoid_algebra k H :=
{ map_one' := map_domain_one f,
map_mul' := λ x y, map_domain_mul f x y,
..(finsupp.map_domain.add_monoid_hom f : monoid_algebra k G →+ monoid_algebra k H) }
/-- If two ring homomorphisms from `monoid_algebra k G` are equal on all `single a 1`
and `single 1 b`, then they are equal. -/
lemma ring_hom_ext {R} [semiring k] [mul_one_class G] [semiring R]
{f g : monoid_algebra k G →+* R} (h₁ : ∀ b, f (single 1 b) = g (single 1 b))
(h_of : ∀ a, f (single a 1) = g (single a 1)) : f = g :=
ring_hom.coe_add_monoid_hom_injective $ add_hom_ext $ λ a b,
by rw [← one_mul a, ← mul_one b, ← single_mul_single, f.coe_add_monoid_hom,
g.coe_add_monoid_hom, f.map_mul, g.map_mul, h₁, h_of]
/-- If two ring homomorphisms from `monoid_algebra k G` are equal on all `single a 1`
and `single 1 b`, then they are equal.
See note [partially-applied ext lemmas]. -/
@[ext] lemma ring_hom_ext' {R} [semiring k] [mul_one_class G] [semiring R]
{f g : monoid_algebra k G →+* R} (h₁ : f.comp single_one_ring_hom = g.comp single_one_ring_hom)
(h_of : (f : monoid_algebra k G →* R).comp (of k G) =
(g : monoid_algebra k G →* R).comp (of k G)) :
f = g :=
ring_hom_ext (ring_hom.congr_fun h₁) (monoid_hom.congr_fun h_of)
/--
The instance `algebra k (monoid_algebra A G)` whenever we have `algebra k A`.
In particular this provides the instance `algebra k (monoid_algebra k G)`.
-/
instance {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] :
algebra k (monoid_algebra A G) :=
{ smul_def' := λ r a, by { ext, simp [single_one_mul_apply, algebra.smul_def, pi.smul_apply], },
commutes' := λ r f, by { ext, simp [single_one_mul_apply, mul_single_one_apply,
algebra.commutes], },
..single_one_ring_hom.comp (algebra_map k A) }
/-- `finsupp.single 1` as a `alg_hom` -/
@[simps]
def single_one_alg_hom {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] :
A →ₐ[k] monoid_algebra A G :=
{ commutes' := λ r, by { ext, simp, refl, }, ..single_one_ring_hom}
@[simp] lemma coe_algebra_map {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] :
⇑(algebra_map k (monoid_algebra A G)) = single 1 ∘ (algebra_map k A) :=
rfl
lemma single_eq_algebra_map_mul_of [comm_semiring k] [monoid G] (a : G) (b : k) :
single a b = algebra_map k (monoid_algebra k G) b * of k G a :=
by simp
lemma single_algebra_map_eq_algebra_map_mul_of {A : Type*} [comm_semiring k] [semiring A]
[algebra k A] [monoid G] (a : G) (b : k) :
single a (algebra_map k A b) = algebra_map k (monoid_algebra A G) b * of A G a :=
by simp
lemma induction_on [semiring k] [monoid G] {p : monoid_algebra k G → Prop} (f : monoid_algebra k G)
(hM : ∀ g, p (of k G g)) (hadd : ∀ f g : monoid_algebra k G, p f → p g → p (f + g))
(hsmul : ∀ (r : k) f, p f → p (r • f)) : p f :=
begin
refine finsupp.induction_linear f _ (λ f g hf hg, hadd f g hf hg) (λ g r, _),
{ simpa using hsmul 0 (of k G 1) (hM 1) },
{ convert hsmul r (of k G g) (hM g),
simp only [mul_one, smul_single', of_apply] },
end
end algebra
section lift
variables {k G} [comm_semiring k] [monoid G]
variables {A : Type u₃} [semiring A] [algebra k A] {B : Type*} [semiring B] [algebra k B]
/-- `lift_nc_ring_hom` as a `alg_hom`, for when `f` is an `alg_hom` -/
def lift_nc_alg_hom (f : A →ₐ[k] B) (g : G →* B) (h_comm : ∀ x y, commute (f x) (g y)) :
monoid_algebra A G →ₐ[k] B :=
{ to_fun := lift_nc_ring_hom (f : A →+* B) g h_comm,
commutes' := by simp [lift_nc_ring_hom],
..(lift_nc_ring_hom (f : A →+* B) g h_comm)}
/-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its
values on the functions `single a 1`. -/
lemma alg_hom_ext ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] A⦄
(h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ :=
alg_hom.to_linear_map_injective $ finsupp.lhom_ext' $ λ a, linear_map.ext_ring (h a)
/-- See note [partially-applied ext lemmas]. -/
@[ext] lemma alg_hom_ext' ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] A⦄
(h : (φ₁ : monoid_algebra k G →* A).comp (of k G) =
(φ₂ : monoid_algebra k G →* A).comp (of k G)) : φ₁ = φ₂ :=
alg_hom_ext $ monoid_hom.congr_fun h
variables (k G A)
/-- Any monoid homomorphism `G →* A` can be lifted to an algebra homomorphism
`monoid_algebra k G →ₐ[k] A`. -/
def lift : (G →* A) ≃ (monoid_algebra k G →ₐ[k] A) :=
{ inv_fun := λ f, (f : monoid_algebra k G →* A).comp (of k G),
to_fun := λ F, lift_nc_alg_hom (algebra.of_id k A) F $ λ _ _, algebra.commutes _ _,
left_inv := λ f, by { ext, simp [lift_nc_alg_hom, lift_nc_ring_hom] },
right_inv := λ F, by { ext, simp [lift_nc_alg_hom, lift_nc_ring_hom] } }
variables {k G A}
lemma lift_apply' (F : G →* A) (f : monoid_algebra k G) :
lift k G A F f = f.sum (λ a b, (algebra_map k A b) * F a) := rfl
lemma lift_apply (F : G →* A) (f : monoid_algebra k G) :
lift k G A F f = f.sum (λ a b, b • F a) :=
by simp only [lift_apply', algebra.smul_def]
lemma lift_def (F : G →* A) :
⇑(lift k G A F) = lift_nc ((algebra_map k A : k →+* A) : k →+ A) F :=
rfl
@[simp] lemma lift_symm_apply (F : monoid_algebra k G →ₐ[k] A) (x : G) :
(lift k G A).symm F x = F (single x 1) := rfl
lemma lift_of (F : G →* A) (x) :
lift k G A F (of k G x) = F x :=
by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply]
@[simp] lemma lift_single (F : G →* A) (a b) :
lift k G A F (single a b) = b • F a :=
by rw [lift_def, lift_nc_single, algebra.smul_def, ring_hom.coe_add_monoid_hom]
lemma lift_unique' (F : monoid_algebra k G →ₐ[k] A) :
F = lift k G A ((F : monoid_algebra k G →* A).comp (of k G)) :=
((lift k G A).apply_symm_apply F).symm
/-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by
its values on `F (single a 1)`. -/
lemma lift_unique (F : monoid_algebra k G →ₐ[k] A) (f : monoid_algebra k G) :
F f = f.sum (λ a b, b • F (single a 1)) :=
by conv_lhs { rw lift_unique' F, simp [lift_apply] }
/-- If `f : G → H` is a homomorphism between two magmas, then
`finsupp.map_domain f` is a non-unital algebra homomorphism between their magma algebras. -/
@[simps]
def map_domain_non_unital_alg_hom (k A : Type*) [comm_semiring k] [semiring A] [algebra k A]
{G H F : Type*} [has_mul G] [has_mul H] [mul_hom_class F G H] (f : F) :
monoid_algebra A G →ₙₐ[k] monoid_algebra A H :=
{ map_mul' := λ x y, map_domain_mul f x y,
map_smul' := λ r x, map_domain_smul r x,
..(finsupp.map_domain.add_monoid_hom f : monoid_algebra A G →+ monoid_algebra A H) }
lemma map_domain_algebra_map (k A : Type*) {H F : Type*} [comm_semiring k] [semiring A]
[algebra k A] [monoid H] [monoid_hom_class F G H] (f : F) (r : k) :
map_domain f (algebra_map k (monoid_algebra A G) r) =
algebra_map k (monoid_algebra A H) r :=
by simp only [coe_algebra_map, map_domain_single, map_one]
/-- If `f : G → H` is a multiplicative homomorphism between two monoids, then
`finsupp.map_domain f` is an algebra homomorphism between their monoid algebras. -/
@[simps]
def map_domain_alg_hom (k A : Type*) [comm_semiring k] [semiring A] [algebra k A] {H F : Type*}
[monoid H] [monoid_hom_class F G H] (f : F) :
monoid_algebra A G →ₐ[k] monoid_algebra A H :=
{ commutes' := map_domain_algebra_map k A f,
..map_domain_ring_hom A f}
end lift
section
local attribute [reducible] monoid_algebra
variables (k)
/-- When `V` is a `k[G]`-module, multiplication by a group element `g` is a `k`-linear map. -/
def group_smul.linear_map [monoid G] [comm_semiring k]
(V : Type u₃) [add_comm_monoid V] [module k V] [module (monoid_algebra k G) V]
[is_scalar_tower k (monoid_algebra k G) V] (g : G) :
V →ₗ[k] V :=
{ to_fun := λ v, (single g (1 : k) • v : V),
map_add' := λ x y, smul_add (single g (1 : k)) x y,
map_smul' := λ c x, smul_algebra_smul_comm _ _ _ }
@[simp]
lemma group_smul.linear_map_apply [monoid G] [comm_semiring k]
(V : Type u₃) [add_comm_monoid V] [module k V] [module (monoid_algebra k G) V]
[is_scalar_tower k (monoid_algebra k G) V] (g : G) (v : V) :
(group_smul.linear_map k V g) v = (single g (1 : k) • v : V) :=
rfl
section
variables {k}
variables [monoid G] [comm_semiring k] {V W : Type u₃}
[add_comm_monoid V] [module k V] [module (monoid_algebra k G) V]
[is_scalar_tower k (monoid_algebra k G) V]
[add_comm_monoid W] [module k W] [module (monoid_algebra k G) W]
[is_scalar_tower k (monoid_algebra k G) W]
(f : V →ₗ[k] W)
(h : ∀ (g : G) (v : V), f (single g (1 : k) • v : V) = (single g (1 : k) • (f v) : W))
include h
/-- Build a `k[G]`-linear map from a `k`-linear map and evidence that it is `G`-equivariant. -/
def equivariant_of_linear_of_comm : V →ₗ[monoid_algebra k G] W :=
{ to_fun := f,
map_add' := λ v v', by simp,
map_smul' := λ c v,
begin
apply finsupp.induction c,
{ simp, },
{ intros g r c' nm nz w,
dsimp at *,
simp only [add_smul, f.map_add, w, add_left_inj, single_eq_algebra_map_mul_of, ← smul_smul],
erw [algebra_map_smul (monoid_algebra k G) r, algebra_map_smul (monoid_algebra k G) r,
f.map_smul, h g v, of_apply],
all_goals { apply_instance } }
end, }
@[simp]
lemma equivariant_of_linear_of_comm_apply (v : V) : (equivariant_of_linear_of_comm f h) v = f v :=
rfl
end
end
section
universe ui
variable {ι : Type ui}
local attribute [reducible] monoid_algebra
lemma prod_single [comm_semiring k] [comm_monoid G]
{s : finset ι} {a : ι → G} {b : ι → k} :
(∏ i in s, single (a i) (b i)) = single (∏ i in s, a i) (∏ i in s, b i) :=
finset.cons_induction_on s rfl $ λ a s has ih, by rw [prod_cons has, ih,
single_mul_single, prod_cons has, prod_cons has]
end
section -- We now prove some additional statements that hold for group algebras.
variables [semiring k] [group G]
local attribute [reducible] monoid_algebra
@[simp]
lemma mul_single_apply (f : monoid_algebra k G) (r : k) (x y : G) :
(f * single x r) y = f (y * x⁻¹) * r :=
f.mul_single_apply_aux $ λ a, eq_mul_inv_iff_mul_eq.symm
@[simp]
lemma single_mul_apply (r : k) (x : G) (f : monoid_algebra k G) (y : G) :
(single x r * f) y = r * f (x⁻¹ * y) :=
f.single_mul_apply_aux $ λ z, eq_inv_mul_iff_mul_eq.symm
lemma mul_apply_left (f g : monoid_algebra k G) (x : G) :
(f * g) x = (f.sum $ λ a b, b * (g (a⁻¹ * x))) :=
calc (f * g) x = sum f (λ a b, (single a b * g) x) :
by rw [← finsupp.sum_apply, ← finsupp.sum_mul, f.sum_single]
... = _ : by simp only [single_mul_apply, finsupp.sum]
-- If we'd assumed `comm_semiring`, we could deduce this from `mul_apply_left`.
lemma mul_apply_right (f g : monoid_algebra k G) (x : G) :
(f * g) x = (g.sum $ λa b, (f (x * a⁻¹)) * b) :=
calc (f * g) x = sum g (λ a b, (f * single a b) x) :
by rw [← finsupp.sum_apply, ← finsupp.mul_sum, g.sum_single]
... = _ : by simp only [mul_single_apply, finsupp.sum]
end
section span
variables [semiring k] [mul_one_class G]
/-- An element of `monoid_algebra R M` is in the subalgebra generated by its support. -/
lemma mem_span_support (f : monoid_algebra k G) :
f ∈ submodule.span k (of k G '' (f.support : set G)) :=
by rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported]
end span
section opposite
open finsupp mul_opposite
variables [semiring k]
/-- The opposite of an `monoid_algebra R I` equivalent as a ring to
the `monoid_algebra Rᵐᵒᵖ Iᵐᵒᵖ` over the opposite ring, taking elements to their opposite. -/
@[simps {simp_rhs := tt}] protected noncomputable def op_ring_equiv [monoid G] :
(monoid_algebra k G)ᵐᵒᵖ ≃+* monoid_algebra kᵐᵒᵖ Gᵐᵒᵖ :=
{ map_mul' := begin
dsimp only [add_equiv.to_fun_eq_coe, ←add_equiv.coe_to_add_monoid_hom],
rw add_monoid_hom.map_mul_iff,
ext i₁ r₁ i₂ r₂ : 6,
simp
end,
..op_add_equiv.symm.trans $ (finsupp.map_range.add_equiv (op_add_equiv : k ≃+ kᵐᵒᵖ)).trans $
finsupp.dom_congr op_equiv }
@[simp] lemma op_ring_equiv_single [monoid G] (r : k) (x : G) :
monoid_algebra.op_ring_equiv (op (single x r)) = single (op x) (op r) :=
by simp
@[simp] lemma op_ring_equiv_symm_single [monoid G] (r : kᵐᵒᵖ) (x : Gᵐᵒᵖ) :
monoid_algebra.op_ring_equiv.symm (single x r) = op (single x.unop r.unop) :=
by simp
end opposite
section submodule
variables {k G} [comm_semiring k] [monoid G]
variables {V : Type*} [add_comm_monoid V]
variables [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V]
/-- A submodule over `k` which is stable under scalar multiplication by elements of `G` is a
submodule over `monoid_algebra k G` -/
def submodule_of_smul_mem (W : submodule k V) (h : ∀ (g : G) (v : V), v ∈ W → (of k G g) • v ∈ W) :
submodule (monoid_algebra k G) V :=
{ carrier := W,
zero_mem' := W.zero_mem',
add_mem' := W.add_mem',
smul_mem' := begin
intros f v hv,
rw [←finsupp.sum_single f, finsupp.sum, finset.sum_smul],
simp_rw [←smul_of, smul_assoc],
exact submodule.sum_smul_mem W _ (λ g _, h g v hv)
end }
end submodule
end monoid_algebra
/-! ### Additive monoids -/
section
variables [semiring k]
/--
The monoid algebra over a semiring `k` generated by the additive monoid `G`.
It is the type of finite formal `k`-linear combinations of terms of `G`,
endowed with the convolution product.
-/
@[derive [inhabited, add_comm_monoid]]
def add_monoid_algebra := G →₀ k
instance : has_coe_to_fun (add_monoid_algebra k G) (λ _, G → k) :=
finsupp.has_coe_to_fun
end
namespace add_monoid_algebra
variables {k G}
section
variables [semiring k] [non_unital_non_assoc_semiring R]
/-- A non-commutative version of `add_monoid_algebra.lift`: given a additive homomorphism `f : k →+
R` and a map `g : multiplicative G → R`, returns the additive
homomorphism from `add_monoid_algebra k G` such that `lift_nc f g (single a b) = f b * g a`. If `f`
is a ring homomorphism and the range of either `f` or `g` is in center of `R`, then the result is a
ring homomorphism. If `R` is a `k`-algebra and `f = algebra_map k R`, then the result is an algebra
homomorphism called `add_monoid_algebra.lift`. -/
def lift_nc (f : k →+ R) (g : multiplicative G → R) : add_monoid_algebra k G →+ R :=
lift_add_hom (λ x : G, (add_monoid_hom.mul_right (g $ multiplicative.of_add x)).comp f)
@[simp] lemma lift_nc_single (f : k →+ R) (g : multiplicative G → R) (a : G) (b : k) :
lift_nc f g (single a b) = f b * g (multiplicative.of_add a) :=
lift_add_hom_apply_single _ _ _
end
section has_mul
variables [semiring k] [has_add G]
/-- The product of `f g : add_monoid_algebra k G` is the finitely supported function
whose value at `a` is the sum of `f x * g y` over all pairs `x, y`
such that `x + y = a`. (Think of the product of multivariate
polynomials where `α` is the additive monoid of monomial exponents.) -/
instance : has_mul (add_monoid_algebra k G) :=
⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩
lemma mul_def {f g : add_monoid_algebra k G} :
f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) :=
rfl
instance : non_unital_non_assoc_semiring (add_monoid_algebra k G) :=
{ zero := 0,
mul := (*),
add := (+),
left_distrib := assume f g h, by simp only [mul_def, sum_add_index, mul_add, mul_zero,
single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add],
right_distrib := assume f g h, by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul,
single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero,
sum_add],
zero_mul := assume f, by simp only [mul_def, sum_zero_index],
mul_zero := assume f, by simp only [mul_def, sum_zero_index, sum_zero],
nsmul := λ n f, n • f,
nsmul_zero' := by { intros, ext, simp [-nsmul_eq_mul, add_smul] },
nsmul_succ' := by { intros, ext, simp [-nsmul_eq_mul, nat.succ_eq_one_add, add_smul] },
.. finsupp.add_comm_monoid }
variables [semiring R]
lemma lift_nc_mul {g_hom : Type*} [mul_hom_class g_hom (multiplicative G) R] (f : k →+* R)
(g : g_hom) (a b : add_monoid_algebra k G)
(h_comm : ∀ {x y}, y ∈ a.support → commute (f (b x)) (g $ multiplicative.of_add y)) :
lift_nc (f : k →+ R) g (a * b) = lift_nc (f : k →+ R) g a * lift_nc (f : k →+ R) g b :=
(monoid_algebra.lift_nc_mul f g _ _ @h_comm : _)
end has_mul
section has_one
variables [semiring k] [has_zero G] [non_assoc_semiring R]
/-- The unit of the multiplication is `single 1 1`, i.e. the function
that is `1` at `0` and zero elsewhere. -/
instance : has_one (add_monoid_algebra k G) :=
⟨single 0 1⟩
lemma one_def : (1 : add_monoid_algebra k G) = single 0 1 :=
rfl
@[simp] lemma lift_nc_one {g_hom : Type*} [one_hom_class g_hom (multiplicative G) R]
(f : k →+* R) (g : g_hom) :
lift_nc (f : k →+ R) g 1 = 1 :=
(monoid_algebra.lift_nc_one f g : _)
end has_one
section semigroup
variables [semiring k] [add_semigroup G]
instance : non_unital_semiring (add_monoid_algebra k G) :=
{ zero := 0,
mul := (*),
add := (+),
mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff,
add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add],
.. add_monoid_algebra.non_unital_non_assoc_semiring }
end semigroup
section mul_one_class
variables [semiring k] [add_zero_class G]
instance : non_assoc_semiring (add_monoid_algebra k G) :=
{ one := 1,
mul := (*),
zero := 0,
add := (+),
nat_cast := λ n, single 0 n,
nat_cast_zero := by simp [nat.cast],
nat_cast_succ := λ _, by simp [nat.cast]; refl,
one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul,
single_zero, sum_zero, zero_add, one_mul, sum_single],
mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero,
single_zero, sum_zero, add_zero, mul_one, sum_single],
.. add_monoid_algebra.non_unital_non_assoc_semiring }
end mul_one_class
/-! #### Semiring structure -/
section semiring
instance {R : Type*} [monoid R] [semiring k] [distrib_mul_action R k] :
has_smul R (add_monoid_algebra k G) :=
finsupp.has_smul
variables [semiring k] [add_monoid G]
instance : semiring (add_monoid_algebra k G) :=
{ one := 1,
mul := (*),
zero := 0,
add := (+),
.. add_monoid_algebra.non_unital_semiring,
.. add_monoid_algebra.non_assoc_semiring, }
variables [semiring R]
/-- `lift_nc` as a `ring_hom`, for when `f` and `g` commute -/
def lift_nc_ring_hom (f : k →+* R) (g : multiplicative G →* R)
(h_comm : ∀ x y, commute (f x) (g y)) :
add_monoid_algebra k G →+* R :=
{ to_fun := lift_nc (f : k →+ R) g,
map_one' := lift_nc_one _ _,
map_mul' := λ a b, lift_nc_mul _ _ _ _ $ λ _ _ _, h_comm _ _,
..(lift_nc (f : k →+ R) g)}
end semiring
instance [comm_semiring k] [add_comm_semigroup G] :
non_unital_comm_semiring (add_monoid_algebra k G) :=
{ mul_comm := @mul_comm (monoid_algebra k $ multiplicative G) _,
.. add_monoid_algebra.non_unital_semiring }
instance [semiring k] [nontrivial k] [nonempty G] : nontrivial (add_monoid_algebra k G) :=
finsupp.nontrivial
/-! #### Derived instances -/
section derived_instances
instance [comm_semiring k] [add_comm_monoid G] : comm_semiring (add_monoid_algebra k G) :=
{ .. add_monoid_algebra.non_unital_comm_semiring,
.. add_monoid_algebra.semiring }
instance [semiring k] [subsingleton k] : unique (add_monoid_algebra k G) :=
finsupp.unique_of_right
instance [ring k] : add_comm_group (add_monoid_algebra k G) :=
finsupp.add_comm_group
instance [ring k] [has_add G] : non_unital_non_assoc_ring (add_monoid_algebra k G) :=
{ .. add_monoid_algebra.add_comm_group,
.. add_monoid_algebra.non_unital_non_assoc_semiring }
instance [ring k] [add_semigroup G] : non_unital_ring (add_monoid_algebra k G) :=
{ .. add_monoid_algebra.add_comm_group,
.. add_monoid_algebra.non_unital_semiring }
instance [ring k] [add_zero_class G] : non_assoc_ring (add_monoid_algebra k G) :=
{ .. add_monoid_algebra.add_comm_group,
.. add_monoid_algebra.non_assoc_semiring }
instance [ring k] [add_monoid G] : ring (add_monoid_algebra k G) :=
{ .. add_monoid_algebra.non_unital_non_assoc_ring,
.. add_monoid_algebra.semiring }
instance [comm_ring k] [add_comm_semigroup G] : non_unital_comm_ring (add_monoid_algebra k G) :=
{ .. add_monoid_algebra.non_unital_comm_semiring,
.. add_monoid_algebra.non_unital_ring }
instance [comm_ring k] [add_comm_monoid G] : comm_ring (add_monoid_algebra k G) :=
{ .. add_monoid_algebra.non_unital_comm_ring,
.. add_monoid_algebra.ring }
variables {S : Type*}
instance [monoid R] [semiring k] [distrib_mul_action R k] :
distrib_mul_action R (add_monoid_algebra k G) :=
finsupp.distrib_mul_action G k
instance [monoid R] [semiring k] [distrib_mul_action R k] [has_faithful_smul R k] [nonempty G] :
has_faithful_smul R (add_monoid_algebra k G) :=
finsupp.has_faithful_smul
instance [semiring R] [semiring k] [module R k] : module R (add_monoid_algebra k G) :=
finsupp.module G k
instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k]
[has_smul R S] [is_scalar_tower R S k] :
is_scalar_tower R S (add_monoid_algebra k G) :=
finsupp.is_scalar_tower G k
instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k]
[smul_comm_class R S k] :
smul_comm_class R S (add_monoid_algebra k G) :=
finsupp.smul_comm_class G k
instance [monoid R] [semiring k] [distrib_mul_action R k] [distrib_mul_action Rᵐᵒᵖ k]
[is_central_scalar R k] :
is_central_scalar R (add_monoid_algebra k G) :=
finsupp.is_central_scalar G k
/-! It is hard to state the equivalent of `distrib_mul_action G (add_monoid_algebra k G)`
because we've never discussed actions of additive groups. -/
end derived_instances
section misc_theorems
variables [semiring k]
lemma mul_apply [decidable_eq G] [has_add G] (f g : add_monoid_algebra k G) (x : G) :
(f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ + a₂ = x then b₁ * b₂ else 0) :=
@monoid_algebra.mul_apply k (multiplicative G) _ _ _ _ _ _
lemma mul_apply_antidiagonal [has_add G] (f g : add_monoid_algebra k G) (x : G) (s : finset (G × G))
(hs : ∀ {p : G × G}, p ∈ s ↔ p.1 + p.2 = x) :
(f * g) x = ∑ p in s, (f p.1 * g p.2) :=
@monoid_algebra.mul_apply_antidiagonal k (multiplicative G) _ _ _ _ _ s @hs
lemma support_mul [decidable_eq G] [has_add G] (a b : add_monoid_algebra k G) :
(a * b).support ⊆ a.support.bUnion (λa₁, b.support.bUnion $ λa₂, {a₁ + a₂}) :=
@monoid_algebra.support_mul k (multiplicative G) _ _ _ _ _
lemma single_mul_single [has_add G] {a₁ a₂ : G} {b₁ b₂ : k} :
(single a₁ b₁ * single a₂ b₂ : add_monoid_algebra k G) = single (a₁ + a₂) (b₁ * b₂) :=
@monoid_algebra.single_mul_single k (multiplicative G) _ _ _ _ _ _
-- This should be a `@[simp]` lemma, but the simp_nf linter times out if we add this.
-- Probably the correct fix is to make a `[add_]monoid_algebra.single` with the correct type,
-- instead of relying on `finsupp.single`.
lemma single_pow [add_monoid G] {a : G} {b : k} :
∀ n : ℕ, ((single a b)^n : add_monoid_algebra k G) = single (n • a) (b ^ n)
| 0 := by { simp only [pow_zero, zero_nsmul], refl }
| (n+1) :=
by rw [pow_succ, pow_succ, single_pow n, single_mul_single, add_comm, add_nsmul, one_nsmul]
/-- Like `finsupp.map_domain_zero`, but for the `1` we define in this file -/
@[simp] lemma map_domain_one {α : Type*} {β : Type*} {α₂ : Type*}
[semiring β] [has_zero α] [has_zero α₂] {F : Type*} [zero_hom_class F α α₂] (f : F) :
(map_domain f (1 : add_monoid_algebra β α) : add_monoid_algebra β α₂) =
(1 : add_monoid_algebra β α₂) :=
by simp_rw [one_def, map_domain_single, map_zero]
/-- Like `finsupp.map_domain_add`, but for the convolutive multiplication we define in this file -/
lemma map_domain_mul {α : Type*} {β : Type*} {α₂ : Type*} [semiring β] [has_add α] [has_add α₂]
{F : Type*} [add_hom_class F α α₂] (f : F) (x y : add_monoid_algebra β α) :
(map_domain f (x * y : add_monoid_algebra β α) : add_monoid_algebra β α₂) =
(map_domain f x * map_domain f y : add_monoid_algebra β α₂) :=
begin
simp_rw [mul_def, map_domain_sum, map_domain_single, map_add],
rw finsupp.sum_map_domain_index,
{ congr,
ext a b,
rw finsupp.sum_map_domain_index,
{ simp },
{ simp [mul_add] } },
{ simp },
{ simp [add_mul] }
end
section
variables (k G)
/-- The embedding of an additive magma into its additive magma algebra. -/
@[simps] def of_magma [has_add G] : multiplicative G →ₙ* add_monoid_algebra k G :=
{ to_fun := λ a, single a 1,
map_mul' := λ a b, by simpa only [mul_def, mul_one, sum_single_index, single_eq_zero, mul_zero], }
/-- Embedding of a magma with zero into its magma algebra. -/
def of [add_zero_class G] : multiplicative G →* add_monoid_algebra k G :=
{ to_fun := λ a, single a 1,
map_one' := rfl,
.. of_magma k G }
/-- Embedding of a magma with zero `G`, into its magma algebra, having `G` as source. -/
def of' : G → add_monoid_algebra k G := λ a, single a 1
end
@[simp] lemma of_apply [add_zero_class G] (a : multiplicative G) : of k G a = single a.to_add 1 :=
rfl
@[simp] lemma of'_apply (a : G) : of' k G a = single a 1 := rfl
lemma of'_eq_of [add_zero_class G] (a : G) : of' k G a = of k G a := rfl
lemma of_injective [nontrivial k] [add_zero_class G] : function.injective (of k G) :=
λ a b h, by simpa using (single_eq_single_iff _ _ _ _).mp h
/--
`finsupp.single` as a `monoid_hom` from the product type into the additive monoid algebra.
Note the order of the elements of the product are reversed compared to the arguments of
`finsupp.single`.
-/
@[simps] def single_hom [add_zero_class G] : k × multiplicative G →* add_monoid_algebra k G :=
{ to_fun := λ a, single a.2.to_add a.1,
map_one' := rfl,
map_mul' := λ a b, single_mul_single.symm }
lemma mul_single_apply_aux [has_add G] (f : add_monoid_algebra k G) (r : k)
(x y z : G) (H : ∀ a, a + x = z ↔ a = y) :
(f * single x r) z = f y * r :=
@monoid_algebra.mul_single_apply_aux k (multiplicative G) _ _ _ _ _ _ _ H
lemma mul_single_zero_apply [add_zero_class G] (f : add_monoid_algebra k G) (r : k) (x : G) :
(f * single 0 r) x = f x * r :=
f.mul_single_apply_aux r _ _ _ $ λ a, by rw [add_zero]
lemma single_mul_apply_aux [has_add G] (f : add_monoid_algebra k G) (r : k) (x y z : G)
(H : ∀ a, x + a = y ↔ a = z) :
(single x r * f : add_monoid_algebra k G) y = r * f z :=
@monoid_algebra.single_mul_apply_aux k (multiplicative G) _ _ _ _ _ _ _ H
lemma single_zero_mul_apply [add_zero_class G] (f : add_monoid_algebra k G) (r : k) (x : G) :
(single 0 r * f : add_monoid_algebra k G) x = r * f x :=
f.single_mul_apply_aux r _ _ _ $ λ a, by rw [zero_add]
lemma mul_single_apply [add_group G] (f : add_monoid_algebra k G) (r : k) (x y : G) :
(f * single x r) y = f (y - x) * r :=
(sub_eq_add_neg y x).symm ▸
@monoid_algebra.mul_single_apply k (multiplicative G) _ _ _ _ _ _
lemma single_mul_apply [add_group G] (r : k) (x : G) (f : add_monoid_algebra k G) (y : G) :
(single x r * f : add_monoid_algebra k G) y = r * f (- x + y) :=
@monoid_algebra.single_mul_apply k (multiplicative G) _ _ _ _ _ _
lemma support_mul_single [add_right_cancel_semigroup G]
(f : add_monoid_algebra k G) (r : k) (hr : ∀ y, y * r = 0 ↔ y = 0) (x : G) :
(f * single x r : add_monoid_algebra k G).support = f.support.map (add_right_embedding x) :=
@monoid_algebra.support_mul_single k (multiplicative G) _ _ _ _ hr _
lemma support_single_mul [add_left_cancel_semigroup G]
(f : add_monoid_algebra k G) (r : k) (hr : ∀ y, r * y = 0 ↔ y = 0) (x : G) :
(single x r * f : add_monoid_algebra k G).support = f.support.map (add_left_embedding x) :=
@monoid_algebra.support_single_mul k (multiplicative G) _ _ _ _ hr _
lemma lift_nc_smul {R : Type*} [add_zero_class G] [semiring R] (f : k →+* R)
(g : multiplicative G →* R) (c : k) (φ : monoid_algebra k G) :
lift_nc (f : k →+ R) g (c • φ) = f c * lift_nc (f : k →+ R) g φ :=
@monoid_algebra.lift_nc_smul k (multiplicative G) _ _ _ _ f g c φ
lemma induction_on [add_monoid G] {p : add_monoid_algebra k G → Prop} (f : add_monoid_algebra k G)
(hM : ∀ g, p (of k G (multiplicative.of_add g)))
(hadd : ∀ f g : add_monoid_algebra k G, p f → p g → p (f + g))
(hsmul : ∀ (r : k) f, p f → p (r • f)) : p f :=
begin
refine finsupp.induction_linear f _ (λ f g hf hg, hadd f g hf hg) (λ g r, _),
{ simpa using hsmul 0 (of k G (multiplicative.of_add 0)) (hM 0) },
{ convert hsmul r (of k G (multiplicative.of_add g)) (hM g),
simp only [mul_one, to_add_of_add, smul_single', of_apply] },
end
/-- If `f : G → H` is an additive homomorphism between two additive monoids, then
`finsupp.map_domain f` is a ring homomorphism between their add monoid algebras. -/
@[simps]
def map_domain_ring_hom (k : Type*) [semiring k] {H F : Type*} [add_monoid G] [add_monoid H]
[add_monoid_hom_class F G H] (f : F) :
add_monoid_algebra k G →+* add_monoid_algebra k H :=
{ map_one' := map_domain_one f,
map_mul' := λ x y, map_domain_mul f x y,
..(finsupp.map_domain.add_monoid_hom f : monoid_algebra k G →+ monoid_algebra k H) }
end misc_theorems
section span
variables [semiring k]
/-- An element of `add_monoid_algebra R M` is in the submodule generated by its support. -/
lemma mem_span_support [add_zero_class G] (f : add_monoid_algebra k G) :
f ∈ submodule.span k (of k G '' (f.support : set G)) :=
by rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported]
/-- An element of `add_monoid_algebra R M` is in the subalgebra generated by its support, using
unbundled inclusion. -/
lemma mem_span_support' (f : add_monoid_algebra k G) :
f ∈ submodule.span k (of' k G '' (f.support : set G)) :=
by rw [of', ← finsupp.supported_eq_span_single, finsupp.mem_supported]
end span
end add_monoid_algebra
/-!
#### Conversions between `add_monoid_algebra` and `monoid_algebra`
We have not defined `add_monoid_algebra k G = monoid_algebra k (multiplicative G)`
because historically this caused problems;
since the changes that have made `nsmul` definitional, this would be possible,
but for now we just contruct the ring isomorphisms using `ring_equiv.refl _`.
-/
/-- The equivalence between `add_monoid_algebra` and `monoid_algebra` in terms of
`multiplicative` -/
protected def add_monoid_algebra.to_multiplicative [semiring k] [has_add G] :
add_monoid_algebra k G ≃+* monoid_algebra k (multiplicative G) :=
{ to_fun := equiv_map_domain multiplicative.of_add,
map_mul' := λ x y, begin
repeat {rw equiv_map_domain_eq_map_domain},
dsimp [multiplicative.of_add],
convert monoid_algebra.map_domain_mul (mul_hom.id (multiplicative G)) _ _,
end,
..finsupp.dom_congr multiplicative.of_add }
/-- The equivalence between `monoid_algebra` and `add_monoid_algebra` in terms of `additive` -/
protected def monoid_algebra.to_additive [semiring k] [has_mul G] :
monoid_algebra k G ≃+* add_monoid_algebra k (additive G) :=
{ to_fun := equiv_map_domain additive.of_mul,
map_mul' := λ x y, begin
repeat {rw equiv_map_domain_eq_map_domain},
dsimp [additive.of_mul],
convert monoid_algebra.map_domain_mul (mul_hom.id G) _ _,
end,
..finsupp.dom_congr additive.of_mul }
namespace add_monoid_algebra
variables {k G}
/-! #### Non-unital, non-associative algebra structure -/
section non_unital_non_assoc_algebra
variables (k) [monoid R] [semiring k] [distrib_mul_action R k] [has_add G]
instance is_scalar_tower_self [is_scalar_tower R k k] :
is_scalar_tower R (add_monoid_algebra k G) (add_monoid_algebra k G) :=
@monoid_algebra.is_scalar_tower_self k (multiplicative G) R _ _ _ _ _
/-- Note that if `k` is a `comm_semiring` then we have `smul_comm_class k k k` and so we can take
`R = k` in the below. In other words, if the coefficients are commutative amongst themselves, they
also commute with the algebra multiplication. -/
instance smul_comm_class_self [smul_comm_class R k k] :
smul_comm_class R (add_monoid_algebra k G) (add_monoid_algebra k G) :=
@monoid_algebra.smul_comm_class_self k (multiplicative G) R _ _ _ _ _
instance smul_comm_class_symm_self [smul_comm_class k R k] :
smul_comm_class (add_monoid_algebra k G) R (add_monoid_algebra k G) :=
@monoid_algebra.smul_comm_class_symm_self k (multiplicative G) R _ _ _ _ _
variables {A : Type u₃} [non_unital_non_assoc_semiring A]
/-- A non_unital `k`-algebra homomorphism from `add_monoid_algebra k G` is uniquely defined by its
values on the functions `single a 1`. -/
lemma non_unital_alg_hom_ext [distrib_mul_action k A]
{φ₁ φ₂ : add_monoid_algebra k G →ₙₐ[k] A}
(h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ :=
@monoid_algebra.non_unital_alg_hom_ext k (multiplicative G) _ _ _ _ _ φ₁ φ₂ h
/-- See note [partially-applied ext lemmas]. -/
@[ext] lemma non_unital_alg_hom_ext' [distrib_mul_action k A]
{φ₁ φ₂ : add_monoid_algebra k G →ₙₐ[k] A}
(h : φ₁.to_mul_hom.comp (of_magma k G) = φ₂.to_mul_hom.comp (of_magma k G)) : φ₁ = φ₂ :=
@monoid_algebra.non_unital_alg_hom_ext' k (multiplicative G) _ _ _ _ _ φ₁ φ₂ h
/-- The functor `G ↦ add_monoid_algebra k G`, from the category of magmas to the category of
non-unital, non-associative algebras over `k` is adjoint to the forgetful functor in the other
direction. -/
@[simps] def lift_magma [module k A] [is_scalar_tower k A A] [smul_comm_class k A A] :
(multiplicative G →ₙ* A) ≃ (add_monoid_algebra k G →ₙₐ[k] A) :=
{ to_fun := λ f, { to_fun := λ a, sum a (λ m t, t • f (multiplicative.of_add m)),
.. (monoid_algebra.lift_magma k f : _)},
inv_fun := λ F, F.to_mul_hom.comp (of_magma k G),
.. (monoid_algebra.lift_magma k : (multiplicative G →ₙ* A) ≃ (_ →ₙₐ[k] A)) }
end non_unital_non_assoc_algebra
/-! #### Algebra structure -/
section algebra
local attribute [reducible] add_monoid_algebra
/-- `finsupp.single 0` as a `ring_hom` -/
@[simps] def single_zero_ring_hom [semiring k] [add_monoid G] : k →+* add_monoid_algebra k G :=
{ map_one' := rfl,
map_mul' := λ x y, by rw [single_add_hom, single_mul_single, zero_add],
..finsupp.single_add_hom 0}
/-- If two ring homomorphisms from `add_monoid_algebra k G` are equal on all `single a 1`
and `single 0 b`, then they are equal. -/
lemma ring_hom_ext {R} [semiring k] [add_monoid G] [semiring R]
{f g : add_monoid_algebra k G →+* R} (h₀ : ∀ b, f (single 0 b) = g (single 0 b))
(h_of : ∀ a, f (single a 1) = g (single a 1)) : f = g :=
@monoid_algebra.ring_hom_ext k (multiplicative G) R _ _ _ _ _ h₀ h_of
/-- If two ring homomorphisms from `add_monoid_algebra k G` are equal on all `single a 1`
and `single 0 b`, then they are equal.
See note [partially-applied ext lemmas]. -/
@[ext] lemma ring_hom_ext' {R} [semiring k] [add_monoid G] [semiring R]
{f g : add_monoid_algebra k G →+* R}
(h₁ : f.comp single_zero_ring_hom = g.comp single_zero_ring_hom)
(h_of : (f : add_monoid_algebra k G →* R).comp (of k G) =
(g : add_monoid_algebra k G →* R).comp (of k G)) :
f = g :=
ring_hom_ext (ring_hom.congr_fun h₁) (monoid_hom.congr_fun h_of)
section opposite
open finsupp mul_opposite
variables [semiring k]
/-- The opposite of an `add_monoid_algebra R I` is ring equivalent to
the `add_monoid_algebra Rᵐᵒᵖ I` over the opposite ring, taking elements to their opposite. -/
@[simps {simp_rhs := tt}] protected noncomputable def op_ring_equiv [add_comm_monoid G] :
(add_monoid_algebra k G)ᵐᵒᵖ ≃+* add_monoid_algebra kᵐᵒᵖ G :=
{ map_mul' := begin
dsimp only [add_equiv.to_fun_eq_coe, ←add_equiv.coe_to_add_monoid_hom],
rw add_monoid_hom.map_mul_iff,
ext i r i' r' : 6,
dsimp,
simp only [map_range_single, single_mul_single, ←op_mul, add_comm]
end,
..mul_opposite.op_add_equiv.symm.trans
(finsupp.map_range.add_equiv (mul_opposite.op_add_equiv : k ≃+ kᵐᵒᵖ))}
@[simp] lemma op_ring_equiv_single [add_comm_monoid G] (r : k) (x : G) :
add_monoid_algebra.op_ring_equiv (op (single x r)) = single x (op r) :=
by simp
@[simp] lemma op_ring_equiv_symm_single [add_comm_monoid G] (r : kᵐᵒᵖ) (x : Gᵐᵒᵖ) :
add_monoid_algebra.op_ring_equiv.symm (single x r) = op (single x r.unop) :=
by simp
end opposite
/--
The instance `algebra R (add_monoid_algebra k G)` whenever we have `algebra R k`.
In particular this provides the instance `algebra k (add_monoid_algebra k G)`.
-/
instance [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] :
algebra R (add_monoid_algebra k G) :=
{ smul_def' := λ r a, by { ext, simp [single_zero_mul_apply, algebra.smul_def, pi.smul_apply], },
commutes' := λ r f, by { ext, simp [single_zero_mul_apply, mul_single_zero_apply,
algebra.commutes], },
..single_zero_ring_hom.comp (algebra_map R k) }
/-- `finsupp.single 0` as a `alg_hom` -/
@[simps] def single_zero_alg_hom [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] :
k →ₐ[R] add_monoid_algebra k G :=
{ commutes' := λ r, by { ext, simp, refl, }, ..single_zero_ring_hom}
@[simp] lemma coe_algebra_map [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] :
(algebra_map R (add_monoid_algebra k G) : R → add_monoid_algebra k G) =
single 0 ∘ (algebra_map R k) :=
rfl
end algebra
section lift
variables {k G} [comm_semiring k] [add_monoid G]
variables {A : Type u₃} [semiring A] [algebra k A] {B : Type*} [semiring B] [algebra k B]
/-- `lift_nc_ring_hom` as a `alg_hom`, for when `f` is an `alg_hom` -/
def lift_nc_alg_hom (f : A →ₐ[k] B) (g : multiplicative G →* B)
(h_comm : ∀ x y, commute (f x) (g y)) :
add_monoid_algebra A G →ₐ[k] B :=
{ to_fun := lift_nc_ring_hom (f : A →+* B) g h_comm,
commutes' := by simp [lift_nc_ring_hom],
..(lift_nc_ring_hom (f : A →+* B) g h_comm)}
/-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its
values on the functions `single a 1`. -/
lemma alg_hom_ext ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A⦄
(h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ :=
@monoid_algebra.alg_hom_ext k (multiplicative G) _ _ _ _ _ _ _ h
/-- See note [partially-applied ext lemmas]. -/
@[ext] lemma alg_hom_ext' ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A⦄
(h : (φ₁ : add_monoid_algebra k G →* A).comp (of k G) =
(φ₂ : add_monoid_algebra k G →* A).comp (of k G)) : φ₁ = φ₂ :=
alg_hom_ext $ monoid_hom.congr_fun h
variables (k G A)
/-- Any monoid homomorphism `G →* A` can be lifted to an algebra homomorphism
`monoid_algebra k G →ₐ[k] A`. -/
def lift : (multiplicative G →* A) ≃ (add_monoid_algebra k G →ₐ[k] A) :=
{ inv_fun := λ f, (f : add_monoid_algebra k G →* A).comp (of k G),
to_fun := λ F,
{ to_fun := lift_nc_alg_hom (algebra.of_id k A) F $ λ _ _, algebra.commutes _ _,
.. @monoid_algebra.lift k (multiplicative G) _ _ A _ _ F},
.. @monoid_algebra.lift k (multiplicative G) _ _ A _ _ }
variables {k G A}
lemma lift_apply' (F : multiplicative G →* A) (f : monoid_algebra k G) :
lift k G A F f = f.sum (λ a b, (algebra_map k A b) * F (multiplicative.of_add a)) := rfl
lemma lift_apply (F : multiplicative G →* A) (f : monoid_algebra k G) :
lift k G A F f = f.sum (λ a b, b • F (multiplicative.of_add a)) :=
by simp only [lift_apply', algebra.smul_def]
lemma lift_def (F : multiplicative G →* A) :
⇑(lift k G A F) = lift_nc ((algebra_map k A : k →+* A) : k →+ A) F :=
rfl
@[simp] lemma lift_symm_apply (F : add_monoid_algebra k G →ₐ[k] A) (x : multiplicative G) :
(lift k G A).symm F x = F (single x.to_add 1) := rfl
lemma lift_of (F : multiplicative G →* A) (x : multiplicative G) :
lift k G A F (of k G x) = F x :=
by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply]
@[simp] lemma lift_single (F : multiplicative G →* A) (a b) :
lift k G A F (single a b) = b • F (multiplicative.of_add a) :=
by rw [lift_def, lift_nc_single, algebra.smul_def, ring_hom.coe_add_monoid_hom]
lemma lift_unique' (F : add_monoid_algebra k G →ₐ[k] A) :
F = lift k G A ((F : add_monoid_algebra k G →* A).comp (of k G)) :=
((lift k G A).apply_symm_apply F).symm
/-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by
its values on `F (single a 1)`. -/
lemma lift_unique (F : add_monoid_algebra k G →ₐ[k] A) (f : monoid_algebra k G) :
F f = f.sum (λ a b, b • F (single a 1)) :=
by conv_lhs { rw lift_unique' F, simp [lift_apply] }
lemma alg_hom_ext_iff {φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A} :
(∀ x, φ₁ (finsupp.single x 1) = φ₂ (finsupp.single x 1)) ↔ φ₁ = φ₂ :=
⟨λ h, alg_hom_ext h, by rintro rfl _; refl⟩
end lift
section
local attribute [reducible] add_monoid_algebra
universe ui
variable {ι : Type ui}
lemma prod_single [comm_semiring k] [add_comm_monoid G]
{s : finset ι} {a : ι → G} {b : ι → k} :
(∏ i in s, single (a i) (b i)) = single (∑ i in s, a i) (∏ i in s, b i) :=
finset.cons_induction_on s rfl $ λ a s has ih, by rw [prod_cons has, ih,
single_mul_single, sum_cons has, prod_cons has]
end
lemma map_domain_algebra_map {A H F : Type*} [comm_semiring k] [semiring A]
[algebra k A] [add_monoid G] [add_monoid H] [add_monoid_hom_class F G H] (f : F) (r : k) :
map_domain f (algebra_map k (add_monoid_algebra A G) r) =
algebra_map k (add_monoid_algebra A H) r :=
by simp only [function.comp_app, map_domain_single, add_monoid_algebra.coe_algebra_map, map_zero]
/-- If `f : G → H` is a homomorphism between two additive magmas, then `finsupp.map_domain f` is a
non-unital algebra homomorphism between their additive magma algebras. -/
@[simps]
def map_domain_non_unital_alg_hom (k A : Type*) [comm_semiring k] [semiring A] [algebra k A]
{G H F : Type*} [has_add G] [has_add H] [add_hom_class F G H] (f : F) :
add_monoid_algebra A G →ₙₐ[k] add_monoid_algebra A H :=
{ map_mul' := λ x y, map_domain_mul f x y,
map_smul' := λ r x, map_domain_smul r x,
..(finsupp.map_domain.add_monoid_hom f : monoid_algebra A G →+ monoid_algebra A H) }
/-- If `f : G → H` is an additive homomorphism between two additive monoids, then
`finsupp.map_domain f` is an algebra homomorphism between their add monoid algebras. -/
@[simps] def map_domain_alg_hom (k A : Type*) [comm_semiring k] [semiring A] [algebra k A]
[add_monoid G] {H F : Type*} [add_monoid H] [add_monoid_hom_class F G H] (f : F) :
add_monoid_algebra A G →ₐ[k] add_monoid_algebra A H :=
{ commutes' := map_domain_algebra_map f,
..map_domain_ring_hom A f}
end add_monoid_algebra
variables [comm_semiring R] (k G)
/-- The algebra equivalence between `add_monoid_algebra` and `monoid_algebra` in terms of
`multiplicative`. -/
def add_monoid_algebra.to_multiplicative_alg_equiv [semiring k] [algebra R k] [add_monoid G] :
add_monoid_algebra k G ≃ₐ[R] monoid_algebra k (multiplicative G) :=
{ commutes' := λ r, by simp [add_monoid_algebra.to_multiplicative],
..add_monoid_algebra.to_multiplicative k G }
/-- The algebra equivalence between `monoid_algebra` and `add_monoid_algebra` in terms of
`additive`. -/
def monoid_algebra.to_additive_alg_equiv [semiring k] [algebra R k] [monoid G] :
monoid_algebra k G ≃ₐ[R] add_monoid_algebra k (additive G) :=
{ commutes' := λ r, by simp [monoid_algebra.to_additive],
..monoid_algebra.to_additive k G }
|
9c5c2c5cdd8c7b6cbe98295d7379da60c63618c2 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/coe10.lean | cf3101b311633516678bcb0c4f7ba56e450d499b | [
"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 | 377 | lean | import data.nat
open nat
inductive fn2 (A B C : Type) :=
mk : (A → C) → (B → C) → fn2 A B C
definition to_ac [coercion] {A B C : Type} (f : fn2 A B C) : A → C :=
fn2.rec (λ f g, f) f
definition to_bc [coercion] {A B C : Type} (f : fn2 A B C) : B → C :=
fn2.rec (λ f g, g) f
constant f : fn2 Prop nat nat
constant a : Prop
constant n : nat
check f a
check f n
|
4a13a1d04d3a2b6b1aaf59e6cdfa3b0d08a11f8c | 2a70b774d16dbdf5a533432ee0ebab6838df0948 | /_target/deps/mathlib/src/analysis/convex/basic.lean | 96827ac41c31876b81237281ea8c8604e452b53d | [
"Apache-2.0"
] | permissive | hjvromen/lewis | 40b035973df7c77ebf927afab7878c76d05ff758 | 105b675f73630f028ad5d890897a51b3c1146fb0 | refs/heads/master | 1,677,944,636,343 | 1,676,555,301,000 | 1,676,555,301,000 | 327,553,599 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 58,212 | lean | /-
Copyright (c) 2019 Alexander Bentkamp. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp, Yury Kudriashov
-/
import data.set.intervals.ord_connected
import data.set.intervals.image_preimage
import data.complex.module
import linear_algebra.affine_space.affine_map
import algebra.module.ordered
/-!
# Convex sets and functions on real vector spaces
In a real vector space, we define the following objects and properties.
* `segment x y` is the closed segment joining `x` and `y`.
* A set `s` is `convex` if for any two points `x y ∈ s` it includes `segment x y`;
* A function `f : E → β` is `convex_on` a set `s` if `s` is itself a convex set, and for any two
points `x y ∈ s` the segment joining `(x, f x)` to `(y, f y)` is (non-strictly) above the graph
of `f`; equivalently, `convex_on f s` means that the epigraph
`{p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2}` is a convex set;
* Center mass of a finite set of points with prescribed weights.
* Convex hull of a set `s` is the minimal convex set that includes `s`.
* Standard simplex `std_simplex ι [fintype ι]` is the intersection of the positive quadrant with
the hyperplane `s.sum = 1` in the space `ι → ℝ`.
We also provide various equivalent versions of the definitions above, prove that some specific sets
are convex, and prove Jensen's inequality.
Note: To define convexity for functions `f : E → β`, we need `β` to be an ordered vector space,
defined using the instance `ordered_semimodule ℝ β`.
## Notations
We use the following local notations:
* `I = Icc (0:ℝ) 1`;
* `[x, y] = segment x y`.
They are defined using `local notation`, so they are not available outside of this file.
-/
universes u' u v v' w x
variables {E : Type u} {F : Type v} {ι : Type w} {ι' : Type x} {α : Type v'}
[add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F]
[linear_ordered_field α]
{s : set E}
open set linear_map
open_locale classical big_operators
local notation `I` := (Icc 0 1 : set ℝ)
section sets
/-! ### Segment -/
/-- Segments in a vector space. -/
def segment (x y : E) : set E :=
{z : E | ∃ (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), a • x + b • y = z}
local notation `[`x `, ` y `]` := segment x y
lemma segment_symm (x y : E) : [x, y] = [y, x] :=
set.ext $ λ z,
⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩,
λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩
lemma left_mem_segment (x y : E) : x ∈ [x, y] :=
⟨1, 0, zero_le_one, le_refl 0, add_zero 1, by rw [zero_smul, one_smul, add_zero]⟩
lemma right_mem_segment (x y : E) : y ∈ [x, y] :=
segment_symm y x ▸ left_mem_segment y x
lemma segment_same (x : E) : [x, x] = {x} :=
set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩,
by simpa only [(add_smul _ _ _).symm, mem_singleton_iff, hab, one_smul, eq_comm] using hz,
λ h, mem_singleton_iff.1 h ▸ left_mem_segment z z⟩
lemma segment_eq_image (x y : E) : segment x y = (λ (θ : ℝ), (1 - θ) • x + θ • y) '' I :=
set.ext $ λ z,
⟨λ ⟨a, b, ha, hb, hab, hz⟩,
⟨b, ⟨hb, hab ▸ le_add_of_nonneg_left ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩,
λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1-θ, θ, sub_nonneg.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩
lemma segment_eq_image' (x y : E) : segment x y = (λ (θ : ℝ), x + θ • (y - x)) '' I :=
by { convert segment_eq_image x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel }
lemma segment_eq_image₂ (x y : E) :
segment x y = (λ p:ℝ×ℝ, p.1 • x + p.2 • y) '' {p | 0 ≤ p.1 ∧ 0 ≤ p.2 ∧ p.1 + p.2 = 1} :=
by simp only [segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc]
lemma segment_eq_Icc {a b : ℝ} (h : a ≤ b) : [a, b] = Icc a b :=
begin
rw [segment_eq_image'],
show (((+) a) ∘ (λ t, t * (b - a))) '' Icc 0 1 = Icc a b,
rw [image_comp, image_mul_right_Icc (@zero_le_one ℝ _) (sub_nonneg.2 h), image_const_add_Icc],
simp
end
lemma segment_eq_Icc' (a b : ℝ) : [a, b] = Icc (min a b) (max a b) :=
by cases le_total a b; [skip, rw segment_symm]; simp [segment_eq_Icc, *]
lemma segment_eq_interval (a b : ℝ) : segment a b = interval a b :=
segment_eq_Icc' _ _
lemma mem_segment_translate (a : E) {x b c} : a + x ∈ [a + b, a + c] ↔ x ∈ [b, c] :=
begin
rw [segment_eq_image', segment_eq_image'],
refine exists_congr (λ θ, and_congr iff.rfl _),
simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj]
end
lemma segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' [a + b, a + c] = [b, c] :=
set.ext $ λ x, mem_segment_translate a
lemma segment_translate_image (a b c: E) : (λx, a + x) '' [b, c] = [a + b, a + c] :=
segment_translate_preimage a b c ▸ image_preimage_eq _ $ add_left_surjective a
/-! ### Convexity of sets -/
/-- Convexity of sets. -/
def convex (s : set E) :=
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 →
a • x + b • y ∈ s
lemma convex_iff_forall_pos :
convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ s :=
begin
refine ⟨λ h x y hx hy a b ha hb hab, h hx hy (le_of_lt ha) (le_of_lt hb) hab, _⟩,
intros h x y hx hy a b ha hb hab,
cases eq_or_lt_of_le ha with ha ha,
{ subst a, rw [zero_add] at hab, simp [hab, hy] },
cases eq_or_lt_of_le hb with hb hb,
{ subst b, rw [add_zero] at hab, simp [hab, hx] },
exact h hx hy ha hb hab
end
lemma convex_iff_segment_subset : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → [x, y] ⊆ s :=
by simp only [convex, segment_eq_image₂, subset_def, ball_image_iff, prod.forall,
mem_set_of_eq, and_imp]
lemma convex.segment_subset (h : convex s) {x y:E} (hx : x ∈ s) (hy : y ∈ s) : [x, y] ⊆ s :=
convex_iff_segment_subset.1 h hx hy
/-- Alternative definition of set convexity, in terms of pointwise set operations. -/
lemma convex_iff_pointwise_add_subset:
convex s ↔ ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • s + b • s ⊆ s :=
iff.intro
begin
rintros hA a b ha hb hab w ⟨au, bv, ⟨u, hu, rfl⟩, ⟨v, hv, rfl⟩, rfl⟩,
exact hA hu hv ha hb hab
end
(λ h x y hx hy a b ha hb hab,
(h ha hb hab) (set.add_mem_add ⟨_, hx, rfl⟩ ⟨_, hy, rfl⟩))
/-- Alternative definition of set convexity, using division. -/
lemma convex_iff_div:
convex s ↔ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄,
0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • x + (b/(a+b)) • y ∈ s :=
⟨begin
assume h x y hx hy a b ha hb hab,
apply h hx hy,
have ha', from mul_le_mul_of_nonneg_left ha (le_of_lt (inv_pos.2 hab)),
rwa [mul_zero, ←div_eq_inv_mul] at ha',
have hb', from mul_le_mul_of_nonneg_left hb (le_of_lt (inv_pos.2 hab)),
rwa [mul_zero, ←div_eq_inv_mul] at hb',
rw [←add_div],
exact div_self (ne_of_lt hab).symm
end,
begin
assume h x y hx hy a b ha hb hab,
have h', from h hx hy ha hb,
rw [hab, div_one, div_one] at h',
exact h' zero_lt_one
end⟩
/-! ### Examples of convex sets -/
lemma convex_empty : convex (∅ : set E) := by finish
lemma convex_singleton (c : E) : convex ({c} : set E) :=
begin
intros x y hx hy a b ha hb hab,
rw [set.eq_of_mem_singleton hx, set.eq_of_mem_singleton hy, ←add_smul, hab, one_smul],
exact mem_singleton c
end
lemma convex_univ : convex (set.univ : set E) := λ _ _ _ _ _ _ _ _ _, trivial
lemma convex.inter {t : set E} (hs: convex s) (ht: convex t) : convex (s ∩ t) :=
λ x y (hx : x ∈ s ∩ t) (hy : y ∈ s ∩ t) a b (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1),
⟨hs hx.left hy.left ha hb hab, ht hx.right hy.right ha hb hab⟩
lemma convex_sInter {S : set (set E)} (h : ∀ s ∈ S, convex s) : convex (⋂₀ S) :=
assume x y hx hy a b ha hb hab s hs,
h s hs (hx s hs) (hy s hs) ha hb hab
lemma convex_Inter {ι : Sort*} {s: ι → set E} (h: ∀ i : ι, convex (s i)) : convex (⋂ i, s i) :=
(sInter_range s) ▸ convex_sInter $ forall_range_iff.2 h
lemma convex.prod {s : set E} {t : set F} (hs : convex s) (ht : convex t) :
convex (s.prod t) :=
begin
intros x y hx hy a b ha hb hab,
apply mem_prod.2,
exact ⟨hs (mem_prod.1 hx).1 (mem_prod.1 hy).1 ha hb hab,
ht (mem_prod.1 hx).2 (mem_prod.1 hy).2 ha hb hab⟩
end
lemma convex.combo_to_vadd {a b : ℝ} {x y : E} (h : a + b = 1) :
a • x + b • y = b • (y - x) + x :=
calc
a • x + b • y = (b • y - b • x) + (a • x + b • x) : by abel
... = b • (y - x) + (a + b) • x : by rw [smul_sub, add_smul]
... = b • (y - x) + (1 : ℝ) • x : by rw [h]
... = b • (y - x) + x : by rw [one_smul]
/--
Applying an affine map to an affine combination of two points yields
an affine combination of the images.
-/
lemma convex.combo_affine_apply {a b : ℝ} {x y : E} {f : E →ᵃ[ℝ] F} (h : a + b = 1) :
f (a • x + b • y) = a • f x + b • f y :=
begin
simp only [convex.combo_to_vadd h, ← vsub_eq_sub],
exact f.apply_line_map _ _ _,
end
/-- The preimage of a convex set under an affine map is convex. -/
lemma convex.affine_preimage (f : E →ᵃ[ℝ] F) {s : set F} (hs : convex s) :
convex (f ⁻¹' s) :=
begin
intros x y xs ys a b ha hb hab,
rw [mem_preimage, convex.combo_affine_apply hab],
exact hs xs ys ha hb hab,
end
/-- The image of a convex set under an affine map is convex. -/
lemma convex.affine_image (f : E →ᵃ[ℝ] F) {s : set E} (hs : convex s) :
convex (f '' s) :=
begin
rintros x y ⟨x', ⟨hx', hx'f⟩⟩ ⟨y', ⟨hy', hy'f⟩⟩ a b ha hb hab,
refine ⟨a • x' + b • y', ⟨hs hx' hy' ha hb hab, _⟩⟩,
rw [convex.combo_affine_apply hab, hx'f, hy'f]
end
lemma convex.linear_image (hs : convex s) (f : E →ₗ[ℝ] F) : convex (image f s) :=
hs.affine_image f.to_affine_map
lemma convex.is_linear_image (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) :
convex (f '' s) :=
hs.linear_image $ hf.mk' f
lemma convex.linear_preimage {s : set F} (hs : convex s) (f : E →ₗ[ℝ] F) :
convex (preimage f s) :=
hs.affine_preimage f.to_affine_map
lemma convex.is_linear_preimage {s : set F} (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) :
convex (preimage f s) :=
hs.linear_preimage $ hf.mk' f
lemma convex.neg (hs : convex s) : convex ((λ z, -z) '' s) :=
hs.is_linear_image is_linear_map.is_linear_map_neg
lemma convex.neg_preimage (hs : convex s) : convex ((λ z, -z) ⁻¹' s) :=
hs.is_linear_preimage is_linear_map.is_linear_map_neg
lemma convex.smul (c : ℝ) (hs : convex s) : convex (c • s) :=
hs.linear_image (linear_map.lsmul _ _ c)
lemma convex.smul_preimage (c : ℝ) (hs : convex s) : convex ((λ z, c • z) ⁻¹' s) :=
hs.linear_preimage (linear_map.lsmul _ _ c)
lemma convex.add {t : set E} (hs : convex s) (ht : convex t) : convex (s + t) :=
by { rw ← add_image_prod, exact (hs.prod ht).is_linear_image is_linear_map.is_linear_map_add }
lemma convex.sub {t : set E} (hs : convex s) (ht : convex t) :
convex ((λx : E × E, x.1 - x.2) '' (s.prod t)) :=
(hs.prod ht).is_linear_image is_linear_map.is_linear_map_sub
lemma convex.translate (hs : convex s) (z : E) : convex ((λx, z + x) '' s) :=
hs.affine_image $ affine_map.const ℝ E z +ᵥ affine_map.id ℝ E
/-- The translation of a convex set is also convex. -/
lemma convex.translate_preimage_right (hs : convex s) (a : E) : convex ((λ z, a + z) ⁻¹' s) :=
hs.affine_preimage $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E
/-- The translation of a convex set is also convex. -/
lemma convex.translate_preimage_left (hs : convex s) (a : E) : convex ((λ z, z + a) ⁻¹' s) :=
by simpa only [add_comm] using hs.translate_preimage_right a
lemma convex.affinity (hs : convex s) (z : E) (c : ℝ) : convex ((λx, z + c • x) '' s) :=
hs.affine_image $ affine_map.const ℝ E z +ᵥ c • affine_map.id ℝ E
lemma real.convex_iff_ord_connected {s : set ℝ} : convex s ↔ ord_connected s :=
begin
simp only [convex_iff_segment_subset, segment_eq_interval, ord_connected_iff_interval_subset],
exact forall_congr (λ x, forall_swap)
end
alias real.convex_iff_ord_connected ↔ convex.ord_connected set.ord_connected.convex
lemma convex_Iio (r : ℝ) : convex (Iio r) := ord_connected_Iio.convex
lemma convex_Ioi (r : ℝ) : convex (Ioi r) := ord_connected_Ioi.convex
lemma convex_Iic (r : ℝ) : convex (Iic r) := ord_connected_Iic.convex
lemma convex_Ici (r : ℝ) : convex (Ici r) := ord_connected_Ici.convex
lemma convex_Ioo (r s : ℝ) : convex (Ioo r s) := ord_connected_Ioo.convex
lemma convex_Ico (r s : ℝ) : convex (Ico r s) := ord_connected_Ico.convex
lemma convex_Ioc (r : ℝ) (s : ℝ) : convex (Ioc r s) := ord_connected_Ioc.convex
lemma convex_Icc (r : ℝ) (s : ℝ) : convex (Icc r s) := ord_connected_Icc.convex
lemma convex_interval (r : ℝ) (s : ℝ) : convex (interval r s) := ord_connected_interval.convex
lemma convex_segment (a b : E) : convex [a, b] :=
begin
have : (λ (t : ℝ), a + t • (b - a)) = (λz : E, a + z) ∘ (λt:ℝ, t • (b - a)) := rfl,
rw [segment_eq_image', this, image_comp],
refine ((convex_Icc _ _).is_linear_image _).translate _,
exact is_linear_map.is_linear_map_smul' _
end
lemma convex_halfspace_lt {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) :
convex {w | f w < r} :=
(convex_Iio r).is_linear_preimage h
lemma convex_halfspace_le {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) :
convex {w | f w ≤ r} :=
(convex_Iic r).is_linear_preimage h
lemma convex_halfspace_gt {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) :
convex {w | r < f w} :=
(convex_Ioi r).is_linear_preimage h
lemma convex_halfspace_ge {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) :
convex {w | r ≤ f w} :=
(convex_Ici r).is_linear_preimage h
lemma convex_hyperplane {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) :
convex {w | f w = r} :=
begin
show convex (f ⁻¹' {p | p = r}),
rw set_of_eq_eq_singleton,
exact (convex_singleton r).is_linear_preimage h
end
lemma convex_halfspace_re_lt (r : ℝ) : convex {c : ℂ | c.re < r} :=
convex_halfspace_lt (is_linear_map.mk complex.add_re complex.smul_re) _
lemma convex_halfspace_re_le (r : ℝ) : convex {c : ℂ | c.re ≤ r} :=
convex_halfspace_le (is_linear_map.mk complex.add_re complex.smul_re) _
lemma convex_halfspace_re_gt (r : ℝ) : convex {c : ℂ | r < c.re } :=
convex_halfspace_gt (is_linear_map.mk complex.add_re complex.smul_re) _
lemma convex_halfspace_re_lge (r : ℝ) : convex {c : ℂ | r ≤ c.re} :=
convex_halfspace_ge (is_linear_map.mk complex.add_re complex.smul_re) _
lemma convex_halfspace_im_lt (r : ℝ) : convex {c : ℂ | c.im < r} :=
convex_halfspace_lt (is_linear_map.mk complex.add_im complex.smul_im) _
lemma convex_halfspace_im_le (r : ℝ) : convex {c : ℂ | c.im ≤ r} :=
convex_halfspace_le (is_linear_map.mk complex.add_im complex.smul_im) _
lemma convex_halfspace_im_gt (r : ℝ) : convex {c : ℂ | r < c.im } :=
convex_halfspace_gt (is_linear_map.mk complex.add_im complex.smul_im) _
lemma convex_halfspace_im_lge (r : ℝ) : convex {c : ℂ | r ≤ c.im} :=
convex_halfspace_ge (is_linear_map.mk complex.add_im complex.smul_im) _
/-! ### Convex combinations in intervals -/
lemma convex.combo_self (a : α) {x y : α} (h : x + y = 1) : a = x * a + y * a :=
calc
a = 1 * a : by rw [one_mul]
... = (x + y) * a : by rw [h]
... = x * a + y * a : by rw [add_mul]
/--
If `x` is in an `Ioo`, it can be expressed as a convex combination of the endpoints.
-/
lemma convex.mem_Ioo {a b x : α} (h : a < b) :
x ∈ Ioo a b ↔ ∃ (x_a x_b : α), 0 < x_a ∧ 0 < x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x :=
begin
split,
{ rintros ⟨h_ax, h_bx⟩,
by_cases hab : ¬a < b,
{ exfalso; exact hab h },
{ refine ⟨(b-x) / (b-a), (x-a) / (b-a), _⟩,
refine ⟨div_pos (by linarith) (by linarith), div_pos (by linarith) (by linarith),_,_⟩;
{ field_simp [show b - a ≠ 0, by linarith], ring } } },
{ rw [mem_Ioo],
rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩,
rw [←h₂],
exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ }
end
/-- If `x` is in an `Ioc`, it can be expressed as a convex combination of the endpoints. -/
lemma convex.mem_Ioc {a b x : α} (h : a < b) :
x ∈ Ioc a b ↔ ∃ (x_a x_b : α), 0 ≤ x_a ∧ 0 < x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x :=
begin
split,
{ rintros ⟨h_ax, h_bx⟩,
by_cases h_x : x = b,
{ exact ⟨0, 1, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ },
{ rcases (convex.mem_Ioo h).mp ⟨h_ax, lt_of_le_of_ne h_bx h_x⟩ with ⟨x_a, x_b, Ioo_case⟩,
exact ⟨x_a, x_b, by linarith, Ioo_case.2⟩ } },
{ rw [mem_Ioc],
rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩,
rw [←h₂],
exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ }
end
/-- If `x` is in an `Ico`, it can be expressed as a convex combination of the endpoints. -/
lemma convex.mem_Ico {a b x : α} (h : a < b) :
x ∈ Ico a b ↔ ∃ (x_a x_b : α), 0 < x_a ∧ 0 ≤ x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x :=
begin
split,
{ rintros ⟨h_ax, h_bx⟩,
by_cases h_x : x = a,
{ exact ⟨1, 0, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ },
{ rcases (convex.mem_Ioo h).mp ⟨lt_of_le_of_ne h_ax (ne.symm h_x), h_bx⟩
with ⟨x_a, x_b, Ioo_case⟩,
exact ⟨x_a, x_b, Ioo_case.1, by linarith, (Ioo_case.2).2⟩ } },
{ rw [mem_Ico],
rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩,
rw [←h₂],
exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ }
end
/-- If `x` is in an `Icc`, it can be expressed as a convex combination of the endpoints. -/
lemma convex.mem_Icc {a b x : α} (h : a ≤ b) :
x ∈ Icc a b ↔ ∃ (x_a x_b : α), 0 ≤ x_a ∧ 0 ≤ x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x :=
begin
split,
{ intro x_in_I,
rw [Icc, mem_set_of_eq] at x_in_I,
rcases x_in_I with ⟨h_ax, h_bx⟩,
by_cases hab' : a = b,
{ exact ⟨0, 1, le_refl 0, by linarith, by ring, by linarith⟩ },
change a ≠ b at hab',
replace h : a < b, exact lt_of_le_of_ne h hab',
by_cases h_x : x = a,
{ exact ⟨1, 0, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ },
{ rcases (convex.mem_Ioc h).mp ⟨lt_of_le_of_ne h_ax (ne.symm h_x), h_bx⟩
with ⟨x_a, x_b, Ioo_case⟩,
exact ⟨x_a, x_b, Ioo_case.1, by linarith, (Ioo_case.2).2⟩ } },
{ rw [mem_Icc],
rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩,
rw [←h₂],
exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ }
end
section submodule
open submodule
lemma submodule.convex (K : submodule ℝ E) : convex (↑K : set E) :=
by { repeat {intro}, refine add_mem _ (smul_mem _ _ _) (smul_mem _ _ _); assumption }
lemma subspace.convex (K : subspace ℝ E) : convex (↑K : set E) := K.convex
end submodule
end sets
/-! ### Convex and concave functions -/
section functions
variables {β : Type*} [ordered_add_comm_monoid β] [semimodule ℝ β]
local notation `[`x `, ` y `]` := segment x y
/-- Convexity of functions -/
def convex_on (s : set E) (f : E → β) : Prop :=
convex s ∧
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 →
f (a • x + b • y) ≤ a • f x + b • f y
/-- Concavity of functions -/
def concave_on (s : set E) (f : E → β) : Prop :=
convex s ∧
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 →
a • f x + b • f y ≤ f (a • x + b • y)
section
variables [ordered_semimodule ℝ β]
/-- A function `f` is concave iff `-f` is convex. -/
@[simp] lemma neg_convex_on_iff {γ : Type*} [ordered_add_comm_group γ] [semimodule ℝ γ]
(s : set E) (f : E → γ) : convex_on s (-f) ↔ concave_on s f :=
begin
split,
{ rintros ⟨hconv, h⟩,
refine ⟨hconv, _⟩,
intros x y xs ys a b ha hb hab,
specialize h xs ys ha hb hab,
simp [neg_apply, neg_le, add_comm] at h,
exact h },
{ rintros ⟨hconv, h⟩,
refine ⟨hconv, _⟩,
intros x y xs ys a b ha hb hab,
specialize h xs ys ha hb hab,
simp [neg_apply, neg_le, add_comm, h] }
end
/-- A function `f` is concave iff `-f` is convex. -/
@[simp] lemma neg_concave_on_iff {γ : Type*} [ordered_add_comm_group γ] [semimodule ℝ γ]
(s : set E) (f : E → γ) : concave_on s (-f) ↔ convex_on s f:=
by rw [← neg_convex_on_iff s (-f), neg_neg f]
end
lemma convex_on_id {s : set ℝ} (hs : convex s) : convex_on s id := ⟨hs, by { intros, refl }⟩
lemma concave_on_id {s : set ℝ} (hs : convex s) : concave_on s id := ⟨hs, by { intros, refl }⟩
lemma convex_on_const (c : β) (hs : convex s) : convex_on s (λ x:E, c) :=
⟨hs, by { intros, simp only [← add_smul, *, one_smul] }⟩
lemma concave_on_const (c : β) (hs : convex s) : concave_on s (λ x:E, c) :=
@convex_on_const _ _ _ _ (order_dual β) _ _ c hs
variables {t : set E}
lemma convex_on_iff_div {f : E → β} :
convex_on s f ↔ convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b →
f ((a/(a+b)) • x + (b/(a+b)) • y) ≤ (a/(a+b)) • f x + (b/(a+b)) • f y :=
and_congr iff.rfl
⟨begin
intros h x y hx hy a b ha hb hab,
apply h hx hy (div_nonneg ha $ le_of_lt hab) (div_nonneg hb $ le_of_lt hab),
rw [←add_div],
exact div_self (ne_of_gt hab)
end,
begin
intros h x y hx hy a b ha hb hab,
simpa [hab, zero_lt_one] using h hx hy ha hb,
end⟩
lemma concave_on_iff_div {f : E → β} :
concave_on s f ↔ convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b →
(a/(a+b)) • f x + (b/(a+b)) • f y ≤ f ((a/(a+b)) • x + (b/(a+b)) • y) :=
@convex_on_iff_div _ _ _ _ (order_dual β) _ _ _
/-- For a function on a convex set in a linear ordered space, in order to prove that it is convex
it suffices to verify the inequality `f (a • x + b • y) ≤ a • f x + b • f y` only for `x < y`
and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with
lexicographic order. -/
lemma linear_order.convex_on_of_lt {f : E → β} [linear_order E] (hs : convex s)
(hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 →
f (a • x + b • y) ≤ a • f x + b • f y) : convex_on s f :=
begin
use hs,
intros x y hx hy a b ha hb hab,
wlog hxy : x<=y using [x y a b, y x b a],
{ exact le_total _ _ },
{ cases eq_or_lt_of_le hxy with hxy hxy,
by { subst y, rw [← add_smul, ← add_smul, hab, one_smul, one_smul] },
cases eq_or_lt_of_le ha with ha ha,
by { subst a, rw [zero_add] at hab, subst b, simp },
cases eq_or_lt_of_le hb with hb hb,
by { subst b, rw [add_zero] at hab, subst a, simp },
exact hf hx hy hxy ha hb hab }
end
/-- For a function on a convex set in a linear ordered space, in order to prove that it is concave
it suffices to verify the inequality `a • f x + b • f y ≤ f (a • x + b • y)` only for `x < y`
and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with
lexicographic order. -/
lemma linear_order.concave_on_of_lt {f : E → β} [linear_order E] (hs : convex s)
(hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 →
a • f x + b • f y ≤ f (a • x + b • y)) : concave_on s f :=
@linear_order.convex_on_of_lt _ _ _ _ (order_dual β) _ _ f _ hs hf
/-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z`
the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope
of the secant line of `f` on `[x, z]`, then `f` is convex on `D`. This way of proving convexity
of a function is used in the proof of convexity of a function with a monotone derivative. -/
lemma convex_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ}
(hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z →
(f y - f x) / (y - x) ≤ (f z - f y) / (z - y)) :
convex_on s f :=
linear_order.convex_on_of_lt hs
begin
assume x z hx hz hxz a b ha hb hab,
let y := a * x + b * z,
have hxy : x < y,
{ rw [← one_mul x, ← hab, add_mul],
exact add_lt_add_left ((mul_lt_mul_left hb).2 hxz) _ },
have hyz : y < z,
{ rw [← one_mul z, ← hab, add_mul],
exact add_lt_add_right ((mul_lt_mul_left ha).2 hxz) _ },
have : (f y - f x) * (z - y) ≤ (f z - f y) * (y - x),
from (div_le_div_iff (sub_pos.2 hxy) (sub_pos.2 hyz)).1 (hf hx hz hxy hyz),
have A : z - y + (y - x) = z - x, by abel,
have B : 0 < z - x, from sub_pos.2 (lt_trans hxy hyz),
rw [sub_mul, sub_mul, sub_le_iff_le_add', ← add_sub_assoc, le_sub_iff_add_le, ← mul_add, A,
← le_div_iff B, add_div, mul_div_assoc, mul_div_assoc,
mul_comm (f x), mul_comm (f z)] at this,
rw [eq_comm, ← sub_eq_iff_eq_add] at hab; subst a,
convert this; symmetry; simp only [div_eq_iff (ne_of_gt B), y]; ring
end
/-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is convex on `D`, then for any three
points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope
of the secant line of `f` on `[x, z]`. -/
lemma convex_on.slope_mono_adjacent {s : set ℝ} {f : ℝ → ℝ} (hf : convex_on s f)
{x y z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) :
(f y - f x) / (y - x) ≤ (f z - f y) / (z - y) :=
begin
have h₁ : 0 < y - x := by linarith,
have h₂ : 0 < z - y := by linarith,
have h₃ : 0 < z - x := by linarith,
suffices : f y / (y - x) + f y / (z - y) ≤ f x / (y - x) + f z / (z - y),
by { ring at this ⊢, linarith },
set a := (z - y) / (z - x),
set b := (y - x) / (z - x),
have heqz : a • x + b • z = y, by { field_simp, rw div_eq_iff; [ring, linarith], },
have key, from
hf.2 hx hz
(show 0 ≤ a, by apply div_nonneg; linarith)
(show 0 ≤ b, by apply div_nonneg; linarith)
(show a + b = 1, by { field_simp, rw div_eq_iff; [ring, linarith], }),
rw heqz at key,
replace key := mul_le_mul_of_nonneg_left key (le_of_lt h₃),
field_simp [ne_of_gt h₁, ne_of_gt h₂, ne_of_gt h₃, mul_comm (z - x) _] at key ⊢,
rw div_le_div_right,
{ linarith, },
{ nlinarith, },
end
/-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is convex on `D` iff for any three
points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope
of the secant line of `f` on `[x, z]`. -/
lemma convex_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} :
convex_on s f ↔
(∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z →
(f y - f x) / (y - x) ≤ (f z - f y) / (z - y)) :=
⟨convex_on.slope_mono_adjacent, convex_on_real_of_slope_mono_adjacent hs⟩
/-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z`
the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope
of the secant line of `f` on `[x, z]`, then `f` is concave on `D`. -/
lemma concave_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ}
(hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z →
(f z - f y) / (z - y) ≤ (f y - f x) / (y - x)) : concave_on s f :=
begin
rw [←neg_convex_on_iff],
apply convex_on_real_of_slope_mono_adjacent hs,
intros x y z xs zs xy yz,
rw [←neg_le_neg_iff, ←neg_div, ←neg_div, neg_sub, neg_sub],
simp only [hf xs zs xy yz, neg_sub_neg, pi.neg_apply],
end
/-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is concave on `D`, then for any three
points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is greater than or equal to the
slope of the secant line of `f` on `[x, z]`. -/
lemma concave_on.slope_mono_adjacent {s : set ℝ} {f : ℝ → ℝ} (hf : concave_on s f)
{x y z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) :
(f z - f y) / (z - y) ≤ (f y - f x) / (y - x) :=
begin
rw [←neg_le_neg_iff, ←neg_div, ←neg_div, neg_sub, neg_sub],
rw [←neg_sub_neg (f y), ←neg_sub_neg (f z)],
simp_rw [←pi.neg_apply],
rw [←neg_convex_on_iff] at hf,
apply convex_on.slope_mono_adjacent hf; assumption,
end
/-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is concave on `D` iff for any
three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to
the slope of the secant line of `f` on `[x, z]`. -/
lemma concave_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} :
concave_on s f ↔
(∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z →
(f z - f y) / (z - y) ≤ (f y - f x) / (y - x)) :=
⟨concave_on.slope_mono_adjacent, concave_on_real_of_slope_mono_adjacent hs⟩
lemma convex_on.subset {f : E → β} (h_convex_on : convex_on t f)
(h_subset : s ⊆ t) (h_convex : convex s) : convex_on s f :=
begin
apply and.intro h_convex,
intros x y hx hy,
exact h_convex_on.2 (h_subset hx) (h_subset hy),
end
lemma concave_on.subset {f : E → β} (h_concave_on : concave_on t f)
(h_subset : s ⊆ t) (h_convex : convex s) : concave_on s f :=
@convex_on.subset _ _ _ _ (order_dual β) _ _ t f h_concave_on h_subset h_convex
lemma convex_on.add {f g : E → β} (hf : convex_on s f) (hg : convex_on s g) :
convex_on s (λx, f x + g x) :=
begin
apply and.intro hf.1,
intros x y hx hy a b ha hb hab,
calc
f (a • x + b • y) + g (a • x + b • y) ≤ (a • f x + b • f y) + (a • g x + b • g y)
: add_le_add (hf.2 hx hy ha hb hab) (hg.2 hx hy ha hb hab)
... = a • f x + a • g x + b • f y + b • g y : by abel
... = a • (f x + g x) + b • (f y + g y) : by simp [smul_add, add_assoc]
end
lemma concave_on.add {f g : E → β} (hf : concave_on s f) (hg : concave_on s g) :
concave_on s (λx, f x + g x) :=
@convex_on.add _ _ _ _ (order_dual β) _ _ f g hf hg
lemma convex_on.smul [ordered_semimodule ℝ β] {f : E → β} {c : ℝ} (hc : 0 ≤ c)
(hf : convex_on s f) : convex_on s (λx, c • f x) :=
begin
apply and.intro hf.1,
intros x y hx hy a b ha hb hab,
calc
c • f (a • x + b • y) ≤ c • (a • f x + b • f y)
: smul_le_smul_of_nonneg (hf.2 hx hy ha hb hab) hc
... = a • (c • f x) + b • (c • f y) : by simp only [smul_add, smul_comm c]
end
lemma concave_on.smul [ordered_semimodule ℝ β] {f : E → β} {c : ℝ} (hc : 0 ≤ c)
(hf : concave_on s f) : concave_on s (λx, c • f x) :=
@convex_on.smul _ _ _ _ (order_dual β) _ _ _ f c hc hf
/-- A convex function on a segment is upper-bounded by the max of its endpoints. -/
lemma convex_on.le_on_segment' {γ : Type*}
[linear_ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ]
{f : E → γ} {x y : E} {a b : ℝ}
(hf : convex_on s f) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) :
f (a • x + b • y) ≤ max (f x) (f y) :=
calc
f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab
... ≤ a • max (f x) (f y) + b • max (f x) (f y) :
add_le_add (smul_le_smul_of_nonneg (le_max_left _ _) ha)
(smul_le_smul_of_nonneg (le_max_right _ _) hb)
... ≤ max (f x) (f y) : by rw [←add_smul, hab, one_smul]
/-- A concave function on a segment is lower-bounded by the min of its endpoints. -/
lemma concave_on.le_on_segment' {γ : Type*}
[linear_ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ]
{f : E → γ} {x y : E} {a b : ℝ}
(hf : concave_on s f) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) :
min (f x) (f y) ≤ f (a • x + b • y) :=
@convex_on.le_on_segment' _ _ _ _ (order_dual γ) _ _ _ f x y a b hf hx hy ha hb hab
/-- A convex function on a segment is upper-bounded by the max of its endpoints. -/
lemma convex_on.le_on_segment {γ : Type*}
[linear_ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ]
{f : E → γ} (hf : convex_on s f) {x y z : E}
(hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x, y]) :
f z ≤ max (f x) (f y) :=
let ⟨a, b, ha, hb, hab, hz⟩ := hz in hz ▸ hf.le_on_segment' hx hy ha hb hab
/-- A concave function on a segment is lower-bounded by the min of its endpoints. -/
lemma concave_on.le_on_segment {γ : Type*}
[linear_ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ]
{f : E → γ} (hf : concave_on s f) {x y z : E}
(hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x, y]) :
min (f x) (f y) ≤ f z :=
@convex_on.le_on_segment _ _ _ _ (order_dual γ) _ _ _ f hf x y z hx hy hz
lemma convex_on.convex_le [ordered_semimodule ℝ β] {f : E → β} (hf : convex_on s f) (r : β) :
convex {x ∈ s | f x ≤ r} :=
convex_iff_segment_subset.2 $ λ x y hx hy z hz,
begin
refine ⟨hf.1.segment_subset hx.1 hy.1 hz,_⟩,
rcases hz with ⟨za,zb,hza,hzb,hzazb,H⟩,
rw ←H,
calc
f (za • x + zb • y) ≤ za • (f x) + zb • (f y) : hf.2 hx.1 hy.1 hza hzb hzazb
... ≤ za • r + zb • r : add_le_add (smul_le_smul_of_nonneg hx.2 hza)
(smul_le_smul_of_nonneg hy.2 hzb)
... ≤ r : by simp [←add_smul, hzazb]
end
lemma concave_on.concave_le [ordered_semimodule ℝ β] {f : E → β} (hf : concave_on s f) (r : β) :
convex {x ∈ s | r ≤ f x} :=
@convex_on.convex_le _ _ _ _ (order_dual β) _ _ _ f hf r
lemma convex_on.convex_lt {γ : Type*} [ordered_cancel_add_comm_monoid γ]
[semimodule ℝ γ] [ordered_semimodule ℝ γ]
{f : E → γ} (hf : convex_on s f) (r : γ) : convex {x ∈ s | f x < r} :=
begin
intros a b as bs xa xb hxa hxb hxaxb,
refine ⟨hf.1 as.1 bs.1 hxa hxb hxaxb, _⟩,
dsimp,
by_cases H : xa = 0,
{ have H' : xb = 1 := by rwa [H, zero_add] at hxaxb,
rw [H, H', zero_smul, one_smul, zero_add],
exact bs.2 },
{ calc
f (xa • a + xb • b) ≤ xa • (f a) + xb • (f b) : hf.2 as.1 bs.1 hxa hxb hxaxb
... < xa • r + xb • (f b) : (add_lt_add_iff_right (xb • (f b))).mpr
(smul_lt_smul_of_pos as.2
(lt_of_le_of_ne hxa (ne.symm H)))
... ≤ xa • r + xb • r : (add_le_add_iff_left (xa • r)).mpr
(smul_le_smul_of_nonneg bs.2.le hxb)
... = r : by simp only [←add_smul, hxaxb, one_smul] }
end
lemma concave_on.convex_lt {γ : Type*} [ordered_cancel_add_comm_monoid γ]
[semimodule ℝ γ] [ordered_semimodule ℝ γ]
{f : E → γ} (hf : concave_on s f) (r : γ) : convex {x ∈ s | r < f x} :=
@convex_on.convex_lt _ _ _ _ (order_dual γ) _ _ _ f hf r
lemma convex_on.convex_epigraph {γ : Type*} [ordered_add_comm_group γ]
[semimodule ℝ γ] [ordered_semimodule ℝ γ]
{f : E → γ} (hf : convex_on s f) :
convex {p : E × γ | p.1 ∈ s ∧ f p.1 ≤ p.2} :=
begin
rintros ⟨x, r⟩ ⟨y, t⟩ ⟨hx, hr⟩ ⟨hy, ht⟩ a b ha hb hab,
refine ⟨hf.1 hx hy ha hb hab, _⟩,
calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab
... ≤ a • r + b • t : add_le_add (smul_le_smul_of_nonneg hr ha)
(smul_le_smul_of_nonneg ht hb)
end
lemma concave_on.convex_hypograph {γ : Type*} [ordered_add_comm_group γ]
[semimodule ℝ γ] [ordered_semimodule ℝ γ]
{f : E → γ} (hf : concave_on s f) :
convex {p : E × γ | p.1 ∈ s ∧ p.2 ≤ f p.1} :=
@convex_on.convex_epigraph _ _ _ _ (order_dual γ) _ _ _ f hf
lemma convex_on_iff_convex_epigraph {γ : Type*} [ordered_add_comm_group γ]
[semimodule ℝ γ] [ordered_semimodule ℝ γ]
{f : E → γ} :
convex_on s f ↔ convex {p : E × γ | p.1 ∈ s ∧ f p.1 ≤ p.2} :=
begin
refine ⟨convex_on.convex_epigraph, λ h, ⟨_, _⟩⟩,
{ assume x y hx hy a b ha hb hab,
exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).1 },
{ assume x y hx hy a b ha hb hab,
exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).2 }
end
lemma concave_on_iff_convex_hypograph {γ : Type*} [ordered_add_comm_group γ]
[semimodule ℝ γ] [ordered_semimodule ℝ γ]
{f : E → γ} :
concave_on s f ↔ convex {p : E × γ | p.1 ∈ s ∧ p.2 ≤ f p.1} :=
@convex_on_iff_convex_epigraph _ _ _ _ (order_dual γ) _ _ _ f
/-- If a function is convex on `s`, it remains convex when precomposed by an affine map. -/
lemma convex_on.comp_affine_map {f : F → β} (g : E →ᵃ[ℝ] F) {s : set F}
(hf : convex_on s f) : convex_on (g ⁻¹' s) (f ∘ g) :=
begin
refine ⟨hf.1.affine_preimage _,_⟩,
intros x y xs ys a b ha hb hab,
calc
(f ∘ g) (a • x + b • y) = f (g (a • x + b • y)) : rfl
... = f (a • (g x) + b • (g y)) : by rw [convex.combo_affine_apply hab]
... ≤ a • f (g x) + b • f (g y) : hf.2 xs ys ha hb hab
... = a • (f ∘ g) x + b • (f ∘ g) y : rfl
end
/-- If a function is concave on `s`, it remains concave when precomposed by an affine map. -/
lemma concave_on.comp_affine_map {f : F → β} (g : E →ᵃ[ℝ] F) {s : set F}
(hf : concave_on s f) : concave_on (g ⁻¹' s) (f ∘ g) :=
@convex_on.comp_affine_map _ _ _ _ _ _ (order_dual β) _ _ f g s hf
/-- If `g` is convex on `s`, so is `(g ∘ f)` on `f ⁻¹' s` for a linear `f`. -/
lemma convex_on.comp_linear_map {g : F → β} {s : set F} (hg : convex_on s g) (f : E →ₗ[ℝ] F) :
convex_on (f ⁻¹' s) (g ∘ f) :=
hg.comp_affine_map f.to_affine_map
/-- If `g` is concave on `s`, so is `(g ∘ f)` on `f ⁻¹' s` for a linear `f`. -/
lemma concave_on.comp_linear_map {g : F → β} {s : set F} (hg : concave_on s g) (f : E →ₗ[ℝ] F) :
concave_on (f ⁻¹' s) (g ∘ f) :=
hg.comp_affine_map f.to_affine_map
/-- If a function is convex on `s`, it remains convex after a translation. -/
lemma convex_on.translate_right {f : E → β} {s : set E} {a : E} (hf : convex_on s f) :
convex_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, a + z)) :=
hf.comp_affine_map $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E
/-- If a function is concave on `s`, it remains concave after a translation. -/
lemma concave_on.translate_right {f : E → β} {s : set E} {a : E} (hf : concave_on s f) :
concave_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, a + z)) :=
hf.comp_affine_map $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E
/-- If a function is convex on `s`, it remains convex after a translation. -/
lemma convex_on.translate_left {f : E → β} {s : set E} {a : E} (hf : convex_on s f) :
convex_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, z + a)) :=
by simpa only [add_comm] using hf.translate_right
/-- If a function is concave on `s`, it remains concave after a translation. -/
lemma concave_on.translate_left {f : E → β} {s : set E} {a : E} (hf : concave_on s f) :
concave_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, z + a)) :=
by simpa only [add_comm] using hf.translate_right
end functions
/-! ### Center of mass -/
section center_mass
/-- Center of mass of a finite collection of points with prescribed weights.
Note that we require neither `0 ≤ w i` nor `∑ w = 1`. -/
noncomputable def finset.center_mass (t : finset ι) (w : ι → ℝ) (z : ι → E) : E :=
(∑ i in t, w i)⁻¹ • (∑ i in t, w i • z i)
variables (i j : ι) (c : ℝ) (t : finset ι) (w : ι → ℝ) (z : ι → E)
open finset
lemma finset.center_mass_empty : (∅ : finset ι).center_mass w z = 0 :=
by simp only [center_mass, sum_empty, smul_zero]
lemma finset.center_mass_pair (hne : i ≠ j) :
({i, j} : finset ι).center_mass w z = (w i / (w i + w j)) • z i + (w j / (w i + w j)) • z j :=
by simp only [center_mass, sum_pair hne, smul_add, (mul_smul _ _ _).symm, div_eq_inv_mul]
variable {w}
lemma finset.center_mass_insert (ha : i ∉ t) (hw : ∑ j in t, w j ≠ 0) :
(insert i t).center_mass w z = (w i / (w i + ∑ j in t, w j)) • z i +
((∑ j in t, w j) / (w i + ∑ j in t, w j)) • t.center_mass w z :=
begin
simp only [center_mass, sum_insert ha, smul_add, (mul_smul _ _ _).symm, ← div_eq_inv_mul],
congr' 2,
rw [div_mul_eq_mul_div, mul_inv_cancel hw, one_div]
end
lemma finset.center_mass_singleton (hw : w i ≠ 0) : ({i} : finset ι).center_mass w z = z i :=
by rw [center_mass, sum_singleton, sum_singleton, ← mul_smul, inv_mul_cancel hw, one_smul]
lemma finset.center_mass_eq_of_sum_1 (hw : ∑ i in t, w i = 1) :
t.center_mass w z = ∑ i in t, w i • z i :=
by simp only [finset.center_mass, hw, inv_one, one_smul]
lemma finset.center_mass_smul : t.center_mass w (λ i, c • z i) = c • t.center_mass w z :=
by simp only [finset.center_mass, finset.smul_sum, (mul_smul _ _ _).symm, mul_comm c, mul_assoc]
/-- A convex combination of two centers of mass is a center of mass as well. This version
deals with two different index types. -/
lemma finset.center_mass_segment'
(s : finset ι) (t : finset ι') (ws : ι → ℝ) (zs : ι → E) (wt : ι' → ℝ) (zt : ι' → E)
(hws : ∑ i in s, ws i = 1) (hwt : ∑ i in t, wt i = 1) (a b : ℝ) (hab : a + b = 1) :
a • s.center_mass ws zs + b • t.center_mass wt zt =
(s.image sum.inl ∪ t.image sum.inr).center_mass
(sum.elim (λ i, a * ws i) (λ j, b * wt j))
(sum.elim zs zt) :=
begin
rw [s.center_mass_eq_of_sum_1 _ hws, t.center_mass_eq_of_sum_1 _ hwt,
smul_sum, smul_sum, ← finset.sum_sum_elim, finset.center_mass_eq_of_sum_1],
{ congr' with ⟨⟩; simp only [sum.elim_inl, sum.elim_inr, mul_smul] },
{ rw [sum_sum_elim, ← mul_sum, ← mul_sum, hws, hwt, mul_one, mul_one, hab] }
end
/-- A convex combination of two centers of mass is a center of mass as well. This version
works if two centers of mass share the set of original points. -/
lemma finset.center_mass_segment
(s : finset ι) (w₁ w₂ : ι → ℝ) (z : ι → E)
(hw₁ : ∑ i in s, w₁ i = 1) (hw₂ : ∑ i in s, w₂ i = 1) (a b : ℝ) (hab : a + b = 1) :
a • s.center_mass w₁ z + b • s.center_mass w₂ z =
s.center_mass (λ i, a * w₁ i + b * w₂ i) z :=
have hw : ∑ i in s, (a * w₁ i + b * w₂ i) = 1,
by simp only [mul_sum.symm, sum_add_distrib, mul_one, *],
by simp only [finset.center_mass_eq_of_sum_1, smul_sum, sum_add_distrib, add_smul, mul_smul, *]
lemma finset.center_mass_ite_eq (hi : i ∈ t) :
t.center_mass (λ j, if (i = j) then 1 else 0) z = z i :=
begin
rw [finset.center_mass_eq_of_sum_1],
transitivity ∑ j in t, if (i = j) then z i else 0,
{ congr' with i, split_ifs, exacts [h ▸ one_smul _ _, zero_smul _ _] },
{ rw [sum_ite_eq, if_pos hi] },
{ rw [sum_ite_eq, if_pos hi] }
end
variables {t w}
lemma finset.center_mass_subset {t' : finset ι} (ht : t ⊆ t')
(h : ∀ i ∈ t', i ∉ t → w i = 0) :
t.center_mass w z = t'.center_mass w z :=
begin
rw [center_mass, sum_subset ht h, smul_sum, center_mass, smul_sum],
apply sum_subset ht,
assume i hit' hit,
rw [h i hit' hit, zero_smul, smul_zero]
end
lemma finset.center_mass_filter_ne_zero :
(t.filter (λ i, w i ≠ 0)).center_mass w z = t.center_mass w z :=
finset.center_mass_subset z (filter_subset _ _) $ λ i hit hit',
by simpa only [hit, mem_filter, true_and, ne.def, not_not] using hit'
variable {z}
/-- The center of mass of a finite subset of a convex set belongs to the set
provided that all weights are non-negative, and the total weight is positive. -/
lemma convex.center_mass_mem (hs : convex s) :
(∀ i ∈ t, 0 ≤ w i) → (0 < ∑ i in t, w i) → (∀ i ∈ t, z i ∈ s) → t.center_mass w z ∈ s :=
begin
induction t using finset.induction with i t hi ht, { simp [lt_irrefl] },
intros h₀ hpos hmem,
have zi : z i ∈ s, from hmem _ (mem_insert_self _ _),
have hs₀ : ∀ j ∈ t, 0 ≤ w j, from λ j hj, h₀ j $ mem_insert_of_mem hj,
rw [sum_insert hi] at hpos,
by_cases hsum_t : ∑ j in t, w j = 0,
{ have ws : ∀ j ∈ t, w j = 0, from (sum_eq_zero_iff_of_nonneg hs₀).1 hsum_t,
have wz : ∑ j in t, w j • z j = 0, from sum_eq_zero (λ i hi, by simp [ws i hi]),
simp only [center_mass, sum_insert hi, wz, hsum_t, add_zero],
simp only [hsum_t, add_zero] at hpos,
rw [← mul_smul, inv_mul_cancel (ne_of_gt hpos), one_smul],
exact zi },
{ rw [finset.center_mass_insert _ _ _ hi hsum_t],
refine convex_iff_div.1 hs zi (ht hs₀ _ _) _ (sum_nonneg hs₀) hpos,
{ exact lt_of_le_of_ne (sum_nonneg hs₀) (ne.symm hsum_t) },
{ intros j hj, exact hmem j (mem_insert_of_mem hj) },
{ exact h₀ _ (mem_insert_self _ _) } }
end
lemma convex.sum_mem (hs : convex s) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i in t, w i = 1)
(hz : ∀ i ∈ t, z i ∈ s) :
∑ i in t, w i • z i ∈ s :=
by simpa only [h₁, center_mass, inv_one, one_smul] using
hs.center_mass_mem h₀ (h₁.symm ▸ zero_lt_one) hz
lemma convex_iff_sum_mem :
convex s ↔
(∀ (t : finset E) (w : E → ℝ),
(∀ i ∈ t, 0 ≤ w i) → ∑ i in t, w i = 1 → (∀ x ∈ t, x ∈ s) → ∑ x in t, w x • x ∈ s ) :=
begin
refine ⟨λ hs t w hw₀ hw₁ hts, hs.sum_mem hw₀ hw₁ hts, _⟩,
intros h x y hx hy a b ha hb hab,
by_cases h_cases: x = y,
{ rw [h_cases, ←add_smul, hab, one_smul], exact hy },
{ convert h {x, y} (λ z, if z = y then b else a) _ _ _,
{ simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl] },
{ simp_intros i hi,
cases hi; subst i; simp [ha, hb, if_neg h_cases] },
{ simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl, hab] },
{ simp_intros i hi,
cases hi; subst i; simp [hx, hy, if_neg h_cases] } }
end
/-- Jensen's inequality, `finset.center_mass` version. -/
lemma convex_on.map_center_mass_le {f : E → ℝ} (hf : convex_on s f)
(h₀ : ∀ i ∈ t, 0 ≤ w i) (hpos : 0 < ∑ i in t, w i)
(hmem : ∀ i ∈ t, z i ∈ s) : f (t.center_mass w z) ≤ t.center_mass w (f ∘ z) :=
begin
have hmem' : ∀ i ∈ t, (z i, (f ∘ z) i) ∈ {p : E × ℝ | p.1 ∈ s ∧ f p.1 ≤ p.2},
from λ i hi, ⟨hmem i hi, le_refl _⟩,
convert (hf.convex_epigraph.center_mass_mem h₀ hpos hmem').2;
simp only [center_mass, function.comp, prod.smul_fst, prod.fst_sum, prod.smul_snd, prod.snd_sum]
end
/-- Jensen's inequality, `finset.sum` version. -/
lemma convex_on.map_sum_le {f : E → ℝ} (hf : convex_on s f)
(h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i in t, w i = 1)
(hmem : ∀ i ∈ t, z i ∈ s) : f (∑ i in t, w i • z i) ≤ ∑ i in t, w i * (f (z i)) :=
by simpa only [center_mass, h₁, inv_one, one_smul]
using hf.map_center_mass_le h₀ (h₁.symm ▸ zero_lt_one) hmem
/-- If a function `f` is convex on `s` takes value `y` at the center of mass of some points
`z i ∈ s`, then for some `i` we have `y ≤ f (z i)`. -/
lemma convex_on.exists_ge_of_center_mass {f : E → ℝ} (h : convex_on s f)
(hw₀ : ∀ i ∈ t, 0 ≤ w i) (hws : 0 < ∑ i in t, w i) (hz : ∀ i ∈ t, z i ∈ s) :
∃ i ∈ t, f (t.center_mass w z) ≤ f (z i) :=
begin
set y := t.center_mass w z,
have : f y ≤ t.center_mass w (f ∘ z) := h.map_center_mass_le hw₀ hws hz,
rw ← sum_filter_ne_zero at hws,
rw [← finset.center_mass_filter_ne_zero (f ∘ z), center_mass, smul_eq_mul,
← div_eq_inv_mul, le_div_iff hws, mul_sum] at this,
replace : ∃ i ∈ t.filter (λ i, w i ≠ 0), f y * w i ≤ w i • (f ∘ z) i :=
exists_le_of_sum_le (nonempty_of_sum_ne_zero (ne_of_gt hws)) this,
rcases this with ⟨i, hi, H⟩,
rw [mem_filter] at hi,
use [i, hi.1],
simp only [smul_eq_mul, mul_comm (w i)] at H,
refine (mul_le_mul_right _).1 H,
exact lt_of_le_of_ne (hw₀ i hi.1) hi.2.symm
end
end center_mass
/-! ### Convex hull -/
section convex_hull
variable {t : set E}
/-- The convex hull of a set `s` is the minimal convex set that includes `s`. -/
def convex_hull (s : set E) : set E :=
⋂ (t : set E) (hst : s ⊆ t) (ht : convex t), t
variable (s)
lemma subset_convex_hull : s ⊆ convex_hull s :=
set.subset_Inter $ λ t, set.subset_Inter $ λ hst, set.subset_Inter $ λ ht, hst
lemma convex_convex_hull : convex (convex_hull s) :=
convex_Inter $ λ t, convex_Inter $ λ ht, convex_Inter id
variable {s}
lemma convex_hull_min (hst : s ⊆ t) (ht : convex t) : convex_hull s ⊆ t :=
set.Inter_subset_of_subset t $ set.Inter_subset_of_subset hst $ set.Inter_subset _ ht
lemma convex_hull_mono (hst : s ⊆ t) : convex_hull s ⊆ convex_hull t :=
convex_hull_min (set.subset.trans hst $ subset_convex_hull t) (convex_convex_hull t)
lemma convex.convex_hull_eq {s : set E} (hs : convex s) : convex_hull s = s :=
set.subset.antisymm (convex_hull_min (set.subset.refl _) hs) (subset_convex_hull s)
@[simp]
lemma convex_hull_singleton {x : E} : convex_hull ({x} : set E) = {x} :=
(convex_singleton x).convex_hull_eq
lemma is_linear_map.image_convex_hull {f : E → F} (hf : is_linear_map ℝ f) :
f '' (convex_hull s) = convex_hull (f '' s) :=
begin
refine set.subset.antisymm _ _,
{ rw [set.image_subset_iff],
exact convex_hull_min (set.image_subset_iff.1 $ subset_convex_hull $ f '' s)
((convex_convex_hull (f '' s)).is_linear_preimage hf) },
{ exact convex_hull_min (set.image_subset _ $ subset_convex_hull s)
((convex_convex_hull s).is_linear_image hf) }
end
lemma linear_map.image_convex_hull (f : E →ₗ[ℝ] F) :
f '' (convex_hull s) = convex_hull (f '' s) :=
f.is_linear.image_convex_hull
lemma finset.center_mass_mem_convex_hull (t : finset ι) {w : ι → ℝ} (hw₀ : ∀ i ∈ t, 0 ≤ w i)
(hws : 0 < ∑ i in t, w i) {z : ι → E} (hz : ∀ i ∈ t, z i ∈ s) :
t.center_mass w z ∈ convex_hull s :=
(convex_convex_hull s).center_mass_mem hw₀ hws (λ i hi, subset_convex_hull s $ hz i hi)
-- TODO : Do we need other versions of the next lemma?
/-- Convex hull of `s` is equal to the set of all centers of masses of `finset`s `t`, `z '' t ⊆ s`.
This version allows finsets in any type in any universe. -/
lemma convex_hull_eq (s : set E) :
convex_hull s = {x : E | ∃ (ι : Type u') (t : finset ι) (w : ι → ℝ) (z : ι → E)
(hw₀ : ∀ i ∈ t, 0 ≤ w i) (hw₁ : ∑ i in t, w i = 1) (hz : ∀ i ∈ t, z i ∈ s),
t.center_mass w z = x} :=
begin
refine subset.antisymm (convex_hull_min _ _) _,
{ intros x hx,
use [punit, {punit.star}, λ _, 1, λ _, x, λ _ _, zero_le_one,
finset.sum_singleton, λ _ _, hx],
simp only [finset.center_mass, finset.sum_singleton, inv_one, one_smul] },
{ rintros x y ⟨ι, sx, wx, zx, hwx₀, hwx₁, hzx, rfl⟩ ⟨ι', sy, wy, zy, hwy₀, hwy₁, hzy, rfl⟩
a b ha hb hab,
rw [finset.center_mass_segment' _ _ _ _ _ _ hwx₁ hwy₁ _ _ hab],
refine ⟨_, _, _, _, _, _, _, rfl⟩,
{ rintros i hi,
rw [finset.mem_union, finset.mem_image, finset.mem_image] at hi,
rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩;
simp only [sum.elim_inl, sum.elim_inr];
apply_rules [mul_nonneg, hwx₀, hwy₀] },
{ simp [finset.sum_sum_elim, finset.mul_sum.symm, *] },
{ intros i hi,
rw [finset.mem_union, finset.mem_image, finset.mem_image] at hi,
rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩;
simp only [sum.elim_inl, sum.elim_inr]; apply_rules [hzx, hzy] } },
{ rintros _ ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩,
exact t.center_mass_mem_convex_hull hw₀ (hw₁.symm ▸ zero_lt_one) hz }
end
/-- Maximum principle for convex functions. If a function `f` is convex on the convex hull of `s`,
then `f` can't have a maximum on `convex_hull s` outside of `s`. -/
lemma convex_on.exists_ge_of_mem_convex_hull {f : E → ℝ} (hf : convex_on (convex_hull s) f)
{x} (hx : x ∈ convex_hull s) : ∃ y ∈ s, f x ≤ f y :=
begin
rw convex_hull_eq at hx,
rcases hx with ⟨α, t, w, z, hw₀, hw₁, hz, rfl⟩,
rcases hf.exists_ge_of_center_mass hw₀ (hw₁.symm ▸ zero_lt_one)
(λ i hi, subset_convex_hull s (hz i hi)) with ⟨i, hit, Hi⟩,
exact ⟨z i, hz i hit, Hi⟩
end
lemma finset.convex_hull_eq (s : finset E) :
convex_hull ↑s = {x : E | ∃ (w : E → ℝ) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : ∑ y in s, w y = 1),
s.center_mass w id = x} :=
begin
refine subset.antisymm (convex_hull_min _ _) _,
{ intros x hx,
rw [finset.mem_coe] at hx,
refine ⟨_, _, _, finset.center_mass_ite_eq _ _ _ hx⟩,
{ intros, split_ifs, exacts [zero_le_one, le_refl 0] },
{ rw [finset.sum_ite_eq, if_pos hx] } },
{ rintros x y ⟨wx, hwx₀, hwx₁, rfl⟩ ⟨wy, hwy₀, hwy₁, rfl⟩
a b ha hb hab,
rw [finset.center_mass_segment _ _ _ _ hwx₁ hwy₁ _ _ hab],
refine ⟨_, _, _, rfl⟩,
{ rintros i hi,
apply_rules [add_nonneg, mul_nonneg, hwx₀, hwy₀], },
{ simp only [finset.sum_add_distrib, finset.mul_sum.symm, mul_one, *] } },
{ rintros _ ⟨w, hw₀, hw₁, rfl⟩,
exact s.center_mass_mem_convex_hull (λ x hx, hw₀ _ hx)
(hw₁.symm ▸ zero_lt_one) (λ x hx, hx) }
end
lemma set.finite.convex_hull_eq {s : set E} (hs : finite s) :
convex_hull s = {x : E | ∃ (w : E → ℝ) (hw₀ : ∀ y ∈ s, 0 ≤ w y)
(hw₁ : ∑ y in hs.to_finset, w y = 1), hs.to_finset.center_mass w id = x} :=
by simpa only [set.finite.coe_to_finset, set.finite.mem_to_finset, exists_prop]
using hs.to_finset.convex_hull_eq
lemma convex_hull_eq_union_convex_hull_finite_subsets (s : set E) :
convex_hull s = ⋃ (t : finset E) (w : ↑t ⊆ s), convex_hull ↑t :=
begin
refine subset.antisymm _ _,
{ rw [convex_hull_eq.{u}],
rintros x ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩,
simp only [mem_Union],
refine ⟨t.image z, _, _⟩,
{ rw [finset.coe_image, image_subset_iff],
exact hz },
{ apply t.center_mass_mem_convex_hull hw₀,
{ simp only [hw₁, zero_lt_one] },
{ exact λ i hi, finset.mem_coe.2 (finset.mem_image_of_mem _ hi) } } },
{ exact Union_subset (λ i, Union_subset convex_hull_mono), },
end
lemma is_linear_map.convex_hull_image {f : E → F} (hf : is_linear_map ℝ f) (s : set E) :
convex_hull (f '' s) = f '' convex_hull s :=
set.subset.antisymm (convex_hull_min (image_subset _ (subset_convex_hull s)) $
(convex_convex_hull s).is_linear_image hf)
(image_subset_iff.2 $ convex_hull_min
(image_subset_iff.1 $ subset_convex_hull _)
((convex_convex_hull _).is_linear_preimage hf))
lemma linear_map.convex_hull_image (f : E →ₗ[ℝ] F) (s : set E) :
convex_hull (f '' s) = f '' convex_hull s :=
f.is_linear.convex_hull_image s
end convex_hull
/-! ### Simplex -/
section simplex
variables (ι) [fintype ι] {f : ι → ℝ}
/-- The standard simplex in the space of functions `ι → ℝ` is the set
of vectors with non-negative coordinates with total sum `1`. -/
def std_simplex (ι : Type*) [fintype ι] : set (ι → ℝ) :=
{f | (∀ x, 0 ≤ f x) ∧ ∑ x, f x = 1}
lemma std_simplex_eq_inter :
std_simplex ι = (⋂ x, {f | 0 ≤ f x}) ∩ {f | ∑ x, f x = 1} :=
by { ext f, simp only [std_simplex, set.mem_inter_eq, set.mem_Inter, set.mem_set_of_eq] }
lemma convex_std_simplex : convex (std_simplex ι) :=
begin
refine λ f g hf hg a b ha hb hab, ⟨λ x, _, _⟩,
{ apply_rules [add_nonneg, mul_nonneg, hf.1, hg.1] },
{ erw [finset.sum_add_distrib, ← finset.smul_sum, ← finset.smul_sum, hf.2, hg.2,
smul_eq_mul, smul_eq_mul, mul_one, mul_one],
exact hab }
end
variable {ι}
lemma ite_eq_mem_std_simplex (i : ι) : (λ j, ite (i = j) (1:ℝ) 0) ∈ std_simplex ι :=
⟨λ j, by simp only; split_ifs; norm_num, by rw [finset.sum_ite_eq, if_pos (finset.mem_univ _)]⟩
/-- `std_simplex ι` is the convex hull of the canonical basis in `ι → ℝ`. -/
lemma convex_hull_basis_eq_std_simplex :
convex_hull (range $ λ(i j:ι), if i = j then (1:ℝ) else 0) = std_simplex ι :=
begin
refine subset.antisymm (convex_hull_min _ (convex_std_simplex ι)) _,
{ rintros _ ⟨i, rfl⟩,
exact ite_eq_mem_std_simplex i },
{ rintros w ⟨hw₀, hw₁⟩,
rw [pi_eq_sum_univ w, ← finset.univ.center_mass_eq_of_sum_1 _ hw₁],
exact finset.univ.center_mass_mem_convex_hull (λ i hi, hw₀ i)
(hw₁.symm ▸ zero_lt_one) (λ i hi, mem_range_self i) }
end
variable {ι}
/-- The convex hull of a finite set is the image of the standard simplex in `s → ℝ`
under the linear map sending each function `w` to `∑ x in s, w x • x`.
Since we have no sums over finite sets, we use sum over `@finset.univ _ hs.fintype`.
The map is defined in terms of operations on `(s → ℝ) →ₗ[ℝ] ℝ` so that later we will not need
to prove that this map is linear. -/
lemma set.finite.convex_hull_eq_image {s : set E} (hs : finite s) :
convex_hull s = by haveI := hs.fintype; exact
(⇑(∑ x : s, (@linear_map.proj ℝ s _ (λ i, ℝ) _ _ x).smul_right x.1)) '' (std_simplex s) :=
begin
rw [← convex_hull_basis_eq_std_simplex, ← linear_map.convex_hull_image, ← set.range_comp, (∘)],
apply congr_arg,
convert subtype.range_coe.symm,
ext x,
simp [linear_map.sum_apply, ite_smul, finset.filter_eq]
end
/-- All values of a function `f ∈ std_simplex ι` belong to `[0, 1]`. -/
lemma mem_Icc_of_mem_std_simplex (hf : f ∈ std_simplex ι) (x) :
f x ∈ I :=
⟨hf.1 x, hf.2 ▸ finset.single_le_sum (λ y hy, hf.1 y) (finset.mem_univ x)⟩
end simplex
|
f33892e97761ceabde1f82f07145ce515afec2c7 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/topology/algebra/open_subgroup.lean | ab088c33023483f73b7aadfb3000eb7ebb68ad11 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 7,216 | lean | /-
Copyright (c) 2019 Johan Commelin All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import order.filter.lift
import topology.opens
import topology.algebra.ring
open topological_space
open_locale topological_space
set_option old_structure_cmd true
/-- The type of open subgroups of a topological additive group. -/
@[ancestor add_subgroup]
structure open_add_subgroup (G : Type*) [add_group G] [topological_space G]
extends add_subgroup G :=
(is_open' : is_open carrier)
/-- The type of open subgroups of a topological group. -/
@[ancestor subgroup, to_additive]
structure open_subgroup (G : Type*) [group G] [topological_space G] extends subgroup G :=
(is_open' : is_open carrier)
/-- Reinterpret an `open_subgroup` as a `subgroup`. -/
add_decl_doc open_subgroup.to_subgroup
/-- Reinterpret an `open_add_subgroup` as an `add_subgroup`. -/
add_decl_doc open_add_subgroup.to_add_subgroup
-- Tell Lean that `open_add_subgroup` is a namespace
namespace open_add_subgroup
end open_add_subgroup
namespace open_subgroup
open function topological_space
variables {G : Type*} [group G] [topological_space G]
variables {U V : open_subgroup G} {g : G}
@[to_additive]
instance has_coe_set : has_coe_t (open_subgroup G) (set G) := ⟨λ U, U.1⟩
@[to_additive]
instance : has_mem G (open_subgroup G) := ⟨λ g U, g ∈ (U : set G)⟩
@[to_additive]
instance has_coe_subgroup : has_coe_t (open_subgroup G) (subgroup G) := ⟨to_subgroup⟩
@[to_additive]
instance has_coe_opens : has_coe_t (open_subgroup G) (opens G) := ⟨λ U, ⟨U, U.is_open'⟩⟩
@[simp, to_additive] lemma mem_coe : g ∈ (U : set G) ↔ g ∈ U := iff.rfl
@[simp, to_additive] lemma mem_coe_opens : g ∈ (U : opens G) ↔ g ∈ U := iff.rfl
@[simp, to_additive]
lemma mem_coe_subgroup : g ∈ (U : subgroup G) ↔ g ∈ U := iff.rfl
attribute [norm_cast] mem_coe mem_coe_opens mem_coe_subgroup open_add_subgroup.mem_coe
open_add_subgroup.mem_coe_opens open_add_subgroup.mem_coe_add_subgroup
@[to_additive] lemma coe_injective : injective (coe : open_subgroup G → set G) :=
λ U V h, by cases U; cases V; congr; assumption
@[ext, to_additive]
lemma ext (h : ∀ x, x ∈ U ↔ x ∈ V) : (U = V) := coe_injective $ set.ext h
@[to_additive]
lemma ext_iff : (U = V) ↔ (∀ x, x ∈ U ↔ x ∈ V) := ⟨λ h x, h ▸ iff.rfl, ext⟩
variable (U)
@[to_additive]
protected lemma is_open : is_open (U : set G) := U.is_open'
@[to_additive]
protected lemma one_mem : (1 : G) ∈ U := U.one_mem'
@[to_additive]
protected lemma inv_mem {g : G} (h : g ∈ U) : g⁻¹ ∈ U := U.inv_mem' h
@[to_additive]
protected lemma mul_mem {g₁ g₂ : G} (h₁ : g₁ ∈ U) (h₂ : g₂ ∈ U) : g₁ * g₂ ∈ U := U.mul_mem' h₁ h₂
@[to_additive]
lemma mem_nhds_one : (U : set G) ∈ 𝓝 (1 : G) :=
mem_nhds_sets U.is_open U.one_mem
variable {U}
@[to_additive]
instance : has_top (open_subgroup G) := ⟨{ is_open' := is_open_univ, .. (⊤ : subgroup G) }⟩
@[to_additive]
instance : inhabited (open_subgroup G) := ⟨⊤⟩
@[to_additive]
lemma is_closed [has_continuous_mul G] (U : open_subgroup G) : is_closed (U : set G) :=
begin
refine is_open_iff_forall_mem_open.2 (λ x hx, ⟨(λ y, y * x⁻¹) ⁻¹' U, _, _, _⟩),
{ intros u hux,
simp only [set.mem_preimage, set.mem_compl_iff, mem_coe] at hux hx ⊢,
refine mt (λ hu, _) hx,
convert U.mul_mem (U.inv_mem hux) hu,
simp },
{ exact (continuous_mul_right _) _ U.is_open },
{ simp [U.one_mem] }
end
section
variables {H : Type*} [group H] [topological_space H]
@[to_additive]
def prod (U : open_subgroup G) (V : open_subgroup H) : open_subgroup (G × H) :=
{ carrier := (U : set G).prod (V : set H),
is_open' := is_open_prod U.is_open V.is_open,
.. (U : subgroup G).prod (V : subgroup H) }
end
@[to_additive]
instance : partial_order (open_subgroup G) :=
{ le := λ U V, ∀ ⦃x⦄, x ∈ U → x ∈ V,
.. partial_order.lift (coe : open_subgroup G → set G) coe_injective }
@[to_additive]
instance : semilattice_inf_top (open_subgroup G) :=
{ inf := λ U V, { is_open' := is_open_inter U.is_open V.is_open, .. (U : subgroup G) ⊓ V },
inf_le_left := λ U V, set.inter_subset_left _ _,
inf_le_right := λ U V, set.inter_subset_right _ _,
le_inf := λ U V W hV hW, set.subset_inter hV hW,
top := ⊤,
le_top := λ U, set.subset_univ _,
..open_subgroup.partial_order }
@[simp, to_additive] lemma coe_inf : (↑(U ⊓ V) : set G) = (U : set G) ∩ V := rfl
@[simp, to_additive] lemma coe_subset : (U : set G) ⊆ V ↔ U ≤ V := iff.rfl
@[simp, to_additive] lemma coe_subgroup_le : (U : subgroup G) ≤ (V : subgroup G) ↔ U ≤ V := iff.rfl
attribute [norm_cast] coe_inf coe_subset coe_subgroup_le open_add_subgroup.coe_inf
open_add_subgroup.coe_subset open_add_subgroup.coe_add_subgroup_le
end open_subgroup
namespace subgroup
variables {G : Type*} [group G] [topological_space G] [has_continuous_mul G] (H : subgroup G)
@[to_additive]
lemma is_open_of_mem_nhds {g : G} (hg : (H : set G) ∈ 𝓝 g) :
is_open (H : set G) :=
begin
simp only [is_open_iff_mem_nhds, subgroup.mem_coe] at hg ⊢,
intros x hx,
have : filter.tendsto (λ y, y * (x⁻¹ * g)) (𝓝 x) (𝓝 $ x * (x⁻¹ * g)) :=
(continuous_id.mul continuous_const).tendsto _,
rw [mul_inv_cancel_left] at this,
have := filter.mem_map.1 (this hg),
replace hg : g ∈ H := subgroup.mem_coe.1 (mem_of_nhds hg),
simp only [subgroup.mem_coe, H.mul_mem_cancel_right (H.mul_mem (H.inv_mem hx) hg)] at this,
exact this
end
@[to_additive]
lemma is_open_of_open_subgroup {U : open_subgroup G} (h : U.1 ≤ H) :
is_open (H : set G) :=
H.is_open_of_mem_nhds (filter.mem_sets_of_superset U.mem_nhds_one h)
@[to_additive]
lemma is_open_mono {H₁ H₂ : subgroup G} (h : H₁ ≤ H₂) (h₁ : is_open (H₁ :set G)) :
is_open (H₂ : set G) :=
@is_open_of_open_subgroup _ _ _ _ H₂ { is_open' := h₁, .. H₁ } h
end subgroup
namespace open_subgroup
variables {G : Type*} [group G] [topological_space G] [has_continuous_mul G]
@[to_additive]
instance : semilattice_sup_top (open_subgroup G) :=
{ sup := λ U V,
{ is_open' := show is_open (((U : subgroup G) ⊔ V : subgroup G) : set G),
from subgroup.is_open_mono le_sup_left U.is_open,
.. ((U : subgroup G) ⊔ V) },
le_sup_left := λ U V, coe_subgroup_le.1 le_sup_left,
le_sup_right := λ U V, coe_subgroup_le.1 le_sup_right,
sup_le := λ U V W hU hV, coe_subgroup_le.1 (sup_le hU hV),
..open_subgroup.semilattice_inf_top }
end open_subgroup
namespace submodule
open open_add_subgroup
variables {R : Type*} {M : Type*} [comm_ring R]
variables [add_comm_group M] [topological_space M] [topological_add_group M] [module R M]
lemma is_open_mono {U P : submodule R M} (h : U ≤ P) (hU : is_open (U : set M)) :
is_open (P : set M) :=
@add_subgroup.is_open_mono M _ _ _ U.to_add_subgroup P.to_add_subgroup h hU
end submodule
namespace ideal
variables {R : Type*} [comm_ring R]
variables [topological_space R] [topological_ring R]
lemma is_open_of_open_subideal {U I : ideal R} (h : U ≤ I) (hU : is_open (U : set R)) :
is_open (I : set R) :=
submodule.is_open_mono h hU
end ideal
|
6b3c352580afcfdfafc9e86c4ebaa37eed746023 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/is_R_or_C/lemmas.lean | 93d976cb3acab79a8a0006d2369e3155f18d0314 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,728 | lean | /-
Copyright (c) 2020 Frédéric Dupuis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Frédéric Dupuis
-/
import analysis.normed_space.finite_dimension
import field_theory.tower
import data.is_R_or_C.basic
/-! # Further lemmas about `is_R_or_C`
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.-/
variables {K E : Type*} [is_R_or_C K]
namespace polynomial
open_locale polynomial
lemma of_real_eval (p : ℝ[X]) (x : ℝ) : (p.eval x : K) = aeval ↑x p :=
(@aeval_algebra_map_apply_eq_algebra_map_eval ℝ K _ _ _ x p).symm
end polynomial
namespace finite_dimensional
open_locale classical
open is_R_or_C
/-- This instance generates a type-class problem with a metavariable `?m` that should satisfy
`is_R_or_C ?m`. Since this can only be satisfied by `ℝ` or `ℂ`, this does not cause problems. -/
library_note "is_R_or_C instance"
/-- An `is_R_or_C` field is finite-dimensional over `ℝ`, since it is spanned by `{1, I}`. -/
@[nolint dangerous_instance] instance is_R_or_C_to_real : finite_dimensional ℝ K :=
⟨⟨{1, I},
begin
rw eq_top_iff,
intros a _,
rw [finset.coe_insert, finset.coe_singleton, submodule.mem_span_insert],
refine ⟨re a, (im a) • I, _, _⟩,
{ rw submodule.mem_span_singleton,
use im a },
simp [re_add_im a, algebra.smul_def, algebra_map_eq_of_real]
end⟩⟩
variables (K E) [normed_add_comm_group E] [normed_space K E]
/-- A finite dimensional vector space over an `is_R_or_C` is a proper metric space.
This is not an instance because it would cause a search for `finite_dimensional ?x E` before
`is_R_or_C ?x`. -/
lemma proper_is_R_or_C [finite_dimensional K E] : proper_space E :=
begin
letI : normed_space ℝ E := restrict_scalars.normed_space ℝ K E,
letI : finite_dimensional ℝ E := finite_dimensional.trans ℝ K E,
apply_instance
end
variable {E}
instance is_R_or_C.proper_space_submodule (S : submodule K E) [finite_dimensional K ↥S] :
proper_space S :=
proper_is_R_or_C K S
end finite_dimensional
namespace is_R_or_C
@[simp, is_R_or_C_simps] lemma re_clm_norm : ‖(re_clm : K →L[ℝ] ℝ)‖ = 1 :=
begin
apply le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _),
convert continuous_linear_map.ratio_le_op_norm _ (1 : K),
{ simp },
{ apply_instance }
end
@[simp, is_R_or_C_simps] lemma conj_cle_norm : ‖(@conj_cle K _ : K →L[ℝ] K)‖ = 1 :=
(@conj_lie K _).to_linear_isometry.norm_to_continuous_linear_map
@[simp, is_R_or_C_simps] lemma of_real_clm_norm : ‖(of_real_clm : ℝ →L[ℝ] K)‖ = 1 :=
linear_isometry.norm_to_continuous_linear_map of_real_li
end is_R_or_C
|
ae15d77d7c43baca3f5f3aba6f03c8814fb4d753 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/topology/homeomorph.lean | 1bda797af539909f7f4b1f6933d0e2a0f0d73775 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 9,771 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Patrick Massot, Sébastien Gouëzel, Zhouhang Zhou, Reid Barton
-/
import topology.dense_embedding
open set
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
/-- α and β are homeomorph, also called topological isomoph -/
structure homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β]
extends α ≃ β :=
(continuous_to_fun : continuous to_fun . tactic.interactive.continuity')
(continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity')
infix ` ≃ₜ `:25 := homeomorph
namespace homeomorph
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
instance : has_coe_to_fun (α ≃ₜ β) := ⟨λ_, α → β, λe, e.to_equiv⟩
@[simp] lemma homeomorph_mk_coe (a : equiv α β) (b c) :
((homeomorph.mk a b c) : α → β) = a :=
rfl
lemma coe_eq_to_equiv (h : α ≃ₜ β) (a : α) : h a = h.to_equiv a := rfl
/-- Identity map is a homeomorphism. -/
protected def refl (α : Type*) [topological_space α] : α ≃ₜ α :=
{ continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, .. equiv.refl α }
/-- Composition of two homeomorphisms. -/
protected def trans (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) : α ≃ₜ γ :=
{ continuous_to_fun := h₂.continuous_to_fun.comp h₁.continuous_to_fun,
continuous_inv_fun := h₁.continuous_inv_fun.comp h₂.continuous_inv_fun,
.. equiv.trans h₁.to_equiv h₂.to_equiv }
/-- Inverse of a homeomorphism. -/
protected def symm (h : α ≃ₜ β) : β ≃ₜ α :=
{ continuous_to_fun := h.continuous_inv_fun,
continuous_inv_fun := h.continuous_to_fun,
.. h.to_equiv.symm }
@[simp] lemma homeomorph_mk_coe_symm (a : equiv α β) (b c) :
((homeomorph.mk a b c).symm : β → α) = a.symm :=
rfl
@[continuity]
protected lemma continuous (h : α ≃ₜ β) : continuous h := h.continuous_to_fun
/-- Change the homeomorphism `f` to make the inverse function definitionally equal to `g`. -/
def change_inv (f : α ≃ₜ β) (g : β → α) (hg : function.right_inverse g f) : α ≃ₜ β :=
have g = f.symm, from funext (λ x, calc g x = f.symm (f (g x)) : (f.left_inv (g x)).symm
... = f.symm x : by rw hg x),
{ to_fun := f,
inv_fun := g,
left_inv := by convert f.left_inv,
right_inv := by convert f.right_inv,
continuous_to_fun := f.continuous,
continuous_inv_fun := by convert f.symm.continuous }
lemma symm_comp_self (h : α ≃ₜ β) : ⇑h.symm ∘ ⇑h = id :=
funext $ assume a, h.to_equiv.left_inv a
lemma self_comp_symm (h : α ≃ₜ β) : ⇑h ∘ ⇑h.symm = id :=
funext $ assume a, h.to_equiv.right_inv a
lemma range_coe (h : α ≃ₜ β) : range h = univ :=
eq_univ_of_forall $ assume b, ⟨h.symm b, congr_fun h.self_comp_symm b⟩
lemma image_symm (h : α ≃ₜ β) : image h.symm = preimage h :=
funext h.symm.to_equiv.image_eq_preimage
lemma preimage_symm (h : α ≃ₜ β) : preimage h.symm = image h :=
(funext h.to_equiv.image_eq_preimage).symm
lemma induced_eq
{α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (h : α ≃ₜ β) :
tβ.induced h = tα :=
le_antisymm
(calc topological_space.induced ⇑h tβ ≤ _ : induced_mono (coinduced_le_iff_le_induced.1 h.symm.continuous)
... ≤ tα : by rw [induced_compose, symm_comp_self, induced_id] ; exact le_refl _)
(coinduced_le_iff_le_induced.1 h.continuous)
lemma coinduced_eq
{α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (h : α ≃ₜ β) :
tα.coinduced h = tβ :=
le_antisymm
h.continuous
begin
have : (tβ.coinduced h.symm).coinduced h ≤ tα.coinduced h := coinduced_mono h.symm.continuous,
rwa [coinduced_compose, self_comp_symm, coinduced_id] at this,
end
protected lemma embedding (h : α ≃ₜ β) : embedding h :=
⟨⟨h.induced_eq.symm⟩, h.to_equiv.injective⟩
lemma compact_image {s : set α} (h : α ≃ₜ β) : is_compact (h '' s) ↔ is_compact s :=
h.embedding.compact_iff_compact_image.symm
lemma compact_preimage {s : set β} (h : α ≃ₜ β) : is_compact (h ⁻¹' s) ↔ is_compact s :=
by rw ← image_symm; exact h.symm.compact_image
protected lemma dense_embedding (h : α ≃ₜ β) : dense_embedding h :=
{ dense := assume a, by rw [h.range_coe, closure_univ]; trivial,
inj := h.to_equiv.injective,
induced := (induced_iff_nhds_eq _).2 (assume a, by rw [← nhds_induced, h.induced_eq]) }
protected lemma is_open_map (h : α ≃ₜ β) : is_open_map h :=
begin
assume s,
rw ← h.preimage_symm,
exact h.symm.continuous s
end
protected lemma is_closed_map (h : α ≃ₜ β) : is_closed_map h :=
begin
assume s,
rw ← h.preimage_symm,
exact continuous_iff_is_closed.1 (h.symm.continuous) _
end
@[simp] lemma is_open_preimage (h : α ≃ₜ β) {s : set β} : is_open (h ⁻¹' s) ↔ is_open s :=
begin
refine ⟨λ hs, _, h.continuous_to_fun s⟩,
rw [← (image_preimage_eq h.to_equiv.surjective : _ = s)], exact h.is_open_map _ hs
end
/-- If an bijective map `e : α ≃ β` is continuous and open, then it is a homeomorphism. -/
def homeomorph_of_continuous_open (e : α ≃ β) (h₁ : continuous e) (h₂ : is_open_map e) :
α ≃ₜ β :=
{ continuous_to_fun := h₁,
continuous_inv_fun := begin
intros s hs,
convert ← h₂ s hs using 1,
apply e.image_eq_preimage
end,
.. e }
lemma comp_continuous_on_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) :
continuous_on (h ∘ f) s ↔ continuous_on f s :=
begin
split,
{ assume H,
have : continuous_on (h.symm ∘ (h ∘ f)) s :=
h.symm.continuous.comp_continuous_on H,
rwa [← function.comp.assoc h.symm h f, symm_comp_self h] at this },
{ exact λ H, h.continuous.comp_continuous_on H }
end
lemma comp_continuous_iff (h : α ≃ₜ β) (f : γ → α) :
continuous (h ∘ f) ↔ continuous f :=
by simp [continuous_iff_continuous_on_univ, comp_continuous_on_iff]
protected lemma quotient_map (h : α ≃ₜ β) : quotient_map h :=
⟨h.to_equiv.surjective, h.coinduced_eq.symm⟩
/-- If two sets are equal, then they are homeomorphic. -/
def set_congr {s t : set α} (h : s = t) : s ≃ₜ t :=
{ continuous_to_fun := continuous_subtype_mk _ continuous_subtype_val,
continuous_inv_fun := continuous_subtype_mk _ continuous_subtype_val,
.. equiv.set_congr h }
/-- Sum of two homeomorphisms. -/
def sum_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α ⊕ γ ≃ₜ β ⊕ δ :=
{ continuous_to_fun :=
continuous_sum_rec (continuous_inl.comp h₁.continuous) (continuous_inr.comp h₂.continuous),
continuous_inv_fun :=
continuous_sum_rec (continuous_inl.comp h₁.symm.continuous) (continuous_inr.comp h₂.symm.continuous),
.. h₁.to_equiv.sum_congr h₂.to_equiv }
/-- Product of two homeomorphisms. -/
def prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α × γ ≃ₜ β × δ :=
{ continuous_to_fun :=
continuous.prod_mk (h₁.continuous.comp continuous_fst) (h₂.continuous.comp continuous_snd),
continuous_inv_fun :=
continuous.prod_mk (h₁.symm.continuous.comp continuous_fst) (h₂.symm.continuous.comp continuous_snd),
.. h₁.to_equiv.prod_congr h₂.to_equiv }
section
variables (α β γ)
/-- `α × β` is homeomorphic to `β × α`. -/
def prod_comm : α × β ≃ₜ β × α :=
{ continuous_to_fun := continuous.prod_mk continuous_snd continuous_fst,
continuous_inv_fun := continuous.prod_mk continuous_snd continuous_fst,
.. equiv.prod_comm α β }
/-- `(α × β) × γ` is homeomorphic to `α × (β × γ)`. -/
def prod_assoc : (α × β) × γ ≃ₜ α × (β × γ) :=
{ continuous_to_fun :=
continuous.prod_mk (continuous_fst.comp continuous_fst)
(continuous.prod_mk (continuous_snd.comp continuous_fst) continuous_snd),
continuous_inv_fun := continuous.prod_mk
(continuous.prod_mk continuous_fst (continuous_fst.comp continuous_snd))
(continuous_snd.comp continuous_snd),
.. equiv.prod_assoc α β γ }
end
/-- `ulift α` is homeomorphic to `α`. -/
def {u v} ulift {α : Type u} [topological_space α] : ulift.{v u} α ≃ₜ α :=
{ continuous_to_fun := continuous_ulift_down,
continuous_inv_fun := continuous_ulift_up,
.. equiv.ulift }
section distrib
/-- `(α ⊕ β) × γ` is homeomorphic to `α × γ ⊕ β × γ`. -/
def sum_prod_distrib : (α ⊕ β) × γ ≃ₜ α × γ ⊕ β × γ :=
homeomorph.symm $
homeomorph.homeomorph_of_continuous_open (equiv.sum_prod_distrib α β γ).symm
(continuous_sum_rec
((continuous_inl.comp continuous_fst).prod_mk continuous_snd)
((continuous_inr.comp continuous_fst).prod_mk continuous_snd))
(is_open_map_sum
(open_embedding_inl.prod open_embedding_id).is_open_map
(open_embedding_inr.prod open_embedding_id).is_open_map)
/-- `α × (β ⊕ γ)` is homeomorphic to `α × β ⊕ α × γ`. -/
def prod_sum_distrib : α × (β ⊕ γ) ≃ₜ α × β ⊕ α × γ :=
(prod_comm _ _).trans $
sum_prod_distrib.trans $
sum_congr (prod_comm _ _) (prod_comm _ _)
variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)]
/-- `(Σ i, σ i) × β` is homeomorphic to `Σ i, (σ i × β)`. -/
def sigma_prod_distrib : ((Σ i, σ i) × β) ≃ₜ (Σ i, (σ i × β)) :=
homeomorph.symm $
homeomorph_of_continuous_open (equiv.sigma_prod_distrib σ β).symm
(continuous_sigma $ λ i,
continuous.prod_mk (continuous_sigma_mk.comp continuous_fst) continuous_snd)
(is_open_map_sigma $ λ i,
(open_embedding.prod open_embedding_sigma_mk open_embedding_id).is_open_map)
end distrib
end homeomorph
|
6fabc65b6a306eea8dcc288dbce1cc3f0f2350fa | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/normed_space/compact_operator.lean | 3561553dd0bce697aa90ff746253b061aa23c706 | [
"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 | 22,379 | lean | /-
Copyright (c) 2022 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker
-/
import analysis.locally_convex.bounded
import topology.algebra.module.strong_topology
/-!
# Compact operators
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define compact linear operators between two topological vector spaces (TVS).
## Main definitions
* `is_compact_operator` : predicate for compact operators
## Main statements
* `is_compact_operator_iff_is_compact_closure_image_closed_ball` : the usual characterization of
compact operators from a normed space to a T2 TVS.
* `is_compact_operator.comp_clm` : precomposing a compact operator by a continuous linear map gives
a compact operator
* `is_compact_operator.clm_comp` : postcomposing a compact operator by a continuous linear map
gives a compact operator
* `is_compact_operator.continuous` : compact operators are automatically continuous
* `is_closed_set_of_is_compact_operator` : the set of compact operators is closed for the operator
norm
## Implementation details
We define `is_compact_operator` as a predicate, because the space of compact operators inherits all
of its structure from the space of continuous linear maps (e.g we want to have the usual operator
norm on compact operators).
The two natural options then would be to make it a predicate over linear maps or continuous linear
maps. Instead we define it as a predicate over bare functions, although it really only makes sense
for linear functions, because Lean is really good at finding coercions to bare functions (whereas
coercing from continuous linear maps to linear maps often needs type ascriptions).
## References
* Bourbaki, *Spectral Theory*, chapters 3 to 5, to be published (2022)
## Tags
Compact operator
-/
open function set filter bornology metric
open_locale pointwise big_operators topology
/-- A compact operator between two topological vector spaces. This definition is usually
given as "there exists a neighborhood of zero whose image is contained in a compact set",
but we choose a definition which involves fewer existential quantifiers and replaces images
with preimages.
We prove the equivalence in `is_compact_operator_iff_exists_mem_nhds_image_subset_compact`. -/
def is_compact_operator {M₁ M₂ : Type*} [has_zero M₁] [topological_space M₁]
[topological_space M₂] (f : M₁ → M₂) : Prop :=
∃ K, is_compact K ∧ f ⁻¹' K ∈ (𝓝 0 : filter M₁)
lemma is_compact_operator_zero {M₁ M₂ : Type*} [has_zero M₁] [topological_space M₁]
[topological_space M₂] [has_zero M₂] : is_compact_operator (0 : M₁ → M₂) :=
⟨{0}, is_compact_singleton, mem_of_superset univ_mem (λ x _, rfl)⟩
section characterizations
section
variables {R₁ R₂ : Type*} [semiring R₁] [semiring R₂] {σ₁₂ : R₁ →+* R₂} {M₁ M₂ : Type*}
[topological_space M₁] [add_comm_monoid M₁] [topological_space M₂]
lemma is_compact_operator_iff_exists_mem_nhds_image_subset_compact (f : M₁ → M₂) :
is_compact_operator f ↔ ∃ V ∈ (𝓝 0 : filter M₁), ∃ (K : set M₂), is_compact K ∧ f '' V ⊆ K :=
⟨λ ⟨K, hK, hKf⟩, ⟨f ⁻¹' K, hKf, K, hK, image_preimage_subset _ _⟩,
λ ⟨V, hV, K, hK, hVK⟩, ⟨K, hK, mem_of_superset hV (image_subset_iff.mp hVK)⟩⟩
lemma is_compact_operator_iff_exists_mem_nhds_is_compact_closure_image [t2_space M₂]
(f : M₁ → M₂) :
is_compact_operator f ↔ ∃ V ∈ (𝓝 0 : filter M₁), is_compact (closure $ f '' V) :=
begin
rw is_compact_operator_iff_exists_mem_nhds_image_subset_compact,
exact ⟨λ ⟨V, hV, K, hK, hKV⟩, ⟨V, hV, is_compact_closure_of_subset_compact hK hKV⟩,
λ ⟨V, hV, hVc⟩, ⟨V, hV, closure (f '' V), hVc, subset_closure⟩⟩,
end
end
section bounded
variables {𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁] [semi_normed_ring 𝕜₂] {σ₁₂ : 𝕜₁ →+* 𝕜₂}
{M₁ M₂ : Type*} [topological_space M₁] [add_comm_monoid M₁] [topological_space M₂]
[add_comm_monoid M₂] [module 𝕜₁ M₁] [module 𝕜₂ M₂] [has_continuous_const_smul 𝕜₂ M₂]
lemma is_compact_operator.image_subset_compact_of_vonN_bounded {f : M₁ →ₛₗ[σ₁₂] M₂}
(hf : is_compact_operator f) {S : set M₁} (hS : is_vonN_bounded 𝕜₁ S) :
∃ (K : set M₂), is_compact K ∧ f '' S ⊆ K :=
let ⟨K, hK, hKf⟩ := hf,
⟨r, hr, hrS⟩ := hS hKf,
⟨c, hc⟩ := normed_field.exists_lt_norm 𝕜₁ r,
this := ne_zero_of_norm_ne_zero (hr.trans hc).ne.symm in
⟨σ₁₂ c • K, hK.image $ continuous_id.const_smul (σ₁₂ c),
by rw [image_subset_iff, preimage_smul_setₛₗ _ _ _ f this.is_unit]; exact hrS c hc.le⟩
lemma is_compact_operator.is_compact_closure_image_of_vonN_bounded [t2_space M₂]
{f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) {S : set M₁}
(hS : is_vonN_bounded 𝕜₁ S) : is_compact (closure $ f '' S) :=
let ⟨K, hK, hKf⟩ := hf.image_subset_compact_of_vonN_bounded hS in
is_compact_closure_of_subset_compact hK hKf
end bounded
section normed_space
variables {𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁] [semi_normed_ring 𝕜₂] {σ₁₂ : 𝕜₁ →+* 𝕜₂}
{M₁ M₂ M₃ : Type*} [seminormed_add_comm_group M₁] [topological_space M₂]
[add_comm_monoid M₂] [normed_space 𝕜₁ M₁] [module 𝕜₂ M₂]
lemma is_compact_operator.image_subset_compact_of_bounded [has_continuous_const_smul 𝕜₂ M₂]
{f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) {S : set M₁} (hS : metric.bounded S) :
∃ (K : set M₂), is_compact K ∧ f '' S ⊆ K :=
hf.image_subset_compact_of_vonN_bounded
(by rwa [normed_space.is_vonN_bounded_iff, ← metric.bounded_iff_is_bounded])
lemma is_compact_operator.is_compact_closure_image_of_bounded [has_continuous_const_smul 𝕜₂ M₂]
[t2_space M₂] {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) {S : set M₁}
(hS : metric.bounded S) : is_compact (closure $ f '' S) :=
hf.is_compact_closure_image_of_vonN_bounded
(by rwa [normed_space.is_vonN_bounded_iff, ← metric.bounded_iff_is_bounded])
lemma is_compact_operator.image_ball_subset_compact [has_continuous_const_smul 𝕜₂ M₂]
{f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) (r : ℝ) :
∃ (K : set M₂), is_compact K ∧ f '' metric.ball 0 r ⊆ K :=
hf.image_subset_compact_of_vonN_bounded (normed_space.is_vonN_bounded_ball 𝕜₁ M₁ r)
lemma is_compact_operator.image_closed_ball_subset_compact [has_continuous_const_smul 𝕜₂ M₂]
{f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) (r : ℝ) :
∃ (K : set M₂), is_compact K ∧ f '' metric.closed_ball 0 r ⊆ K :=
hf.image_subset_compact_of_vonN_bounded (normed_space.is_vonN_bounded_closed_ball 𝕜₁ M₁ r)
lemma is_compact_operator.is_compact_closure_image_ball [has_continuous_const_smul 𝕜₂ M₂]
[t2_space M₂] {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) (r : ℝ) :
is_compact (closure $ f '' metric.ball 0 r) :=
hf.is_compact_closure_image_of_vonN_bounded (normed_space.is_vonN_bounded_ball 𝕜₁ M₁ r)
lemma is_compact_operator.is_compact_closure_image_closed_ball [has_continuous_const_smul 𝕜₂ M₂]
[t2_space M₂] {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) (r : ℝ) :
is_compact (closure $ f '' metric.closed_ball 0 r) :=
hf.is_compact_closure_image_of_vonN_bounded (normed_space.is_vonN_bounded_closed_ball 𝕜₁ M₁ r)
lemma is_compact_operator_iff_image_ball_subset_compact [has_continuous_const_smul 𝕜₂ M₂]
(f : M₁ →ₛₗ[σ₁₂] M₂) {r : ℝ} (hr : 0 < r) :
is_compact_operator f ↔ ∃ (K : set M₂), is_compact K ∧ f '' metric.ball 0 r ⊆ K :=
⟨λ hf, hf.image_ball_subset_compact r,
λ ⟨K, hK, hKr⟩, (is_compact_operator_iff_exists_mem_nhds_image_subset_compact f).mpr
⟨metric.ball 0 r, ball_mem_nhds _ hr, K, hK, hKr⟩⟩
lemma is_compact_operator_iff_image_closed_ball_subset_compact [has_continuous_const_smul 𝕜₂ M₂]
(f : M₁ →ₛₗ[σ₁₂] M₂) {r : ℝ} (hr : 0 < r) :
is_compact_operator f ↔ ∃ (K : set M₂), is_compact K ∧ f '' metric.closed_ball 0 r ⊆ K :=
⟨λ hf, hf.image_closed_ball_subset_compact r,
λ ⟨K, hK, hKr⟩, (is_compact_operator_iff_exists_mem_nhds_image_subset_compact f).mpr
⟨metric.closed_ball 0 r, closed_ball_mem_nhds _ hr, K, hK, hKr⟩⟩
lemma is_compact_operator_iff_is_compact_closure_image_ball [has_continuous_const_smul 𝕜₂ M₂]
[t2_space M₂] (f : M₁ →ₛₗ[σ₁₂] M₂) {r : ℝ} (hr : 0 < r) :
is_compact_operator f ↔ is_compact (closure $ f '' metric.ball 0 r) :=
⟨λ hf, hf.is_compact_closure_image_ball r,
λ hf, (is_compact_operator_iff_exists_mem_nhds_is_compact_closure_image f).mpr
⟨metric.ball 0 r, ball_mem_nhds _ hr, hf⟩⟩
lemma is_compact_operator_iff_is_compact_closure_image_closed_ball
[has_continuous_const_smul 𝕜₂ M₂] [t2_space M₂] (f : M₁ →ₛₗ[σ₁₂] M₂) {r : ℝ} (hr : 0 < r) :
is_compact_operator f ↔ is_compact (closure $ f '' metric.closed_ball 0 r) :=
⟨λ hf, hf.is_compact_closure_image_closed_ball r,
λ hf, (is_compact_operator_iff_exists_mem_nhds_is_compact_closure_image f).mpr
⟨metric.closed_ball 0 r, closed_ball_mem_nhds _ hr, hf⟩⟩
end normed_space
end characterizations
section operations
variables {R₁ R₂ R₃ R₄ : Type*} [semiring R₁] [semiring R₂] [comm_semiring R₃] [comm_semiring R₄]
{σ₁₂ : R₁ →+* R₂} {σ₁₄ : R₁ →+* R₄} {σ₃₄ : R₃ →+* R₄} {M₁ M₂ M₃ M₄ : Type*}
[topological_space M₁] [add_comm_monoid M₁] [topological_space M₂] [add_comm_monoid M₂]
[topological_space M₃] [add_comm_group M₃] [topological_space M₄] [add_comm_group M₄]
lemma is_compact_operator.smul {S : Type*} [monoid S] [distrib_mul_action S M₂]
[has_continuous_const_smul S M₂] {f : M₁ → M₂}
(hf : is_compact_operator f) (c : S) :
is_compact_operator (c • f) :=
let ⟨K, hK, hKf⟩ := hf in ⟨c • K, hK.image $ continuous_id.const_smul c,
mem_of_superset hKf (λ x hx, smul_mem_smul_set hx)⟩
lemma is_compact_operator.add [has_continuous_add M₂] {f g : M₁ → M₂}
(hf : is_compact_operator f) (hg : is_compact_operator g) :
is_compact_operator (f + g) :=
let ⟨A, hA, hAf⟩ := hf, ⟨B, hB, hBg⟩ := hg in
⟨A + B, hA.add hB, mem_of_superset (inter_mem hAf hBg) (λ x ⟨hxA, hxB⟩, set.add_mem_add hxA hxB)⟩
lemma is_compact_operator.neg [has_continuous_neg M₄] {f : M₁ → M₄}
(hf : is_compact_operator f) : is_compact_operator (-f) :=
let ⟨K, hK, hKf⟩ := hf in
⟨-K, hK.neg, mem_of_superset hKf $ λ x (hx : f x ∈ K), set.neg_mem_neg.mpr hx⟩
lemma is_compact_operator.sub [topological_add_group M₄] {f g : M₁ → M₄}
(hf : is_compact_operator f) (hg : is_compact_operator g) : is_compact_operator (f - g) :=
by rw sub_eq_add_neg; exact hf.add hg.neg
variables (σ₁₄ M₁ M₄)
/-- The submodule of compact continuous linear maps. -/
def compact_operator [module R₁ M₁] [module R₄ M₄] [has_continuous_const_smul R₄ M₄]
[topological_add_group M₄] :
submodule R₄ (M₁ →SL[σ₁₄] M₄) :=
{ carrier := {f | is_compact_operator f},
add_mem' := λ f g hf hg, hf.add hg,
zero_mem' := is_compact_operator_zero,
smul_mem' := λ c f hf, hf.smul c }
end operations
section comp
variables {R₁ R₂ R₃ : Type*} [semiring R₁] [semiring R₂] [semiring R₃] {σ₁₂ : R₁ →+* R₂}
{σ₂₃ : R₂ →+* R₃} {M₁ M₂ M₃ : Type*} [topological_space M₁] [topological_space M₂]
[topological_space M₃] [add_comm_monoid M₁] [module R₁ M₁]
lemma is_compact_operator.comp_clm [add_comm_monoid M₂] [module R₂ M₂] {f : M₂ → M₃}
(hf : is_compact_operator f) (g : M₁ →SL[σ₁₂] M₂) :
is_compact_operator (f ∘ g) :=
begin
have := g.continuous.tendsto 0,
rw map_zero at this,
rcases hf with ⟨K, hK, hKf⟩,
exact ⟨K, hK, this hKf⟩
end
lemma is_compact_operator.continuous_comp {f : M₁ → M₂} (hf : is_compact_operator f) {g : M₂ → M₃}
(hg : continuous g) :
is_compact_operator (g ∘ f) :=
begin
rcases hf with ⟨K, hK, hKf⟩,
refine ⟨g '' K, hK.image hg, mem_of_superset hKf _⟩,
nth_rewrite 1 preimage_comp,
exact preimage_mono (subset_preimage_image _ _)
end
lemma is_compact_operator.clm_comp [add_comm_monoid M₂] [module R₂ M₂] [add_comm_monoid M₃]
[module R₃ M₃] {f : M₁ → M₂} (hf : is_compact_operator f) (g : M₂ →SL[σ₂₃] M₃) :
is_compact_operator (g ∘ f) :=
hf.continuous_comp g.continuous
end comp
section cod_restrict
variables {R₁ R₂ : Type*} [semiring R₁] [semiring R₂] {σ₁₂ : R₁ →+* R₂}
{M₁ M₂ : Type*} [topological_space M₁] [topological_space M₂]
[add_comm_monoid M₁] [add_comm_monoid M₂] [module R₁ M₁] [module R₂ M₂]
lemma is_compact_operator.cod_restrict {f : M₁ → M₂} (hf : is_compact_operator f)
{V : submodule R₂ M₂} (hV : ∀ x, f x ∈ V) (h_closed : is_closed (V : set M₂)):
is_compact_operator (set.cod_restrict f V hV) :=
let ⟨K, hK, hKf⟩ := hf in
⟨coe ⁻¹' K, (closed_embedding_subtype_coe h_closed).is_compact_preimage hK, hKf⟩
end cod_restrict
section restrict
variables {R₁ R₂ R₃ : Type*} [semiring R₁] [semiring R₂] [semiring R₃] {σ₁₂ : R₁ →+* R₂}
{σ₂₃ : R₂ →+* R₃} {M₁ M₂ M₃ : Type*} [topological_space M₁] [uniform_space M₂]
[topological_space M₃] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₃]
[module R₁ M₁] [module R₂ M₂] [module R₃ M₃]
/-- If a compact operator preserves a closed submodule, its restriction to that submodule is
compact.
Note that, following mathlib's convention in linear algebra, `restrict` designates the restriction
of an endomorphism `f : E →ₗ E` to an endomorphism `f' : ↥V →ₗ ↥V`. To prove that the restriction
`f' : ↥U →ₛₗ ↥V` of a compact operator `f : E →ₛₗ F` is compact, apply
`is_compact_operator.cod_restrict` to `f ∘ U.subtypeL`, which is compact by
`is_compact_operator.comp_clm`. -/
lemma is_compact_operator.restrict {f : M₁ →ₗ[R₁] M₁} (hf : is_compact_operator f)
{V : submodule R₁ M₁} (hV : ∀ v ∈ V, f v ∈ V) (h_closed : is_closed (V : set M₁)):
is_compact_operator (f.restrict hV) :=
(hf.comp_clm V.subtypeL).cod_restrict (set_like.forall.2 hV) h_closed
/-- If a compact operator preserves a complete submodule, its restriction to that submodule is
compact.
Note that, following mathlib's convention in linear algebra, `restrict` designates the restriction
of an endomorphism `f : E →ₗ E` to an endomorphism `f' : ↥V →ₗ ↥V`. To prove that the restriction
`f' : ↥U →ₛₗ ↥V` of a compact operator `f : E →ₛₗ F` is compact, apply
`is_compact_operator.cod_restrict` to `f ∘ U.subtypeL`, which is compact by
`is_compact_operator.comp_clm`. -/
lemma is_compact_operator.restrict' [separated_space M₂] {f : M₂ →ₗ[R₂] M₂}
(hf : is_compact_operator f) {V : submodule R₂ M₂} (hV : ∀ v ∈ V, f v ∈ V)
[hcomplete : complete_space V] : is_compact_operator (f.restrict hV) :=
hf.restrict hV (complete_space_coe_iff_is_complete.mp hcomplete).is_closed
end restrict
section continuous
variables {𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁] [nontrivially_normed_field 𝕜₂]
{σ₁₂ : 𝕜₁ →+* 𝕜₂} [ring_hom_isometric σ₁₂] {M₁ M₂ : Type*} [topological_space M₁]
[add_comm_group M₁] [topological_space M₂] [add_comm_group M₂] [module 𝕜₁ M₁] [module 𝕜₂ M₂]
[topological_add_group M₁] [has_continuous_const_smul 𝕜₁ M₁]
[topological_add_group M₂] [has_continuous_smul 𝕜₂ M₂]
@[continuity] lemma is_compact_operator.continuous {f : M₁ →ₛₗ[σ₁₂] M₂}
(hf : is_compact_operator f) : continuous f :=
begin
letI : uniform_space M₂ := topological_add_group.to_uniform_space _,
haveI : uniform_add_group M₂ := topological_add_comm_group_is_uniform,
-- Since `f` is linear, we only need to show that it is continuous at zero.
-- Let `U` be a neighborhood of `0` in `M₂`.
refine continuous_of_continuous_at_zero f (λ U hU, _),
rw map_zero at hU,
-- The compactness of `f` gives us a compact set `K : set M₂` such that `f ⁻¹' K` is a
-- neighborhood of `0` in `M₁`.
rcases hf with ⟨K, hK, hKf⟩,
-- But any compact set is totally bounded, hence Von-Neumann bounded. Thus, `K` absorbs `U`.
-- This gives `r > 0` such that `∀ a : 𝕜₂, r ≤ ‖a‖ → K ⊆ a • U`.
rcases hK.totally_bounded.is_vonN_bounded 𝕜₂ hU with ⟨r, hr, hrU⟩,
-- Choose `c : 𝕜₂` with `r < ‖c‖`.
rcases normed_field.exists_lt_norm 𝕜₁ r with ⟨c, hc⟩,
have hcnz : c ≠ 0 := ne_zero_of_norm_ne_zero (hr.trans hc).ne.symm,
-- We have `f ⁻¹' ((σ₁₂ c⁻¹) • K) = c⁻¹ • f ⁻¹' K ∈ 𝓝 0`. Thus, showing that
-- `(σ₁₂ c⁻¹) • K ⊆ U` is enough to deduce that `f ⁻¹' U ∈ 𝓝 0`.
suffices : (σ₁₂ $ c⁻¹) • K ⊆ U,
{ refine mem_of_superset _ this,
have : is_unit c⁻¹ := hcnz.is_unit.inv,
rwa [mem_map, preimage_smul_setₛₗ _ _ _ f this, set_smul_mem_nhds_zero_iff (inv_ne_zero hcnz)],
apply_instance },
-- Since `σ₁₂ c⁻¹` = `(σ₁₂ c)⁻¹`, we have to prove that `K ⊆ σ₁₂ c • U`.
rw [map_inv₀, ← subset_set_smul_iff₀ ((map_ne_zero σ₁₂).mpr hcnz)],
-- But `σ₁₂` is isometric, so `‖σ₁₂ c‖ = ‖c‖ > r`, which concludes the argument since
-- `∀ a : 𝕜₂, r ≤ ‖a‖ → K ⊆ a • U`.
refine hrU (σ₁₂ c) _,
rw ring_hom_isometric.is_iso,
exact hc.le
end
/-- Upgrade a compact `linear_map` to a `continuous_linear_map`. -/
def continuous_linear_map.mk_of_is_compact_operator {f : M₁ →ₛₗ[σ₁₂] M₂}
(hf : is_compact_operator f) : M₁ →SL[σ₁₂] M₂ :=
⟨f, hf.continuous⟩
@[simp] lemma continuous_linear_map.mk_of_is_compact_operator_to_linear_map {f : M₁ →ₛₗ[σ₁₂] M₂}
(hf : is_compact_operator f) :
(continuous_linear_map.mk_of_is_compact_operator hf : M₁ →ₛₗ[σ₁₂] M₂) = f :=
rfl
@[simp] lemma continuous_linear_map.coe_mk_of_is_compact_operator {f : M₁ →ₛₗ[σ₁₂] M₂}
(hf : is_compact_operator f) :
(continuous_linear_map.mk_of_is_compact_operator hf : M₁ → M₂) = f :=
rfl
lemma continuous_linear_map.mk_of_is_compact_operator_mem_compact_operator {f : M₁ →ₛₗ[σ₁₂] M₂}
(hf : is_compact_operator f) :
continuous_linear_map.mk_of_is_compact_operator hf ∈ compact_operator σ₁₂ M₁ M₂ :=
hf
end continuous
/-- The set of compact operators from a normed space to a complete topological vector space is
closed. -/
lemma is_closed_set_of_is_compact_operator {𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁]
[normed_field 𝕜₂] {σ₁₂ : 𝕜₁ →+* 𝕜₂} {M₁ M₂ : Type*} [seminormed_add_comm_group M₁]
[add_comm_group M₂] [normed_space 𝕜₁ M₁] [module 𝕜₂ M₂] [uniform_space M₂] [uniform_add_group M₂]
[has_continuous_const_smul 𝕜₂ M₂] [t2_space M₂] [complete_space M₂] :
is_closed {f : M₁ →SL[σ₁₂] M₂ | is_compact_operator f} :=
begin
refine is_closed_of_closure_subset _,
rintros u hu,
rw [mem_closure_iff_nhds_zero] at hu,
suffices : totally_bounded (u '' metric.closed_ball 0 1),
{ change is_compact_operator (u : M₁ →ₛₗ[σ₁₂] M₂),
rw is_compact_operator_iff_is_compact_closure_image_closed_ball (u : M₁ →ₛₗ[σ₁₂] M₂)
zero_lt_one,
exact is_compact_of_totally_bounded_is_closed this.closure is_closed_closure },
rw totally_bounded_iff_subset_finite_Union_nhds_zero,
intros U hU,
rcases exists_nhds_zero_half hU with ⟨V, hV, hVU⟩,
let SV : set M₁ × set M₂ := ⟨closed_ball 0 1, -V⟩,
rcases hu {f | ∀ x ∈ SV.1, f x ∈ SV.2} (continuous_linear_map.has_basis_nhds_zero.mem_of_mem
⟨normed_space.is_vonN_bounded_closed_ball _ _ _, neg_mem_nhds_zero M₂ hV⟩) with ⟨v, hv, huv⟩,
rcases totally_bounded_iff_subset_finite_Union_nhds_zero.mp
(hv.is_compact_closure_image_closed_ball 1).totally_bounded V hV with ⟨T, hT, hTv⟩,
have hTv : v '' closed_ball 0 1 ⊆ _ := subset_closure.trans hTv,
refine ⟨T, hT, _⟩,
rw [image_subset_iff, preimage_Union₂] at ⊢ hTv,
intros x hx,
specialize hTv hx,
rw [mem_Union₂] at ⊢ hTv,
rcases hTv with ⟨t, ht, htx⟩,
refine ⟨t, ht, _⟩,
rw [mem_preimage, mem_vadd_set_iff_neg_vadd_mem, vadd_eq_add, neg_add_eq_sub] at ⊢ htx,
convert hVU _ htx _ (huv x hx) using 1,
rw [continuous_linear_map.sub_apply],
abel
end
lemma compact_operator_topological_closure {𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁]
[normed_field 𝕜₂] {σ₁₂ : 𝕜₁ →+* 𝕜₂} {M₁ M₂ : Type*}
[seminormed_add_comm_group M₁] [add_comm_group M₂] [normed_space 𝕜₁ M₁] [module 𝕜₂ M₂]
[uniform_space M₂] [uniform_add_group M₂] [has_continuous_const_smul 𝕜₂ M₂] [t2_space M₂]
[complete_space M₂] [has_continuous_smul 𝕜₂ (M₁ →SL[σ₁₂] M₂)] :
(compact_operator σ₁₂ M₁ M₂).topological_closure = compact_operator σ₁₂ M₁ M₂ :=
set_like.ext' (is_closed_set_of_is_compact_operator.closure_eq)
lemma is_compact_operator_of_tendsto {ι 𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁]
[normed_field 𝕜₂] {σ₁₂ : 𝕜₁ →+* 𝕜₂} {M₁ M₂ : Type*}
[seminormed_add_comm_group M₁] [add_comm_group M₂] [normed_space 𝕜₁ M₁] [module 𝕜₂ M₂]
[uniform_space M₂] [uniform_add_group M₂] [has_continuous_const_smul 𝕜₂ M₂] [t2_space M₂]
[complete_space M₂] {l : filter ι} [l.ne_bot] {F : ι → M₁ →SL[σ₁₂] M₂} {f : M₁ →SL[σ₁₂] M₂}
(hf : tendsto F l (𝓝 f)) (hF : ∀ᶠ i in l, is_compact_operator (F i)) :
is_compact_operator f :=
is_closed_set_of_is_compact_operator.mem_of_tendsto hf hF
|
3aaa2004a6c8dee83d98bcbfda1805ed3218d9d7 | 618003631150032a5676f229d13a079ac875ff77 | /src/logic/relator.lean | 9b1e6c39071a16db5d57187beffc67026e1716a4 | [
"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 | 3,831 | 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
Relator for functions, pairs, sums, and lists.
-/
namespace relator
universe variables u₁ u₂ v₁ v₂
reserve infixr ` ⇒ `:40
/- TODO(johoelzl):
* should we introduce relators of datatypes as recursive function or as inductive
predicate? For now we stick to the recursor approach.
* relation lift for datatypes, Π, Σ, set, and subtype types
* proof composition and identity laws
* implement method to derive relators from datatype
-/
section
variables {α : Sort u₁} {β : Sort u₂} {γ : Sort v₁} {δ : Sort v₂}
variables (R : α → β → Prop) (S : γ → δ → Prop)
def lift_fun (f : α → γ) (g : β → δ) : Prop :=
∀⦃a b⦄, R a b → S (f a) (g b)
infixr ⇒ := lift_fun
end
section
variables {α : Type u₁} {β : out_param $ Type u₂} (R : out_param $ α → β → Prop)
@[class] def right_total := ∀b, ∃a, R a b
@[class] def left_total := ∀a, ∃b, R a b
@[class] def bi_total := left_total R ∧ right_total R
end
section
variables {α : Type u₁} {β : Type u₂} (R : α → β → Prop)
@[class] def left_unique := ∀{a b c}, R a b → R c b → a = c
@[class] def right_unique := ∀{a b c}, R a b → R a c → b = c
lemma rel_forall_of_right_total [t : right_total R] : ((R ⇒ implies) ⇒ implies) (λp, ∀i, p i) (λq, ∀i, q i) :=
assume p q Hrel H b, exists.elim (t b) (assume a Rab, Hrel Rab (H _))
lemma rel_exists_of_left_total [t : left_total R] : ((R ⇒ implies) ⇒ implies) (λp, ∃i, p i) (λq, ∃i, q i) :=
assume p q Hrel ⟨a, pa⟩, let ⟨b, Rab⟩ := t a in ⟨b, Hrel Rab pa⟩
lemma rel_forall_of_total [t : bi_total R] : ((R ⇒ iff) ⇒ iff) (λp, ∀i, p i) (λq, ∀i, q i) :=
assume p q Hrel,
⟨assume H b, exists.elim (t.right b) (assume a Rab, (Hrel Rab).mp (H _)),
assume H a, exists.elim (t.left a) (assume b Rab, (Hrel Rab).mpr (H _))⟩
lemma rel_exists_of_total [t : bi_total R] : ((R ⇒ iff) ⇒ iff) (λp, ∃i, p i) (λq, ∃i, q i) :=
assume p q Hrel,
⟨assume ⟨a, pa⟩, let ⟨b, Rab⟩ := t.left a in ⟨b, (Hrel Rab).1 pa⟩,
assume ⟨b, qb⟩, let ⟨a, Rab⟩ := t.right b in ⟨a, (Hrel Rab).2 qb⟩⟩
lemma left_unique_of_rel_eq {eq' : β → β → Prop} (he : (R ⇒ (R ⇒ iff)) eq eq') : left_unique R
| a b c (ab : R a b) (cb : R c b) :=
have eq' b b,
from iff.mp (he ab ab) rfl,
iff.mpr (he ab cb) this
end
lemma rel_imp : (iff ⇒ (iff ⇒ iff)) implies implies :=
assume p q h r s l, imp_congr h l
lemma rel_not : (iff ⇒ iff) not not :=
assume p q h, not_congr h
@[priority 100] -- see Note [lower instance priority]
-- (this is an instance is always applies, since the relation is an out-param)
instance bi_total_eq {α : Type u₁} : relator.bi_total (@eq α) :=
⟨assume a, ⟨a, rfl⟩, assume a, ⟨a, rfl⟩⟩
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
variables {r : α → β → Prop} {p : β → γ → Prop} {q : γ → δ → Prop}
def bi_unique (r : α → β → Prop) : Prop := left_unique r ∧ right_unique r
lemma left_unique_flip (h : left_unique r) : right_unique (flip r)
| a b c h₁ h₂ := h h₁ h₂
lemma rel_and : ((↔) ⇒ (↔) ⇒ (↔)) (∧) (∧) :=
assume a b h₁ c d h₂, and_congr h₁ h₂
lemma rel_or : ((↔) ⇒ (↔) ⇒ (↔)) (∨) (∨) :=
assume a b h₁ c d h₂, or_congr h₁ h₂
lemma rel_iff : ((↔) ⇒ (↔) ⇒ (↔)) (↔) (↔) :=
assume a b h₁ c d h₂, iff_congr h₁ h₂
lemma rel_eq {r : α → β → Prop} (hr : bi_unique r) : (r ⇒ r ⇒ (↔)) (=) (=) :=
assume a b h₁ c d h₂,
iff.intro
begin intro h, subst h, exact hr.right h₁ h₂ end
begin intro h, subst h, exact hr.left h₁ h₂ end
end relator
|
5d11b8b39887388bf0ce853226a395624ab51124 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/topology/metric_space/gluing.lean | e294f78628db1ea733ef517814fa6ef3987d9677 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 23,684 | 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 topology.metric_space.isometry
/-!
# Metric space gluing
Gluing two metric spaces along a common subset. Formally, we are given
```
Φ
Z ---> X
|
|Ψ
v
Y
```
where `hΦ : isometry Φ` and `hΨ : isometry Ψ`.
We want to complete the square by a space `glue_space hΦ hΨ` and two isometries
`to_glue_l hΦ hΨ` and `to_glue_r hΦ hΨ` that make the square commute.
We start by defining a predistance on the disjoint union `X ⊕ Y`, for which
points `Φ p` and `Ψ p` are at distance 0. The (quotient) metric space associated
to this predistance is the desired space.
This is an instance of a more general construction, where `Φ` and `Ψ` do not have to be isometries,
but the distances in the image almost coincide, up to `2ε` say. Then one can almost glue the two
spaces so that the images of a point under `Φ` and `Ψ` are `ε`-close. If `ε > 0`, this yields a
metric space structure on `X ⊕ Y`, without the need to take a quotient. In particular, when `X`
and `Y` are inhabited, this gives a natural metric space structure on `X ⊕ Y`, where the basepoints
are at distance 1, say, and the distances between other points are obtained by going through the two
basepoints.
We also define the inductive limit of metric spaces. Given
```
f 0 f 1 f 2 f 3
X 0 -----> X 1 -----> X 2 -----> X 3 -----> ...
```
where the `X n` are metric spaces and `f n` isometric embeddings, we define the inductive
limit of the `X n`, also known as the increasing union of the `X n` in this context, if we
identify `X n` and `X (n+1)` through `f n`. This is a metric space in which all `X n` embed
isometrically and in a way compatible with `f n`.
-/
noncomputable theory
universes u v w
open function set
open_locale uniformity
namespace metric
section approx_gluing
variables {X : Type u} {Y : Type v} {Z : Type w}
variables [metric_space X] [metric_space Y]
{Φ : Z → X} {Ψ : Z → Y} {ε : ℝ}
open _root_.sum (inl inr)
/-- Define a predistance on `X ⊕ Y`, for which `Φ p` and `Ψ p` are at distance `ε` -/
def glue_dist (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) : X ⊕ Y → X ⊕ Y → ℝ
| (inl x) (inl y) := dist x y
| (inr x) (inr y) := dist x y
| (inl x) (inr y) := (⨅ p, dist x (Φ p) + dist y (Ψ p)) + ε
| (inr x) (inl y) := (⨅ p, dist y (Φ p) + dist x (Ψ p)) + ε
private lemma glue_dist_self (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) : ∀ x, glue_dist Φ Ψ ε x x = 0
| (inl x) := dist_self _
| (inr x) := dist_self _
lemma glue_dist_glued_points [nonempty Z] (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) (p : Z) :
glue_dist Φ Ψ ε (inl (Φ p)) (inr (Ψ p)) = ε :=
begin
have : (⨅ q, dist (Φ p) (Φ q) + dist (Ψ p) (Ψ q)) = 0,
{ have A : ∀ q, 0 ≤ dist (Φ p) (Φ q) + dist (Ψ p) (Ψ q) :=
λq, by rw ← add_zero (0 : ℝ); exact add_le_add dist_nonneg dist_nonneg,
refine le_antisymm _ (le_cinfi A),
have : 0 = dist (Φ p) (Φ p) + dist (Ψ p) (Ψ p), by simp,
rw this,
exact cinfi_le ⟨0, forall_range_iff.2 A⟩ p },
rw [glue_dist, this, zero_add]
end
private lemma glue_dist_comm (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) :
∀ x y, glue_dist Φ Ψ ε x y = glue_dist Φ Ψ ε y x
| (inl x) (inl y) := dist_comm _ _
| (inr x) (inr y) := dist_comm _ _
| (inl x) (inr y) := rfl
| (inr x) (inl y) := rfl
variable [nonempty Z]
private lemma glue_dist_triangle (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ)
(H : ∀ p q, |dist (Φ p) (Φ q) - dist (Ψ p) (Ψ q)| ≤ 2 * ε) :
∀ x y z, glue_dist Φ Ψ ε x z ≤ glue_dist Φ Ψ ε x y + glue_dist Φ Ψ ε y z
| (inl x) (inl y) (inl z) := dist_triangle _ _ _
| (inr x) (inr y) (inr z) := dist_triangle _ _ _
| (inr x) (inl y) (inl z) := begin
have B : ∀ a b, bdd_below (range (λ (p : Z), dist a (Φ p) + dist b (Ψ p))) :=
λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩,
unfold glue_dist,
have : (⨅ p, dist z (Φ p) + dist x (Ψ p)) ≤ (⨅ p, dist y (Φ p) + dist x (Ψ p)) + dist y z,
{ have : (⨅ p, dist y (Φ p) + dist x (Ψ p)) + dist y z =
infi ((λt, t + dist y z) ∘ (λp, dist y (Φ p) + dist x (Ψ p))),
{ refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _
(B _ _),
intros x y hx, simpa },
rw [this, comp],
refine cinfi_le_cinfi (B _ _) (λp, _),
calc
dist z (Φ p) + dist x (Ψ p) ≤ (dist y z + dist y (Φ p)) + dist x (Ψ p) :
add_le_add (dist_triangle_left _ _ _) le_rfl
... = dist y (Φ p) + dist x (Ψ p) + dist y z : by ring },
linarith
end
| (inr x) (inr y) (inl z) := begin
have B : ∀ a b, bdd_below (range (λ (p : Z), dist a (Φ p) + dist b (Ψ p))) :=
λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩,
unfold glue_dist,
have : (⨅ p, dist z (Φ p) + dist x (Ψ p)) ≤ dist x y + ⨅ p, dist z (Φ p) + dist y (Ψ p),
{ have : dist x y + (⨅ p, dist z (Φ p) + dist y (Ψ p)) =
infi ((λt, dist x y + t) ∘ (λp, dist z (Φ p) + dist y (Ψ p))),
{ refine map_cinfi_of_continuous_at_of_monotone (continuous_at_const.add continuous_at_id) _
(B _ _),
intros x y hx, simpa },
rw [this, comp],
refine cinfi_le_cinfi (B _ _) (λp, _),
calc
dist z (Φ p) + dist x (Ψ p) ≤ dist z (Φ p) + (dist x y + dist y (Ψ p)) :
add_le_add le_rfl (dist_triangle _ _ _)
... = dist x y + (dist z (Φ p) + dist y (Ψ p)) : by ring },
linarith
end
| (inl x) (inl y) (inr z) := begin
have B : ∀ a b, bdd_below (range (λ (p : Z), dist a (Φ p) + dist b (Ψ p))) :=
λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩,
unfold glue_dist,
have : (⨅ p, dist x (Φ p) + dist z (Ψ p)) ≤ dist x y + ⨅ p, dist y (Φ p) + dist z (Ψ p),
{ have : dist x y + (⨅ p, dist y (Φ p) + dist z (Ψ p)) =
infi ((λt, dist x y + t) ∘ (λp, dist y (Φ p) + dist z (Ψ p))),
{ refine map_cinfi_of_continuous_at_of_monotone (continuous_at_const.add continuous_at_id) _
(B _ _),
intros x y hx, simpa },
rw [this, comp],
refine cinfi_le_cinfi (B _ _) (λp, _),
calc
dist x (Φ p) + dist z (Ψ p) ≤ (dist x y + dist y (Φ p)) + dist z (Ψ p) :
add_le_add (dist_triangle _ _ _) le_rfl
... = dist x y + (dist y (Φ p) + dist z (Ψ p)) : by ring },
linarith
end
| (inl x) (inr y) (inr z) := begin
have B : ∀ a b, bdd_below (range (λ (p : Z), dist a (Φ p) + dist b (Ψ p))) :=
λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩,
unfold glue_dist,
have : (⨅ p, dist x (Φ p) + dist z (Ψ p)) ≤ (⨅ p, dist x (Φ p) + dist y (Ψ p)) + dist y z,
{ have : (⨅ p, dist x (Φ p) + dist y (Ψ p)) + dist y z =
infi ((λt, t + dist y z) ∘ (λp, dist x (Φ p) + dist y (Ψ p))),
{ refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _
(B _ _),
intros x y hx, simpa },
rw [this, comp],
refine cinfi_le_cinfi (B _ _) (λp, _),
calc
dist x (Φ p) + dist z (Ψ p) ≤ dist x (Φ p) + (dist y z + dist y (Ψ p)) :
add_le_add le_rfl (dist_triangle_left _ _ _)
... = dist x (Φ p) + dist y (Ψ p) + dist y z : by ring },
linarith
end
| (inl x) (inr y) (inl z) := le_of_forall_pos_le_add $ λδ δpos, begin
obtain ⟨p, hp⟩ : ∃ p, dist x (Φ p) + dist y (Ψ p) < (⨅ p, dist x (Φ p) + dist y (Ψ p)) + δ / 2,
from exists_lt_of_cinfi_lt (by linarith),
obtain ⟨q, hq⟩ : ∃ q, dist z (Φ q) + dist y (Ψ q) < (⨅ p, dist z (Φ p) + dist y (Ψ p)) + δ / 2,
from exists_lt_of_cinfi_lt (by linarith),
have : dist (Φ p) (Φ q) ≤ dist (Ψ p) (Ψ q) + 2 * ε,
{ have := le_trans (le_abs_self _) (H p q), by linarith },
calc dist x z ≤ dist x (Φ p) + dist (Φ p) (Φ q) + dist (Φ q) z : dist_triangle4 _ _ _ _
... ≤ dist x (Φ p) + dist (Ψ p) (Ψ q) + dist z (Φ q) + 2 * ε : by rw [dist_comm z]; linarith
... ≤ dist x (Φ p) + (dist y (Ψ p) + dist y (Ψ q)) + dist z (Φ q) + 2 * ε :
add_le_add (add_le_add (add_le_add le_rfl (dist_triangle_left _ _ _)) le_rfl) le_rfl
... ≤ ((⨅ p, dist x (Φ p) + dist y (Ψ p)) + ε) +
((⨅ p, dist z (Φ p) + dist y (Ψ p)) + ε) + δ : by linarith
end
| (inr x) (inl y) (inr z) := le_of_forall_pos_le_add $ λδ δpos, begin
obtain ⟨p, hp⟩ : ∃ p, dist y (Φ p) + dist x (Ψ p) < (⨅ p, dist y (Φ p) + dist x (Ψ p)) + δ / 2,
from exists_lt_of_cinfi_lt (by linarith),
obtain ⟨q, hq⟩ : ∃ q, dist y (Φ q) + dist z (Ψ q) < (⨅ p, dist y (Φ p) + dist z (Ψ p)) + δ / 2,
from exists_lt_of_cinfi_lt (by linarith),
have : dist (Ψ p) (Ψ q) ≤ dist (Φ p) (Φ q) + 2 * ε,
{ have := le_trans (neg_le_abs_self _) (H p q), by linarith },
calc dist x z ≤ dist x (Ψ p) + dist (Ψ p) (Ψ q) + dist (Ψ q) z : dist_triangle4 _ _ _ _
... ≤ dist x (Ψ p) + dist (Φ p) (Φ q) + dist z (Ψ q) + 2 * ε : by rw [dist_comm z]; linarith
... ≤ dist x (Ψ p) + (dist y (Φ p) + dist y (Φ q)) + dist z (Ψ q) + 2 * ε :
add_le_add (add_le_add (add_le_add le_rfl (dist_triangle_left _ _ _)) le_rfl) le_rfl
... ≤ ((⨅ p, dist y (Φ p) + dist x (Ψ p)) + ε) +
((⨅ p, dist y (Φ p) + dist z (Ψ p)) + ε) + δ : by linarith
end
private lemma glue_eq_of_dist_eq_zero (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) (ε0 : 0 < ε) :
∀ p q : X ⊕ Y, glue_dist Φ Ψ ε p q = 0 → p = q
| (inl x) (inl y) h := by rw eq_of_dist_eq_zero h
| (inl x) (inr y) h := begin
have : 0 ≤ (⨅ p, dist x (Φ p) + dist y (Ψ p)) :=
le_cinfi (λp, by simpa using add_le_add (@dist_nonneg _ _ x _) (@dist_nonneg _ _ y _)),
have : 0 + ε ≤ glue_dist Φ Ψ ε (inl x) (inr y) := add_le_add this (le_refl ε),
exfalso,
linarith
end
| (inr x) (inl y) h := begin
have : 0 ≤ ⨅ p, dist y (Φ p) + dist x (Ψ p) :=
le_cinfi (λp, by simpa [add_comm]
using add_le_add (@dist_nonneg _ _ x _) (@dist_nonneg _ _ y _)),
have : 0 + ε ≤ glue_dist Φ Ψ ε (inr x) (inl y) := add_le_add this (le_refl ε),
exfalso,
linarith
end
| (inr x) (inr y) h := by rw eq_of_dist_eq_zero h
/-- Given two maps `Φ` and `Ψ` intro metric spaces `X` and `Y` such that the distances between
`Φ p` and `Φ q`, and between `Ψ p` and `Ψ q`, coincide up to `2 ε` where `ε > 0`, one can almost
glue the two spaces `X` and `Y` along the images of `Φ` and `Ψ`, so that `Φ p` and `Ψ p` are
at distance `ε`. -/
def glue_metric_approx (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) (ε0 : 0 < ε)
(H : ∀ p q, |dist (Φ p) (Φ q) - dist (Ψ p) (Ψ q)| ≤ 2 * ε) : metric_space (X ⊕ Y) :=
{ dist := glue_dist Φ Ψ ε,
dist_self := glue_dist_self Φ Ψ ε,
dist_comm := glue_dist_comm Φ Ψ ε,
dist_triangle := glue_dist_triangle Φ Ψ ε H,
eq_of_dist_eq_zero := glue_eq_of_dist_eq_zero Φ Ψ ε ε0 }
end approx_gluing
section sum
/- A particular case of the previous construction is when one uses basepoints in `X` and `Y` and one
glues only along the basepoints, putting them at distance 1. We give a direct definition of
the distance, without infi, as it is easier to use in applications, and show that it is equal to
the gluing distance defined above to take advantage of the lemmas we have already proved. -/
variables {X : Type u} {Y : Type v} {Z : Type w}
variables [metric_space X] [metric_space Y] [inhabited X] [inhabited Y]
open sum (inl inr)
/-- Distance on a disjoint union. There are many (noncanonical) ways to put a distance compatible
with each factor.
If the two spaces are bounded, one can say for instance that each point in the first is at distance
`diam X + diam Y + 1` of each point in the second.
Instead, we choose a construction that works for unbounded spaces, but requires basepoints.
We embed isometrically each factor, set the basepoints at distance 1,
arbitrarily, and say that the distance from `a` to `b` is the sum of the distances of `a` and `b` to
their respective basepoints, plus the distance 1 between the basepoints.
Since there is an arbitrary choice in this construction, it is not an instance by default. -/
def sum.dist : X ⊕ Y → X ⊕ Y → ℝ
| (inl a) (inl a') := dist a a'
| (inr b) (inr b') := dist b b'
| (inl a) (inr b) := dist a default + 1 + dist default b
| (inr b) (inl a) := dist b default + 1 + dist default a
lemma sum.dist_eq_glue_dist {p q : X ⊕ Y} :
sum.dist p q = glue_dist (λ_ : unit, default) (λ_ : unit, default) 1 p q :=
by cases p; cases q; refl <|> simp [sum.dist, glue_dist, dist_comm, add_comm, add_left_comm]
private lemma sum.dist_comm (x y : X ⊕ Y) : sum.dist x y = sum.dist y x :=
by cases x; cases y; simp only [sum.dist, dist_comm, add_comm, add_left_comm]
lemma sum.one_dist_le {x : X} {y : Y} : 1 ≤ sum.dist (inl x) (inr y) :=
le_trans (le_add_of_nonneg_right dist_nonneg) $
add_le_add_right (le_add_of_nonneg_left dist_nonneg) _
lemma sum.one_dist_le' {x : X} {y : Y} : 1 ≤ sum.dist (inr y) (inl x) :=
by rw sum.dist_comm; exact sum.one_dist_le
private lemma sum.mem_uniformity (s : set ((X ⊕ Y) × (X ⊕ Y))) :
s ∈ 𝓤 (X ⊕ Y) ↔ ∃ ε > 0, ∀ a b, sum.dist a b < ε → (a, b) ∈ s :=
begin
split,
{ rintro ⟨hsX, hsY⟩,
rcases mem_uniformity_dist.1 hsX with ⟨εX, εX0, hX⟩,
rcases mem_uniformity_dist.1 hsY with ⟨εY, εY0, hY⟩,
refine ⟨min (min εX εY) 1, lt_min (lt_min εX0 εY0) zero_lt_one, _⟩,
rintro (a|a) (b|b) h,
{ exact hX (lt_of_lt_of_le h (le_trans (min_le_left _ _) (min_le_left _ _))) },
{ cases not_le_of_lt (lt_of_lt_of_le h (min_le_right _ _)) sum.one_dist_le },
{ cases not_le_of_lt (lt_of_lt_of_le h (min_le_right _ _)) sum.one_dist_le' },
{ exact hY (lt_of_lt_of_le h (le_trans (min_le_left _ _) (min_le_right _ _))) } },
{ rintro ⟨ε, ε0, H⟩,
split; rw [filter.mem_sets, filter.mem_map, mem_uniformity_dist];
exact ⟨ε, ε0, λ x y h, H _ _ (by exact h)⟩ }
end
/-- The distance on the disjoint union indeed defines a metric space. All the distance properties
follow from our choice of the distance. The harder work is to show that the uniform structure
defined by the distance coincides with the disjoint union uniform structure. -/
def metric_space_sum : metric_space (X ⊕ Y) :=
{ dist := sum.dist,
dist_self := λx, by cases x; simp only [sum.dist, dist_self],
dist_comm := sum.dist_comm,
dist_triangle := λp q r,
by simp only [dist, sum.dist_eq_glue_dist]; exact glue_dist_triangle _ _ _ (by norm_num) _ _ _,
eq_of_dist_eq_zero := λp q,
by simp only [dist, sum.dist_eq_glue_dist]; exact glue_eq_of_dist_eq_zero _ _ _ zero_lt_one _ _,
to_uniform_space := sum.uniform_space,
uniformity_dist := uniformity_dist_of_mem_uniformity _ _ sum.mem_uniformity }
local attribute [instance] metric_space_sum
lemma sum.dist_eq {x y : X ⊕ Y} : dist x y = sum.dist x y := rfl
/-- The left injection of a space in a disjoint union in an isometry -/
lemma isometry_on_inl : isometry (sum.inl : X → (X ⊕ Y)) :=
isometry_emetric_iff_metric.2 $ λx y, rfl
/-- The right injection of a space in a disjoint union in an isometry -/
lemma isometry_on_inr : isometry (sum.inr : Y → (X ⊕ Y)) :=
isometry_emetric_iff_metric.2 $ λx y, rfl
end sum
section gluing
/- Exact gluing of two metric spaces along isometric subsets. -/
variables {X : Type u} {Y : Type v} {Z : Type w}
variables [nonempty Z] [metric_space Z] [metric_space X] [metric_space Y]
{Φ : Z → X} {Ψ : Z → Y} {ε : ℝ}
open _root_.sum (inl inr)
local attribute [instance] pseudo_metric.dist_setoid
/-- Given two isometric embeddings `Φ : Z → X` and `Ψ : Z → Y`, we define a pseudo metric space
structure on `X ⊕ Y` by declaring that `Φ x` and `Ψ x` are at distance `0`. -/
def glue_premetric (hΦ : isometry Φ) (hΨ : isometry Ψ) : pseudo_metric_space (X ⊕ Y) :=
{ dist := glue_dist Φ Ψ 0,
dist_self := glue_dist_self Φ Ψ 0,
dist_comm := glue_dist_comm Φ Ψ 0,
dist_triangle := glue_dist_triangle Φ Ψ 0 $ λp q, by rw [hΦ.dist_eq, hΨ.dist_eq]; simp }
/-- Given two isometric embeddings `Φ : Z → X` and `Ψ : Z → Y`, we define a
space `glue_space hΦ hΨ` by identifying in `X ⊕ Y` the points `Φ x` and `Ψ x`. -/
def glue_space (hΦ : isometry Φ) (hΨ : isometry Ψ) : Type* :=
@pseudo_metric_quot _ (glue_premetric hΦ hΨ)
instance metric_space_glue_space (hΦ : isometry Φ) (hΨ : isometry Ψ) :
metric_space (glue_space hΦ hΨ) :=
@metric_space_quot _ (glue_premetric hΦ hΨ)
/-- The canonical map from `X` to the space obtained by gluing isometric subsets in `X` and `Y`. -/
def to_glue_l (hΦ : isometry Φ) (hΨ : isometry Ψ) (x : X) : glue_space hΦ hΨ :=
by letI : pseudo_metric_space (X ⊕ Y) := glue_premetric hΦ hΨ; exact ⟦inl x⟧
/-- The canonical map from `Y` to the space obtained by gluing isometric subsets in `X` and `Y`. -/
def to_glue_r (hΦ : isometry Φ) (hΨ : isometry Ψ) (y : Y) : glue_space hΦ hΨ :=
by letI : pseudo_metric_space (X ⊕ Y) := glue_premetric hΦ hΨ; exact ⟦inr y⟧
instance inhabited_left (hΦ : isometry Φ) (hΨ : isometry Ψ) [inhabited X] :
inhabited (glue_space hΦ hΨ) :=
⟨to_glue_l _ _ default⟩
instance inhabited_right (hΦ : isometry Φ) (hΨ : isometry Ψ) [inhabited Y] :
inhabited (glue_space hΦ hΨ) :=
⟨to_glue_r _ _ default⟩
lemma to_glue_commute (hΦ : isometry Φ) (hΨ : isometry Ψ) :
(to_glue_l hΦ hΨ) ∘ Φ = (to_glue_r hΦ hΨ) ∘ Ψ :=
begin
letI : pseudo_metric_space (X ⊕ Y) := glue_premetric hΦ hΨ,
funext,
simp only [comp, to_glue_l, to_glue_r, quotient.eq],
exact glue_dist_glued_points Φ Ψ 0 x
end
lemma to_glue_l_isometry (hΦ : isometry Φ) (hΨ : isometry Ψ) : isometry (to_glue_l hΦ hΨ) :=
isometry_emetric_iff_metric.2 $ λ_ _, rfl
lemma to_glue_r_isometry (hΦ : isometry Φ) (hΨ : isometry Ψ) : isometry (to_glue_r hΦ hΨ) :=
isometry_emetric_iff_metric.2 $ λ_ _, rfl
end gluing --section
section inductive_limit
/- In this section, we define the inductive limit of
f 0 f 1 f 2 f 3
X 0 -----> X 1 -----> X 2 -----> X 3 -----> ...
where the X n are metric spaces and f n isometric embeddings. We do it by defining a premetric
space structure on Σ n, X n, where the predistance dist x y is obtained by pushing x and y in a
common X k using composition by the f n, and taking the distance there. This does not depend on
the choice of k as the f n are isometries. The metric space associated to this premetric space
is the desired inductive limit.-/
open nat
variables {X : ℕ → Type u} [∀ n, metric_space (X n)] {f : Π n, X n → X (n+1)}
/-- Predistance on the disjoint union `Σ n, X n`. -/
def inductive_limit_dist (f : Π n, X n → X (n+1)) (x y : Σ n, X n) : ℝ :=
dist (le_rec_on (le_max_left x.1 y.1) f x.2 : X (max x.1 y.1))
(le_rec_on (le_max_right x.1 y.1) f y.2 : X (max x.1 y.1))
/-- The predistance on the disjoint union `Σ n, X n` can be computed in any `X k` for large
enough `k`. -/
lemma inductive_limit_dist_eq_dist (I : ∀ n, isometry (f n))
(x y : Σ n, X n) (m : ℕ) : ∀ hx : x.1 ≤ m, ∀ hy : y.1 ≤ m,
inductive_limit_dist f x y = dist (le_rec_on hx f x.2 : X m) (le_rec_on hy f y.2 : X m) :=
begin
induction m with m hm,
{ assume hx hy,
have A : max x.1 y.1 = 0, { rw [nonpos_iff_eq_zero.1 hx, nonpos_iff_eq_zero.1 hy], simp },
unfold inductive_limit_dist,
congr; simp only [A] },
{ assume hx hy,
by_cases h : max x.1 y.1 = m.succ,
{ unfold inductive_limit_dist,
congr; simp only [h] },
{ have : max x.1 y.1 ≤ succ m := by simp [hx, hy],
have : max x.1 y.1 ≤ m := by simpa [h] using of_le_succ this,
have xm : x.1 ≤ m := le_trans (le_max_left _ _) this,
have ym : y.1 ≤ m := le_trans (le_max_right _ _) this,
rw [le_rec_on_succ xm, le_rec_on_succ ym, (I m).dist_eq],
exact hm xm ym }}
end
/-- Premetric space structure on `Σ n, X n`.-/
def inductive_premetric (I : ∀ n, isometry (f n)) :
pseudo_metric_space (Σ n, X n) :=
{ dist := inductive_limit_dist f,
dist_self := λx, by simp [dist, inductive_limit_dist],
dist_comm := λx y, begin
let m := max x.1 y.1,
have hx : x.1 ≤ m := le_max_left _ _,
have hy : y.1 ≤ m := le_max_right _ _,
unfold dist,
rw [inductive_limit_dist_eq_dist I x y m hx hy, inductive_limit_dist_eq_dist I y x m hy hx,
dist_comm]
end,
dist_triangle := λx y z, begin
let m := max (max x.1 y.1) z.1,
have hx : x.1 ≤ m := le_trans (le_max_left _ _) (le_max_left _ _),
have hy : y.1 ≤ m := le_trans (le_max_right _ _) (le_max_left _ _),
have hz : z.1 ≤ m := le_max_right _ _,
calc inductive_limit_dist f x z
= dist (le_rec_on hx f x.2 : X m) (le_rec_on hz f z.2 : X m) :
inductive_limit_dist_eq_dist I x z m hx hz
... ≤ dist (le_rec_on hx f x.2 : X m) (le_rec_on hy f y.2 : X m)
+ dist (le_rec_on hy f y.2 : X m) (le_rec_on hz f z.2 : X m) :
dist_triangle _ _ _
... = inductive_limit_dist f x y + inductive_limit_dist f y z :
by rw [inductive_limit_dist_eq_dist I x y m hx hy,
inductive_limit_dist_eq_dist I y z m hy hz]
end }
local attribute [instance] inductive_premetric pseudo_metric.dist_setoid
/-- The type giving the inductive limit in a metric space context. -/
def inductive_limit (I : ∀ n, isometry (f n)) : Type* :=
@pseudo_metric_quot _ (inductive_premetric I)
/-- Metric space structure on the inductive limit. -/
instance metric_space_inductive_limit (I : ∀ n, isometry (f n)) :
metric_space (inductive_limit I) :=
@metric_space_quot _ (inductive_premetric I)
/-- Mapping each `X n` to the inductive limit. -/
def to_inductive_limit (I : ∀ n, isometry (f n)) (n : ℕ) (x : X n) : metric.inductive_limit I :=
by letI : pseudo_metric_space (Σ n, X n) := inductive_premetric I; exact ⟦sigma.mk n x⟧
instance (I : ∀ n, isometry (f n)) [inhabited (X 0)] : inhabited (inductive_limit I) :=
⟨to_inductive_limit _ 0 default⟩
/-- The map `to_inductive_limit n` mapping `X n` to the inductive limit is an isometry. -/
lemma to_inductive_limit_isometry (I : ∀ n, isometry (f n)) (n : ℕ) :
isometry (to_inductive_limit I n) := isometry_emetric_iff_metric.2 $ λx y,
begin
change inductive_limit_dist f ⟨n, x⟩ ⟨n, y⟩ = dist x y,
rw [inductive_limit_dist_eq_dist I ⟨n, x⟩ ⟨n, y⟩ n (le_refl n) (le_refl n),
le_rec_on_self, le_rec_on_self]
end
/-- The maps `to_inductive_limit n` are compatible with the maps `f n`. -/
lemma to_inductive_limit_commute (I : ∀ n, isometry (f n)) (n : ℕ) :
(to_inductive_limit I n.succ) ∘ (f n) = to_inductive_limit I n :=
begin
funext,
simp only [comp, to_inductive_limit, quotient.eq],
show inductive_limit_dist f ⟨n.succ, f n x⟩ ⟨n, x⟩ = 0,
{ rw [inductive_limit_dist_eq_dist I ⟨n.succ, f n x⟩ ⟨n, x⟩ n.succ,
le_rec_on_self, le_rec_on_succ, le_rec_on_self, dist_self],
exact le_rfl,
exact le_rfl,
exact le_succ _ }
end
end inductive_limit --section
end metric --namespace
|
8db0de0ca3e60425ffbc5aefe3b48548d90f758b | a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7 | /src/analysis/normed_space/basic.lean | 717384a85ae9afe17e2cbff411805f6028d366c4 | [
"Apache-2.0"
] | permissive | kmill/mathlib | ea5a007b67ae4e9e18dd50d31d8aa60f650425ee | 1a419a9fea7b959317eddd556e1bb9639f4dcc05 | refs/heads/master | 1,668,578,197,719 | 1,593,629,163,000 | 1,593,629,163,000 | 276,482,939 | 0 | 0 | null | 1,593,637,960,000 | 1,593,637,959,000 | null | UTF-8 | Lean | false | false | 46,844 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Johannes Hölzl
-/
import topology.instances.nnreal
import topology.instances.complex
import topology.algebra.module
import topology.metric_space.antilipschitz
/-!
# Normed spaces
-/
variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*}
noncomputable theory
open filter metric
open_locale topological_space big_operators
localized "notation f `→_{`:50 a `}`:0 b := filter.tendsto f (_root_.nhds a) (_root_.nhds b)" in filter
/-- Auxiliary class, endowing a type `α` with a function `norm : α → ℝ`. This class is designed to
be extended in more interesting classes specifying the properties of the norm. -/
class has_norm (α : Type*) := (norm : α → ℝ)
export has_norm (norm)
notation `∥`:1024 e:1 `∥`:1 := norm e
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A normed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines
a metric space structure. -/
class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
end prio
/-- Construct a normed group from a translation invariant distance -/
def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α]
(H1 : ∀ x:α, ∥x∥ = dist x 0)
(H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α :=
{ dist_eq := λ x y, begin
rw H1, apply le_antisymm,
{ rw [sub_eq_add_neg, ← add_right_neg y], apply H2 },
{ have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }
end }
/-- Construct a normed group from a translation invariant distance -/
def normed_group.of_add_dist' [has_norm α] [add_comm_group α] [metric_space α]
(H1 : ∀ x:α, ∥x∥ = dist x 0)
(H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : normed_group α :=
{ dist_eq := λ x y, begin
rw H1, apply le_antisymm,
{ have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this },
{ rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }
end }
/-- A normed group can be built from a norm that satisfies algebraic properties. This is
formalised in this structure. -/
structure normed_group.core (α : Type*) [add_comm_group α] [has_norm α] : Prop :=
(norm_eq_zero_iff : ∀ x : α, ∥x∥ = 0 ↔ x = 0)
(triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥)
(norm_neg : ∀ x : α, ∥-x∥ = ∥x∥)
/-- Constructing a normed group from core properties of a norm, i.e., registering the distance and
the metric space structure from the norm properties. -/
noncomputable def normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α]
(C : normed_group.core α) : normed_group α :=
{ dist := λ x y, ∥x - y∥,
dist_eq := assume x y, by refl,
dist_self := assume x, (C.norm_eq_zero_iff (x - x)).mpr (show x - x = 0, by simp),
eq_of_dist_eq_zero := assume x y h, show (x = y), from sub_eq_zero.mp $ (C.norm_eq_zero_iff (x - y)).mp h,
dist_triangle := assume x y z,
calc ∥x - z∥ = ∥x - y + (y - z)∥ : by rw sub_add_sub_cancel
... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _,
dist_comm := assume x y,
calc ∥x - y∥ = ∥ -(y - x)∥ : by simp
... = ∥y - x∥ : by { rw [C.norm_neg] } }
section normed_group
variables [normed_group α] [normed_group β]
lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ :=
normed_group.dist_eq _ _
@[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ :=
by rw [dist_eq_norm, sub_zero]
lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ :=
by simpa only [dist_eq_norm] using dist_comm g h
@[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ :=
by simpa using norm_sub_rev 0 g
@[simp] lemma dist_add_left (g h₁ h₂ : α) : dist (g + h₁) (g + h₂) = dist h₁ h₂ :=
by simp [dist_eq_norm]
@[simp] lemma dist_add_right (g₁ g₂ h : α) : dist (g₁ + h) (g₂ + h) = dist g₁ g₂ :=
by simp [dist_eq_norm]
@[simp] lemma dist_neg_neg (g h : α) : dist (-g) (-h) = dist g h :=
by simp only [dist_eq_norm, neg_sub_neg, norm_sub_rev]
@[simp] lemma dist_sub_left (g h₁ h₂ : α) : dist (g - h₁) (g - h₂) = dist h₁ h₂ :=
by simp only [sub_eq_add_neg, dist_add_left, dist_neg_neg]
@[simp] lemma dist_sub_right (g₁ g₂ h : α) : dist (g₁ - h) (g₂ - h) = dist g₁ g₂ :=
dist_add_right _ _ _
/-- Triangle inequality for the norm. -/
lemma norm_add_le (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ :=
by simpa [dist_eq_norm] using dist_triangle g 0 (-h)
lemma norm_add_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) :
∥g₁ + g₂∥ ≤ n₁ + n₂ :=
le_trans (norm_add_le g₁ g₂) (add_le_add H₁ H₂)
lemma dist_add_add_le (g₁ g₂ h₁ h₂ : α) :
dist (g₁ + g₂) (h₁ + h₂) ≤ dist g₁ h₁ + dist g₂ h₂ :=
by simpa only [dist_add_left, dist_add_right] using dist_triangle (g₁ + g₂) (h₁ + g₂) (h₁ + h₂)
lemma dist_add_add_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ}
(H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) :
dist (g₁ + g₂) (h₁ + h₂) ≤ d₁ + d₂ :=
le_trans (dist_add_add_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂)
lemma dist_sub_sub_le (g₁ g₂ h₁ h₂ : α) :
dist (g₁ - g₂) (h₁ - h₂) ≤ dist g₁ h₁ + dist g₂ h₂ :=
dist_neg_neg g₂ h₂ ▸ dist_add_add_le _ _ _ _
lemma dist_sub_sub_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ}
(H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) :
dist (g₁ - g₂) (h₁ - h₂) ≤ d₁ + d₂ :=
le_trans (dist_sub_sub_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂)
lemma abs_dist_sub_le_dist_add_add (g₁ g₂ h₁ h₂ : α) :
abs (dist g₁ h₁ - dist g₂ h₂) ≤ dist (g₁ + g₂) (h₁ + h₂) :=
by simpa only [dist_add_left, dist_add_right, dist_comm h₂]
using abs_dist_sub_le (g₁ + g₂) (h₁ + h₂) (h₁ + g₂)
@[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ :=
by { rw[←dist_zero_right], exact dist_nonneg }
@[simp] lemma norm_eq_zero {g : α} : ∥g∥ = 0 ↔ g = 0 :=
dist_zero_right g ▸ dist_eq_zero
@[simp] lemma norm_zero : ∥(0:α)∥ = 0 := norm_eq_zero.2 rfl
lemma norm_sum_le {β} : ∀(s : finset β) (f : β → α), ∥∑ a in s, f a∥ ≤ ∑ a in s, ∥ f a ∥ :=
finset.le_sum_of_subadditive norm norm_zero norm_add_le
lemma norm_sum_le_of_le {β} (s : finset β) {f : β → α} {n : β → ℝ} (h : ∀ b ∈ s, ∥f b∥ ≤ n b) :
∥∑ b in s, f b∥ ≤ ∑ b in s, n b :=
le_trans (norm_sum_le s f) (finset.sum_le_sum h)
lemma norm_pos_iff {g : α} : 0 < ∥ g ∥ ↔ g ≠ 0 :=
dist_zero_right g ▸ dist_pos
lemma norm_le_zero_iff {g : α} : ∥g∥ ≤ 0 ↔ g = 0 :=
by { rw[←dist_zero_right], exact dist_le_zero }
lemma norm_sub_le (g h : α) : ∥g - h∥ ≤ ∥g∥ + ∥h∥ :=
by simpa [dist_eq_norm] using dist_triangle g 0 h
lemma norm_sub_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) :
∥g₁ - g₂∥ ≤ n₁ + n₂ :=
le_trans (norm_sub_le g₁ g₂) (add_le_add H₁ H₂)
lemma dist_le_norm_add_norm (g h : α) : dist g h ≤ ∥g∥ + ∥h∥ :=
by { rw dist_eq_norm, apply norm_sub_le }
lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ :=
by simpa [dist_eq_norm] using abs_dist_sub_le g h 0
lemma norm_sub_norm_le (g h : α) : ∥g∥ - ∥h∥ ≤ ∥g - h∥ :=
le_trans (le_abs_self _) (abs_norm_sub_norm_le g h)
lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ :=
abs_norm_sub_norm_le g h
lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} :=
set.ext $ assume a, by simp
lemma norm_le_of_mem_closed_ball {g h : α} {r : ℝ} (H : h ∈ closed_ball g r) :
∥h∥ ≤ ∥g∥ + r :=
calc
∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right]
... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _
... ≤ ∥g∥ + r : by { apply add_le_add_left, rw ← dist_eq_norm, exact H }
lemma norm_lt_of_mem_ball {g h : α} {r : ℝ} (H : h ∈ ball g r) :
∥h∥ < ∥g∥ + r :=
calc
∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right]
... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _
... < ∥g∥ + r : by { apply add_lt_add_left, rw ← dist_eq_norm, exact H }
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem normed_group.tendsto_nhds_zero {f : γ → α} {l : filter γ} :
tendsto f l (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in l, ∥ f x ∥ < ε :=
metric.tendsto_nhds.trans $ by simp only [dist_zero_right]
section nnnorm
/-- Version of the norm taking values in nonnegative reals. -/
def nnnorm (a : α) : nnreal := ⟨norm a, norm_nonneg a⟩
@[simp] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl
lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _
@[simp] lemma nnnorm_eq_zero {a : α} : nnnorm a = 0 ↔ a = 0 :=
by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero]
@[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 :=
nnreal.eq norm_zero
lemma nnnorm_add_le (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h :=
nnreal.coe_le_coe.2 $ norm_add_le g h
@[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g :=
nnreal.eq $ norm_neg g
lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) :=
nnreal.coe_le_coe.2 $ dist_norm_norm_le g h
lemma of_real_norm_eq_coe_nnnorm (x : β) : ennreal.of_real ∥x∥ = (nnnorm x : ennreal) :=
ennreal.of_real_eq_coe_nnreal _
lemma edist_eq_coe_nnnorm_sub (x y : β) : edist x y = (nnnorm (x - y) : ennreal) :=
by rw [edist_dist, dist_eq_norm, of_real_norm_eq_coe_nnnorm]
lemma edist_eq_coe_nnnorm (x : β) : edist x 0 = (nnnorm x : ennreal) :=
by rw [edist_eq_coe_nnnorm_sub, _root_.sub_zero]
lemma nndist_add_add_le (g₁ g₂ h₁ h₂ : α) :
nndist (g₁ + g₂) (h₁ + h₂) ≤ nndist g₁ h₁ + nndist g₂ h₂ :=
nnreal.coe_le_coe.2 $ dist_add_add_le g₁ g₂ h₁ h₂
lemma edist_add_add_le (g₁ g₂ h₁ h₂ : α) :
edist (g₁ + g₂) (h₁ + h₂) ≤ edist g₁ h₁ + edist g₂ h₂ :=
by { simp only [edist_nndist], norm_cast, apply nndist_add_add_le }
lemma nnnorm_sum_le {β} : ∀(s : finset β) (f : β → α), nnnorm (∑ a in s, f a) ≤ ∑ a in s, nnnorm (f a) :=
finset.le_sum_of_subadditive nnnorm nnnorm_zero nnnorm_add_le
end nnnorm
lemma lipschitz_with.neg {α : Type*} [emetric_space α] {K : nnreal} {f : α → β}
(hf : lipschitz_with K f) : lipschitz_with K (λ x, -f x) :=
λ x y, by simpa only [edist_dist, dist_neg_neg] using hf x y
lemma lipschitz_with.add {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β}
(hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) :
lipschitz_with (Kf + Kg) (λ x, f x + g x) :=
λ x y,
calc edist (f x + g x) (f y + g y) ≤ edist (f x) (f y) + edist (g x) (g y) :
edist_add_add_le _ _ _ _
... ≤ Kf * edist x y + Kg * edist x y :
add_le_add (hf x y) (hg x y)
... = (Kf + Kg) * edist x y :
(add_mul _ _ _).symm
lemma lipschitz_with.sub {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β}
(hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) :
lipschitz_with (Kf + Kg) (λ x, f x - g x) :=
hf.add hg.neg
lemma antilipschitz_with.add_lipschitz_with {α : Type*} [metric_space α] {Kf : nnreal} {f : α → β}
(hf : antilipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g)
(hK : Kg < Kf⁻¹) :
antilipschitz_with (Kf⁻¹ - Kg)⁻¹ (λ x, f x + g x) :=
begin
refine antilipschitz_with.of_le_mul_dist (λ x y, _),
rw [nnreal.coe_inv, ← div_eq_inv_mul],
apply le_div_of_mul_le (nnreal.coe_pos.2 $ nnreal.sub_pos.2 hK),
rw [mul_comm, nnreal.coe_sub (le_of_lt hK), sub_mul],
calc ↑Kf⁻¹ * dist x y - Kg * dist x y ≤ dist (f x) (f y) - dist (g x) (g y) :
sub_le_sub (hf.mul_le_dist x y) (hg.dist_le_mul x y)
... ≤ _ : le_trans (le_abs_self _) (abs_dist_sub_le_dist_add_add _ _ _ _)
end
/-- A submodule of a normed group is also a normed group, with the restriction of the norm.
As all instances can be inferred from the submodule `s`, they are put as implicit instead of
typeclasses. -/
instance submodule.normed_group {𝕜 : Type*} {_ : ring 𝕜}
{E : Type*} [normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_group s :=
{ norm := λx, norm (x : E),
dist_eq := λx y, dist_eq_norm (x : E) (y : E) }
/-- normed group instance on the product of two normed groups, using the sup norm. -/
instance prod.normed_group : normed_group (α × β) :=
{ norm := λx, max ∥x.1∥ ∥x.2∥,
dist_eq := assume (x y : α × β),
show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] }
lemma prod.norm_def (x : α × β) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl
lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ :=
le_max_left _ _
lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ :=
le_max_right _ _
lemma norm_prod_le_iff {x : α × β} {r : ℝ} :
∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r :=
max_le_iff
/-- normed group instance on the product of finitely many normed groups, using the sup norm. -/
instance pi.normed_group {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] :
normed_group (Πi, π i) :=
{ norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : nnreal) : ℝ),
dist_eq := assume x y,
congr_arg (coe : nnreal → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a,
show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ }
/-- The norm of an element in a product space is `≤ r` if and only if the norm of each
component is. -/
lemma pi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 ≤ r)
{x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r :=
by { simp only [(dist_zero_right _).symm, dist_pi_le_iff hr], refl }
lemma norm_le_pi_norm {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] (x : Πi, π i) (i : ι) :
∥x i∥ ≤ ∥x∥ :=
(pi_norm_le_iff (norm_nonneg x)).1 (le_refl _) i
lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} :
tendsto f a (𝓝 b) ↔ tendsto (λ e, ∥ f e - b ∥) a (𝓝 0) :=
by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm]
lemma tendsto_zero_iff_norm_tendsto_zero {f : γ → β} {a : filter γ} :
tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e ∥) a (𝓝 0) :=
have tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e - 0 ∥) a (𝓝 0) :=
tendsto_iff_norm_tendsto_zero,
by simpa
lemma lim_norm (x : α) : (λg:α, ∥g - x∥) →_{x} 0 :=
tendsto_iff_norm_tendsto_zero.1 (continuous_iff_continuous_at.1 continuous_id x)
lemma lim_norm_zero : (λg:α, ∥g∥) →_{0} 0 :=
by simpa using lim_norm (0:α)
lemma continuous_norm : continuous (λg:α, ∥g∥) :=
begin
rw continuous_iff_continuous_at,
intro x,
rw [continuous_at, tendsto_iff_dist_tendsto_zero],
exact squeeze_zero (λ t, abs_nonneg _) (λ t, abs_norm_sub_norm_le _ _) (lim_norm x)
end
lemma filter.tendsto.norm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) :
tendsto (λ x, ∥f x∥) l (𝓝 ∥a∥) :=
tendsto.comp continuous_norm.continuous_at h
lemma continuous_nnnorm : continuous (nnnorm : α → nnreal) :=
continuous_subtype_mk _ continuous_norm
lemma filter.tendsto.nnnorm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) :
tendsto (λ x, nnnorm (f x)) l (𝓝 (nnnorm a)) :=
tendsto.comp continuous_nnnorm.continuous_at h
/-- If `∥y∥→∞`, then we can assume `y≠x` for any fixed `x`. -/
lemma eventually_ne_of_tendsto_norm_at_top {l : filter γ} {f : γ → α}
(h : tendsto (λ y, ∥f y∥) l at_top) (x : α) :
∀ᶠ y in l, f y ≠ x :=
begin
have : ∀ᶠ y in l, 1 + ∥x∥ ≤ ∥f y∥ := h (mem_at_top (1 + ∥x∥)),
refine this.mono (λ y hy hxy, _),
subst x,
exact not_le_of_lt zero_lt_one (add_le_iff_nonpos_left.1 hy)
end
/-- A normed group is a uniform additive group, i.e., addition and subtraction are uniformly
continuous. -/
@[priority 100] -- see Note [lower instance priority]
instance normed_uniform_group : uniform_add_group α :=
begin
refine ⟨metric.uniform_continuous_iff.2 $ assume ε hε, ⟨ε / 2, half_pos hε, assume a b h, _⟩⟩,
rw [prod.dist_eq, max_lt_iff, dist_eq_norm, dist_eq_norm] at h,
calc dist (a.1 - a.2) (b.1 - b.2) = ∥(a.1 - b.1) - (a.2 - b.2)∥ :
by simp [dist_eq_norm, sub_eq_add_neg]; abel
... ≤ ∥a.1 - b.1∥ + ∥a.2 - b.2∥ : norm_sub_le _ _
... < ε / 2 + ε / 2 : add_lt_add h.1 h.2
... = ε : add_halves _
end
@[priority 100] -- see Note [lower instance priority]
instance normed_top_monoid : topological_add_monoid α := by apply_instance -- short-circuit type class inference
@[priority 100] -- see Note [lower instance priority]
instance normed_top_group : topological_add_group α := by apply_instance -- short-circuit type class inference
end normed_group
section normed_ring
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A normed ring is a ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/
class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b)
end prio
@[priority 100] -- see Note [lower instance priority]
instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β }
lemma norm_mul_le {α : Type*} [normed_ring α] (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) :=
normed_ring.norm_mul _ _
lemma norm_pow_le {α : Type*} [normed_ring α] (a : α) : ∀ {n : ℕ}, 0 < n → ∥a^n∥ ≤ ∥a∥^n
| 1 h := by simp
| (n+2) h :=
le_trans (norm_mul_le a (a^(n+1)))
(mul_le_mul (le_refl _)
(norm_pow_le (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _))
/-- Normed ring structure on the product of two normed rings, using the sup norm. -/
instance prod.normed_ring [normed_ring α] [normed_ring β] : normed_ring (α × β) :=
{ norm_mul := assume x y,
calc
∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl
... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl
... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) :
max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2))
... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm]
... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by { apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] }
... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp[max_comm]
... = (∥x∥*∥y∥) : rfl,
..prod.normed_group }
end normed_ring
@[priority 100] -- see Note [lower instance priority]
instance normed_ring_top_monoid [normed_ring α] : topological_monoid α :=
⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $
have ∀ e : α × α, e.fst * e.snd - x.fst * x.snd =
e.fst * e.snd - e.fst * x.snd + (e.fst * x.snd - x.fst * x.snd), by intro; rw sub_add_sub_cancel,
begin
apply squeeze_zero,
{ intro, apply norm_nonneg },
{ simp only [this], intro, apply norm_add_le },
{ rw ←zero_add (0 : ℝ), apply tendsto.add,
{ apply squeeze_zero,
{ intro, apply norm_nonneg },
{ intro t, show ∥t.fst * t.snd - t.fst * x.snd∥ ≤ ∥t.fst∥ * ∥t.snd - x.snd∥,
rw ←mul_sub, apply norm_mul_le },
{ rw ←mul_zero (∥x.fst∥), apply tendsto.mul,
{ apply continuous_iff_continuous_at.1,
apply continuous_norm.comp continuous_fst },
{ apply tendsto_iff_norm_tendsto_zero.1,
apply continuous_iff_continuous_at.1,
apply continuous_snd }}},
{ apply squeeze_zero,
{ intro, apply norm_nonneg },
{ intro t, show ∥t.fst * x.snd - x.fst * x.snd∥ ≤ ∥t.fst - x.fst∥ * ∥x.snd∥,
rw ←sub_mul, apply norm_mul_le },
{ rw ←zero_mul (∥x.snd∥), apply tendsto.mul,
{ apply tendsto_iff_norm_tendsto_zero.1,
apply continuous_iff_continuous_at.1,
apply continuous_fst },
{ apply tendsto_const_nhds }}}}
end ⟩
/-- A normed ring is a topological ring. -/
@[priority 100] -- see Note [lower instance priority]
instance normed_top_ring [normed_ring α] : topological_ring α :=
⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $
have ∀ e : α, -e - -x = -(e - x), by intro; simp,
by simp only [this, norm_neg]; apply lim_norm ⟩
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A normed field is a field with a norm satisfying ∥x y∥ = ∥x∥ ∥y∥. -/
class normed_field (α : Type*) extends has_norm α, field α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_mul' : ∀ a b, norm (a * b) = norm a * norm b)
/-- A nondiscrete normed field is a normed field in which there is an element of norm different from
`0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication
by the powers of any element, and thus to relate algebra and topology. -/
class nondiscrete_normed_field (α : Type*) extends normed_field α :=
(non_trivial : ∃x:α, 1<∥x∥)
end prio
@[priority 100] -- see Note [lower instance priority]
instance normed_field.to_normed_ring [i : normed_field α] : normed_ring α :=
{ norm_mul := by finish [i.norm_mul'], ..i }
namespace normed_field
@[simp] lemma norm_one {α : Type*} [normed_field α] : ∥(1 : α)∥ = 1 :=
have ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α)∥ * 1, by calc
∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α) * (1 : α)∥ : by rw normed_field.norm_mul'
... = ∥(1 : α)∥ * 1 : by simp,
eq_of_mul_eq_mul_left (ne_of_gt (norm_pos_iff.2 (by simp))) this
@[simp] lemma norm_mul [normed_field α] (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ :=
normed_field.norm_mul' a b
@[simp] lemma nnnorm_one [normed_field α] : nnnorm (1:α) = 1 := nnreal.eq $ by simp
instance normed_field.is_monoid_hom_norm [normed_field α] : is_monoid_hom (norm : α → ℝ) :=
{ map_one := norm_one, map_mul := norm_mul }
@[simp] lemma norm_pow [normed_field α] (a : α) : ∀ (n : ℕ), ∥a^n∥ = ∥a∥^n :=
is_monoid_hom.map_pow norm a
@[simp] lemma norm_prod {β : Type*} [normed_field α] (s : finset β) (f : β → α) :
∥∏ b in s, f b∥ = ∏ b in s, ∥f b∥ :=
eq.symm (s.prod_hom norm)
@[simp] lemma norm_div {α : Type*} [normed_field α] (a b : α) : ∥a/b∥ = ∥a∥/∥b∥ :=
begin
classical,
by_cases hb : b = 0, {simp [hb]},
apply eq_div_of_mul_eq,
{ apply ne_of_gt, apply norm_pos_iff.mpr hb },
{ rw [←normed_field.norm_mul, div_mul_cancel _ hb] }
end
@[simp] lemma norm_inv {α : Type*} [normed_field α] (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ :=
by simp only [inv_eq_one_div, norm_div, norm_one]
@[simp] lemma nnnorm_inv {α : Type*} [normed_field α] (a : α) : nnnorm (a⁻¹) = (nnnorm a)⁻¹ :=
nnreal.eq $ by simp
@[simp] lemma norm_fpow {α : Type*} [normed_field α] (a : α) : ∀n : ℤ,
∥a^n∥ = ∥a∥^n
| (n : ℕ) := norm_pow a n
| -[1+ n] := by simp [fpow_neg_succ_of_nat]
lemma exists_one_lt_norm (α : Type*) [i : nondiscrete_normed_field α] : ∃x : α, 1 < ∥x∥ :=
i.non_trivial
lemma exists_norm_lt_one (α : Type*) [nondiscrete_normed_field α] : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 :=
begin
rcases exists_one_lt_norm α with ⟨y, hy⟩,
refine ⟨y⁻¹, _, _⟩,
{ simp only [inv_eq_zero, ne.def, norm_pos_iff],
assume h,
rw ← norm_eq_zero at h,
rw h at hy,
exact lt_irrefl _ (lt_trans zero_lt_one hy) },
{ simp [inv_lt_one hy] }
end
lemma exists_lt_norm (α : Type*) [nondiscrete_normed_field α]
(r : ℝ) : ∃ x : α, r < ∥x∥ :=
let ⟨w, hw⟩ := exists_one_lt_norm α in
let ⟨n, hn⟩ := pow_unbounded_of_one_lt r hw in
⟨w^n, by rwa norm_pow⟩
lemma exists_norm_lt (α : Type*) [nondiscrete_normed_field α]
{r : ℝ} (hr : 0 < r) : ∃ x : α, 0 < ∥x∥ ∧ ∥x∥ < r :=
let ⟨w, hw⟩ := exists_one_lt_norm α in
let ⟨n, hle, hlt⟩ := exists_int_pow_near' hr hw in
⟨w^n, by { rw norm_fpow; exact fpow_pos_of_pos (lt_trans zero_lt_one hw) _},
by rwa norm_fpow⟩
lemma punctured_nhds_ne_bot {α : Type*} [nondiscrete_normed_field α] (x : α) :
nhds_within x {x}ᶜ ≠ ⊥ :=
begin
rw [← mem_closure_iff_nhds_within_ne_bot, metric.mem_closure_iff],
rintros ε ε0,
rcases normed_field.exists_norm_lt α ε0 with ⟨b, hb0, hbε⟩,
refine ⟨x + b, mt (set.mem_singleton_iff.trans add_right_eq_self).1 $ norm_pos_iff.1 hb0, _⟩,
rwa [dist_comm, dist_eq_norm, add_sub_cancel'],
end
lemma tendsto_inv [normed_field α] {r : α} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) :=
begin
refine (nhds_basis_closed_ball.tendsto_iff nhds_basis_closed_ball).2 (λε εpos, _),
let δ := min (ε/2 * ∥r∥^2) (∥r∥/2),
have norm_r_pos : 0 < ∥r∥ := norm_pos_iff.mpr r0,
have A : 0 < ε / 2 * ∥r∥ ^ 2 := mul_pos (half_pos εpos) (pow_pos norm_r_pos 2),
have δpos : 0 < δ, by simp [half_pos norm_r_pos, A],
refine ⟨δ, δpos, λ x hx, _⟩,
have rx : ∥r∥/2 ≤ ∥x∥ := calc
∥r∥/2 = ∥r∥ - ∥r∥/2 : by ring
... ≤ ∥r∥ - ∥r - x∥ :
begin
apply sub_le_sub (le_refl _),
rw [← dist_eq_norm, dist_comm],
exact le_trans hx (min_le_right _ _)
end
... ≤ ∥r - (r - x)∥ : norm_sub_norm_le r (r - x)
... = ∥x∥ : by simp [sub_sub_cancel],
have norm_x_pos : 0 < ∥x∥ := lt_of_lt_of_le (half_pos norm_r_pos) rx,
have : x⁻¹ - r⁻¹ = (r - x) * x⁻¹ * r⁻¹,
by rw [sub_mul, sub_mul, mul_inv_cancel (norm_pos_iff.mp norm_x_pos), one_mul, mul_comm,
← mul_assoc, inv_mul_cancel r0, one_mul],
calc dist x⁻¹ r⁻¹ = ∥x⁻¹ - r⁻¹∥ : dist_eq_norm _ _
... ≤ ∥r-x∥ * ∥x∥⁻¹ * ∥r∥⁻¹ : by rw [this, norm_mul, norm_mul, norm_inv, norm_inv]
... ≤ (ε/2 * ∥r∥^2) * (2 * ∥r∥⁻¹) * (∥r∥⁻¹) : begin
apply_rules [mul_le_mul, inv_nonneg.2, le_of_lt A, norm_nonneg, inv_nonneg.2, mul_nonneg,
(inv_le_inv norm_x_pos norm_r_pos).2, le_refl],
show ∥r - x∥ ≤ ε / 2 * ∥r∥ ^ 2,
by { rw [← dist_eq_norm, dist_comm], exact le_trans hx (min_le_left _ _) },
show ∥x∥⁻¹ ≤ 2 * ∥r∥⁻¹,
{ convert (inv_le_inv norm_x_pos (half_pos norm_r_pos)).2 rx,
rw [inv_div, div_eq_inv_mul, mul_comm] },
show (0 : ℝ) ≤ 2, by norm_num
end
... = ε * (∥r∥ * ∥r∥⁻¹)^2 : by { generalize : ∥r∥⁻¹ = u, ring }
... = ε : by { rw [mul_inv_cancel (ne.symm (ne_of_lt norm_r_pos))], simp }
end
lemma continuous_on_inv [normed_field α] : continuous_on (λ(x:α), x⁻¹) {x | x ≠ 0} :=
begin
assume x hx,
apply continuous_at.continuous_within_at,
exact (tendsto_inv hx)
end
end normed_field
instance : normed_field ℝ :=
{ norm := λ x, abs x,
dist_eq := assume x y, rfl,
norm_mul' := abs_mul }
instance : nondiscrete_normed_field ℝ :=
{ non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ }
/-- If a function converges to a nonzero value, its inverse converges to the inverse of this value.
We use the name `tendsto.inv'` as `tendsto.inv` is already used in multiplicative topological
groups. -/
lemma filter.tendsto.inv' [normed_field α] {l : filter β} {f : β → α} {y : α}
(hy : y ≠ 0) (h : tendsto f l (𝓝 y)) :
tendsto (λx, (f x)⁻¹) l (𝓝 y⁻¹) :=
(normed_field.tendsto_inv hy).comp h
lemma filter.tendsto.div [normed_field α] {l : filter β} {f g : β → α} {x y : α}
(hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) (hy : y ≠ 0) :
tendsto (λa, f a / g a) l (𝓝 (x / y)) :=
hf.mul (hg.inv' hy)
lemma filter.tendsto.div_const [normed_field α] {l : filter β} {f : β → α} {x y : α}
(hf : tendsto f l (𝓝 x)) : tendsto (λa, f a / y) l (𝓝 (x / y)) :=
by { simp only [div_eq_inv_mul], exact tendsto_const_nhds.mul hf }
/-- Continuity at a point of the result of dividing two functions
continuous at that point, where the denominator is nonzero. -/
lemma continuous_at.div [topological_space α] [normed_field β] {f : α → β} {g : α → β} {x : α}
(hf : continuous_at f x) (hg : continuous_at g x) (hnz : g x ≠ 0) :
continuous_at (λ x, f x / g x) x :=
hf.div hg hnz
namespace real
lemma norm_eq_abs (r : ℝ) : ∥r∥ = abs r := rfl
@[simp] lemma norm_coe_nat (n : ℕ) : ∥(n : ℝ)∥ = n := abs_of_nonneg n.cast_nonneg
@[simp] lemma nnnorm_coe_nat (n : ℕ) : nnnorm (n : ℝ) = n := nnreal.eq $ by simp
@[simp] lemma norm_two : ∥(2:ℝ)∥ = 2 := abs_of_pos (@two_pos ℝ _)
@[simp] lemma nnnorm_two : nnnorm (2:ℝ) = 2 := nnreal.eq $ by simp
end real
@[simp] lemma norm_norm [normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ :=
by rw [real.norm_eq_abs, abs_of_nonneg (norm_nonneg _)]
@[simp] lemma nnnorm_norm [normed_group α] (a : α) : nnnorm ∥a∥ = nnnorm a :=
by simp only [nnnorm, norm_norm]
instance : normed_ring ℤ :=
{ norm := λ n, ∥(n : ℝ)∥,
norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul],
dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub] }
@[norm_cast] lemma int.norm_cast_real (m : ℤ) : ∥(m : ℝ)∥ = ∥m∥ := rfl
instance : normed_field ℚ :=
{ norm := λ r, ∥(r : ℝ)∥,
norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul],
dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] }
instance : nondiscrete_normed_field ℚ :=
{ non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ }
@[norm_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ∥(r : ℝ)∥ = ∥r∥ := rfl
@[norm_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ∥(m : ℚ)∥ = ∥m∥ :=
by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast
section normed_space
section prio
set_option default_priority 920 -- see Note [default priority]. Here, we set a rather high priority,
-- to take precedence over `semiring.to_semimodule` as this leads to instance paths with better
-- unification properties.
-- see Note[vector space definition] for why we extend `semimodule`.
/-- A normed space over a normed field is a vector space endowed with a norm which satisfies the
equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove
`∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. -/
class normed_space (α : Type*) (β : Type*) [normed_field α] [normed_group β]
extends semimodule α β :=
(norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥)
end prio
variables [normed_field α] [normed_group β]
instance normed_field.to_normed_space : normed_space α α :=
{ norm_smul_le := λ a b, le_of_eq (normed_field.norm_mul a b) }
lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ :=
begin
classical,
by_cases h : s = 0,
{ simp [h] },
{ refine le_antisymm (normed_space.norm_smul_le s x) _,
calc ∥s∥ * ∥x∥ = ∥s∥ * ∥s⁻¹ • s • x∥ : by rw [inv_smul_smul' h]
... ≤ ∥s∥ * (∥s⁻¹∥ * ∥s • x∥) : _
... = ∥s • x∥ : _,
exact mul_le_mul_of_nonneg_left (normed_space.norm_smul_le _ _) (norm_nonneg _),
rw [normed_field.norm_inv, ← mul_assoc, mul_inv_cancel, one_mul],
rwa [ne.def, norm_eq_zero] }
end
lemma dist_smul [normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ∥s∥ * dist x y :=
by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub]
lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x :=
nnreal.eq $ norm_smul s x
lemma nndist_smul [normed_space α β] (s : α) (x y : β) :
nndist (s • x) (s • y) = nnnorm s * nndist x y :=
nnreal.eq $ dist_smul s x y
variables {E : Type*} {F : Type*}
[normed_group E] [normed_space α E] [normed_group F] [normed_space α F]
@[priority 100] -- see Note [lower instance priority]
instance normed_space.topological_vector_space : topological_vector_space α E :=
begin
refine { continuous_smul := continuous_iff_continuous_at.2 $
λ p, tendsto_iff_norm_tendsto_zero.2 _ },
refine squeeze_zero (λ _, norm_nonneg _) _ _,
{ exact λ q, ∥q.1 - p.1∥ * ∥q.2∥ + ∥p.1∥ * ∥q.2 - p.2∥ },
{ intro q,
rw [← sub_add_sub_cancel, ← norm_smul, ← norm_smul, smul_sub, sub_smul],
exact norm_add_le _ _ },
{ conv { congr, skip, skip, congr, rw [← zero_add (0:ℝ)], congr,
rw [← zero_mul ∥p.2∥], skip, rw [← mul_zero ∥p.1∥] },
exact ((tendsto_iff_norm_tendsto_zero.1 (continuous_fst.tendsto p)).mul
(continuous_snd.tendsto p).norm).add
(tendsto_const_nhds.mul (tendsto_iff_norm_tendsto_zero.1 (continuous_snd.tendsto p))) }
end
/-- In a normed space over a nondiscrete normed field, only `⊤` submodule has a nonempty interior.
See also `submodule.eq_top_of_nonempty_interior'` for a `topological_module` version. -/
lemma submodule.eq_top_of_nonempty_interior {α E : Type*} [nondiscrete_normed_field α]
[normed_group E] [normed_space α E] (s : submodule α E) (hs : (interior (s:set E)).nonempty) :
s = ⊤ :=
begin
refine s.eq_top_of_nonempty_interior' _ hs,
simp only [is_unit_iff_ne_zero, @ne.def α, set.mem_singleton_iff.symm],
exact normed_field.punctured_nhds_ne_bot _
end
theorem closure_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) :
closure (ball x r) = closed_ball x r :=
begin
refine set.subset.antisymm closure_ball_subset_closed_ball (λ y hy, _),
have : continuous_within_at (λ c : ℝ, c • (y - x) + x) (set.Ico 0 1) 1 :=
((continuous_id.smul continuous_const).add continuous_const).continuous_within_at,
convert this.mem_closure _ _,
{ rw [one_smul, sub_add_cancel] },
{ simp [closure_Ico (@zero_lt_one ℝ _), zero_le_one] },
{ rintros c ⟨hc0, hc1⟩,
rw [set.mem_preimage, mem_ball, dist_eq_norm, add_sub_cancel, norm_smul, real.norm_eq_abs,
abs_of_nonneg hc0, mul_comm, ← mul_one r],
rw [mem_closed_ball, dist_eq_norm] at hy,
apply mul_lt_mul'; assumption }
end
theorem frontier_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) :
frontier (ball x r) = sphere x r :=
begin
rw [frontier, closure_ball x hr, interior_eq_of_open is_open_ball],
ext x, exact (@eq_iff_le_not_lt ℝ _ _ _).symm
end
theorem interior_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) :
interior (closed_ball x r) = ball x r :=
begin
refine set.subset.antisymm _ ball_subset_interior_closed_ball,
intros y hy,
rcases le_iff_lt_or_eq.1 (mem_closed_ball.1 $ interior_subset hy) with hr|rfl, { exact hr },
set f : ℝ → E := λ c : ℝ, c • (y - x) + x,
suffices : f ⁻¹' closed_ball x (dist y x) ⊆ set.Icc (-1) 1,
{ have hfc : continuous f := (continuous_id.smul continuous_const).add continuous_const,
have hf1 : (1:ℝ) ∈ f ⁻¹' (interior (closed_ball x $ dist y x)), by simpa [f],
have h1 : (1:ℝ) ∈ interior (set.Icc (-1:ℝ) 1) :=
interior_mono this (preimage_interior_subset_interior_preimage hfc hf1),
contrapose h1,
simp },
intros c hc,
rw [set.mem_Icc, ← abs_le, ← real.norm_eq_abs, ← mul_le_mul_right hr],
simpa [f, dist_eq_norm, norm_smul] using hc
end
theorem interior_closed_ball' [normed_space ℝ E] (x : E) (r : ℝ) (hE : ∃ z : E, z ≠ 0) :
interior (closed_ball x r) = ball x r :=
begin
rcases lt_trichotomy r 0 with hr|rfl|hr,
{ simp [closed_ball_eq_empty_iff_neg.2 hr, ball_eq_empty_iff_nonpos.2 (le_of_lt hr)] },
{ suffices : x ∉ interior {x},
{ rw [ball_zero, closed_ball_zero, ← set.subset_empty_iff],
intros y hy,
obtain rfl : y = x := set.mem_singleton_iff.1 (interior_subset hy),
exact this hy },
rw [← set.mem_compl_iff, ← closure_compl],
rcases hE with ⟨z, hz⟩,
suffices : (λ c : ℝ, x + c • z) 0 ∈ closure ({x}ᶜ : set E),
by simpa only [zero_smul, add_zero] using this,
have : (0:ℝ) ∈ closure (set.Ioi (0:ℝ)), by simp [closure_Ioi],
refine (continuous_const.add (continuous_id.smul
continuous_const)).continuous_within_at.mem_closure this _,
intros c hc,
simp [smul_eq_zero, hz, ne_of_gt hc] },
{ exact interior_closed_ball x hr }
end
theorem frontier_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) :
frontier (closed_ball x r) = sphere x r :=
by rw [frontier, closure_closed_ball, interior_closed_ball x hr,
closed_ball_diff_ball]
theorem frontier_closed_ball' [normed_space ℝ E] (x : E) (r : ℝ) (hE : ∃ z : E, z ≠ 0) :
frontier (closed_ball x r) = sphere x r :=
by rw [frontier, closure_closed_ball, interior_closed_ball' x r hE,
closed_ball_diff_ball]
open normed_field
/-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to
any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows
up in applications. -/
lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) :
∃d:α, d ≠ 0 ∧ ∥d • x∥ ≤ ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) :=
begin
have xεpos : 0 < ∥x∥/ε := div_pos_of_pos_of_pos (norm_pos_iff.2 hx) εpos,
rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩,
have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc,
have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 },
refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩,
show (c ^ (n + 1))⁻¹ ≠ 0,
by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff],
show ∥(c ^ (n + 1))⁻¹ • x∥ ≤ ε,
{ rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_le_iff cnpos, mul_comm, norm_fpow],
exact (div_le_iff εpos).1 (le_of_lt (hn.2)) },
show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥,
{ rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos),
fpow_one, mul_inv', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos),
one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm],
exact (le_div_iff εpos).1 hn.1 },
show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥,
{ have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring,
rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, this, ← div_eq_inv_mul],
exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) }
end
/-- The product of two normed spaces is a normed space, with the sup norm. -/
instance : normed_space α (E × F) :=
{ norm_smul_le := λ s x, le_of_eq $ by simp [prod.norm_def, norm_smul, mul_max_of_nonneg],
-- TODO: without the next two lines Lean unfolds `≤` to `real.le`
add_smul := λ r x y, prod.ext (add_smul _ _ _) (add_smul _ _ _),
smul_add := λ r x y, prod.ext (smul_add _ _ _) (smul_add _ _ _),
..prod.normed_group,
..prod.semimodule }
/-- The product of finitely many normed spaces is a normed space, with the sup norm. -/
instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, normed_group (E i)]
[∀i, normed_space α (E i)] : normed_space α (Πi, E i) :=
{ norm_smul_le := λ a f, le_of_eq $
show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) =
nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))),
by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] }
/-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/
instance submodule.normed_space {𝕜 : Type*} [normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E] (s : submodule 𝕜 E) : normed_space 𝕜 s :=
{ norm_smul_le := λc x, le_of_eq $ norm_smul c (x : E) }
end normed_space
section normed_algebra
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A normed algebra `𝕜'` over `𝕜` is an algebra endowed with a norm for which the embedding of
`𝕜` in `𝕜'` is an isometry. -/
class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜']
extends algebra 𝕜 𝕜' :=
(norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥)
end prio
@[simp] lemma norm_algebra_map_eq {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜']
[h : normed_algebra 𝕜 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ :=
normed_algebra.norm_algebra_map_eq _
@[priority 100]
instance normed_algebra.to_normed_space (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜']
[h : normed_algebra 𝕜 𝕜'] : normed_space 𝕜 𝕜' :=
{ norm_smul_le := λ s x, calc
∥s • x∥ = ∥((algebra_map 𝕜 𝕜') s) * x∥ : by { rw h.smul_def', refl }
... ≤ ∥algebra_map 𝕜 𝕜' s∥ * ∥x∥ : normed_ring.norm_mul _ _
... = ∥s∥ * ∥x∥ : by rw norm_algebra_map_eq,
..h }
instance normed_algebra.id (𝕜 : Type*) [normed_field 𝕜] : normed_algebra 𝕜 𝕜 :=
{ norm_algebra_map_eq := by simp,
.. algebra.id 𝕜}
end normed_algebra
section restrict_scalars
variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
{E : Type*} [normed_group E] [normed_space 𝕜' E]
/-- `𝕜`-normed space structure induced by a `𝕜'`-normed space structure when `𝕜'` is a
normed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred. -/
-- We could add a type synonym equipped with this as an instance,
-- as we've done for `module.restrict_scalars`.
def normed_space.restrict_scalars : normed_space 𝕜 E :=
{ norm_smul_le := λc x, le_of_eq $ begin
change ∥(algebra_map 𝕜 𝕜' c) • x∥ = ∥c∥ * ∥x∥,
simp [norm_smul]
end,
..module.restrict_scalars' 𝕜 𝕜' E }
end restrict_scalars
section summable
open_locale classical
open finset filter
variables [normed_group α]
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma cauchy_seq_finset_iff_vanishing_norm {f : ι → α} :
cauchy_seq (λ s : finset ι, ∑ i in s, f i) ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε :=
begin
simp only [cauchy_seq_finset_iff_vanishing, metric.mem_nhds_iff, exists_imp_distrib],
split,
{ assume h ε hε, refine h {x | ∥x∥ < ε} ε hε _, rw [ball_0_eq ε] },
{ assume h s ε hε hs,
rcases h ε hε with ⟨t, ht⟩,
refine ⟨t, assume u hu, hs _⟩,
rw [ball_0_eq],
exact ht u hu }
end
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma summable_iff_vanishing_norm [complete_space α] {f : ι → α} :
summable f ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε :=
by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing_norm]
lemma cauchy_seq_finset_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g)
(h : ∀i, ∥f i∥ ≤ g i) : cauchy_seq (λ s : finset ι, ∑ i in s, f i) :=
cauchy_seq_finset_iff_vanishing_norm.2 $ assume ε hε,
let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hg ε hε in
⟨s, assume t ht,
have ∥∑ i in t, g i∥ < ε := hs t ht,
have nn : 0 ≤ ∑ i in t, g i := finset.sum_nonneg (assume a _, le_trans (norm_nonneg _) (h a)),
lt_of_le_of_lt (norm_sum_le_of_le t (λ i _, h i)) $
by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩
lemma cauchy_seq_finset_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) :
cauchy_seq (λ s : finset ι, ∑ a in s, f a) :=
cauchy_seq_finset_of_norm_bounded _ hf (assume i, le_refl _)
/-- If a function `f` is summable in norm, and along some sequence of finsets exhausting the space
its sum is converging to a limit `a`, then this holds along all finsets, i.e., `f` is summable
with sum `a`. -/
lemma has_sum_of_subseq_of_summable {f : ι → α} (hf : summable (λa, ∥f a∥))
{s : β → finset ι} {p : filter β} (hp : p ≠ ⊥)
(hs : tendsto s p at_top) {a : α} (ha : tendsto (λ b, ∑ i in s b, f i) p (𝓝 a)) :
has_sum f a :=
tendsto_nhds_of_cauchy_seq_of_subseq (cauchy_seq_finset_of_summable_norm hf) hp hs ha
/-- If `∑' i, ∥f i∥` is summable, then `∥(∑' i, f i)∥ ≤ (∑' i, ∥f i∥)`. Note that we do not assume
that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/
lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) :
∥(∑'i, f i)∥ ≤ (∑' i, ∥f i∥) :=
begin
by_cases h : summable f,
{ have h₁ : tendsto (λs:finset ι, ∥∑ i in s, f i∥) at_top (𝓝 ∥(∑' i, f i)∥) :=
(continuous_norm.tendsto _).comp h.has_sum,
have h₂ : tendsto (λs:finset ι, ∑ i in s, ∥f i∥) at_top (𝓝 (∑' i, ∥f i∥)) :=
hf.has_sum,
exact le_of_tendsto_of_tendsto' at_top_ne_bot h₁ h₂ (assume s, norm_sum_le _ _) },
{ rw tsum_eq_zero_of_not_summable h,
simp [tsum_nonneg] }
end
lemma has_sum_iff_tendsto_nat_of_summable_norm {f : ℕ → α} {a : α} (hf : summable (λi, ∥f i∥)) :
has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) :=
⟨λ h, h.tendsto_sum_nat,
λ h, has_sum_of_subseq_of_summable hf at_top_ne_bot tendsto_finset_range h⟩
variable [complete_space α]
lemma summable_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) :
summable f :=
by { rw summable_iff_cauchy_seq_finset, exact cauchy_seq_finset_of_norm_bounded g hg h }
lemma summable_of_nnnorm_bounded {f : ι → α} (g : ι → nnreal) (hg : summable g)
(h : ∀i, nnnorm (f i) ≤ g i) : summable f :=
summable_of_norm_bounded (λ i, (g i : ℝ)) (nnreal.summable_coe.2 hg) (λ i, by exact_mod_cast h i)
lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f :=
summable_of_norm_bounded _ hf (assume i, le_refl _)
lemma summable_of_summable_nnnorm {f : ι → α} (hf : summable (λa, nnnorm (f a))) : summable f :=
summable_of_nnnorm_bounded _ hf (assume i, le_refl _)
end summable
|
c72ded8631c61617cea91f6cc81a6c56d5436c62 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/homology/short_exact/preadditive.lean | 899a730744bd9e9595196351604ecc3e8faeba25 | [
"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,718 | lean | /-
Copyright (c) 2021 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Andrew Yang
-/
import algebra.homology.exact
import category_theory.preadditive.additive_functor
/-!
# Short exact sequences, and splittings.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
`short_exact f g` is the proposition that `0 ⟶ A -f⟶ B -g⟶ C ⟶ 0` is an exact sequence.
We define when a short exact sequence is left-split, right-split, and split.
## See also
In `algebra.homology.short_exact.abelian` we show that in an abelian category
a left-split short exact sequences admits a splitting.
-/
noncomputable theory
open category_theory category_theory.limits category_theory.preadditive
variables {𝒜 : Type*} [category 𝒜]
namespace category_theory
variables {A B C A' B' C' : 𝒜} (f : A ⟶ B) (g : B ⟶ C) (f' : A' ⟶ B') (g' : B' ⟶ C')
section has_zero_morphisms
variables [has_zero_morphisms 𝒜] [has_kernels 𝒜] [has_images 𝒜]
/-- If `f : A ⟶ B` and `g : B ⟶ C` then `short_exact f g` is the proposition saying
the resulting diagram `0 ⟶ A ⟶ B ⟶ C ⟶ 0` is an exact sequence. -/
structure short_exact : Prop :=
[mono : mono f]
[epi : epi g]
(exact : exact f g)
/-- An exact sequence `A -f⟶ B -g⟶ C` is *left split*
if there exists a morphism `φ : B ⟶ A` such that `f ≫ φ = 𝟙 A` and `g` is epi.
Such a sequence is automatically short exact (i.e., `f` is mono). -/
structure left_split : Prop :=
(left_split : ∃ φ : B ⟶ A, f ≫ φ = 𝟙 A)
[epi : epi g]
(exact : exact f g)
lemma left_split.short_exact {f : A ⟶ B} {g : B ⟶ C} (h : left_split f g) : short_exact f g :=
{ mono :=
begin
obtain ⟨φ, hφ⟩ := h.left_split,
haveI : mono (f ≫ φ) := by { rw hφ, apply_instance },
exact mono_of_mono f φ,
end,
epi := h.epi,
exact := h.exact }
/-- An exact sequence `A -f⟶ B -g⟶ C` is *right split*
if there exists a morphism `φ : C ⟶ B` such that `f ≫ φ = 𝟙 A` and `f` is mono.
Such a sequence is automatically short exact (i.e., `g` is epi). -/
structure right_split : Prop :=
(right_split : ∃ χ : C ⟶ B, χ ≫ g = 𝟙 C)
[mono : mono f]
(exact : exact f g)
lemma right_split.short_exact {f : A ⟶ B} {g : B ⟶ C} (h : right_split f g) : short_exact f g :=
{ epi :=
begin
obtain ⟨χ, hχ⟩ := h.right_split,
haveI : epi (χ ≫ g) := by { rw hχ, apply_instance },
exact epi_of_epi χ g,
end,
mono := h.mono,
exact := h.exact }
end has_zero_morphisms
section preadditive
variables [preadditive 𝒜]
/-- An exact sequence `A -f⟶ B -g⟶ C` is *split* if there exist
`φ : B ⟶ A` and `χ : C ⟶ B` such that:
* `f ≫ φ = 𝟙 A`
* `χ ≫ g = 𝟙 C`
* `f ≫ g = 0`
* `χ ≫ φ = 0`
* `φ ≫ f + g ≫ χ = 𝟙 B`
Such a sequence is automatically short exact (i.e., `f` is mono and `g` is epi). -/
structure split : Prop :=
(split : ∃ (φ : B ⟶ A) (χ : C ⟶ B),
f ≫ φ = 𝟙 A ∧ χ ≫ g = 𝟙 C ∧ f ≫ g = 0 ∧ χ ≫ φ = 0 ∧ φ ≫ f + g ≫ χ = 𝟙 B)
variables [has_kernels 𝒜] [has_images 𝒜]
lemma exact_of_split {A B C : 𝒜} {f : A ⟶ B} {g : B ⟶ C} {χ : C ⟶ B} {φ : B ⟶ A}
(hfg : f ≫ g = 0) (H : φ ≫ f + g ≫ χ = 𝟙 B) : exact f g :=
{ w := hfg,
epi :=
begin
let ψ : (kernel_subobject g : 𝒜) ⟶ image_subobject f :=
subobject.arrow _ ≫ φ ≫ factor_thru_image_subobject f,
suffices : ψ ≫ image_to_kernel f g hfg = 𝟙 _,
{ convert epi_of_epi ψ _, rw this, apply_instance },
rw ← cancel_mono (subobject.arrow _), swap, { apply_instance },
simp only [image_to_kernel_arrow, image_subobject_arrow_comp, category.id_comp, category.assoc],
calc (kernel_subobject g).arrow ≫ φ ≫ f
= (kernel_subobject g).arrow ≫ 𝟙 B : _
... = (kernel_subobject g).arrow : category.comp_id _,
rw [← H, preadditive.comp_add],
simp only [add_zero, zero_comp, kernel_subobject_arrow_comp_assoc],
end }
section
variables {f g}
lemma split.exact (h : split f g) : exact f g :=
by { obtain ⟨φ, χ, -, -, h1, -, h2⟩ := h, exact exact_of_split h1 h2 }
lemma split.left_split (h : split f g) : left_split f g :=
{ left_split := by { obtain ⟨φ, χ, h1, -⟩ := h, exact ⟨φ, h1⟩, },
epi := begin
obtain ⟨φ, χ, -, h2, -⟩ := h,
have : epi (χ ≫ g), { rw h2, apply_instance },
exactI epi_of_epi χ g,
end,
exact := h.exact }
lemma split.right_split (h : split f g) : right_split f g :=
{ right_split := by { obtain ⟨φ, χ, -, h1, -⟩ := h, exact ⟨χ, h1⟩, },
mono := begin
obtain ⟨φ, χ, h1, -⟩ := h,
have : mono (f ≫ φ), { rw h1, apply_instance },
exactI mono_of_mono f φ,
end,
exact := h.exact }
lemma split.short_exact (h : split f g) : short_exact f g :=
h.left_split.short_exact
end
lemma split.map {𝒜 ℬ : Type*} [category 𝒜] [preadditive 𝒜] [category ℬ] [preadditive ℬ]
(F : 𝒜 ⥤ ℬ) [functor.additive F] {A B C : 𝒜} {f : A ⟶ B} {g : B ⟶ C} (h : split f g) :
split (F.map f) (F.map g) :=
begin
obtain ⟨φ, χ, h1, h2, h3, h4, h5⟩ := h,
refine ⟨⟨F.map φ, F.map χ, _⟩⟩,
simp only [← F.map_comp, ← F.map_id, ← F.map_add, F.map_zero, *, eq_self_iff_true, and_true],
end
/-- The sequence `A ⟶ A ⊞ B ⟶ B` is exact. -/
lemma exact_inl_snd [has_binary_biproducts 𝒜] (A B : 𝒜) :
exact (biprod.inl : A ⟶ A ⊞ B) biprod.snd :=
exact_of_split biprod.inl_snd biprod.total
/-- The sequence `B ⟶ A ⊞ B ⟶ A` is exact. -/
lemma exact_inr_fst [has_binary_biproducts 𝒜] (A B : 𝒜) :
exact (biprod.inr : B ⟶ A ⊞ B) biprod.fst :=
exact_of_split biprod.inr_fst ((add_comm _ _).trans biprod.total)
end preadditive
/-- A *splitting* of a sequence `A -f⟶ B -g⟶ C` is an isomorphism
to the short exact sequence `0 ⟶ A ⟶ A ⊞ C ⟶ C ⟶ 0` such that
the vertical maps on the left and the right are the identity. -/
@[nolint has_nonempty_instance]
structure splitting [has_zero_morphisms 𝒜] [has_binary_biproducts 𝒜] :=
(iso : B ≅ A ⊞ C)
(comp_iso_eq_inl : f ≫ iso.hom = biprod.inl)
(iso_comp_snd_eq : iso.hom ≫ biprod.snd = g)
variables {f g}
namespace splitting
section has_zero_morphisms
variables [has_zero_morphisms 𝒜] [has_binary_biproducts 𝒜]
attribute [simp, reassoc] comp_iso_eq_inl iso_comp_snd_eq
variables (h : splitting f g)
@[simp, reassoc] lemma inl_comp_iso_eq : biprod.inl ≫ h.iso.inv = f :=
by rw [iso.comp_inv_eq, h.comp_iso_eq_inl]
@[simp, reassoc] lemma iso_comp_eq_snd : h.iso.inv ≫ g = biprod.snd :=
by rw [iso.inv_comp_eq, h.iso_comp_snd_eq]
/-- If `h` is a splitting of `A -f⟶ B -g⟶ C`,
then `h.section : C ⟶ B` is the morphism satisfying `h.section ≫ g = 𝟙 C`. -/
def _root_.category_theory.splitting.section : C ⟶ B := biprod.inr ≫ h.iso.inv
/-- If `h` is a splitting of `A -f⟶ B -g⟶ C`,
then `h.retraction : B ⟶ A` is the morphism satisfying `f ≫ h.retraction = 𝟙 A`. -/
def retraction : B ⟶ A := h.iso.hom ≫ biprod.fst
@[simp, reassoc] lemma section_π : h.section ≫ g = 𝟙 C := by { delta splitting.section, simp }
@[simp, reassoc] lemma ι_retraction : f ≫ h.retraction = 𝟙 A := by { delta retraction, simp }
@[simp, reassoc] lemma section_retraction : h.section ≫ h.retraction = 0 :=
by { delta splitting.section retraction, simp }
/-- The retraction in a splitting is a split mono. -/
protected def split_mono : split_mono f := ⟨h.retraction, by simp⟩
/-- The section in a splitting is a split epi. -/
protected def split_epi : split_epi g := ⟨h.section, by simp⟩
@[simp, reassoc] lemma inr_iso_inv : biprod.inr ≫ h.iso.inv = h.section := rfl
@[simp, reassoc] lemma iso_hom_fst : h.iso.hom ≫ biprod.fst = h.retraction := rfl
/-- A short exact sequence of the form `X -f⟶ Y -0⟶ Z` where `f` is an iso and `Z` is zero
has a splitting. -/
def splitting_of_is_iso_zero {X Y Z : 𝒜} (f : X ⟶ Y) [is_iso f] (hZ : is_zero Z) :
splitting f (0 : Y ⟶ Z) :=
⟨(as_iso f).symm ≪≫ iso_biprod_zero hZ, by simp [hZ.eq_of_tgt _ 0], by simp⟩
include h
protected lemma mono : mono f :=
begin
apply mono_of_mono _ h.retraction,
rw h.ι_retraction,
apply_instance
end
protected lemma epi : epi g :=
begin
apply_with (epi_of_epi h.section) { instances := ff },
rw h.section_π,
apply_instance
end
instance : mono h.section :=
by { delta splitting.section, apply_instance }
instance : epi h.retraction :=
by { delta retraction, apply epi_comp }
end has_zero_morphisms
section preadditive
variables [preadditive 𝒜] [has_binary_biproducts 𝒜]
variables (h : splitting f g)
lemma split_add : h.retraction ≫ f + g ≫ h.section = 𝟙 _ :=
begin
delta splitting.section retraction,
rw [← cancel_mono h.iso.hom, ← cancel_epi h.iso.inv],
simp only [category.comp_id, category.id_comp, category.assoc,
iso.inv_hom_id_assoc, iso.inv_hom_id, limits.biprod.total,
preadditive.comp_add, preadditive.add_comp,
splitting.comp_iso_eq_inl, splitting.iso_comp_eq_snd_assoc]
end
@[reassoc]
lemma retraction_ι_eq_id_sub :
h.retraction ≫ f = 𝟙 _ - g ≫ h.section :=
eq_sub_iff_add_eq.mpr h.split_add
@[reassoc]
lemma π_section_eq_id_sub :
g ≫ h.section = 𝟙 _ - h.retraction ≫ f :=
eq_sub_iff_add_eq.mpr ((add_comm _ _).trans h.split_add)
lemma splittings_comm (h h' : splitting f g) :
h'.section ≫ h.retraction = - h.section ≫ h'.retraction :=
begin
haveI := h.mono,
rw ← cancel_mono f,
simp [retraction_ι_eq_id_sub],
end
include h
lemma split : split f g :=
begin
let φ := h.iso.hom ≫ biprod.fst,
let χ := biprod.inr ≫ h.iso.inv,
refine ⟨⟨h.retraction, h.section, h.ι_retraction, h.section_π, _,
h.section_retraction, h.split_add⟩⟩,
rw [← h.inl_comp_iso_eq, category.assoc, h.iso_comp_eq_snd, biprod.inl_snd],
end
@[reassoc] lemma comp_eq_zero : f ≫ g = 0 :=
h.split.1.some_spec.some_spec.2.2.1
variables [has_kernels 𝒜] [has_images 𝒜] [has_zero_object 𝒜] [has_cokernels 𝒜]
protected lemma exact : exact f g :=
begin
rw exact_iff_exact_of_iso f g (biprod.inl : A ⟶ A ⊞ C) (biprod.snd : A ⊞ C ⟶ C) _ _ _,
{ exact exact_inl_snd _ _ },
{ refine arrow.iso_mk (iso.refl _) h.iso _,
simp only [iso.refl_hom, arrow.mk_hom, category.id_comp, comp_iso_eq_inl], },
{ refine arrow.iso_mk h.iso (iso.refl _) _,
dsimp, simp, },
{ refl }
end
protected
lemma short_exact : short_exact f g :=
{ mono := h.mono, epi := h.epi, exact := h.exact }
end preadditive
end splitting
end category_theory
|
a056cfbaad76fc093fd95fe6fb12eb7399aa4c35 | 7b681d6cc18477cf6b60470d9782923d3ea63915 | /W2-logic.lean | 761bcce9d9f17a86ca02ee4ee7be40f129604db6 | [] | no_license | osoulim/LEAN | a7458f597abbe5c36ebbb3f36eab29a4c60f5140 | 5e0dc240e86e392fdab4b2ffdcc3174c0cce7b66 | refs/heads/master | 1,591,850,481,195 | 1,561,547,647,000 | 1,561,547,647,000 | 193,852,039 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 655 | lean | def P := 0 = 0
def Q := 1 = 1
#check Q
lemma proofP : P := eq.refl 0
lemma proofQ : Q := sorry
theorem and1 : P ∧ Q
:= and.intro proofP proofQ
#check and1
#check and.intro proofQ proofP
theorem pfPQ : P ∧ Q :=
begin
apply and.intro,
exact eq.refl 0,
exact eq.refl 1
end
theorem pfPQ' : P ∧ Q :=
begin
have A := eq.refl 0,
have B := eq.refl 1,
apply and.intro A B
end
#check and.right pfPQ
axiom f : false
#check f
theorem zeroEqualToOne : "" = "asghar" := false.elim f
#check zeroEqualToOne
theorem pfPnP : P ∧ ¬P := sorry
#check pfPnP
theorem pfParrQ : P ∧ ¬P -> false := sorry
#check pfParrQ pfPnP
|
55e714b9fc163486a0fbfd6c1881800fd1d1d502 | 4da0c8e61fcd6ec3f3be47ee14a038850c03d0c3 | /src/s5/completeness.lean | a09fd5f47a9b125f37674af5f695f35913d990f3 | [
"Apache-2.0"
] | permissive | bbentzen/mpl | fcbea60204bc8fd64667e0f76a5cebf4b67fb6ca | bb5066ec51fa11a4b66f440c4f6c9a3d8fb2e0de | refs/heads/master | 1,625,175,849,308 | 1,624,207,634,000 | 1,624,207,634,000 | 142,774,375 | 9 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,629 | lean | /-
Copyright (c) 2018 Bruno Bentzen. All rights reserved.
Released under the Apache License 2.0 (see "License");
Author: Bruno Bentzen
-/
import .consistency ..encode
open nat set classical
local attribute [instance, priority 0] prop_decidable
variables {σ : nat}
/- maximal set of a context -/
namespace ctx
def is_max (Γ : ctx σ) := is_consist Γ ∧ ∀ p, p ∈ Γ ∨ (~p) ∈ Γ
def insert_form (Γ : ctx σ) (p : form σ) : ctx σ :=
if is_consist (Γ ⸴ p) then Γ ⸴ p else Γ ⸴ ~p
def insert_code (Γ : ctx σ) (n : nat) : ctx σ :=
match encodable.decode (form σ) n with
| none := Γ
| some p := insert_form Γ p
end
@[simp]
def maxn (Γ : ctx σ) : nat → ctx σ
| 0 := Γ
| (n+1) := insert_code (maxn n) n
@[simp]
def max (Γ : ctx σ) : ctx σ :=
⋃ n, maxn Γ n
/- maximal extensions are extensions -/
lemma subset_insert_code {Γ : ctx σ} (n) :
Γ ⊆ insert_code Γ n :=
begin
intros v hv,
unfold insert_code,
cases (encodable.decode (form σ) _); unfold insert_code insert_form,
{ assumption },
{ split_ifs; exact set.mem_insert_of_mem _ hv },
end
lemma subset_maxn {Γ : ctx σ} :
∀ n, Γ ⊆ maxn Γ n
| 0 := by refl
| (succ n) := subset.trans (subset_maxn n) (subset_insert_code _)
lemma maxn_subset_max {Γ : ctx σ} (n) :
maxn Γ n ⊆ max Γ :=
subset_Union _ _
lemma subset_max_self {Γ : ctx σ} :
Γ ⊆ max Γ :=
maxn_subset_max 0
lemma maxn_subset_succ {Γ : ctx σ} {n : nat} :
maxn Γ n ⊆ maxn Γ (n+1) :=
subset_insert_code _
lemma maxn_mono {Γ : ctx σ} {m n : nat} (h : n ≤ m) :
maxn Γ n ⊆ maxn Γ m :=
by induction h; [refl, exact subset.trans h_ih (subset_insert_code _)]
/- maximal extensions are maximal -/
lemma insert_form_self {Γ : ctx σ} {p : form σ} :
p ∈ insert_form Γ p ∨ (~p) ∈ insert_form Γ p :=
begin
unfold insert_form, split_ifs,
{ exact or.inl (mem_insert _ _) },
{ exact or.inr (mem_insert _ _) },
end
lemma insert_code_self {Γ : ctx σ} (p : form σ) :
p ∈ insert_code Γ (encodable.encode p) ∨ (~p) ∈ insert_code Γ (encodable.encode p) :=
begin
unfold insert_code,
rw (encodable.encodek p),
apply insert_form_self,
end
lemma mem_or_mem_max {Γ : ctx σ} (p : form σ) :
p ∈ max Γ ∨ (~p) ∈ max Γ :=
begin
have := maxn_subset_max (encodable.encode p + 1),
exact (insert_code_self p).imp (@this _) (@this _),
end
/- maximal extensions preserves consistency -/
lemma is_consist_insert_form {Γ : ctx σ} {p : form σ}
(H : is_consist Γ) : is_consist (insert_form Γ p) :=
begin
rw insert_form, split_ifs,
{ exact h },
{ exact inconsist_to_neg_consist H h },
end
lemma is_consist_insert_code {Γ : ctx σ} (n)
(H : is_consist Γ) : is_consist (insert_code Γ n) :=
begin
rw insert_code, cases encodable.decode _ _,
{ exact H },
{ exact is_consist_insert_form H }
end
lemma is_consist_maxn {Γ : ctx σ} :
∀ n, is_consist Γ → is_consist (maxn Γ n)
| 0 H := H
| (n+1) H := is_consist_insert_code _ (is_consist_maxn _ H)
lemma in_ext_ctx_max_set_is_in_ext_ctx_at {Γ : ctx σ} {p : form σ} :
(p ∈ max Γ) → ∃ n, p ∈ maxn Γ n :=
mem_Union.1
lemma ext_ctx_lvl {Γ : ctx σ} {p : form σ} :
(max Γ ⊢ₛ₅ p) → ∃ n, maxn Γ n ⊢ₛ₅ p :=
begin
generalize eq : max Γ = Γ',
intro h, induction h; subst eq,
{ cases in_ext_ctx_max_set_is_in_ext_ctx_at h_h,
constructor,
apply prf.ax,
assumption },
repeat {
constructor,
apply prf.pl1 <|> apply prf.pl2 <|> apply prf.pl3,
exact 0
},
{ cases h_ih_hpq rfl with n0 h_ext_pq,
cases h_ih_hp rfl with n1 h_ext_p,
cases (prop_decidable (n0 ≤ n1)),
have hh: n1 ≤ n0 :=
begin
cases nat.le_total,
assumption,
contradiction
end,
constructor,
apply prf.mp,
assumption,
apply prf.sub_weak,
exact h_ext_p,
apply maxn_mono,
assumption,
constructor,
apply prf.mp,
apply prf.sub_weak,
exact h_ext_pq,
apply maxn_mono,
assumption,
assumption },
{ constructor,
apply prf.k,
exact 0 },
{ constructor,
apply prf.t,
exact 0 },
{ constructor,
apply prf.s4,
exact 0 },
{ constructor,
apply prf.b,
exact 0 },
{ constructor,
apply prf.nec h_h,
exact 0 }
end
lemma is_consist_max {Γ : ctx σ} :
is_consist Γ → is_consist (max Γ) :=
λ hc nc, let ⟨n, ht⟩ := ext_ctx_lvl nc in is_consist_maxn _ hc ht
/- maximal consistent sets are closed under derivability -/
lemma max_of_max {Γ : ctx σ} {p : form σ} (h : is_consist Γ) : is_max (max Γ) :=
⟨ is_consist_max h , mem_or_mem_max⟩
lemma mem_max_of_prf {Γ : ctx σ} {p : form σ} (h₁ : is_max Γ)
(h₂ : Γ ⊢ₛ₅ p) : p ∈ Γ :=
(h₁.2 p).resolve_right $ λ hn,
h₁.1 (prf.mp (prf.ax hn) h₂)
end ctx
/- the canonical model construction -/
-- domain
namespace canonical
def domain (σ : nat) : set (wrld σ) := {w | ctx.is_max w}
lemma mem_domain_max {w : wrld σ} :
w ∈ domain σ → ∀ p, (p ∈ w) ∨ ((~p) ∈ w) :=
and.right
lemma mem_domain_consist {w : wrld σ} :
w ∈ domain σ → is_consist w :=
and.left
lemma mem_domain {w : wrld σ}
(h : is_consist w) : ctx.max w ∈ domain σ :=
⟨ctx.is_consist_max h, ctx.mem_or_mem_max⟩
lemma mem_domain_of_prf {p : form σ} (w ∈ domain σ)
(h : w ⊢ₛ₅ p) : p ∈ w :=
(mem_domain_max H p).resolve_right $
λ hn, (mem_domain_consist H) (prf.mp (prf.ax hn) h)
-- accessibility
def unbox (w : wrld σ) : wrld σ := {p | (◻p) ∈ w}
noncomputable def access : wrld σ → wrld σ → bool :=
assume w v, if (unbox w ⊆ v) then tt else ff
lemma subset_unbox_iff_access {w v : wrld σ} : access w v = tt ↔ unbox w ⊆ v :=
by unfold access; simp
lemma mem_unbox_iff_mem_box {p : form σ} {w : wrld σ} :
p ∈ unbox w ↔ (◻p) ∈ w :=
⟨ id, id ⟩
lemma not_mem_unbox_of_mem_not_box {p : form σ} {w : wrld σ} (hc : w ∈ domain σ) :
(~◻p) ∈ w → p ∉ unbox w :=
λ h np, (mem_domain_consist hc) (prf.mp (prf.ax h) (prf.ax (mem_unbox_iff_mem_box.1 np)))
lemma mem_box_of_unbox_prf {p : form σ} {w : wrld σ} (H : w ∈ domain σ) :
(unbox w ⊢ₛ₅ p) → (◻p) ∈ w :=
begin
generalize eq : unbox w = Γ',
intro h, induction h; subst eq,
{ assumption },
repeat { apply ctx.mem_max_of_prf H,
apply prf.nec,
apply prf.pl1 <|> apply prf.pl2 <|> apply prf.pl3 },
{ apply ctx.mem_max_of_prf H,
refine prf.mp (prf.ax _) (prf.ax (h_ih_hp rfl)),
exact (ctx.mem_max_of_prf H) (prf.mp prf.k (prf.ax (h_ih_hpq rfl))) },
{ apply ctx.mem_max_of_prf H,
exact prf.nec prf.k },
{ apply ctx.mem_max_of_prf H,
exact prf.nec prf.t },
{ apply ctx.mem_max_of_prf H,
exact prf.nec prf.s4 },
{ apply ctx.mem_max_of_prf H,
exact prf.nec prf.b },
{ apply ctx.mem_max_of_prf H,
apply prf.nec (prf.nec h_h) }
end
lemma not_unbox_prf_of_not_box_mem {p : form σ} {w : wrld σ} (hw : w ∈ domain σ) :
(~◻p) ∈ w → (unbox w ⊬ₛ₅ p) :=
by { intros h nhp, apply mem_domain_consist hw, apply prf.mp (prf.ax h) (prf.ax (mem_box_of_unbox_prf hw nhp)) }
lemma consist_unbox_of_not_box_mem {p : form σ} {w : wrld σ} (hw : w ∈ domain σ) :
(~◻p) ∈ w → is_consist (unbox w ⸴ (~p)) :=
λ hn, consist_not_of_not_prf (not_unbox_prf_of_not_box_mem hw hn)
-- valuation
noncomputable def val : fin σ → wrld σ → bool :=
assume p w, if w ∈ domain σ ∧ (#p) ∈ w then tt else ff
-- reflexivity
lemma access.refl :
∀ w ∈ domain σ, access w w = tt :=
begin
intros w h, unfold access,
simp, intros p hp, cases mem_domain_max h p,
{ assumption },
{ exfalso, apply mem_domain_consist h,
apply prf.mp,
{ apply prf.ax h_1 },
{ apply prf.mp,
{ apply prf.t },
{ apply prf.ax,
apply mem_unbox_iff_mem_box.1,
assumption } } }
end
-- symmetry
lemma access.symm : ∀ w ∈ domain σ, ∀ v ∈ domain σ, access w v = tt → access v w = tt :=
begin
intros w hw v hv, unfold access,
simp, intros sw p hp,
apply mem_domain_of_prf _ hw,
apply prf.mp,
{ apply prf.sub_weak, apply prf.contrap_b, simp },
{ have h₁ : ∀ p, p ∉ v → p ∉ unbox w, from
(λ p, (@not_imp_not _ _ (prop_decidable _)).2 (@sw _ ) ),
have h₂ : (◻~◻p) ∉ w, from
begin
apply h₁,
intro h, apply mem_domain_consist hv,
apply prf.mp,
{ apply prf.ax h },
{ apply prf.ax, assumption }
end,
cases mem_domain_max hw (◻~◻p),
{ contradiction },
{ apply prf.ax, assumption } }
end
-- transitivity
lemma access.trans : ∀ w ∈ domain σ, ∀ v ∈ domain σ, ∀ u ∈ domain σ,
access w v = tt → access v u = tt → access w u = tt :=
begin
intros w hw v hv u hu, unfold access,
simp, intros sw sv p hp,
apply sv, apply mem_unbox_iff_mem_box.2,
apply sw, apply mem_unbox_iff_mem_box.2,
apply mem_domain_of_prf, assumption,
apply prf.mp,
{ exact prf.s4 },
{ apply prf.ax,
apply mem_unbox_iff_mem_box.1,
assumption }
end
noncomputable def model : @model σ :=
begin
fapply model.mk,
apply domain,
apply access,
apply val,
apply access.refl,
apply access.symm,
apply access.trans
end
/- truth is membership in the canonical model -/
lemma form_tt_iff_mem_wrld {p : form σ} :
∀ (w ∈ domain σ), (w ⊩⦃model⦄ p) = tt ↔ p ∈ w :=
begin
induction p with v p q hp hq p hp,
{ intros, unfold forces_form model val, simp,
apply iff.intro,
{ intro h, exact h.right },
{ intro h, split, repeat {assumption} } },
{ unfold forces_form, simp,
intros w wm h, apply mem_domain_consist wm (prf.ax h) },
{ unfold forces_form, simp, intros v wm,
apply iff.intro,
{ intro h, cases h,
{ cases mem_domain_max wm p with h₁ h₂,
{ refine ctx.mem_max_of_prf wm _,
exact (prf.mp prf.pl1 (prf.ax ((hq _ wm).1 h))) },
{ refine ctx.mem_max_of_prf wm _,
apply prf.mp prf.contrap (prf.mp prf.pl1 (prf.ax h₂)) } },
{ cases mem_domain_max wm q with h₁ h₂,
{ refine ctx.mem_max_of_prf wm _,
exact prf.mp prf.pl1 (prf.ax h₁) },
{ refine ctx.mem_max_of_prf wm _,
refine prf.mp prf.contrap (prf.mp prf.pl1 _),
cases mem_domain_max wm p with hp₁ hp₂,
{ exfalso, apply ff_eq_tt_eq_false,
transitivity,
{ exact h.symm },
{ exact (hp _ wm).2 hp₁} },
{ apply prf.ax hp₂ } } } },
{ intro h,
cases mem_domain_max wm q with h₁ h₂,
{ left, exact (hq _ wm).2 h₁ },
{ cases mem_domain_max wm p with hp₁ hp₂,
{ exfalso, apply mem_domain_consist wm,
exact prf.mp (prf.ax h₂) (prf.mp (prf.ax h) (prf.ax hp₁)) },
{ right, apply eq_ff_of_not_eq_tt,
intro ptt, apply mem_domain_consist wm,
exact prf.mp (prf.ax hp₂) (prf.ax ((hp _ wm).1 ptt)) } } } },
{ unfold forces_form,
simp, intros w wm,
apply iff.intro,
{ intro h,
cases mem_domain_max wm (◻p) with h₁ h₂,
{ exact h₁ },
exfalso, apply ctx.is_consist_max (consist_unbox_of_not_box_mem wm h₂),
apply prf.mp,
{ apply prf.ax (ctx.subset_max_self (mem_insert _ _)) },
{ apply prf.ax,
apply (hp _ (mem_domain (consist_unbox_of_not_box_mem wm h₂))).1,
apply h, apply mem_domain (consist_unbox_of_not_box_mem wm h₂), exact wm,
apply subset_unbox_iff_access.2,
intros p pm, apply ctx.subset_max_self,
apply mem_insert_of_mem _ pm } },
{ intro h,
intros w v, unfold model access, simp,
intros wm' rwv,
exact (hp _ v).2 (rwv (mem_unbox_iff_mem_box.2 h)) } }
end
lemma ctx_tt_of_mem_domain (Γ : ctx σ) (wm : Γ ∈ domain σ) :
(Γ ⊩⦃model⦄ Γ) = tt :=
mem_tt_to_ctx_tt Γ (λ p pm, (form_tt_iff_mem_wrld _ wm).2 pm)
/- the completeness lemma -/
theorem completeness {Γ : ctx σ} {p : form σ} :
(Γ ⊨ₛ₅ p) → (Γ ⊢ₛ₅ p) :=
begin
apply (@not_imp_not (Γ ⊢ₛ₅ p) (Γ ⊨ₛ₅ p) (prop_decidable _)).1,
intros nhp hp, cases hp,
have c : is_consist (Γ ⸴ ~p) := consist_not_of_not_prf nhp,
apply absurd,
fapply hp,
{ exact model },
{ exact ctx.max (Γ ⸴ ~p) },
{ apply mem_domain c },
{ apply cons_ctx_tt_to_ctx_tt,
apply ctx_tt_to_subctx_tt,
apply ctx_tt_of_mem_domain (ctx.max (Γ ⸴ ~p)),
apply mem_domain c,
apply ctx.subset_max_self },
{ simp, apply eq_ff_of_not_eq_tt,
apply neg_tt_iff_ff.1,
apply and.elim_right,
apply cons_ctx_tt_iff_and.1,
apply ctx_tt_to_subctx_tt,
apply ctx_tt_of_mem_domain (ctx.max (Γ ⸴ ~p)),
apply mem_domain c,
apply ctx.subset_max_self },
end
end canonical |
6be4d466bac7998898b6759e9d191d5d2d1e8256 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/lean/run/genindices.lean | a7c390a8a3c6d384f96a7afa85e26e9bb5b760bc | [
"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 | 727 | lean | import Init.Lean
universe u
inductive Pred : ∀ (α : Type u), List α → Type (u+1)
| foo {α : Type u} (l1 : List α) (l2 : List (Option α)) : Pred (Option α) l2 → Pred α l1
axiom goal : forall (α : Type u) (xs : List (List α)) (h : Pred (List α) xs), xs ≠ [] → xs = xs
open Lean
open Lean.Meta
def tst1 : MetaM Unit := do
cinfo ← getConstInfo `goal;
let type := cinfo.type;
mvar ← mkFreshExprMVar type;
trace! `Elab (MessageData.ofGoal mvar.mvarId!);
(_, mvarId) ← introN mvar.mvarId! 2;
(fvarId, mvarId) ← intro1 mvarId;
trace! `Elab (MessageData.ofGoal mvarId);
s ← generalizeIndices mvarId fvarId;
trace! `Elab (MessageData.ofGoal s.mvarId);
pure ()
set_option trace.Elab true
#eval tst1
|
5a433034071ff8bcd545f1148676b6db3618dbe9 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/ring_theory/roots_of_unity/complex.lean | d5841c9d4726bcb0eb054920af14ca1638257c14 | [
"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,120 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import analysis.special_functions.complex.log
import ring_theory.roots_of_unity.basic
/-!
# Complex roots of unity
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we show that the `n`-th complex roots of unity
are exactly the complex numbers `e ^ (2 * real.pi * complex.I * (i / n))` for `i ∈ finset.range n`.
## Main declarations
* `complex.mem_roots_of_unity`: the complex `n`-th roots of unity are exactly the
complex numbers of the form `e ^ (2 * real.pi * complex.I * (i / n))` for some `i < n`.
* `complex.card_roots_of_unity`: the number of `n`-th roots of unity is exactly `n`.
-/
namespace complex
open polynomial real
open_locale nat real
lemma is_primitive_root_exp_of_coprime (i n : ℕ) (h0 : n ≠ 0) (hi : i.coprime n) :
is_primitive_root (exp (2 * π * I * (i / n))) n :=
begin
rw is_primitive_root.iff_def,
simp only [← exp_nat_mul, exp_eq_one_iff],
have hn0 : (n : ℂ) ≠ 0, by exact_mod_cast h0,
split,
{ use i,
field_simp [hn0, mul_comm (i : ℂ), mul_comm (n : ℂ)] },
{ simp only [hn0, mul_right_comm _ _ ↑n, mul_left_inj' two_pi_I_ne_zero, ne.def, not_false_iff,
mul_comm _ (i : ℂ), ← mul_assoc _ (i : ℂ), exists_imp_distrib] with field_simps,
norm_cast,
rintro l k hk,
have : n ∣ i * l,
{ rw [← int.coe_nat_dvd, hk], apply dvd_mul_left },
exact hi.symm.dvd_of_dvd_mul_left this }
end
lemma is_primitive_root_exp (n : ℕ) (h0 : n ≠ 0) : is_primitive_root (exp (2 * π * I / n)) n :=
by simpa only [nat.cast_one, one_div]
using is_primitive_root_exp_of_coprime 1 n h0 n.coprime_one_left
lemma is_primitive_root_iff (ζ : ℂ) (n : ℕ) (hn : n ≠ 0) :
is_primitive_root ζ n ↔ (∃ (i < (n : ℕ)) (hi : i.coprime n), exp (2 * π * I * (i / n)) = ζ) :=
begin
have hn0 : (n : ℂ) ≠ 0 := by exact_mod_cast hn,
split, swap,
{ rintro ⟨i, -, hi, rfl⟩, exact is_primitive_root_exp_of_coprime i n hn hi },
intro h,
obtain ⟨i, hi, rfl⟩ :=
(is_primitive_root_exp n hn).eq_pow_of_pow_eq_one h.pow_eq_one (nat.pos_of_ne_zero hn),
refine ⟨i, hi, ((is_primitive_root_exp n hn).pow_iff_coprime (nat.pos_of_ne_zero hn) i).mp h, _⟩,
rw [← exp_nat_mul],
congr' 1,
field_simp [hn0, mul_comm (i : ℂ)]
end
/-- The complex `n`-th roots of unity are exactly the
complex numbers of the form `e ^ (2 * real.pi * complex.I * (i / n))` for some `i < n`. -/
lemma mem_roots_of_unity (n : ℕ+) (x : units ℂ) :
x ∈ roots_of_unity n ℂ ↔ (∃ i < (n : ℕ), exp (2 * π * I * (i / n)) = x) :=
begin
rw [mem_roots_of_unity, units.ext_iff, units.coe_pow, units.coe_one],
have hn0 : (n : ℂ) ≠ 0 := by exact_mod_cast (n.ne_zero),
split,
{ intro h,
obtain ⟨i, hi, H⟩ : ∃ i < (n : ℕ), exp (2 * π * I / n) ^ i = x,
{ simpa only using (is_primitive_root_exp n n.ne_zero).eq_pow_of_pow_eq_one h n.pos },
refine ⟨i, hi, _⟩,
rw [← H, ← exp_nat_mul],
congr' 1,
field_simp [hn0, mul_comm (i : ℂ)] },
{ rintro ⟨i, hi, H⟩,
rw [← H, ← exp_nat_mul, exp_eq_one_iff],
use i,
field_simp [hn0, mul_comm ((n : ℕ) : ℂ), mul_comm (i : ℂ)] }
end
lemma card_roots_of_unity (n : ℕ+) : fintype.card (roots_of_unity n ℂ) = n :=
(is_primitive_root_exp n n.ne_zero).card_roots_of_unity
lemma card_primitive_roots (k : ℕ) : (primitive_roots k ℂ).card = φ k :=
begin
by_cases h : k = 0,
{ simp [h] },
exact (is_primitive_root_exp k h).card_primitive_roots,
end
end complex
lemma is_primitive_root.norm'_eq_one {ζ : ℂ} {n : ℕ} (h : is_primitive_root ζ n) (hn : n ≠ 0) :
‖ζ‖ = 1 := complex.norm_eq_one_of_pow_eq_one h.pow_eq_one hn
lemma is_primitive_root.nnnorm_eq_one {ζ : ℂ} {n : ℕ} (h : is_primitive_root ζ n) (hn : n ≠ 0) :
‖ζ‖₊ = 1 := subtype.ext $ h.norm'_eq_one hn
lemma is_primitive_root.arg_ext {n m : ℕ} {ζ μ : ℂ} (hζ : is_primitive_root ζ n)
(hμ : is_primitive_root μ m) (hn : n ≠ 0) (hm : m ≠ 0) (h : ζ.arg = μ.arg) : ζ = μ :=
complex.ext_abs_arg ((hζ.norm'_eq_one hn).trans (hμ.norm'_eq_one hm).symm) h
lemma is_primitive_root.arg_eq_zero_iff {n : ℕ} {ζ : ℂ} (hζ : is_primitive_root ζ n)
(hn : n ≠ 0) : ζ.arg = 0 ↔ ζ = 1 :=
⟨λ h, hζ.arg_ext is_primitive_root.one hn one_ne_zero (h.trans complex.arg_one.symm),
λ h, h.symm ▸ complex.arg_one⟩
lemma is_primitive_root.arg_eq_pi_iff {n : ℕ} {ζ : ℂ} (hζ : is_primitive_root ζ n)
(hn : n ≠ 0) : ζ.arg = real.pi ↔ ζ = -1 :=
⟨λ h, hζ.arg_ext (is_primitive_root.neg_one 0 two_ne_zero.symm) hn two_ne_zero
(h.trans complex.arg_neg_one.symm), λ h, h.symm ▸ complex.arg_neg_one⟩
lemma is_primitive_root.arg {n : ℕ} {ζ : ℂ} (h : is_primitive_root ζ n) (hn : n ≠ 0) :
∃ i : ℤ, ζ.arg = i / n * (2 * real.pi) ∧ is_coprime i n ∧ i.nat_abs < n :=
begin
rw complex.is_primitive_root_iff _ _ hn at h,
obtain ⟨i, h, hin, rfl⟩ := h,
rw [mul_comm, ←mul_assoc, complex.exp_mul_I],
refine ⟨if i * 2 ≤ n then i else i - n, _, _, _⟩,
work_on_goal 2
{ replace hin := nat.is_coprime_iff_coprime.mpr hin,
split_ifs with _,
{ exact hin },
{ convert hin.add_mul_left_left (-1),
rw [mul_neg_one, sub_eq_add_neg] } },
work_on_goal 2
{ split_ifs with h₂,
{ exact_mod_cast h },
suffices : (i - n : ℤ).nat_abs = n - i,
{ rw this,
apply tsub_lt_self hn.bot_lt,
contrapose! h₂,
rw [nat.eq_zero_of_le_zero h₂, zero_mul],
exact zero_le _ },
rw [←int.nat_abs_neg, neg_sub, int.nat_abs_eq_iff],
exact or.inl (int.coe_nat_sub h.le).symm },
split_ifs with h₂,
{ convert complex.arg_cos_add_sin_mul_I _,
{ push_cast },
{ push_cast },
field_simp [hn],
refine ⟨(neg_lt_neg real.pi_pos).trans_le _, _⟩,
{ rw neg_zero,
exact mul_nonneg (mul_nonneg i.cast_nonneg $ by simp [real.pi_pos.le]) (by simp) },
rw [←mul_rotate', mul_div_assoc],
rw ←mul_one n at h₂,
exact mul_le_of_le_one_right real.pi_pos.le
((div_le_iff' $ by exact_mod_cast (pos_of_gt h)).mpr $ by exact_mod_cast h₂) },
rw [←complex.cos_sub_two_pi, ←complex.sin_sub_two_pi],
convert complex.arg_cos_add_sin_mul_I _,
{ push_cast,
rw [←sub_one_mul, sub_div, div_self],
exact_mod_cast hn },
{ push_cast,
rw [←sub_one_mul, sub_div, div_self],
exact_mod_cast hn },
field_simp [hn],
refine ⟨_, le_trans _ real.pi_pos.le⟩,
work_on_goal 2
{ rw [mul_div_assoc],
exact mul_nonpos_of_nonpos_of_nonneg (sub_nonpos.mpr $ by exact_mod_cast h.le)
(div_nonneg (by simp [real.pi_pos.le]) $ by simp) },
rw [←mul_rotate', mul_div_assoc, neg_lt, ←mul_neg, mul_lt_iff_lt_one_right real.pi_pos,
←neg_div, ←neg_mul, neg_sub, div_lt_iff, one_mul, sub_mul, sub_lt_comm, ←mul_sub_one],
norm_num,
exact_mod_cast not_le.mp h₂,
{ exact (nat.cast_pos.mpr hn.bot_lt) }
end
|
0871336258de85a5415d7c121c59747502f69630 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/has_variable_names.lean | 5ff1c7cec7c4f7e65e56145b0a44bf15598278d0 | [] | 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 | 9,510 | lean | /-
Copyright (c) 2020 Jannis Limperg. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jannis Limperg
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.core
import Mathlib.PostPort
universes u l v u_1 u_2
namespace Mathlib
/-!
# A tactic for type-based naming of variables
When we name hypotheses or variables, we often do so in a type-directed fashion:
a hypothesis of type `ℕ` is called `n` or `m`; a hypothesis of type `list ℕ` is
called `ns`; etc. This module provides a tactic,
`tactic.typical_variable_names`, which looks up typical variable names for a
given type.
Typical variable names are registered by giving an instance of the type class
`has_variable_names`. This file provides `has_variable_names` instances for many
of the core Lean types. If you want to override these, you can declare a
high-priority instance (perhaps localised) of `has_variable_names`. E.g. to
change the names given to natural numbers:
```lean
def foo : has_variable_names ℕ :=
⟨[`i, `j, `k]⟩
local attribute [instance, priority 1000] foo
```
-/
/--
Type class for associating a type `α` with typical variable names for elements
of `α`. See `tactic.typical_variable_names`.
-/
class has_variable_names (α : Sort u)
where
names : List name
names_nonempty : autoParam (0 < list.length names)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.exact_dec_trivial")
(Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "exact_dec_trivial") [])
namespace tactic
/--
`typical_variable_names t` obtains typical names for variables of type `t`.
The returned list is guaranteed to be nonempty. Fails if there is no instance
`has_typical_variable_names t`.
```
typical_variable_names `(ℕ) = [`n, `m, `o]
```
-/
end tactic
namespace has_variable_names
/--
`@make_listlike_instance α _ β` creates an instance `has_variable_names β` from
an instance `has_variable_names α`. If `α` has associated names `a`, `b`, ...,
the generated instance for `β` has names `as`, `bs`, ... This can be used to
create instances for 'containers' such as lists or sets.
-/
def make_listlike_instance (α : Sort u) [has_variable_names α] {β : Sort v} : has_variable_names β :=
mk
(list.map
(fun (n : name) =>
name.append_suffix n (string.str string.empty (char.of_nat (bit1 (bit1 (bit0 (bit0 (bit1 (bit1 1)))))))))
(names α))
/--
`@make_inheriting_instance α _ β` creates an instance `has_variable_names β`
from an instance `has_variable_names α`. The generated instance contains the
same variable names as that of `α`. This can be used to create instances for
'wrapper' types like `option` and `subtype`.
-/
def make_inheriting_instance (α : Sort u) [has_variable_names α] {β : Sort v} : has_variable_names β :=
mk (names α)
end has_variable_names
protected instance d_array.has_variable_names {n : ℕ} {α : Type u_1} [has_variable_names α] : has_variable_names (d_array n fun (_x : fin n) => α) :=
has_variable_names.make_listlike_instance α
protected instance bool.has_variable_names : has_variable_names Bool :=
has_variable_names.mk
[name.mk_string (string.str string.empty (char.of_nat (bit0 (bit1 (bit0 (bit0 (bit0 (bit1 1)))))))) name.anonymous]
protected instance char.has_variable_names : has_variable_names char :=
has_variable_names.mk
[name.mk_string (string.str string.empty (char.of_nat (bit1 (bit1 (bit0 (bit0 (bit0 (bit1 1)))))))) name.anonymous]
protected instance fin.has_variable_names {n : ℕ} : has_variable_names (fin n) :=
has_variable_names.mk
[name.mk_string (string.str string.empty (char.of_nat (bit0 (bit1 (bit1 (bit1 (bit0 (bit1 1)))))))) name.anonymous,
name.mk_string (string.str string.empty (char.of_nat (bit1 (bit0 (bit1 (bit1 (bit0 (bit1 1)))))))) name.anonymous,
name.mk_string (string.str string.empty (char.of_nat (bit1 (bit1 (bit1 (bit1 (bit0 (bit1 1)))))))) name.anonymous]
protected instance int.has_variable_names : has_variable_names ℤ :=
has_variable_names.mk
[name.mk_string (string.str string.empty (char.of_nat (bit0 (bit1 (bit1 (bit1 (bit0 (bit1 1)))))))) name.anonymous,
name.mk_string (string.str string.empty (char.of_nat (bit1 (bit0 (bit1 (bit1 (bit0 (bit1 1)))))))) name.anonymous,
name.mk_string (string.str string.empty (char.of_nat (bit1 (bit1 (bit1 (bit1 (bit0 (bit1 1)))))))) name.anonymous]
protected instance list.has_variable_names {α : Type u_1} [has_variable_names α] : has_variable_names (List α) :=
has_variable_names.make_listlike_instance α
protected instance nat.has_variable_names : has_variable_names ℕ :=
has_variable_names.mk
[name.mk_string (string.str string.empty (char.of_nat (bit0 (bit1 (bit1 (bit1 (bit0 (bit1 1)))))))) name.anonymous,
name.mk_string (string.str string.empty (char.of_nat (bit1 (bit0 (bit1 (bit1 (bit0 (bit1 1)))))))) name.anonymous,
name.mk_string (string.str string.empty (char.of_nat (bit1 (bit1 (bit1 (bit1 (bit0 (bit1 1)))))))) name.anonymous]
protected instance sort.has_variable_names : has_variable_names Prop :=
has_variable_names.mk
[name.mk_string (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit1 (bit0 1)))))))) name.anonymous,
name.mk_string (string.str string.empty (char.of_nat (bit1 (bit0 (bit0 (bit0 (bit1 (bit0 1)))))))) name.anonymous,
name.mk_string (string.str string.empty (char.of_nat (bit0 (bit1 (bit0 (bit0 (bit1 (bit0 1)))))))) name.anonymous]
protected instance thunk.has_variable_names {α : Type u_1} [has_variable_names α] : has_variable_names (thunk α) :=
has_variable_names.make_inheriting_instance α
protected instance prod.has_variable_names {α : Type u_1} {β : Type u_2} : has_variable_names (α × β) :=
has_variable_names.mk
[name.mk_string (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit1 (bit1 1)))))))) name.anonymous]
protected instance pprod.has_variable_names {α : Sort u_1} {β : Sort u_2} : has_variable_names (PProd α β) :=
has_variable_names.mk
[name.mk_string (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit1 (bit1 1)))))))) name.anonymous]
protected instance sigma.has_variable_names {α : Type u_1} {β : α → Type u_2} : has_variable_names (sigma β) :=
has_variable_names.mk
[name.mk_string (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit1 (bit1 1)))))))) name.anonymous]
protected instance psigma.has_variable_names {α : Sort u_1} {β : α → Sort u_2} : has_variable_names (psigma β) :=
has_variable_names.mk
[name.mk_string (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit1 (bit1 1)))))))) name.anonymous]
protected instance subtype.has_variable_names {α : Sort u_1} [has_variable_names α] {p : α → Prop} : has_variable_names (Subtype p) :=
has_variable_names.make_inheriting_instance α
protected instance option.has_variable_names {α : Type u_1} [has_variable_names α] : has_variable_names (Option α) :=
has_variable_names.make_inheriting_instance α
protected instance bin_tree.has_variable_names {α : Type u_1} : has_variable_names (bin_tree α) :=
has_variable_names.mk
[name.mk_string (string.str string.empty (char.of_nat (bit0 (bit0 (bit1 (bit0 (bit1 (bit1 1)))))))) name.anonymous]
protected instance rbtree.has_variable_names {α : Type u_1} [has_variable_names α] {lt : α → α → Prop} : has_variable_names (rbtree α) :=
has_variable_names.make_listlike_instance α
protected instance set.has_variable_names {α : Type u_1} [has_variable_names α] : has_variable_names (set α) :=
has_variable_names.make_listlike_instance α
protected instance string.has_variable_names : has_variable_names string :=
has_variable_names.mk
[name.mk_string (string.str string.empty (char.of_nat (bit1 (bit1 (bit0 (bit0 (bit1 (bit1 1)))))))) name.anonymous]
protected instance unsigned.has_variable_names : has_variable_names unsigned :=
has_variable_names.mk
[name.mk_string (string.str string.empty (char.of_nat (bit0 (bit1 (bit1 (bit1 (bit0 (bit1 1)))))))) name.anonymous,
name.mk_string (string.str string.empty (char.of_nat (bit1 (bit0 (bit1 (bit1 (bit0 (bit1 1)))))))) name.anonymous,
name.mk_string (string.str string.empty (char.of_nat (bit1 (bit1 (bit1 (bit1 (bit0 (bit1 1)))))))) name.anonymous]
protected instance pi.has_variable_names {α : Sort u_1} {β : α → Sort u_2} : has_variable_names ((a : α) → β a) :=
has_variable_names.mk
[name.mk_string (string.str string.empty (char.of_nat (bit0 (bit1 (bit1 (bit0 (bit0 (bit1 1)))))))) name.anonymous,
name.mk_string (string.str string.empty (char.of_nat (bit1 (bit1 (bit1 (bit0 (bit0 (bit1 1)))))))) name.anonymous,
name.mk_string (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit1 (bit0 (bit1 1)))))))) name.anonymous]
protected instance name.has_variable_names : has_variable_names name :=
has_variable_names.mk
[name.mk_string (string.str string.empty (char.of_nat (bit0 (bit1 (bit1 (bit1 (bit0 (bit1 1)))))))) name.anonymous]
protected instance binder_info.has_variable_names : has_variable_names binder_info :=
has_variable_names.mk
[name.mk_string
(string.str (string.str string.empty (char.of_nat (bit0 (bit1 (bit0 (bit0 (bit0 (bit1 1))))))))
(char.of_nat (bit1 (bit0 (bit0 (bit1 (bit0 (bit1 1))))))))
name.anonymous]
|
81507b57bd9489bd091c418bc3a8b7fa86c9ee7d | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/multiset/finset_ops.lean | e8e5a03ff8a3d2f1116704f2d53864501f995650 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 8,673 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.multiset.dedup
/-!
# Preparations for defining operations on `finset`.
The operations here ignore multiplicities,
and preparatory for defining the corresponding operations on `finset`.
-/
namespace multiset
open list
variables {α : Type*} [decidable_eq α] {s : multiset α}
/-! ### finset insert -/
/-- `ndinsert a s` is the lift of the list `insert` operation. This operation
does not respect multiplicities, unlike `cons`, but it is suitable as
an insert operation on `finset`. -/
def ndinsert (a : α) (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (l.insert a : multiset α))
(λ s t p, quot.sound (p.insert a))
@[simp] theorem coe_ndinsert (a : α) (l : list α) : ndinsert a l = (insert a l : list α) := rfl
@[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = {a} := rfl
@[simp, priority 980]
theorem ndinsert_of_mem {a : α} {s : multiset α} : a ∈ s → ndinsert a s = s :=
quot.induction_on s $ λ l h, congr_arg coe $ insert_of_mem h
@[simp, priority 980]
theorem ndinsert_of_not_mem {a : α} {s : multiset α} : a ∉ s → ndinsert a s = a ::ₘ s :=
quot.induction_on s $ λ l h, congr_arg coe $ insert_of_not_mem h
@[simp] theorem mem_ndinsert {a b : α} {s : multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s :=
quot.induction_on s $ λ l, mem_insert_iff
@[simp] theorem le_ndinsert_self (a : α) (s : multiset α) : s ≤ ndinsert a s :=
quot.induction_on s $ λ l, (sublist_insert _ _).subperm
@[simp] theorem mem_ndinsert_self (a : α) (s : multiset α) : a ∈ ndinsert a s :=
mem_ndinsert.2 (or.inl rfl)
theorem mem_ndinsert_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ ndinsert b s :=
mem_ndinsert.2 (or.inr h)
@[simp, priority 980]
theorem length_ndinsert_of_mem {a : α} {s : multiset α} (h : a ∈ s) :
card (ndinsert a s) = card s :=
by simp [h]
@[simp, priority 980]
theorem length_ndinsert_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) :
card (ndinsert a s) = card s + 1 :=
by simp [h]
theorem dedup_cons {a : α} {s : multiset α} :
dedup (a ::ₘ s) = ndinsert a (dedup s) :=
by by_cases a ∈ s; simp [h]
lemma nodup.ndinsert (a : α) : nodup s → nodup (ndinsert a s) :=
quot.induction_on s $ λ l, nodup.insert
theorem ndinsert_le {a : α} {s t : multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t :=
⟨λ h, ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩,
λ ⟨l, m⟩, if h : a ∈ s then by simp [h, l] else
by rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff,
← le_cons_of_not_mem h, cons_erase m]; exact l⟩
lemma attach_ndinsert (a : α) (s : multiset α) :
(s.ndinsert a).attach =
ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, mem_ndinsert_of_mem p.2⟩) :=
have eq : ∀h : ∀(p : {x // x ∈ s}), p.1 ∈ s,
(λ (p : {x // x ∈ s}), ⟨p.val, h p⟩ : {x // x ∈ s} → {x // x ∈ s}) = id, from
assume h, funext $ assume p, subtype.eq rfl,
have ∀t (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩
(s.attach.map $ λp, ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩),
begin
intros t ht,
by_cases a ∈ s,
{ rw [ndinsert_of_mem h] at ht,
subst ht,
rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)] },
{ rw [ndinsert_of_not_mem h] at ht,
subst ht,
simp [attach_cons, h] }
end,
this _ rfl
@[simp] theorem disjoint_ndinsert_left {a : α} {s t : multiset α} :
disjoint (ndinsert a s) t ↔ a ∉ t ∧ disjoint s t :=
iff.trans (by simp [disjoint]) disjoint_cons_left
@[simp] theorem disjoint_ndinsert_right {a : α} {s t : multiset α} :
disjoint s (ndinsert a t) ↔ a ∉ s ∧ disjoint s t :=
by rw [disjoint_comm, disjoint_ndinsert_left]; tauto
/-! ### finset union -/
/-- `ndunion s t` is the lift of the list `union` operation. This operation
does not respect multiplicities, unlike `s ∪ t`, but it is suitable as
a union operation on `finset`. (`s ∪ t` would also work as a union operation
on finset, but this is more efficient.) -/
def ndunion (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.union l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ p₁.union p₂
@[simp] theorem coe_ndunion (l₁ l₂ : list α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : list α) := rfl
@[simp] theorem zero_ndunion (s : multiset α) : ndunion 0 s = s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem cons_ndunion (s t : multiset α) (a : α) :
ndunion (a ::ₘ s) t = ndinsert a (ndunion s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, rfl
@[simp] theorem mem_ndunion {s t : multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, list.mem_union
theorem le_ndunion_right (s t : multiset α) : t ≤ ndunion s t :=
quotient.induction_on₂ s t $ λ l₁ l₂, (suffix_union_right _ _).sublist.subperm
theorem subset_ndunion_right (s t : multiset α) : t ⊆ ndunion s t :=
subset_of_le (le_ndunion_right s t)
theorem ndunion_le_add (s t : multiset α) : ndunion s t ≤ s + t :=
quotient.induction_on₂ s t $ λ l₁ l₂, (union_sublist_append _ _).subperm
theorem ndunion_le {s t u : multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u :=
multiset.induction_on s (by simp)
(by simp [ndinsert_le, and_comm, and.left_comm] {contextual := tt})
theorem subset_ndunion_left (s t : multiset α) : s ⊆ ndunion s t :=
λ a h, mem_ndunion.2 $ or.inl h
theorem le_ndunion_left {s} (t : multiset α) (d : nodup s) : s ≤ ndunion s t :=
(le_iff_subset d).2 $ subset_ndunion_left _ _
theorem ndunion_le_union (s t : multiset α) : ndunion s t ≤ s ∪ t :=
ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩
lemma nodup.ndunion (s : multiset α) {t : multiset α} : nodup t → nodup (ndunion s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, list.nodup.union _
@[simp, priority 980]
theorem ndunion_eq_union {s t : multiset α} (d : nodup s) : ndunion s t = s ∪ t :=
le_antisymm (ndunion_le_union _ _) $ union_le (le_ndunion_left _ d) (le_ndunion_right _ _)
theorem dedup_add (s t : multiset α) : dedup (s + t) = ndunion s (dedup t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ dedup_append _ _
/-! ### finset inter -/
/-- `ndinter s t` is the lift of the list `∩` operation. This operation
does not respect multiplicities, unlike `s ∩ t`, but it is suitable as
an intersection operation on `finset`. (`s ∩ t` would also work as a union operation
on finset, but this is more efficient.) -/
def ndinter (s t : multiset α) : multiset α := filter (∈ t) s
@[simp] theorem coe_ndinter (l₁ l₂ : list α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : list α) := rfl
@[simp] theorem zero_ndinter (s : multiset α) : ndinter 0 s = 0 := rfl
@[simp, priority 980]
theorem cons_ndinter_of_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) :
ndinter (a ::ₘ s) t = a ::ₘ (ndinter s t) := by simp [ndinter, h]
@[simp, priority 980]
theorem ndinter_cons_of_not_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∉ t) :
ndinter (a ::ₘ s) t = ndinter s t := by simp [ndinter, h]
@[simp] theorem mem_ndinter {s t : multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t :=
mem_filter
@[simp]
lemma nodup.ndinter {s : multiset α} (t : multiset α) : nodup s → nodup (ndinter s t) :=
nodup.filter _
theorem le_ndinter {s t u : multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u :=
by simp [ndinter, le_filter, subset_iff]
theorem ndinter_le_left (s t : multiset α) : ndinter s t ≤ s :=
(le_ndinter.1 le_rfl).1
theorem ndinter_subset_left (s t : multiset α) : ndinter s t ⊆ s :=
subset_of_le (ndinter_le_left s t)
theorem ndinter_subset_right (s t : multiset α) : ndinter s t ⊆ t :=
(le_ndinter.1 le_rfl).2
theorem ndinter_le_right {s} (t : multiset α) (d : nodup s) : ndinter s t ≤ t :=
(le_iff_subset $ d.ndinter _).2 $ ndinter_subset_right _ _
theorem inter_le_ndinter (s t : multiset α) : s ∩ t ≤ ndinter s t :=
le_ndinter.2 ⟨inter_le_left _ _, subset_of_le $ inter_le_right _ _⟩
@[simp, priority 980]
theorem ndinter_eq_inter {s t : multiset α} (d : nodup s) : ndinter s t = s ∩ t :=
le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _)
theorem ndinter_eq_zero_iff_disjoint {s t : multiset α} : ndinter s t = 0 ↔ disjoint s t :=
by rw ← subset_zero; simp [subset_iff, disjoint]
end multiset
|
8c1896b50444164889a90368be43652d224ae67b | e61a235b8468b03aee0120bf26ec615c045005d2 | /tests/bench/parser.lean | 4438f318226c1c45a6a100375b94b0842fb518a2 | [
"Apache-2.0"
] | permissive | SCKelemen/lean4 | 140dc63a80539f7c61c8e43e1c174d8500ec3230 | e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc | refs/heads/master | 1,660,973,595,917 | 1,590,278,033,000 | 1,590,278,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 241 | lean | import Init.Lean.Parser
def main : List String → IO Unit
| [fname, n] => do
env ← Lean.mkEmptyEnvironment;
n.toNat!.forM $ fun _ =>
discard $ Lean.Parser.parseFile env fname;
pure ()
| _ => throw $ IO.userError "give file"
|
c468fdf7cbc9fae55fc730716dad6abfc48504a0 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/ring_theory/subring/pointwise.lean | 8bdf8604ce3a67bd6d69b963f11c8c1500e43f5f | [
"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 | 4,489 | lean | /-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import ring_theory.subsemiring.pointwise
import group_theory.subgroup.pointwise
import ring_theory.subring.basic
/-! # Pointwise instances on `subring`s
This file provides the action `subring.pointwise_mul_action` which matches the action of
`mul_action_set`.
This actions is available in the `pointwise` locale.
## Implementation notes
This file is almost identical to `ring_theory/subsemiring/pointwise.lean`. Where possible, try to
keep them in sync.
-/
open set
variables {M R : Type*}
namespace subring
section monoid
variables [monoid M] [ring R] [mul_semiring_action M R]
/-- The action on a subring corresponding to applying the action to every element.
This is available as an instance in the `pointwise` locale. -/
protected def pointwise_mul_action : mul_action M (subring R) :=
{ smul := λ a S, S.map (mul_semiring_action.to_ring_hom _ _ a),
one_smul := λ S,
(congr_arg (λ f, S.map f) (ring_hom.ext $ by exact one_smul M)).trans S.map_id,
mul_smul := λ a₁ a₂ S,
(congr_arg (λ f, S.map f) (ring_hom.ext $ by exact mul_smul _ _)).trans (S.map_map _ _).symm }
localized "attribute [instance] subring.pointwise_mul_action" in pointwise
open_locale pointwise
lemma pointwise_smul_def {a : M} (S : subring R) :
a • S = S.map (mul_semiring_action.to_ring_hom _ _ a) := rfl
@[simp] lemma coe_pointwise_smul (m : M) (S : subring R) : ↑(m • S) = m • (S : set R) := rfl
@[simp] lemma pointwise_smul_to_add_subgroup (m : M) (S : subring R) :
(m • S).to_add_subgroup = m • S.to_add_subgroup := rfl
@[simp] lemma pointwise_smul_to_subsemiring (m : M) (S : subring R) :
(m • S).to_subsemiring = m • S.to_subsemiring := rfl
lemma smul_mem_pointwise_smul (m : M) (r : R) (S : subring R) : r ∈ S → m • r ∈ m • S :=
(set.smul_mem_smul_set : _ → _ ∈ m • (S : set R))
lemma mem_smul_pointwise_iff_exists (m : M) (r : R) (S : subring R) :
r ∈ m • S ↔ ∃ (s : R), s ∈ S ∧ m • s = r :=
(set.mem_smul_set : r ∈ m • (S : set R) ↔ _)
instance pointwise_central_scalar [mul_semiring_action Mᵐᵒᵖ R] [is_central_scalar M R] :
is_central_scalar M (subring R) :=
⟨λ a S, congr_arg (λ f, S.map f) $ ring_hom.ext $ by exact op_smul_eq_smul _⟩
end monoid
section group
variables [group M] [ring R] [mul_semiring_action M R]
open_locale pointwise
@[simp] lemma smul_mem_pointwise_smul_iff {a : M} {S : subring R} {x : R} :
a • x ∈ a • S ↔ x ∈ S :=
smul_mem_smul_set_iff
lemma mem_pointwise_smul_iff_inv_smul_mem {a : M} {S : subring R} {x : R} :
x ∈ a • S ↔ a⁻¹ • x ∈ S :=
mem_smul_set_iff_inv_smul_mem
lemma mem_inv_pointwise_smul_iff {a : M} {S : subring R} {x : R} : x ∈ a⁻¹ • S ↔ a • x ∈ S :=
mem_inv_smul_set_iff
@[simp] lemma pointwise_smul_le_pointwise_smul_iff {a : M} {S T : subring R} :
a • S ≤ a • T ↔ S ≤ T :=
set_smul_subset_set_smul_iff
lemma pointwise_smul_subset_iff {a : M} {S T : subring R} : a • S ≤ T ↔ S ≤ a⁻¹ • T :=
set_smul_subset_iff
lemma subset_pointwise_smul_iff {a : M} {S T : subring R} : S ≤ a • T ↔ a⁻¹ • S ≤ T :=
subset_set_smul_iff
/-! TODO: add `equiv_smul` like we have for subgroup. -/
end group
section group_with_zero
variables [group_with_zero M] [ring R] [mul_semiring_action M R]
open_locale pointwise
@[simp] lemma smul_mem_pointwise_smul_iff₀ {a : M} (ha : a ≠ 0) (S : subring R)
(x : R) : a • x ∈ a • S ↔ x ∈ S :=
smul_mem_smul_set_iff₀ ha (S : set R) x
lemma mem_pointwise_smul_iff_inv_smul_mem₀ {a : M} (ha : a ≠ 0) (S : subring R) (x : R) :
x ∈ a • S ↔ a⁻¹ • x ∈ S :=
mem_smul_set_iff_inv_smul_mem₀ ha (S : set R) x
lemma mem_inv_pointwise_smul_iff₀ {a : M} (ha : a ≠ 0) (S : subring R) (x : R) :
x ∈ a⁻¹ • S ↔ a • x ∈ S :=
mem_inv_smul_set_iff₀ ha (S : set R) x
@[simp] lemma pointwise_smul_le_pointwise_smul_iff₀ {a : M} (ha : a ≠ 0) {S T : subring R} :
a • S ≤ a • T ↔ S ≤ T :=
set_smul_subset_set_smul_iff₀ ha
lemma pointwise_smul_le_iff₀ {a : M} (ha : a ≠ 0) {S T : subring R} : a • S ≤ T ↔ S ≤ a⁻¹ • T :=
set_smul_subset_iff₀ ha
lemma le_pointwise_smul_iff₀ {a : M} (ha : a ≠ 0) {S T : subring R} : S ≤ a • T ↔ a⁻¹ • S ≤ T :=
subset_set_smul_iff₀ ha
end group_with_zero
end subring
|
83a2c890cbcce949e513835073ab84d462bc0ff4 | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/run/e17.lean | 849db414bfb6f325543b0a517f56abaa4dbe06c9 | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 422 | lean | inductive nat : Type :=
| zero : nat
| succ : nat → nat
inductive list (A : Type) : Type :=
| nil {} : list A
| cons : A → list A → list A
inductive int : Type :=
| of_nat : nat → int
| neg : nat → int
coercion of_nat
variables n m : nat
variables i j : int
check cons i (cons i nil)
check cons n (cons n nil)
check cons i (cons n nil)
check cons n (cons i nil)
check cons n (cons i (cons m (cons j nil))) |
88841ecf4981360a6fad0397322c9b3e5ce48638 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /library/init/data/list/lemmas.lean | 319c60f0a7c480b4ab09a238365d2b1ba55d8f6c | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 1,592,202,909,807 | 1,504,624,387,000 | 1,504,624,387,000 | 75,319,626 | 2 | 1 | Apache-2.0 | 1,539,290,164,000 | 1,480,616,104,000 | C++ | UTF-8 | Lean | false | false | 10,451 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn
-/
prelude
import init.data.list.basic init.function init.meta init.data.nat.lemmas
import init.meta.interactive init.meta.smt.rsimp
universes u v w w₁ w₂
variables {α : Type u} {β : Type v} {γ : Type w}
namespace list
open nat
/- append -/
@[simp] lemma nil_append (s : list α) : [] ++ s = s :=
rfl
@[simp] lemma cons_append (x : α) (s t : list α) : (x::s) ++ t = x::(s ++ t) :=
rfl
@[simp] lemma append_nil (t : list α) : t ++ [] = t :=
by induction t; simp [*]
@[simp] lemma append_assoc (s t u : list α) : s ++ t ++ u = s ++ (t ++ u) :=
by induction s; simp [*]
/- length -/
lemma length_cons (a : α) (l : list α) : length (a :: l) = length l + 1 :=
rfl
@[simp] lemma length_append (s t : list α) : length (s ++ t) = length s + length t :=
by induction s; simp [*]
@[simp] lemma length_repeat (a : α) (n : ℕ) : length (repeat a n) = n :=
by induction n; simp [*]; refl
@[simp] lemma length_tail (l : list α) : length (tail l) = length l - 1 :=
by cases l; refl
-- TODO(Leo): cleanup proof after arith dec proc
@[simp] lemma length_drop : ∀ (i : ℕ) (l : list α), length (drop i l) = length l - i
| 0 l := rfl
| (succ i) [] := eq.symm (nat.zero_sub (succ i))
| (succ i) (x::l) := calc
length (drop (succ i) (x::l))
= length l - i : length_drop i l
... = succ (length l) - succ i : (nat.succ_sub_succ_eq_sub (length l) i).symm
/- map -/
lemma map_cons (f : α → β) (a l) : map f (a::l) = f a :: map f l :=
rfl
@[simp] lemma map_append (f : α → β) : ∀ l₁ l₂, map f (l₁ ++ l₂) = (map f l₁) ++ (map f l₂) :=
by intro l₁; induction l₁; intros; simp [*]
lemma map_singleton (f : α → β) (a : α) : map f [a] = [f a] :=
rfl
@[simp] lemma map_id (l : list α) : map id l = l :=
by induction l; simp [*]
@[simp] lemma map_map (g : β → γ) (f : α → β) (l : list α) : map g (map f l) = map (g ∘ f) l :=
by induction l; simp [*]
@[simp] lemma length_map (f : α → β) (l : list α) : length (map f l) = length l :=
by induction l; simp [*]
/- bind -/
@[simp] lemma nil_bind (f : α → list β) : bind [] f = [] :=
by simp [join, bind]
@[simp] lemma cons_bind (x xs) (f : α → list β) : bind (x :: xs) f = f x ++ bind xs f :=
by simp [join, bind]
@[simp] lemma append_bind (xs ys) (f : α → list β) : bind (xs ++ ys) f = bind xs f ++ bind ys f :=
by induction xs; [refl, simp [*, cons_bind]]
/- mem -/
@[simp] lemma mem_nil_iff (a : α) : a ∈ ([] : list α) ↔ false :=
iff.rfl
@[simp] lemma not_mem_nil (a : α) : a ∉ ([] : list α) :=
iff.mp $ mem_nil_iff a
@[simp] lemma mem_cons_self (a : α) (l : list α) : a ∈ a :: l :=
or.inl rfl
@[simp] lemma mem_cons_iff (a y : α) (l : list α) : a ∈ y :: l ↔ (a = y ∨ a ∈ l) :=
iff.rfl
@[rsimp] lemma mem_cons_eq (a y : α) (l : list α) : (a ∈ y :: l) = (a = y ∨ a ∈ l) :=
rfl
lemma mem_cons_of_mem (y : α) {a : α} {l : list α} : a ∈ l → a ∈ y :: l :=
assume H, or.inr H
lemma eq_or_mem_of_mem_cons {a y : α} {l : list α} : a ∈ y::l → a = y ∨ a ∈ l :=
assume h, h
@[simp] lemma mem_append {a : α} {s t : list α} : a ∈ s ++ t ↔ a ∈ s ∨ a ∈ t :=
by induction s; simp *
@[rsimp] lemma mem_append_eq (a : α) (s t : list α) : (a ∈ s ++ t) = (a ∈ s ∨ a ∈ t) :=
propext mem_append
lemma mem_append_left {a : α} {l₁ : list α} (l₂ : list α) (h : a ∈ l₁) : a ∈ l₁ ++ l₂ :=
mem_append.2 (or.inl h)
lemma mem_append_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ++ l₂ :=
mem_append.2 (or.inr h)
@[simp] lemma not_bex_nil (p : α → Prop) : ¬ (∃ x ∈ @nil α, p x) :=
λ⟨x, hx, px⟩, hx
@[simp] lemma ball_nil (p : α → Prop) : ∀ x ∈ @nil α, p x :=
λx, false.elim
@[simp] lemma bex_cons (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ (a :: l), p x) ↔ (p a ∨ ∃ x ∈ l, p x) :=
⟨λ⟨x, h, px⟩, by {
simp at h, cases h with h h, {cases h, exact or.inl px}, {exact or.inr ⟨x, h, px⟩}},
λo, o.elim (λpa, ⟨a, mem_cons_self _ _, pa⟩)
(λ⟨x, h, px⟩, ⟨x, mem_cons_of_mem _ h, px⟩)⟩
@[simp] lemma ball_cons (p : α → Prop) (a : α) (l : list α) : (∀ x ∈ (a :: l), p x) ↔ (p a ∧ ∀ x ∈ l, p x) :=
⟨λal, ⟨al a (mem_cons_self _ _), λx h, al x (mem_cons_of_mem _ h)⟩,
λ⟨pa, al⟩ x o, o.elim (λe, e.symm ▸ pa) (al x)⟩
/- list subset -/
protected def subset (l₁ l₂ : list α) := ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂
instance : has_subset (list α) := ⟨list.subset⟩
@[simp] lemma nil_subset (l : list α) : [] ⊆ l :=
λ b i, false.elim (iff.mp (mem_nil_iff b) i)
@[refl, simp] lemma subset.refl (l : list α) : l ⊆ l :=
λ b i, i
@[trans] lemma subset.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ ⊆ l₂) (h₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ :=
λ b i, h₂ (h₁ i)
@[simp] lemma subset_cons (a : α) (l : list α) : l ⊆ a::l :=
λ b i, or.inr i
lemma subset_of_cons_subset {a : α} {l₁ l₂ : list α} : a::l₁ ⊆ l₂ → l₁ ⊆ l₂ :=
λ s b i, s (mem_cons_of_mem _ i)
lemma cons_subset_cons {l₁ l₂ : list α} (a : α) (s : l₁ ⊆ l₂) : (a::l₁) ⊆ (a::l₂) :=
λ b hin, or.elim (eq_or_mem_of_mem_cons hin)
(λ e : b = a, or.inl e)
(λ i : b ∈ l₁, or.inr (s i))
@[simp] lemma subset_append_left (l₁ l₂ : list α) : l₁ ⊆ l₁++l₂ :=
λ b, mem_append_left _
@[simp] lemma subset_append_right (l₁ l₂ : list α) : l₂ ⊆ l₁++l₂ :=
λ b, mem_append_right _
lemma subset_cons_of_subset (a : α) {l₁ l₂ : list α} : l₁ ⊆ l₂ → l₁ ⊆ (a::l₂) :=
λ (s : l₁ ⊆ l₂) (a : α) (i : a ∈ l₁), or.inr (s i)
theorem eq_nil_of_length_eq_zero {l : list α} : length l = 0 → l = [] :=
by {induction l; intros, refl, contradiction}
theorem ne_nil_of_length_eq_succ {l : list α} : ∀ {n : nat}, length l = succ n → l ≠ [] :=
by induction l; intros; contradiction
@[simp] theorem length_map₂ (f : α → β → γ) (l₁) : ∀ l₂, length (map₂ f l₁ l₂) = min (length l₁) (length l₂) :=
by {induction l₁; intro l₂; cases l₂; simp [*, add_one, min_succ_succ]}
@[simp] theorem length_take : ∀ (i : ℕ) (l : list α), length (take i l) = min i (length l)
| 0 l := by simp
| (succ n) [] := by simp
| (succ n) (a::l) := by simp [*, nat.min_succ_succ, add_one]
theorem length_take_le (n) (l : list α) : length (take n l) ≤ n :=
by simp [min_le_left]
theorem length_remove_nth : ∀ (l : list α) (i : ℕ), i < length l → length (remove_nth l i) = length l - 1
| [] _ h := rfl
| (x::xs) 0 h := by simp [remove_nth, -add_comm]
| (x::xs) (i+1) h := have i < length xs, from lt_of_succ_lt_succ h,
by dsimp [remove_nth]; rw [length_remove_nth xs i this, nat.sub_add_cancel (lt_of_le_of_lt (nat.zero_le _) this)]; refl
@[simp] lemma partition_eq_filter_filter (p : α → Prop) [decidable_pred p] : ∀ (l : list α), partition p l = (filter p l, filter (not ∘ p) l)
| [] := rfl
| (a::l) := by { by_cases p a with pa; simp [partition, filter, pa, partition_eq_filter_filter l],
rw [if_neg (not_not_intro pa)], rw [if_pos pa] }
/- sublists -/
inductive sublist : list α → list α → Prop
| slnil : sublist [] []
| cons (l₁ l₂ a) : sublist l₁ l₂ → sublist l₁ (a::l₂)
| cons2 (l₁ l₂ a) : sublist l₁ l₂ → sublist (a::l₁) (a::l₂)
infix ` <+ `:50 := sublist
lemma length_le_of_sublist : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ ≤ length l₂
| ._ ._ sublist.slnil := le_refl 0
| ._ ._ (sublist.cons l₁ l₂ a s) := le_succ_of_le (length_le_of_sublist s)
| ._ ._ (sublist.cons2 l₁ l₂ a s) := succ_le_succ (length_le_of_sublist s)
/- filter -/
@[simp] theorem filter_nil (p : α → Prop) [h : decidable_pred p] : filter p [] = [] := rfl
@[simp] theorem filter_cons_of_pos {p : α → Prop} [h : decidable_pred p] {a : α} :
∀ l, p a → filter p (a::l) = a :: filter p l :=
λ l pa, if_pos pa
@[simp] theorem filter_cons_of_neg {p : α → Prop} [h : decidable_pred p] {a : α} :
∀ l, ¬ p a → filter p (a::l) = filter p l :=
λ l pa, if_neg pa
@[simp] theorem filter_append {p : α → Prop} [h : decidable_pred p] :
∀ (l₁ l₂ : list α), filter p (l₁++l₂) = filter p l₁ ++ filter p l₂
| [] l₂ := rfl
| (a::l₁) l₂ := by by_cases p a with pa; simp [pa, filter_append]
@[simp] theorem filter_sublist {p : α → Prop} [h : decidable_pred p] : Π (l : list α), filter p l <+ l
| [] := sublist.slnil
| (a::l) := if pa : p a
then by simp [pa]; apply sublist.cons2; apply filter_sublist l
else by simp [pa]; apply sublist.cons; apply filter_sublist l
/- map_accumr -/
section map_accumr
variables {φ : Type w₁} {σ : Type w₂}
-- This runs a function over a list returning the intermediate results and a
-- a final result.
def map_accumr (f : α → σ → σ × β) : list α → σ → (σ × list β)
| [] c := (c, [])
| (y::yr) c :=
let r := map_accumr yr c in
let z := f y r.1 in
(z.1, z.2 :: r.2)
@[simp] theorem length_map_accumr
: ∀ (f : α → σ → σ × β) (x : list α) (s : σ),
length (map_accumr f x s).2 = length x
| f (a::x) s := congr_arg succ (length_map_accumr f x s)
| f [] s := rfl
end map_accumr
section map_accumr₂
variables {φ : Type w₁} {σ : Type w₂}
-- This runs a function over two lists returning the intermediate results and a
-- a final result.
def map_accumr₂ (f : α → β → σ → σ × φ)
: list α → list β → σ → σ × list φ
| [] _ c := (c,[])
| _ [] c := (c,[])
| (x::xr) (y::yr) c :=
let r := map_accumr₂ xr yr c in
let q := f x y r.1 in
(q.1, q.2 :: r.2)
@[simp] theorem length_map_accumr₂ : ∀ (f : α → β → σ → σ × φ) x y c,
length (map_accumr₂ f x y c).2 = min (length x) (length y)
| f (a::x) (b::y) c := calc
succ (length (map_accumr₂ f x y c).2)
= succ (min (length x) (length y))
: congr_arg succ (length_map_accumr₂ f x y c)
... = min (succ (length x)) (succ (length y))
: eq.symm (min_succ_succ (length x) (length y))
| f (a::x) [] c := rfl
| f [] (b::y) c := rfl
| f [] [] c := rfl
end map_accumr₂
end list
|
1e73d13e0ee559e64d00acbb3468329ed5a502e3 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/interactive/hoverBinderUndescore.lean | 04b6c34433c5aae4a3aa056456a060d0545cb1be | [
"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 | 314 | lean | def f : Nat → Bool → Nat :=
fun _ _ => 5
--^ textDocument/hover
--^ textDocument/hover
def g : Nat → Bool → Nat :=
fun (_ _) => 5
--^ textDocument/hover
--^ textDocument/hover
def h : Nat → Bool → Nat :=
fun (_ _ : _) => 5
--^ textDocument/hover
--^ textDocument/hover
|
fb635781d8cf79c127491792be5a8a1fb8495382 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /counterexamples/pseudoelement.lean | ef4f62ba6cb7dd724a0872bdff0a71bdbcaf9020 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 5,414 | lean | /-
Copyright (c) 2022 Riccardo Brasca. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Riccardo Brasca
-/
import category_theory.abelian.pseudoelements
import algebra.category.Module.biproducts
/-!
# Pseudoelements and pullbacks
Borceux claims in Proposition 1.9.5 that the pseudoelement constructed in
`category_theory.abelian.pseudoelement.pseudo_pullback` is unique. We show here that this claim is
false. This means in particular that we cannot have an extensionality principle for pullbacks in
terms of pseudoelements.
## Implementation details
The construction, suggested in https://mathoverflow.net/a/419951/7845, is the following.
We work in the category of `Module ℤ` and we consider the special case of `ℚ ⊞ ℚ` (that is the
pullback over the terminal object). We consider the pseudoelements associated to `x : ℚ ⟶ ℚ ⊞ ℚ`
given by `t ↦ (t, 2 * t)` and `y : ℚ ⟶ ℚ ⊞ ℚ` given by `t ↦ (t, t)`.
## Main results
* `category_theory.abelian.pseudoelement.exist_ne_and_fst_eq_fst_and_snd_eq_snd` : there are two
pseudoelements `x y : ℚ ⊞ ℚ` such that `x ≠ y`, `biprod.fst x = biprod.fst y` and
`biprod.snd x = biprod.snd y`.
## References
* [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2]
-/
open category_theory.abelian category_theory category_theory.limits Module linear_map
noncomputable theory
namespace category_theory.abelian.pseudoelement
/-- `x` is given by `t ↦ (t, 2 * t)`. -/
def x : over ((of ℤ ℚ) ⊞ (of ℤ ℚ)) :=
begin
constructor,
exact biprod.lift (of_hom id) (of_hom (2 * id)),
end
/-- `y` is given by `t ↦ (t, t)`. -/
def y : over ((of ℤ ℚ) ⊞ (of ℤ ℚ)) :=
begin
constructor,
exact biprod.lift (of_hom id) (of_hom id),
end
/-- `biprod.fst ≫ x` is pseudoequal to `biprod.fst y`. -/
lemma fst_x_pseudo_eq_fst_y : pseudo_equal _ (app biprod.fst x) (app biprod.fst y) :=
begin
refine ⟨of ℤ ℚ, (of_hom id), (of_hom id),
category_struct.id.epi (of ℤ ℚ), _, _⟩,
{ exact (Module.epi_iff_surjective _).2 (λ a, ⟨(a : ℚ), by simp⟩) },
{ dsimp [x, y],
simp }
end
/-- `biprod.snd ≫ x` is pseudoequal to `biprod.snd y`. -/
lemma snd_x_pseudo_eq_snd_y : pseudo_equal _
(app biprod.snd x) (app biprod.snd y) :=
begin
refine ⟨of ℤ ℚ, (of_hom id), 2 • (of_hom id),
category_struct.id.epi (of ℤ ℚ), _, _⟩,
{ refine (Module.epi_iff_surjective _).2 (λ a, ⟨(a/2 : ℚ), _⟩),
simp only [two_smul, add_apply, of_hom_apply, id_coe, id.def],
exact add_halves' (show ℚ, from a) },
{ dsimp [x, y],
exact concrete_category.hom_ext _ _ (λ a, by simpa) }
end
/-- `x` is not pseudoequal to `y`. -/
lemma x_not_pseudo_eq : ¬(pseudo_equal _ x y) :=
begin
intro h,
replace h := Module.eq_range_of_pseudoequal h,
dsimp [x, y] at h,
let φ := (biprod.lift (of_hom (id : ℚ →ₗ[ℤ] ℚ)) (of_hom (2 * id))),
have mem_range := mem_range_self φ (1 : ℚ),
rw h at mem_range,
obtain ⟨a, ha⟩ := mem_range,
rw [← Module.id_apply (φ (1 : ℚ)), ← biprod.total, ← linear_map.comp_apply, ← comp_def,
preadditive.comp_add] at ha,
let π₁ := (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _),
have ha₁ := congr_arg π₁ ha,
simp only [← linear_map.comp_apply, ← comp_def] at ha₁,
simp only [biprod.lift_fst, of_hom_apply, id_coe, id.def, preadditive.add_comp, category.assoc,
biprod.inl_fst, category.comp_id, biprod.inr_fst, limits.comp_zero, add_zero] at ha₁,
let π₂ := (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _),
have ha₂ := congr_arg π₂ ha,
simp only [← linear_map.comp_apply, ← comp_def] at ha₂,
have : (2 : ℚ →ₗ[ℤ] ℚ) 1 = 1 + 1 := rfl,
simp only [ha₁, this, biprod.lift_snd, of_hom_apply, id_coe, id.def, preadditive.add_comp,
category.assoc, biprod.inl_snd, limits.comp_zero, biprod.inr_snd, category.comp_id, zero_add,
mul_apply, self_eq_add_left] at ha₂,
exact one_ne_zero' ℚ ha₂,
end
local attribute [instance] pseudoelement.setoid
open_locale pseudoelement
/-- `biprod.fst ⟦x⟧ = biprod.fst ⟦y⟧`. -/
lemma fst_mk_x_eq_fst_mk_y : (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) ⟦x⟧ =
(biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) ⟦y⟧ :=
by simpa only [abelian.pseudoelement.pseudo_apply_mk, quotient.eq] using fst_x_pseudo_eq_fst_y
/-- `biprod.snd ⟦x⟧ = biprod.snd ⟦y⟧`. -/
lemma snd_mk_x_eq_snd_mk_y : (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) ⟦x⟧ =
(biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) ⟦y⟧ :=
by simpa only [abelian.pseudoelement.pseudo_apply_mk, quotient.eq] using snd_x_pseudo_eq_snd_y
/-- `⟦x⟧ ≠ ⟦y⟧`. -/
lemma mk_x_ne_mk_y : ⟦x⟧ ≠ ⟦y⟧ :=
λ h, x_not_pseudo_eq $ quotient.eq.1 h
/-- There are two pseudoelements `x y : ℚ ⊞ ℚ` such that `x ≠ y`, `biprod.fst x = biprod.fst y` and
`biprod.snd x = biprod.snd y`. -/
lemma exist_ne_and_fst_eq_fst_and_snd_eq_snd : ∃ x y : (of ℤ ℚ) ⊞ (of ℤ ℚ),
x ≠ y ∧
(biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) x = (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) y ∧
(biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) x = (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) y:=
⟨⟦x⟧, ⟦y⟧, mk_x_ne_mk_y, fst_mk_x_eq_fst_mk_y, snd_mk_x_eq_snd_mk_y⟩
end category_theory.abelian.pseudoelement
|
56e9d4a21224beaee734f095400216714f4e2b92 | 07c6143268cfb72beccd1cc35735d424ebcb187b | /src/data/list/of_fn.lean | 7afe7e6bb249c023b18e2a2c4e940a8bcb426806 | [
"Apache-2.0"
] | permissive | khoek/mathlib | bc49a842910af13a3c372748310e86467d1dc766 | aa55f8b50354b3e11ba64792dcb06cccb2d8ee28 | refs/heads/master | 1,588,232,063,837 | 1,587,304,803,000 | 1,587,304,803,000 | 176,688,517 | 0 | 0 | Apache-2.0 | 1,553,070,585,000 | 1,553,070,585,000 | null | UTF-8 | Lean | false | false | 2,629 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.list.basic
import data.fin
universes u
variables {α : Type u}
open nat
namespace list
/- of_fn -/
theorem length_of_fn_aux {n} (f : fin n → α) :
∀ m h l, length (of_fn_aux f m h l) = length l + m
| 0 h l := rfl
| (succ m) h l := (length_of_fn_aux m _ _).trans (succ_add _ _)
@[simp] theorem length_of_fn {n} (f : fin n → α) : length (of_fn f) = n :=
(length_of_fn_aux f _ _ _).trans (zero_add _)
theorem nth_of_fn_aux {n} (f : fin n → α) (i) :
∀ m h l,
(∀ i, nth l i = of_fn_nth_val f (i + m)) →
nth (of_fn_aux f m h l) i = of_fn_nth_val f i
| 0 h l H := H i
| (succ m) h l H := nth_of_fn_aux m _ _ begin
intro j, cases j with j,
{ simp only [nth, of_fn_nth_val, zero_add, dif_pos (show m < n, from h)] },
{ simp only [nth, H, succ_add] }
end
@[simp] theorem nth_of_fn {n} (f : fin n → α) (i) :
nth (of_fn f) i = of_fn_nth_val f i :=
nth_of_fn_aux f _ _ _ _ $ λ i,
by simp only [of_fn_nth_val, dif_neg (not_lt.2 (le_add_left n i))]; refl
theorem nth_le_of_fn {n} (f : fin n → α) (i : fin n) :
nth_le (of_fn f) i.1 ((length_of_fn f).symm ▸ i.2) = f i :=
option.some.inj $ by rw [← nth_le_nth];
simp only [list.nth_of_fn, of_fn_nth_val, fin.eta, dif_pos i.2]
@[simp] theorem nth_le_of_fn' {n} (f : fin n → α) {i : ℕ} (h : i < (of_fn f).length) :
nth_le (of_fn f) i h = f ⟨i, ((length_of_fn f) ▸ h)⟩ :=
nth_le_of_fn f ⟨i, ((length_of_fn f) ▸ h)⟩
@[simp] lemma map_of_fn {β : Type*} {n : ℕ} (f : fin n → α) (g : α → β) :
map g (of_fn f) = of_fn (g ∘ f) :=
ext_le (by simp) (λ i h h', by simp)
theorem array_eq_of_fn {n} (a : array n α) : a.to_list = of_fn a.read :=
suffices ∀ {m h l}, d_array.rev_iterate_aux a
(λ i, cons) m h l = of_fn_aux (d_array.read a) m h l, from this,
begin
intros, induction m with m IH generalizing l, {refl},
simp only [d_array.rev_iterate_aux, of_fn_aux, IH]
end
theorem of_fn_zero (f : fin 0 → α) : of_fn f = [] := rfl
theorem of_fn_succ {n} (f : fin (succ n) → α) :
of_fn f = f 0 :: of_fn (λ i, f i.succ) :=
suffices ∀ {m h l}, of_fn_aux f (succ m) (succ_le_succ h) l =
f 0 :: of_fn_aux (λ i, f i.succ) m h l, from this,
begin
intros, induction m with m IH generalizing l, {refl},
rw [of_fn_aux, IH], refl
end
theorem of_fn_nth_le : ∀ l : list α, of_fn (λ i, nth_le l i.1 i.2) = l
| [] := rfl
| (a::l) := by rw of_fn_succ; congr; simp only [fin.succ_val]; exact of_fn_nth_le l
end list
|
c06cea43cdd9e41a9f1cfd00c709ec642cbe166a | f618aea02cb4104ad34ecf3b9713065cc0d06103 | /src/category_theory/instances/Top/opens.lean | fa8eb0bbc9e7956335076ba3ad4bc36284fdc99c | [
"Apache-2.0"
] | permissive | joehendrix/mathlib | 84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5 | c15eab34ad754f9ecd738525cb8b5a870e834ddc | refs/heads/master | 1,589,606,591,630 | 1,555,946,393,000 | 1,555,946,393,000 | 182,813,854 | 0 | 0 | null | 1,555,946,309,000 | 1,555,946,308,000 | null | UTF-8 | Lean | false | false | 3,482 | lean | import category_theory.instances.Top.basic
import category_theory.natural_isomorphism
import category_theory.opposites
import category_theory.eq_to_hom
open category_theory
open category_theory.instances
open topological_space
universe u
open category_theory.instances
namespace topological_space.opens
variables {X Y Z : Top.{u}}
instance opens_category : category.{u+1} (opens X) :=
{ hom := λ U V, ulift (plift (U ≤ V)),
id := λ X, ⟨ ⟨ le_refl X ⟩ ⟩,
comp := λ X Y Z f g, ⟨ ⟨ le_trans f.down.down g.down.down ⟩ ⟩ }
/-- `opens.map f` gives the functor from open sets in Y to open set in X,
given by taking preimages under f. -/
def map (f : X ⟶ Y) : opens Y ⥤ opens X :=
{ obj := λ U, ⟨ f.val ⁻¹' U, f.property _ U.property ⟩,
map := λ U V i, ⟨ ⟨ λ a b, i.down.down b ⟩ ⟩ }.
@[simp] lemma map_id_obj' (U) (p) : (map (𝟙 X)).obj ⟨U, p⟩ = ⟨U, p⟩ :=
rfl
@[simp] lemma map_id_obj (U : opens X) : (map (𝟙 X)).obj U = U :=
by { ext, refl } -- not quite `rfl`, since we don't have eta for records
@[simp] lemma map_id_obj_unop (U : (opens X)ᵒᵖ) : (map (𝟙 X)).obj (unop U) = unop U :=
by simp
@[simp] lemma op_map_id_obj (U : (opens X)ᵒᵖ) : (map (𝟙 X)).op.obj U = U :=
by simp
section
variable (X)
def map_id : map (𝟙 X) ≅ functor.id (opens X) :=
{ hom := { app := λ U, eq_to_hom (map_id_obj U) },
inv := { app := λ U, eq_to_hom (map_id_obj U).symm } }
@[simp] lemma map_id_hom_app (U) : (map_id X).hom.app U = eq_to_hom (map_id_obj U) := rfl
@[simp] lemma map_id_inv_app (U) : (map_id X).inv.app U = eq_to_hom (map_id_obj U).symm := rfl
end
@[simp] lemma map_comp_obj' (f : X ⟶ Y) (g : Y ⟶ Z) (U) (p) : (map (f ≫ g)).obj ⟨U, p⟩ = (map f).obj ((map g).obj ⟨U, p⟩) :=
rfl
@[simp] lemma map_comp_obj (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map (f ≫ g)).obj U = (map f).obj ((map g).obj U) :=
by { ext, refl } -- not quite `rfl`, since we don't have eta for records
@[simp] lemma map_comp_obj_unop (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map (f ≫ g)).obj (unop U) = (map f).obj ((map g).obj (unop U)) :=
by simp
@[simp] lemma op_map_comp_obj (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map (f ≫ g)).op.obj U = (map f).op.obj ((map g).op.obj U) :=
by simp
def map_comp (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map g ⋙ map f :=
{ hom := { app := λ U, eq_to_hom (map_comp_obj f g U) },
inv := { app := λ U, eq_to_hom (map_comp_obj f g U).symm } }
@[simp] lemma map_comp_hom_app (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map_comp f g).hom.app U = eq_to_hom (map_comp_obj f g U) := rfl
@[simp] lemma map_comp_inv_app (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map_comp f g).inv.app U = eq_to_hom (map_comp_obj f g U).symm := rfl
-- We could make f g implicit here, but it's nice to be able to see when
-- they are the identity (often!)
def map_iso (f g : X ⟶ Y) (h : f = g) : map f ≅ map g :=
nat_iso.of_components (λ U, eq_to_iso (congr_fun (congr_arg functor.obj (congr_arg map h)) U) ) (by obviously)
@[simp] lemma map_iso_refl (f : X ⟶ Y) (h) : map_iso f f h = iso.refl (map _) := rfl
@[simp] lemma map_iso_hom_app (f g : X ⟶ Y) (h : f = g) (U : opens Y) :
(map_iso f g h).hom.app U = eq_to_hom (congr_fun (congr_arg functor.obj (congr_arg map h)) U) :=
rfl
@[simp] lemma map_iso_inv_app (f g : X ⟶ Y) (h : f = g) (U : opens Y) :
(map_iso f g h).inv.app U = eq_to_hom (congr_fun (congr_arg functor.obj (congr_arg map h.symm)) U) :=
rfl
end topological_space.opens
|
f38de8e51ad7f0d3c98917fa841cb3877ed79b18 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/ring_theory/algebraic_independent.lean | e7b6cc5ce00c39b0f72b6103997ece7870ade6a3 | [
"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 | 21,887 | lean | /-
Copyright (c) 2021 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import ring_theory.adjoin.basic
import linear_algebra.linear_independent
import ring_theory.mv_polynomial.basic
import data.mv_polynomial.supported
import ring_theory.algebraic
import data.mv_polynomial.equiv
/-!
# Algebraic Independence
This file defines algebraic independence of a family of element of an `R` algebra
## Main definitions
* `algebraic_independent` - `algebraic_independent R x` states the family of elements `x`
is algebraically independent over `R`, meaning that the canonical map out of the multivariable
polynomial ring is injective.
* `algebraic_independent.repr` - The canonical map from the subalgebra generated by an
algebraic independent family into the polynomial ring.
## References
* [Stacks: Transcendence](https://stacks.math.columbia.edu/tag/030D)
## TODO
Prove that a ring is an algebraic extension of the subalgebra generated by a transcendence basis.
## Tags
transcendence basis, transcendence degree, transcendence
-/
noncomputable theory
open function set subalgebra mv_polynomial algebra
open_locale classical big_operators
universes x u v w
variables {ι : Type*} {ι' : Type*} (R : Type*) {K : Type*}
variables {A : Type*} {A' A'' : Type*} {V : Type u} {V' : Type*}
variables (x : ι → A)
variables [comm_ring R] [comm_ring A] [comm_ring A'] [comm_ring A'']
variables [algebra R A] [algebra R A'] [algebra R A'']
variables {a b : R}
/-- `algebraic_independent R x` states the family of elements `x`
is algebraically independent over `R`, meaning that the canonical
map out of the multivariable polynomial ring is injective. -/
def algebraic_independent : Prop :=
injective (mv_polynomial.aeval x : mv_polynomial ι R →ₐ[R] A)
variables {R} {x}
theorem algebraic_independent_iff_ker_eq_bot : algebraic_independent R x ↔
(mv_polynomial.aeval x : mv_polynomial ι R →ₐ[R] A).to_ring_hom.ker = ⊥ :=
ring_hom.injective_iff_ker_eq_bot _
theorem algebraic_independent_iff : algebraic_independent R x ↔
∀p : mv_polynomial ι R, mv_polynomial.aeval (x : ι → A) p = 0 → p = 0 :=
injective_iff_map_eq_zero _
theorem algebraic_independent.eq_zero_of_aeval_eq_zero (h : algebraic_independent R x) :
∀p : mv_polynomial ι R, mv_polynomial.aeval (x : ι → A) p = 0 → p = 0 :=
algebraic_independent_iff.1 h
theorem algebraic_independent_iff_injective_aeval :
algebraic_independent R x ↔ injective (mv_polynomial.aeval x : mv_polynomial ι R →ₐ[R] A) :=
iff.rfl
@[simp] lemma algebraic_independent_empty_type_iff [is_empty ι] :
algebraic_independent R x ↔ injective (algebra_map R A) :=
have aeval x = (algebra.of_id R A).comp (@is_empty_alg_equiv R ι _ _).to_alg_hom,
by { ext i, exact is_empty.elim' ‹is_empty ι› i },
begin
rw [algebraic_independent, this,
← injective.of_comp_iff' _ (@is_empty_alg_equiv R ι _ _).bijective],
refl
end
namespace algebraic_independent
variables (hx : algebraic_independent R x)
include hx
lemma algebra_map_injective : injective (algebra_map R A) :=
by simpa [← mv_polynomial.algebra_map_eq, function.comp] using
(injective.of_comp_iff
(algebraic_independent_iff_injective_aeval.1 hx) (mv_polynomial.C)).2
(mv_polynomial.C_injective _ _)
lemma linear_independent : linear_independent R x :=
begin
rw [linear_independent_iff_injective_total],
have : finsupp.total ι A R x =
(mv_polynomial.aeval x).to_linear_map.comp (finsupp.total ι _ R X),
{ ext, simp },
rw this,
refine hx.comp _,
rw [← linear_independent_iff_injective_total],
exact linear_independent_X _ _
end
protected lemma injective [nontrivial R] : injective x :=
hx.linear_independent.injective
lemma ne_zero [nontrivial R] (i : ι) : x i ≠ 0 :=
hx.linear_independent.ne_zero i
lemma comp (f : ι' → ι) (hf : function.injective f) : algebraic_independent R (x ∘ f) :=
λ p q, by simpa [aeval_rename, (rename_injective f hf).eq_iff] using @hx (rename f p) (rename f q)
lemma coe_range : algebraic_independent R (coe : range x → A) :=
by simpa using hx.comp _ (range_splitting_injective x)
lemma map {f : A →ₐ[R] A'} (hf_inj : set.inj_on f (adjoin R (range x))) :
algebraic_independent R (f ∘ x) :=
have aeval (f ∘ x) = f.comp (aeval x), by ext; simp,
have h : ∀ p : mv_polynomial ι R, aeval x p ∈ (@aeval R _ _ _ _ _ (coe : range x → A)).range,
{ intro p,
rw [alg_hom.mem_range],
refine ⟨mv_polynomial.rename (cod_restrict x (range x) (mem_range_self)) p, _⟩,
simp [function.comp, aeval_rename] },
begin
intros x y hxy,
rw [this] at hxy,
rw [adjoin_eq_range] at hf_inj,
exact hx (hf_inj (h x) (h y) hxy)
end
lemma map' {f : A →ₐ[R] A'} (hf_inj : injective f) : algebraic_independent R (f ∘ x) :=
hx.map (inj_on_of_injective hf_inj _)
omit hx
lemma of_comp (f : A →ₐ[R] A') (hfv : algebraic_independent R (f ∘ x)) :
algebraic_independent R x :=
have aeval (f ∘ x) = f.comp (aeval x), by ext; simp,
by rw [algebraic_independent, this] at hfv; exact hfv.of_comp
end algebraic_independent
open algebraic_independent
lemma alg_hom.algebraic_independent_iff (f : A →ₐ[R] A') (hf : injective f) :
algebraic_independent R (f ∘ x) ↔ algebraic_independent R x :=
⟨λ h, h.of_comp f, λ h, h.map (inj_on_of_injective hf _)⟩
@[nontriviality]
lemma algebraic_independent_of_subsingleton [subsingleton R] : algebraic_independent R x :=
algebraic_independent_iff.2 (λ l hl, subsingleton.elim _ _)
theorem algebraic_independent_equiv (e : ι ≃ ι') {f : ι' → A} :
algebraic_independent R (f ∘ e) ↔ algebraic_independent R f :=
⟨λ h, function.comp.right_id f ▸ e.self_comp_symm ▸ h.comp _ e.symm.injective,
λ h, h.comp _ e.injective⟩
theorem algebraic_independent_equiv' (e : ι ≃ ι') {f : ι' → A} {g : ι → A} (h : f ∘ e = g) :
algebraic_independent R g ↔ algebraic_independent R f :=
h ▸ algebraic_independent_equiv e
theorem algebraic_independent_subtype_range {ι} {f : ι → A} (hf : injective f) :
algebraic_independent R (coe : range f → A) ↔ algebraic_independent R f :=
iff.symm $ algebraic_independent_equiv' (equiv.of_injective f hf) rfl
alias algebraic_independent_subtype_range ↔ algebraic_independent.of_subtype_range _
theorem algebraic_independent_image {ι} {s : set ι} {f : ι → A} (hf : set.inj_on f s) :
algebraic_independent R (λ x : s, f x) ↔ algebraic_independent R (λ x : f '' s, (x : A)) :=
algebraic_independent_equiv' (equiv.set.image_of_inj_on _ _ hf) rfl
lemma algebraic_independent_adjoin (hs : algebraic_independent R x) :
@algebraic_independent ι R (adjoin R (range x))
(λ i : ι, ⟨x i, subset_adjoin (mem_range_self i)⟩) _ _ _ :=
algebraic_independent.of_comp (adjoin R (range x)).val hs
/-- A set of algebraically independent elements in an algebra `A` over a ring `K` is also
algebraically independent over a subring `R` of `K`. -/
lemma algebraic_independent.restrict_scalars {K : Type*} [comm_ring K] [algebra R K]
[algebra K A] [is_scalar_tower R K A]
(hinj : function.injective (algebra_map R K)) (ai : algebraic_independent K x) :
algebraic_independent R x :=
have (aeval x : mv_polynomial ι K →ₐ[K] A).to_ring_hom.comp
(mv_polynomial.map (algebra_map R K)) =
(aeval x : mv_polynomial ι R →ₐ[R] A).to_ring_hom,
by { ext; simp [algebra_map_eq_smul_one] },
begin
show injective (aeval x).to_ring_hom,
rw [← this],
exact injective.comp ai (mv_polynomial.map_injective _ hinj)
end
/-- Every finite subset of an algebraically independent set is algebraically independent. -/
lemma algebraic_independent_finset_map_embedding_subtype
(s : set A) (li : algebraic_independent R (coe : s → A)) (t : finset s) :
algebraic_independent R (coe : (finset.map (embedding.subtype s) t) → A) :=
begin
let f : t.map (embedding.subtype s) → s := λ x, ⟨x.1, begin
obtain ⟨x, h⟩ := x,
rw [finset.mem_map] at h,
obtain ⟨a, ha, rfl⟩ := h,
simp only [subtype.coe_prop, embedding.coe_subtype],
end⟩,
convert algebraic_independent.comp li f _,
rintros ⟨x, hx⟩ ⟨y, hy⟩,
rw [finset.mem_map] at hx hy,
obtain ⟨a, ha, rfl⟩ := hx,
obtain ⟨b, hb, rfl⟩ := hy,
simp only [imp_self, subtype.mk_eq_mk],
end
/--
If every finite set of algebraically independent element has cardinality at most `n`,
then the same is true for arbitrary sets of algebraically independent elements.
-/
lemma algebraic_independent_bounded_of_finset_algebraic_independent_bounded {n : ℕ}
(H : ∀ s : finset A, algebraic_independent R (λ i : s, (i : A)) → s.card ≤ n) :
∀ s : set A, algebraic_independent R (coe : s → A) → cardinal.mk s ≤ n :=
begin
intros s li,
apply cardinal.card_le_of,
intro t,
rw ← finset.card_map (embedding.subtype s),
apply H,
apply algebraic_independent_finset_map_embedding_subtype _ li,
end
section subtype
lemma algebraic_independent.restrict_of_comp_subtype {s : set ι}
(hs : algebraic_independent R (x ∘ coe : s → A)) :
algebraic_independent R (s.restrict x) :=
hs
variables (R A)
lemma algebraic_independent_empty_iff : algebraic_independent R (λ x, x : (∅ : set A) → A) ↔
injective (algebra_map R A) :=
by simp
variables {R A}
lemma algebraic_independent.mono {t s : set A} (h : t ⊆ s)
(hx : algebraic_independent R (λ x, x : s → A)) : algebraic_independent R (λ x, x : t → A) :=
by simpa [function.comp] using hx.comp (inclusion h) (inclusion_injective h)
end subtype
theorem algebraic_independent.to_subtype_range {ι} {f : ι → A} (hf : algebraic_independent R f) :
algebraic_independent R (coe : range f → A) :=
begin
nontriviality R,
{ rwa algebraic_independent_subtype_range hf.injective }
end
theorem algebraic_independent.to_subtype_range' {ι} {f : ι → A} (hf : algebraic_independent R f)
{t} (ht : range f = t) :
algebraic_independent R (coe : t → A) :=
ht ▸ hf.to_subtype_range
theorem algebraic_independent_comp_subtype {s : set ι} :
algebraic_independent R (x ∘ coe : s → A) ↔
∀ p ∈ (mv_polynomial.supported R s), aeval x p = 0 → p = 0 :=
have (aeval (x ∘ coe : s → A) : _ →ₐ[R] _) =
(aeval x).comp (rename coe), by ext; simp,
have ∀ p : mv_polynomial s R, rename (coe : s → ι) p = 0 ↔ p = 0,
from (injective_iff_map_eq_zero' (rename (coe : s → ι) : mv_polynomial s R →ₐ[R] _).to_ring_hom).1
(rename_injective _ subtype.val_injective),
by simp [algebraic_independent_iff, supported_eq_range_rename, *]
theorem algebraic_independent_subtype {s : set A} :
algebraic_independent R (λ x, x : s → A) ↔
∀ (p : mv_polynomial A R), p ∈ mv_polynomial.supported R s → aeval id p = 0 → p = 0 :=
by apply @algebraic_independent_comp_subtype _ _ _ id
lemma algebraic_independent_of_finite (s : set A)
(H : ∀ t ⊆ s, t.finite → algebraic_independent R (λ x, x : t → A)) :
algebraic_independent R (λ x, x : s → A) :=
algebraic_independent_subtype.2 $
λ p hp, algebraic_independent_subtype.1 (H _ (mem_supported.1 hp) (finset.finite_to_set _)) _
(by simp)
theorem algebraic_independent.image_of_comp {ι ι'} (s : set ι) (f : ι → ι') (g : ι' → A)
(hs : algebraic_independent R (λ x : s, g (f x))) :
algebraic_independent R (λ x : f '' s, g x) :=
begin
nontriviality R,
have : inj_on f s, from inj_on_iff_injective.2 hs.injective.of_comp,
exact (algebraic_independent_equiv' (equiv.set.image_of_inj_on f s this) rfl).1 hs
end
theorem algebraic_independent.image {ι} {s : set ι} {f : ι → A}
(hs : algebraic_independent R (λ x : s, f x)) : algebraic_independent R (λ x : f '' s, (x : A)) :=
by convert algebraic_independent.image_of_comp s f id hs
lemma algebraic_independent_Union_of_directed {η : Type*} [nonempty η]
{s : η → set A} (hs : directed (⊆) s)
(h : ∀ i, algebraic_independent R (λ x, x : s i → A)) :
algebraic_independent R (λ x, x : (⋃ i, s i) → A) :=
begin
refine algebraic_independent_of_finite (⋃ i, s i) (λ t ht ft, _),
rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩,
rcases hs.finset_le fi.to_finset with ⟨i, hi⟩,
exact (h i).mono (subset.trans hI $ Union₂_subset $
λ j hj, hi j (fi.mem_to_finset.2 hj))
end
lemma algebraic_independent_sUnion_of_directed {s : set (set A)}
(hsn : s.nonempty)
(hs : directed_on (⊆) s)
(h : ∀ a ∈ s, algebraic_independent R (λ x, x : (a : set A) → A)) :
algebraic_independent R (λ x, x : (⋃₀ s) → A) :=
by letI : nonempty s := nonempty.to_subtype hsn;
rw sUnion_eq_Union; exact
algebraic_independent_Union_of_directed hs.directed_coe (by simpa using h)
lemma exists_maximal_algebraic_independent
(s t : set A) (hst : s ⊆ t)
(hs : algebraic_independent R (coe : s → A)) :
∃ u : set A, algebraic_independent R (coe : u → A) ∧ s ⊆ u ∧ u ⊆ t ∧
∀ x : set A, algebraic_independent R (coe : x → A) →
u ⊆ x → x ⊆ t → x = u :=
begin
rcases zorn_subset_nonempty
{ u : set A | algebraic_independent R (coe : u → A) ∧ s ⊆ u ∧ u ⊆ t }
(λ c hc chainc hcn, ⟨⋃₀ c, begin
refine ⟨⟨algebraic_independent_sUnion_of_directed hcn
chainc.directed_on
(λ a ha, (hc ha).1), _, _⟩, _⟩,
{ cases hcn with x hx,
exact subset_sUnion_of_subset _ x (hc hx).2.1 hx },
{ exact sUnion_subset (λ x hx, (hc hx).2.2) },
{ intros s,
exact subset_sUnion_of_mem }
end⟩)
s ⟨hs, set.subset.refl s, hst⟩ with ⟨u, ⟨huai, hsu, hut⟩, hsu, hx⟩,
use [u, huai, hsu, hut],
intros x hxai huv hxt,
exact hx _ ⟨hxai, trans hsu huv, hxt⟩ huv,
end
section repr
variables (hx : algebraic_independent R x)
/-- Canonical isomorphism between polynomials and the subalgebra generated by
algebraically independent elements. -/
@[simps] def algebraic_independent.aeval_equiv (hx : algebraic_independent R x) :
(mv_polynomial ι R) ≃ₐ[R] algebra.adjoin R (range x) :=
begin
apply alg_equiv.of_bijective
(alg_hom.cod_restrict (@aeval R A ι _ _ _ x) (algebra.adjoin R (range x)) _),
swap,
{ intros x,
rw [adjoin_range_eq_range_aeval],
exact alg_hom.mem_range_self _ _ },
{ split,
{ exact (alg_hom.injective_cod_restrict _ _ _).2 hx },
{ rintros ⟨x, hx⟩,
rw [adjoin_range_eq_range_aeval] at hx,
rcases hx with ⟨y, rfl⟩,
use y,
ext,
simp } }
end
@[simp] lemma algebraic_independent.algebra_map_aeval_equiv (hx : algebraic_independent R x)
(p : mv_polynomial ι R) : algebra_map (algebra.adjoin R (range x)) A (hx.aeval_equiv p) =
aeval x p := rfl
/-- The canonical map from the subalgebra generated by an algebraic independent family
into the polynomial ring. -/
def algebraic_independent.repr (hx : algebraic_independent R x) :
algebra.adjoin R (range x) →ₐ[R] mv_polynomial ι R := hx.aeval_equiv.symm
@[simp] lemma algebraic_independent.aeval_repr (p) : aeval x (hx.repr p) = p :=
subtype.ext_iff.1 (alg_equiv.apply_symm_apply hx.aeval_equiv p)
lemma algebraic_independent.aeval_comp_repr :
(aeval x).comp hx.repr = subalgebra.val _ :=
alg_hom.ext $ hx.aeval_repr
lemma algebraic_independent.repr_ker :
(hx.repr : adjoin R (range x) →+* mv_polynomial ι R).ker = ⊥ :=
(ring_hom.injective_iff_ker_eq_bot _).1 (alg_equiv.injective _)
end repr
-- TODO - make this an `alg_equiv`
/-- The isomorphism between `mv_polynomial (option ι) R` and the polynomial ring over
the algebra generated by an algebraically independent family. -/
def algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin
(hx : algebraic_independent R x) :
mv_polynomial (option ι) R ≃+* polynomial (adjoin R (set.range x)) :=
(mv_polynomial.option_equiv_left _ _).to_ring_equiv.trans
(polynomial.map_equiv hx.aeval_equiv.to_ring_equiv)
@[simp]
lemma algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_apply
(hx : algebraic_independent R x) (y) :
hx.mv_polynomial_option_equiv_polynomial_adjoin y =
polynomial.map (hx.aeval_equiv : mv_polynomial ι R →+* adjoin R (range x))
(aeval (λ (o : option ι), o.elim polynomial.X (λ (s : ι), polynomial.C (X s))) y) :=
rfl
@[simp]
lemma algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_C
(hx : algebraic_independent R x) (r) :
hx.mv_polynomial_option_equiv_polynomial_adjoin (C r) =
polynomial.C (algebra_map _ _ r) :=
begin
rw [algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_apply, aeval_C,
is_scalar_tower.algebra_map_apply R (mv_polynomial ι R), ← polynomial.C_eq_algebra_map,
polynomial.map_C, ring_hom.coe_coe, alg_equiv.commutes]
end
@[simp]
lemma algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_X_none
(hx : algebraic_independent R x) :
hx.mv_polynomial_option_equiv_polynomial_adjoin (X none) = polynomial.X :=
by rw [algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_apply, aeval_X,
option.elim, polynomial.map_X]
@[simp]
lemma algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_X_some
(hx : algebraic_independent R x) (i) :
hx.mv_polynomial_option_equiv_polynomial_adjoin (X (some i)) =
polynomial.C (hx.aeval_equiv (X i)) :=
by rw [algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_apply, aeval_X,
option.elim, polynomial.map_C, ring_hom.coe_coe]
lemma algebraic_independent.aeval_comp_mv_polynomial_option_equiv_polynomial_adjoin
(hx : algebraic_independent R x) (a : A) :
(ring_hom.comp (↑(polynomial.aeval a : polynomial (adjoin R (set.range x)) →ₐ[_] A) :
polynomial (adjoin R (set.range x)) →+* A)
hx.mv_polynomial_option_equiv_polynomial_adjoin.to_ring_hom) =
↑((mv_polynomial.aeval (λ o : option ι, o.elim a x)) :
mv_polynomial (option ι) R →ₐ[R] A) :=
begin
refine mv_polynomial.ring_hom_ext _ _;
simp only [ring_hom.comp_apply, ring_equiv.to_ring_hom_eq_coe, ring_equiv.coe_to_ring_hom,
alg_hom.coe_to_ring_hom, alg_hom.coe_to_ring_hom],
{ intro r,
rw [hx.mv_polynomial_option_equiv_polynomial_adjoin_C,
aeval_C, polynomial.aeval_C, is_scalar_tower.algebra_map_apply R (adjoin R (range x)) A] },
{ rintro (⟨⟩|⟨i⟩),
{ rw [hx.mv_polynomial_option_equiv_polynomial_adjoin_X_none,
aeval_X, polynomial.aeval_X, option.elim] },
{ rw [hx.mv_polynomial_option_equiv_polynomial_adjoin_X_some, polynomial.aeval_C,
hx.algebra_map_aeval_equiv, aeval_X, aeval_X, option.elim] } },
end
theorem algebraic_independent.option_iff (hx : algebraic_independent R x) (a : A) :
(algebraic_independent R (λ o : option ι, o.elim a x)) ↔
¬ is_algebraic (adjoin R (set.range x)) a :=
by erw [algebraic_independent_iff_injective_aeval, is_algebraic_iff_not_injective, not_not,
← alg_hom.coe_to_ring_hom,
← hx.aeval_comp_mv_polynomial_option_equiv_polynomial_adjoin,
ring_hom.coe_comp, injective.of_comp_iff' _ (ring_equiv.bijective _), alg_hom.coe_to_ring_hom]
variable (R)
/--
A family is a transcendence basis if it is a maximal algebraically independent subset.
-/
def is_transcendence_basis (x : ι → A) : Prop :=
algebraic_independent R x ∧
∀ (s : set A) (i' : algebraic_independent R (coe : s → A)) (h : range x ≤ s), range x = s
lemma exists_is_transcendence_basis (h : injective (algebra_map R A)) :
∃ s : set A, is_transcendence_basis R (coe : s → A) :=
begin
cases exists_maximal_algebraic_independent (∅ : set A) set.univ
(set.subset_univ _) ((algebraic_independent_empty_iff R A).2 h) with s hs,
use [s, hs.1],
intros t ht hr,
simp only [subtype.range_coe_subtype, set_of_mem_eq] at *,
exact eq.symm (hs.2.2.2 t ht hr (set.subset_univ _))
end
variable {R}
lemma algebraic_independent.is_transcendence_basis_iff
{ι : Type w} {R : Type u} [comm_ring R] [nontrivial R]
{A : Type v} [comm_ring A] [algebra R A] {x : ι → A} (i : algebraic_independent R x) :
is_transcendence_basis R x ↔ ∀ (κ : Type v) (w : κ → A) (i' : algebraic_independent R w)
(j : ι → κ) (h : w ∘ j = x), surjective j :=
begin
fsplit,
{ rintros p κ w i' j rfl,
have p := p.2 (range w) i'.coe_range (range_comp_subset_range _ _),
rw [range_comp, ←@image_univ _ _ w] at p,
exact range_iff_surjective.mp (image_injective.mpr i'.injective p) },
{ intros p,
use i,
intros w i' h,
specialize p w (coe : w → A) i'
(λ i, ⟨x i, range_subset_iff.mp h i⟩)
(by { ext, simp, }),
have q := congr_arg (λ s, (coe : w → A) '' s) p.range_eq,
dsimp at q,
rw [←image_univ, image_image] at q,
simpa using q, },
end
lemma is_transcendence_basis.is_algebraic [nontrivial R]
(hx : is_transcendence_basis R x) : is_algebraic (adjoin R (range x)) A :=
begin
intro a,
rw [← not_iff_comm.1 (hx.1.option_iff _).symm],
intro ai,
have h₁ : range x ⊆ range (λ o : option ι, o.elim a x),
{ rintros x ⟨y, rfl⟩, exact ⟨some y, rfl⟩ },
have h₂ : range x ≠ range (λ o : option ι, o.elim a x),
{ intro h,
have : a ∈ range x, { rw h, exact ⟨none, rfl⟩ },
rcases this with ⟨b, rfl⟩,
have : some b = none := ai.injective rfl,
simpa },
exact h₂ (hx.2 (set.range (λ o : option ι, o.elim a x))
((algebraic_independent_subtype_range ai.injective).2 ai) h₁)
end
section field
variables [field K] [algebra K A]
@[simp] lemma algebraic_independent_empty_type [is_empty ι] [nontrivial A] :
algebraic_independent K x :=
begin
rw [algebraic_independent_empty_type_iff],
exact ring_hom.injective _,
end
lemma algebraic_independent_empty [nontrivial A] :
algebraic_independent K (coe : ((∅ : set A) → A)) :=
algebraic_independent_empty_type
end field
|
7930d6f4bd3e69bd9a3c5aa6677a06a0702a236c | b561a44b48979a98df50ade0789a21c79ee31288 | /src/Lean/Meta/Basic.lean | d12bb8e480ba06a1d6a6a12b4f3c2a68d0a9ac10 | [
"Apache-2.0"
] | permissive | 3401ijk/lean4 | 97659c475ebd33a034fed515cb83a85f75ccfb06 | a5b1b8de4f4b038ff752b9e607b721f15a9a4351 | refs/heads/master | 1,693,933,007,651 | 1,636,424,845,000 | 1,636,424,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 50,639 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Data.LOption
import Lean.Environment
import Lean.Class
import Lean.ReducibilityAttrs
import Lean.Util.Trace
import Lean.Util.RecDepth
import Lean.Util.PPExt
import Lean.Util.OccursCheck
import Lean.Util.MonadBacktrack
import Lean.Compiler.InlineAttrs
import Lean.Meta.TransparencyMode
import Lean.Meta.DiscrTreeTypes
import Lean.Eval
import Lean.CoreM
/-
This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks.
1- Weak head normal form computation with support for metavariables and transparency modes.
2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality).
3- Type inference.
4- Type class resolution.
They are packed into the MetaM monad.
-/
namespace Lean.Meta
builtin_initialize isDefEqStuckExceptionId : InternalExceptionId ← registerInternalExceptionId `isDefEqStuck
structure Config where
foApprox : Bool := false
ctxApprox : Bool := false
quasiPatternApprox : Bool := false
/-- When `constApprox` is set to true,
we solve `?m t =?= c` using
`?m := fun _ => c`
when `?m t` is not a higher-order pattern and `c` is not an application as -/
constApprox : Bool := false
/--
When the following flag is set,
`isDefEq` throws the exeption `Exeption.isDefEqStuck`
whenever it encounters a constraint `?m ... =?= t` where
`?m` is read only.
This feature is useful for type class resolution where
we may want to notify the caller that the TC problem may be solveable
later after it assigns `?m`. -/
isDefEqStuckEx : Bool := false
transparency : TransparencyMode := TransparencyMode.default
/-- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/
zetaNonDep : Bool := true
/-- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/
trackZeta : Bool := false
unificationHints : Bool := true
/-- Enables proof irrelevance at `isDefEq` -/
proofIrrelevance : Bool := true
/-- By default synthetic opaque metavariables are not assigned by `isDefEq`. Motivation: we want to make
sure typing constraints resolved during elaboration should not "fill" holes that are supposed to be filled using tactics.
However, this restriction is too restrictive for tactics such as `exact t`. When elaborating `t`, we dot not fill
named holes when solving typing constraints or TC resolution. But, we ignore the restriction when we try to unify
the type of `t` with the goal target type. We claim this is not a hack and is defensible behavior because
this last unification step is not really part of the term elaboration. -/
assignSyntheticOpaque : Bool := false
/-- When `ignoreLevelDepth` is `false`, only universe level metavariables with depth == metavariable context depth
can be assigned.
We used to have `ignoreLevelDepth == false` always, but this setting produced counterintuitive behavior in a few
cases. Recall that universe levels are often ignored by users, they may not even be aware they exist.
We still use this restriction for regular metavariables. See discussion at the beginning of `MetavarContext.lean`.
We claim it is reasonable to ignore this restriction for universe metavariables because their values are often
contrained by the terms is instances and simp theorems.
TODO: we should delete this configuration option and the method `isReadOnlyLevelMVar` after we have more tests.
-/
ignoreLevelMVarDepth : Bool := true
/-- Enable/Disable support for offset constraints such as `?x + 1 =?= e` -/
offsetCnstrs : Bool := true
structure ParamInfo where
binderInfo : BinderInfo := BinderInfo.default
hasFwdDeps : Bool := false
backDeps : Array Nat := #[]
deriving Inhabited
def ParamInfo.isImplicit (p : ParamInfo) : Bool :=
p.binderInfo == BinderInfo.implicit
def ParamInfo.isInstImplicit (p : ParamInfo) : Bool :=
p.binderInfo == BinderInfo.instImplicit
def ParamInfo.isStrictImplicit (p : ParamInfo) : Bool :=
p.binderInfo == BinderInfo.strictImplicit
def ParamInfo.isExplicit (p : ParamInfo) : Bool :=
p.binderInfo == BinderInfo.default || p.binderInfo == BinderInfo.auxDecl
structure FunInfo where
paramInfo : Array ParamInfo := #[]
resultDeps : Array Nat := #[]
structure InfoCacheKey where
transparency : TransparencyMode
expr : Expr
nargs? : Option Nat
deriving Inhabited, BEq
namespace InfoCacheKey
instance : Hashable InfoCacheKey :=
⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) <| mixHash (hash expr) (hash nargs)⟩
end InfoCacheKey
open Std (PersistentArray PersistentHashMap)
abbrev SynthInstanceCache := PersistentHashMap Expr (Option Expr)
abbrev InferTypeCache := PersistentExprStructMap Expr
abbrev FunInfoCache := PersistentHashMap InfoCacheKey FunInfo
abbrev WhnfCache := PersistentExprStructMap Expr
/- A set of pairs. TODO: consider more efficient representations (e.g., a proper set) and caching policies (e.g., imperfect cache).
We should also investigate the impact on memory consumption. -/
abbrev DefEqCache := PersistentHashMap (Expr × Expr) Unit
structure Cache where
inferType : InferTypeCache := {}
funInfo : FunInfoCache := {}
synthInstance : SynthInstanceCache := {}
whnfDefault : WhnfCache := {} -- cache for closed terms and `TransparencyMode.default`
whnfAll : WhnfCache := {} -- cache for closed terms and `TransparencyMode.all`
defEqDefault : DefEqCache := {}
defEqAll : DefEqCache := {}
deriving Inhabited
/--
"Context" for a postponed universe constraint.
`lhs` and `rhs` are the surrounding `isDefEq` call when the postponed constraint was created.
-/
structure DefEqContext where
lhs : Expr
rhs : Expr
lctx : LocalContext
localInstances : LocalInstances
/--
Auxiliary structure for representing postponed universe constraints.
Remark: the fields `ref` and `rootDefEq?` are used for error message generation only.
Remark: we may consider improving the error message generation in the future.
-/
structure PostponedEntry where
ref : Syntax -- We save the `ref` at entry creation time
lhs : Level
rhs : Level
ctx? : Option DefEqContext -- Context for the surrounding `isDefEq` call when entry was created
deriving Inhabited
structure State where
mctx : MetavarContext := {}
cache : Cache := {}
/- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/
zetaFVarIds : FVarIdSet := {}
postponed : PersistentArray PostponedEntry := {}
deriving Inhabited
structure SavedState where
core : Core.State
meta : State
deriving Inhabited
structure Context where
config : Config := {}
lctx : LocalContext := {}
localInstances : LocalInstances := #[]
/-- Not `none` when inside of an `isDefEq` test. See `PostponedEntry`. -/
defEqCtx? : Option DefEqContext := none
/--
Track the number of nested `synthPending` invocations. Nested invocations can happen
when the type class resolution invokes `synthPending`.
Remark: in the current implementation, `synthPending` fails if `synthPendingDepth > 0`.
We will add a configuration option if necessary. -/
synthPendingDepth : Nat := 0
abbrev MetaM := ReaderT Context $ StateRefT State CoreM
-- 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 MetaM := let i := inferInstanceAs (Monad MetaM); { pure := i.pure, bind := i.bind }
instance : Inhabited (MetaM α) where
default := fun _ _ => arbitrary
instance : MonadLCtx MetaM where
getLCtx := return (← read).lctx
instance : MonadMCtx MetaM where
getMCtx := return (← get).mctx
modifyMCtx f := modify fun s => { s with mctx := f s.mctx }
instance : AddMessageContext MetaM where
addMessageContext := addMessageContextFull
protected def saveState : MetaM SavedState :=
return { core := (← getThe Core.State), meta := (← get) }
/-- Restore backtrackable parts of the state. -/
def SavedState.restore (b : SavedState) : MetaM Unit := do
Core.restore b.core
modify fun s => { s with mctx := b.meta.mctx, zetaFVarIds := b.meta.zetaFVarIds, postponed := b.meta.postponed }
instance : MonadBacktrack SavedState MetaM where
saveState := Meta.saveState
restoreState s := s.restore
@[inline] def MetaM.run (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM (α × State) :=
x ctx |>.run s
@[inline] def MetaM.run' (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM α :=
Prod.fst <$> x.run ctx s
@[inline] def MetaM.toIO (x : MetaM α) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (α × Core.State × State) := do
let ((a, s), sCore) ← (x.run ctx s).toIO ctxCore sCore
pure (a, sCore, s)
instance [MetaEval α] : MetaEval (MetaM α) :=
⟨fun env opts x _ => MetaEval.eval env opts x.run' true⟩
protected def throwIsDefEqStuck : MetaM α :=
throw <| Exception.internal isDefEqStuckExceptionId
builtin_initialize
registerTraceClass `Meta
registerTraceClass `Meta.debug
@[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM α) : m α :=
liftM x
@[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, MetaM α → MetaM α) {α} (x : m α) : m α :=
controlAt MetaM fun runInBase => f <| runInBase x
@[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → MetaM α) → MetaM α) {α} (k : β → m α) : m α :=
controlAt MetaM fun runInBase => f fun b => runInBase <| k b
@[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → γ → MetaM α) → MetaM α) {α} (k : β → γ → m α) : m α :=
controlAt MetaM fun runInBase => f fun b c => runInBase <| k b c
section Methods
variable [MonadControlT MetaM n] [Monad n]
@[inline] def modifyCache (f : Cache → Cache) : MetaM Unit :=
modify fun ⟨mctx, cache, zetaFVarIds, postponed⟩ => ⟨mctx, f cache, zetaFVarIds, postponed⟩
@[inline] def modifyInferTypeCache (f : InferTypeCache → InferTypeCache) : MetaM Unit :=
modifyCache fun ⟨ic, c1, c2, c3, c4, c5, c6⟩ => ⟨f ic, c1, c2, c3, c4, c5, c6⟩
def getLocalInstances : MetaM LocalInstances :=
return (← read).localInstances
def getConfig : MetaM Config :=
return (← read).config
def setMCtx (mctx : MetavarContext) : MetaM Unit :=
modify fun s => { s with mctx := mctx }
def resetZetaFVarIds : MetaM Unit :=
modify fun s => { s with zetaFVarIds := {} }
def getZetaFVarIds : MetaM FVarIdSet :=
return (← get).zetaFVarIds
def getPostponed : MetaM (PersistentArray PostponedEntry) :=
return (← get).postponed
def setPostponed (postponed : PersistentArray PostponedEntry) : MetaM Unit :=
modify fun s => { s with postponed := postponed }
@[inline] def modifyPostponed (f : PersistentArray PostponedEntry → PersistentArray PostponedEntry) : MetaM Unit :=
modify fun s => { s with postponed := f s.postponed }
/- WARNING: The following 4 constants are a hack for simulating forward declarations.
They are defined later using the `export` attribute. This is hackish because we
have to hard-code the true arity of these definitions here, and make sure the C names match.
We have used another hack based on `IO.Ref`s in the past, it was safer but less efficient. -/
@[extern 6 "lean_whnf"] constant whnf : Expr → MetaM Expr
@[extern 6 "lean_infer_type"] constant inferType : Expr → MetaM Expr
@[extern 7 "lean_is_expr_def_eq"] constant isExprDefEqAux : Expr → Expr → MetaM Bool
@[extern 6 "lean_synth_pending"] protected constant synthPending : MVarId → MetaM Bool
def whnfForall (e : Expr) : MetaM Expr := do
let e' ← whnf e
if e'.isForall then pure e' else pure e
-- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]`
protected def withIncRecDepth (x : n α) : n α :=
mapMetaM (withIncRecDepth (m := MetaM)) x
private def mkFreshExprMVarAtCore
(mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do
modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs;
return mkMVar mvarId
def mkFreshExprMVarAt
(lctx : LocalContext) (localInsts : LocalInstances) (type : Expr)
(kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)
: MetaM Expr := do
mkFreshExprMVarAtCore (← mkFreshMVarId) lctx localInsts type kind userName numScopeArgs
def mkFreshLevelMVar : MetaM Level := do
let mvarId ← mkFreshMVarId
modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId;
return mkLevelMVar mvarId
private def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do
mkFreshExprMVarAt (← getLCtx) (← getLocalInstances) type kind userName
private def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr :=
match type? with
| some type => mkFreshExprMVarCore type kind userName
| none => do
let u ← mkFreshLevelMVar
let type ← mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous
mkFreshExprMVarCore type kind userName
def mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=
mkFreshExprMVarImpl type? kind userName
def mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := do
let u ← mkFreshLevelMVar
mkFreshExprMVar (mkSort u) kind userName
/- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create
the metavar using this method. -/
private def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr)
(kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)
: MetaM Expr := do
mkFreshExprMVarAtCore mvarId (← getLCtx) (← getLocalInstances) type kind userName numScopeArgs
def mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=
match type? with
| some type => mkFreshExprMVarWithIdCore mvarId type kind userName
| none => do
let u ← mkFreshLevelMVar
let type ← mkFreshExprMVar (mkSort u)
mkFreshExprMVarWithIdCore mvarId type kind userName
def mkFreshLevelMVars (num : Nat) : MetaM (List Level) :=
num.foldM (init := []) fun _ us =>
return (← mkFreshLevelMVar)::us
def mkFreshLevelMVarsFor (info : ConstantInfo) : MetaM (List Level) :=
mkFreshLevelMVars info.numLevelParams
def mkConstWithFreshMVarLevels (declName : Name) : MetaM Expr := do
let info ← getConstInfo declName
return mkConst declName (← mkFreshLevelMVarsFor info)
def getTransparency : MetaM TransparencyMode :=
return (← getConfig).transparency
def shouldReduceAll : MetaM Bool :=
return (← getTransparency) == TransparencyMode.all
def shouldReduceReducibleOnly : MetaM Bool :=
return (← getTransparency) == TransparencyMode.reducible
def getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do
match (← getMCtx).findDecl? mvarId with
| some d => pure d
| none => throwError "unknown metavariable '?{mvarId.name}'"
def setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit :=
modifyMCtx fun mctx => mctx.setMVarKind mvarId kind
/- Update the type of the given metavariable. This function assumes the new type is
definitionally equal to the current one -/
def setMVarType (mvarId : MVarId) (type : Expr) : MetaM Unit := do
modifyMCtx fun mctx => mctx.setMVarType mvarId type
def isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do
return (← getMVarDecl mvarId).depth != (← getMCtx).depth
def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do
let mvarDecl ← getMVarDecl mvarId
match mvarDecl.kind with
| MetavarKind.syntheticOpaque => return !(← getConfig).assignSyntheticOpaque
| _ => return mvarDecl.depth != (← getMCtx).depth
def getLevelMVarDepth (mvarId : MVarId) : MetaM Nat := do
match (← getMCtx).findLevelDepth? mvarId with
| some depth => return depth
| _ => throwError "unknown universe metavariable '?{mvarId.name}'"
def isReadOnlyLevelMVar (mvarId : MVarId) : MetaM Bool := do
if (← getConfig).ignoreLevelMVarDepth then
return false
else
return (← getLevelMVarDepth mvarId) != (← getMCtx).depth
def renameMVar (mvarId : MVarId) (newUserName : Name) : MetaM Unit :=
modifyMCtx fun mctx => mctx.renameMVar mvarId newUserName
def isExprMVarAssigned (mvarId : MVarId) : MetaM Bool :=
return (← getMCtx).isExprAssigned mvarId
def getExprMVarAssignment? (mvarId : MVarId) : MetaM (Option Expr) :=
return (← getMCtx).getExprAssignment? mvarId
/-- Return true if `e` contains `mvarId` directly or indirectly -/
def occursCheck (mvarId : MVarId) (e : Expr) : MetaM Bool :=
return (← getMCtx).occursCheck mvarId e
def assignExprMVar (mvarId : MVarId) (val : Expr) : MetaM Unit :=
modifyMCtx fun mctx => mctx.assignExpr mvarId val
def isDelayedAssigned (mvarId : MVarId) : MetaM Bool :=
return (← getMCtx).isDelayedAssigned mvarId
def getDelayedAssignment? (mvarId : MVarId) : MetaM (Option DelayedMetavarAssignment) :=
return (← getMCtx).getDelayedAssignment? mvarId
def hasAssignableMVar (e : Expr) : MetaM Bool :=
return (← getMCtx).hasAssignableMVar e
def throwUnknownFVar (fvarId : FVarId) : MetaM α :=
throwError "unknown free variable '{mkFVar fvarId}'"
def findLocalDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) :=
return (← getLCtx).find? fvarId
def getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do
match (← getLCtx).find? fvarId with
| some d => pure d
| none => throwUnknownFVar fvarId
def getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl :=
getLocalDecl fvar.fvarId!
def getLocalDeclFromUserName (userName : Name) : MetaM LocalDecl := do
match (← getLCtx).findFromUserName? userName with
| some d => pure d
| none => throwError "unknown local declaration '{userName}'"
def instantiateLevelMVars (u : Level) : MetaM Level :=
MetavarContext.instantiateLevelMVars u
def instantiateMVars (e : Expr) : MetaM Expr :=
(MetavarContext.instantiateExprMVars e).run
def instantiateLocalDeclMVars (localDecl : LocalDecl) : MetaM LocalDecl :=
match localDecl with
| LocalDecl.cdecl idx id n type bi =>
return LocalDecl.cdecl idx id n (← instantiateMVars type) bi
| LocalDecl.ldecl idx id n type val nonDep =>
return LocalDecl.ldecl idx id n (← instantiateMVars type) (← instantiateMVars val) nonDep
@[inline] def liftMkBindingM (x : MetavarContext.MkBindingM α) : MetaM α := do
match x (← getLCtx) { mctx := (← getMCtx), ngen := (← getNGen) } with
| EStateM.Result.ok e newS => do
setNGen newS.ngen;
setMCtx newS.mctx;
pure e
| EStateM.Result.error (MetavarContext.MkBinding.Exception.revertFailure mctx lctx toRevert decl) newS => do
setMCtx newS.mctx;
setNGen newS.ngen;
throwError "failed to create binder due to failure when reverting variable dependencies"
def abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MetaM Expr :=
liftMkBindingM <| MetavarContext.abstractRange e n xs
def abstract (e : Expr) (xs : Array Expr) : MetaM Expr :=
abstractRange e xs.size xs
def mkForallFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkForall xs e usedOnly usedLetOnly
def mkLambdaFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkLambda xs e usedOnly usedLetOnly
def mkLetFVars (xs : Array Expr) (e : Expr) (usedLetOnly := true) : MetaM Expr :=
mkLambdaFVars xs e (usedLetOnly := usedLetOnly)
def mkArrow (d b : Expr) : MetaM Expr :=
return Lean.mkForall (← mkFreshUserName `x) BinderInfo.default d b
/-- `fun _ : Unit => a` -/
def mkFunUnit (a : Expr) : MetaM Expr :=
return Lean.mkLambda (← mkFreshUserName `x) BinderInfo.default (mkConst ``Unit) a
def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder
@[inline] def withConfig (f : Config → Config) : n α → n α :=
mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config })
@[inline] def withTrackingZeta (x : n α) : n α :=
withConfig (fun cfg => { cfg with trackZeta := true }) x
@[inline] def withoutProofIrrelevance (x : n α) : n α :=
withConfig (fun cfg => { cfg with proofIrrelevance := false }) x
@[inline] def withTransparency (mode : TransparencyMode) : n α → n α :=
mapMetaM <| withConfig (fun config => { config with transparency := mode })
@[inline] def withDefault (x : n α) : n α :=
withTransparency TransparencyMode.default x
@[inline] def withReducible (x : n α) : n α :=
withTransparency TransparencyMode.reducible x
@[inline] def withReducibleAndInstances (x : n α) : n α :=
withTransparency TransparencyMode.instances x
@[inline] def withAtLeastTransparency (mode : TransparencyMode) (x : n α) : n α :=
withConfig
(fun config =>
let oldMode := config.transparency
let mode := if oldMode.lt mode then mode else oldMode
{ config with transparency := mode })
x
/-- Execute `x` allowing `isDefEq` to assign synthetic opaque metavariables. -/
@[inline] def withAssignableSyntheticOpaque (x : n α) : n α :=
withConfig (fun config => { config with assignSyntheticOpaque := true }) x
/-- Save cache, execute `x`, restore cache -/
@[inline] private def savingCacheImpl (x : MetaM α) : MetaM α := do
let savedCache := (← get).cache
try x finally modify fun s => { s with cache := savedCache }
@[inline] def savingCache : n α → n α :=
mapMetaM savingCacheImpl
def getTheoremInfo (info : ConstantInfo) : MetaM (Option ConstantInfo) := do
if (← shouldReduceAll) then
return some info
else
return none
private def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do
match (← getTransparency) with
| TransparencyMode.all => return some info
| TransparencyMode.default => return some info
| _ =>
if (← isReducible info.name) then
return some info
else
return none
/- Remark: we later define `getConst?` at `GetConst.lean` after we define `Instances.lean`.
This method is only used to implement `isClassQuickConst?`.
It is very similar to `getConst?`, but it returns none when `TransparencyMode.instances` and
`constName` is an instance. This difference should be irrelevant for `isClassQuickConst?`. -/
private def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do
match (← getEnv).find? constName with
| some (info@(ConstantInfo.thmInfo _)) => getTheoremInfo info
| some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info
| some info => pure (some info)
| none => throwUnknownConstant constName
private def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do
if isClass (← getEnv) constName then
pure (LOption.some constName)
else
match (← getConstTemp? constName) with
| some _ => pure LOption.undef
| none => pure LOption.none
private partial def isClassQuick? : Expr → MetaM (LOption Name)
| Expr.bvar .. => pure LOption.none
| Expr.lit .. => pure LOption.none
| Expr.fvar .. => pure LOption.none
| Expr.sort .. => pure LOption.none
| Expr.lam .. => pure LOption.none
| Expr.letE .. => pure LOption.undef
| Expr.proj .. => pure LOption.undef
| Expr.forallE _ _ b _ => isClassQuick? b
| Expr.mdata _ e _ => isClassQuick? e
| Expr.const n _ _ => isClassQuickConst? n
| Expr.mvar mvarId _ => do
match (← getExprMVarAssignment? mvarId) with
| some val => isClassQuick? val
| none => pure LOption.none
| Expr.app f _ _ =>
match f.getAppFn with
| Expr.const n .. => isClassQuickConst? n
| Expr.lam .. => pure LOption.undef
| _ => pure LOption.none
def saveAndResetSynthInstanceCache : MetaM SynthInstanceCache := do
let savedSythInstance := (← get).cache.synthInstance
modifyCache fun c => { c with synthInstance := {} }
pure savedSythInstance
def restoreSynthInstanceCache (cache : SynthInstanceCache) : MetaM Unit :=
modifyCache fun c => { c with synthInstance := cache }
@[inline] private def resettingSynthInstanceCacheImpl (x : MetaM α) : MetaM α := do
let savedSythInstance ← saveAndResetSynthInstanceCache
try x finally restoreSynthInstanceCache savedSythInstance
/-- Reset `synthInstance` cache, execute `x`, and restore cache -/
@[inline] def resettingSynthInstanceCache : n α → n α :=
mapMetaM resettingSynthInstanceCacheImpl
@[inline] def resettingSynthInstanceCacheWhen (b : Bool) (x : n α) : n α :=
if b then resettingSynthInstanceCache x else x
private def withNewLocalInstanceImp (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α := do
let localDecl ← getFVarLocalDecl fvar
/- Recall that we use `auxDecl` binderInfo when compiling recursive declarations. -/
match localDecl.binderInfo with
| BinderInfo.auxDecl => k
| _ =>
resettingSynthInstanceCache <|
withReader
(fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } })
k
/-- Add entry `{ className := className, fvar := fvar }` to localInstances,
and then execute continuation `k`.
It resets the type class cache using `resettingSynthInstanceCache`. -/
def withNewLocalInstance (className : Name) (fvar : Expr) : n α → n α :=
mapMetaM <| withNewLocalInstanceImp className fvar
private def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool :=
match maxFVars? with
| some maxFVars => fvars.size < maxFVars
| none => true
mutual
/--
`withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances
using free variables `fvars[j] ... fvars.back`, and execute `k`.
- `isClassExpensive` is defined later.
- The type class chache is reset whenever a new local instance is found.
- `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances.
Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/
private partial def withNewLocalInstancesImp
(fvars : Array Expr) (i : Nat) (k : MetaM α) : MetaM α := do
if h : i < fvars.size then
let fvar := fvars.get ⟨i, h⟩
let decl ← getFVarLocalDecl fvar
match (← isClassQuick? decl.type) with
| LOption.none => withNewLocalInstancesImp fvars (i+1) k
| LOption.undef =>
match (← isClassExpensive? decl.type) with
| none => withNewLocalInstancesImp fvars (i+1) k
| some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k
| LOption.some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k
else
k
/--
`forallTelescopeAuxAux lctx fvars j type`
Remarks:
- `lctx` is the `MetaM` local context extended with declarations for `fvars`.
- `type` is the type we are computing the telescope for. It contains only
dangling bound variables in the range `[j, fvars.size)`
- if `reducing? == true` and `type` is not `forallE`, we use `whnf`.
- when `type` is not a `forallE` nor it can't be reduced to one, we
excute the continuation `k`.
Here is an example that demonstrates the `reducing?`.
Suppose we have
```
abbrev StateM s a := s -> Prod a s
```
Now, assume we are trying to build the telescope for
```
forall (x : Nat), StateM Int Bool
```
if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`.
if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)`
if `maxFVars?` is `some max`, then we interrupt the telescope construction
when `fvars.size == max`
-/
private partial def forallTelescopeReducingAuxAux
(reducing : Bool) (maxFVars? : Option Nat)
(type : Expr)
(k : Array Expr → Expr → MetaM α) : MetaM α := do
let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM α := do
match type with
| Expr.forallE n d b c =>
if fvarsSizeLtMaxFVars fvars maxFVars? then
let d := d.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshFVarId
let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo
let fvar := mkFVar fvarId
let fvars := fvars.push fvar
process lctx fvars j b
else
let type := type.instantiateRevRange j fvars.size fvars;
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
k fvars type
| _ =>
let type := type.instantiateRevRange j fvars.size fvars;
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then
let newType ← whnf type
if newType.isForall then
process lctx fvars fvars.size newType
else
k fvars type
else
k fvars type
process (← getLCtx) #[] 0 type
private partial def forallTelescopeReducingAux (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do
match maxFVars? with
| some 0 => k #[] type
| _ => do
let newType ← whnf type
if newType.isForall then
forallTelescopeReducingAuxAux true maxFVars? newType k
else
k #[] type
private partial def isClassExpensive? : Expr → MetaM (Option Name)
| type => withReducible <| -- when testing whether a type is a type class, we only unfold reducible constants.
forallTelescopeReducingAux type none fun xs type => do
let env ← getEnv
match type.getAppFn with
| Expr.const c _ _ => do
if isClass env c then
return some c
else
-- make sure abbreviations are unfolded
match (← whnf type).getAppFn with
| Expr.const c _ _ => return if isClass env c then some c else none
| _ => return none
| _ => return none
private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do
match (← isClassQuick? type) with
| LOption.none => pure none
| LOption.some c => pure (some c)
| LOption.undef => isClassExpensive? type
end
def isClass? (type : Expr) : MetaM (Option Name) :=
try isClassImp? type catch _ => pure none
private def withNewLocalInstancesImpAux (fvars : Array Expr) (j : Nat) : n α → n α :=
mapMetaM <| withNewLocalInstancesImp fvars j
partial def withNewLocalInstances (fvars : Array Expr) (j : Nat) : n α → n α :=
mapMetaM <| withNewLocalInstancesImpAux fvars j
@[inline] private def forallTelescopeImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do
forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k
/--
Given `type` of the form `forall xs, A`, execute `k xs A`.
This combinator will declare local declarations, create free variables for them,
execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/
def forallTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => forallTelescopeImp type k) k
private def forallTelescopeReducingImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α :=
forallTelescopeReducingAux type (maxFVars? := none) k
/--
Similar to `forallTelescope`, but given `type` of the form `forall xs, A`,
it reduces `A` and continues bulding the telescope if it is a `forall`. -/
def forallTelescopeReducing (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => forallTelescopeReducingImp type k) k
private def forallBoundedTelescopeImp (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α :=
forallTelescopeReducingAux type maxFVars? k
/--
Similar to `forallTelescopeReducing`, stops constructing the telescope when
it reaches size `maxFVars`. -/
def forallBoundedTelescope (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k
private partial def lambdaTelescopeImp (e : Expr) (consumeLet : Bool) (k : Array Expr → Expr → MetaM α) : MetaM α := do
process consumeLet (← getLCtx) #[] 0 e
where
process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM α := do
match consumeLet, e with
| _, Expr.lam n d b c =>
let d := d.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshFVarId
let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo
let fvar := mkFVar fvarId
process consumeLet lctx (fvars.push fvar) j b
| true, Expr.letE n t v b _ => do
let t := t.instantiateRevRange j fvars.size fvars
let v := v.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshFVarId
let lctx := lctx.mkLetDecl fvarId n t v
let fvar := mkFVar fvarId
process true lctx (fvars.push fvar) j b
| _, e =>
let e := e.instantiateRevRange j fvars.size fvars
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
k fvars e
/-- Similar to `forallTelescope` but for lambda and let expressions. -/
def lambdaLetTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => lambdaTelescopeImp type true k) k
/-- Similar to `forallTelescope` but for lambda expressions. -/
def lambdaTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => lambdaTelescopeImp type false k) k
/-- Return the parameter names for the givel global declaration. -/
def getParamNames (declName : Name) : MetaM (Array Name) := do
forallTelescopeReducing (← getConstInfo declName).type fun xs _ => do
xs.mapM fun x => do
let localDecl ← getLocalDecl x.fvarId!
pure localDecl.userName
-- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments.
private partial def forallMetaTelescopeReducingAux
(e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr × Array BinderInfo × Expr) :=
process #[] #[] 0 e
where
process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do
if maxMVars?.isEqSome mvars.size then
let type := type.instantiateRevRange j mvars.size mvars;
return (mvars, bis, type)
else
match type with
| Expr.forallE n d b c =>
let d := d.instantiateRevRange j mvars.size mvars
let k := if c.binderInfo.isInstImplicit then MetavarKind.synthetic else kind
let mvar ← mkFreshExprMVar d k n
let mvars := mvars.push mvar
let bis := bis.push c.binderInfo
process mvars bis j b
| _ =>
let type := type.instantiateRevRange j mvars.size mvars;
if reducing then do
let newType ← whnf type;
if newType.isForall then
process mvars bis mvars.size newType
else
return (mvars, bis, type)
else
return (mvars, bis, type)
/-- Similar to `forallTelescope`, but creates metavariables instead of free variables. -/
def forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) :=
forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind
/-- Similar to `forallTelescopeReducing`, but creates metavariables instead of free variables. -/
def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) :=
forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind
/-- Similar to `forallMetaTelescopeReducing`, stops constructing the telescope when it reaches size `maxMVars`. -/
def forallMetaBoundedTelescope (e : Expr) (maxMVars : Nat) (kind : MetavarKind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) :=
forallMetaTelescopeReducingAux e (reducing := true) (maxMVars? := some maxMVars) (kind := kind)
/-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/
partial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) :=
process #[] #[] 0 e
where
process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do
let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do
let type := type.instantiateRevRange j mvars.size mvars
pure (mvars, bis, type)
if maxMVars?.isEqSome mvars.size then
finalize ()
else
match type with
| Expr.lam n d b c =>
let d := d.instantiateRevRange j mvars.size mvars
let mvar ← mkFreshExprMVar d
let mvars := mvars.push mvar
let bis := bis.push c.binderInfo
process mvars bis j b
| _ => finalize ()
private def withNewFVar (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do
match (← isClass? fvarType) with
| none => k fvar
| some c => withNewLocalInstance c fvar <| k fvar
private def withLocalDeclImp (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr → MetaM α) : MetaM α := do
let fvarId ← mkFreshFVarId
let ctx ← read
let lctx := ctx.lctx.mkLocalDecl fvarId n type bi
let fvar := mkFVar fvarId
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewFVar fvar type k
def withLocalDecl (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr → n α) : n α :=
map1MetaM (fun k => withLocalDeclImp name bi type k) k
def withLocalDeclD (name : Name) (type : Expr) (k : Expr → n α) : n α :=
withLocalDecl name BinderInfo.default type k
partial def withLocalDecls
[Inhabited α]
(declInfos : Array (Name × BinderInfo × (Array Expr → n Expr)))
(k : (xs : Array Expr) → n α)
: n α :=
loop #[]
where
loop [Inhabited α] (acc : Array Expr) : n α := do
if acc.size < declInfos.size then
let (name, bi, typeCtor) := declInfos[acc.size]
withLocalDecl name bi (←typeCtor acc) fun x => loop (acc.push x)
else
k acc
def withLocalDeclsD [Inhabited α] (declInfos : Array (Name × (Array Expr → n Expr))) (k : (xs : Array Expr) → n α) : n α :=
withLocalDecls
(declInfos.map (fun (name, typeCtor) => (name, BinderInfo.default, typeCtor))) k
private def withNewBinderInfosImp (bs : Array (FVarId × BinderInfo)) (k : MetaM α) : MetaM α := do
let lctx := bs.foldl (init := (← getLCtx)) fun lctx (fvarId, bi) =>
lctx.setBinderInfo fvarId bi
withReader (fun ctx => { ctx with lctx := lctx }) k
def withNewBinderInfos (bs : Array (FVarId × BinderInfo)) (k : n α) : n α :=
mapMetaM (fun k => withNewBinderInfosImp bs k) k
private def withLetDeclImp (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) : MetaM α := do
let fvarId ← mkFreshFVarId
let ctx ← read
let lctx := ctx.lctx.mkLetDecl fvarId n type val
let fvar := mkFVar fvarId
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewFVar fvar type k
def withLetDecl (name : Name) (type : Expr) (val : Expr) (k : Expr → n α) : n α :=
map1MetaM (fun k => withLetDeclImp name type val k) k
private def withExistingLocalDeclsImp (decls : List LocalDecl) (k : MetaM α) : MetaM α := do
let ctx ← read
let numLocalInstances := ctx.localInstances.size
let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx
withReader (fun ctx => { ctx with lctx := lctx }) do
let newLocalInsts ← decls.foldlM
(fun (newlocalInsts : Array LocalInstance) (decl : LocalDecl) => (do {
match (← isClass? decl.type) with
| none => pure newlocalInsts
| some c => pure <| newlocalInsts.push { className := c, fvar := decl.toExpr } } : MetaM _))
ctx.localInstances;
if newLocalInsts.size == numLocalInstances then
k
else
resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := newLocalInsts }) k
def withExistingLocalDecls (decls : List LocalDecl) : n α → n α :=
mapMetaM <| withExistingLocalDeclsImp decls
private def withNewMCtxDepthImp (x : MetaM α) : MetaM α := do
let saved ← get
modify fun s => { s with mctx := s.mctx.incDepth, postponed := {} }
try
x
finally
modify fun s => { s with mctx := saved.mctx, postponed := saved.postponed }
/--
Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`,
and restore saved data. -/
def withNewMCtxDepth : n α → n α :=
mapMetaM withNewMCtxDepthImp
private def withLocalContextImp (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM α) : MetaM α := do
let localInstsCurr ← getLocalInstances
withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do
if localInsts == localInstsCurr then
x
else
resettingSynthInstanceCache x
def withLCtx (lctx : LocalContext) (localInsts : LocalInstances) : n α → n α :=
mapMetaM <| withLocalContextImp lctx localInsts
private def withMVarContextImp (mvarId : MVarId) (x : MetaM α) : MetaM α := do
let mvarDecl ← getMVarDecl mvarId
withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x
/--
Execute `x` using the given metavariable `LocalContext` and `LocalInstances`.
The type class resolution cache is flushed when executing `x` if its `LocalInstances` are
different from the current ones. -/
def withMVarContext (mvarId : MVarId) : n α → n α :=
mapMetaM <| withMVarContextImp mvarId
private def withMCtxImp (mctx : MetavarContext) (x : MetaM α) : MetaM α := do
let mctx' ← getMCtx
setMCtx mctx
try x finally setMCtx mctx'
def withMCtx (mctx : MetavarContext) : n α → n α :=
mapMetaM <| withMCtxImp mctx
@[inline] private def approxDefEqImp (x : MetaM α) : MetaM α :=
withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x
/-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`. -/
@[inline] def approxDefEq : n α → n α :=
mapMetaM approxDefEqImp
@[inline] private def fullApproxDefEqImp (x : MetaM α) : MetaM α :=
withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x
/--
Similar to `approxDefEq`, but uses all available approximations.
We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code.
For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`.
Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved
as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to
solve `[Pure (fun _ => IO Bool)]` -/
@[inline] def fullApproxDefEq : n α → n α :=
mapMetaM fullApproxDefEqImp
def normalizeLevel (u : Level) : MetaM Level := do
let u ← instantiateLevelMVars u
pure u.normalize
def assignLevelMVar (mvarId : MVarId) (u : Level) : MetaM Unit := do
modifyMCtx fun mctx => mctx.assignLevel mvarId u
def whnfR (e : Expr) : MetaM Expr :=
withTransparency TransparencyMode.reducible <| whnf e
def whnfD (e : Expr) : MetaM Expr :=
withTransparency TransparencyMode.default <| whnf e
def whnfI (e : Expr) : MetaM Expr :=
withTransparency TransparencyMode.instances <| whnf e
def setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): MetaM Unit := do
let env ← getEnv
match Compiler.setInlineAttribute env declName kind with
| Except.ok env => setEnv env
| Except.error msg => throwError msg
private partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do
if h : i < ps.size then
let p := ps.get ⟨i, h⟩
match (← whnf e) with
| Expr.forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p)
| _ => throwError "invalid instantiateForall, too many parameters"
else
pure e
/- Given `e` of the form `forall (a_1 : A_1) ... (a_n : A_n), B[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `B[p_1, ..., p_n]`. -/
def instantiateForall (e : Expr) (ps : Array Expr) : MetaM Expr :=
instantiateForallAux ps 0 e
private partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do
if h : i < ps.size then
let p := ps.get ⟨i, h⟩
match (← whnf e) with
| Expr.lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p)
| _ => throwError "invalid instantiateLambda, too many parameters"
else
pure e
/- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`.
It uses `whnf` to reduce `e` if it is not a lambda -/
def instantiateLambda (e : Expr) (ps : Array Expr) : MetaM Expr :=
instantiateLambdaAux ps 0 e
/-- Return true iff `e` depends on the free variable `fvarId` -/
def dependsOn (e : Expr) (fvarId : FVarId) : MetaM Bool :=
return (← getMCtx).exprDependsOn e fvarId
/-- Return true iff `e` depends on a free variable `x` s.t. `p x` -/
def dependsOnPred (e : Expr) (p : FVarId → Bool) : MetaM Bool :=
return (← getMCtx).findExprDependsOn e p
/-- Return true iff the local declaration `localDecl` depends on a free variable `x` s.t. `p x` -/
def localDeclDependsOnPred (localDecl : LocalDecl) (p : FVarId → Bool) : MetaM Bool := do
return (← getMCtx).findLocalDeclDependsOn localDecl p
def ppExpr (e : Expr) : MetaM Format := do
let ctxCore ← readThe Core.Context
Lean.ppExpr { env := (← getEnv), mctx := (← getMCtx), lctx := (← getLCtx), opts := (← getOptions), currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls } e
@[inline] protected def orElse (x : MetaM α) (y : Unit → MetaM α) : MetaM α := do
let s ← saveState
try x catch _ => s.restore; y ()
instance : OrElse (MetaM α) := ⟨Meta.orElse⟩
instance : Alternative MetaM where
failure := fun {α} => throwError "failed"
orElse := Meta.orElse
@[inline] private def orelseMergeErrorsImp (x y : MetaM α)
(mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁)
(mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ m₂) : MetaM α := do
let env ← getEnv
let mctx ← getMCtx
try
x
catch ex =>
setEnv env
setMCtx mctx
match ex with
| Exception.error ref₁ m₁ =>
try
y
catch
| Exception.error ref₂ m₂ => throw <| Exception.error (mergeRef ref₁ ref₂) (mergeMsg m₁ m₂)
| ex => throw ex
| ex => throw ex
/--
Similar to `orelse`, but merge errors. Note that internal errors are not caught.
The default `mergeRef` uses the `ref` (position information) for the first message.
The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/
@[inline] def orelseMergeErrors [MonadControlT MetaM m] [Monad m] (x y : m α)
(mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁)
(mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ Format.line ++ m₂) : m α := do
controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg
/-- Execute `x`, and apply `f` to the produced error message -/
def mapErrorImp (x : MetaM α) (f : MessageData → MessageData) : MetaM α := do
try
x
catch
| Exception.error ref msg => throw <| Exception.error ref <| f msg
| ex => throw ex
@[inline] def mapError [MonadControlT MetaM m] [Monad m] (x : m α) (f : MessageData → MessageData) : m α :=
controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f
/--
Sort free variables using an order `x < y` iff `x` was defined before `y`.
If a free variable is not in the local context, we use their id. -/
def sortFVarIds (fvarIds : Array FVarId) : MetaM (Array FVarId) := do
let lctx ← getLCtx
return fvarIds.qsort fun fvarId₁ fvarId₂ =>
match lctx.find? fvarId₁, lctx.find? fvarId₂ with
| some d₁, some d₂ => d₁.index < d₂.index
| some _, none => false
| none, some _ => true
| none, none => Name.quickLt fvarId₁.name fvarId₂.name
end Methods
def isInductivePredicate (declName : Name) : MetaM Bool := do
match (← getEnv).find? declName with
| some (ConstantInfo.inductInfo { type := type, ..}) =>
forallTelescopeReducing type fun _ type => do
match (← whnfD type) with
| Expr.sort u .. => return u == levelZero
| _ => return false
| _ => return false
end Meta
export Meta (MetaM)
end Lean
|
2acaca46428a65993f72e9b5db910bfe4b362326 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /test/push_neg.lean | ba167094d2dbfb0932ecf7d77d0adc76c65464a2 | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 2,030 | lean | import tactic.push_neg
example (h : ∃ p: ℕ, ¬ ∀ n : ℕ, n > p) (h' : ∃ p: ℕ, ¬ ∃ n : ℕ, n < p) : ¬ ∀ n : ℕ, n = 0 :=
begin
push_neg at *,
guard_target_strict ∃ (n : ℕ), n ≠ 0,
guard_hyp_strict h := ∃ (p n : ℕ), n ≤ p,
guard_hyp_strict h' := ∃ (p : ℕ), ∀ (n : ℕ), p ≤ n,
use 1,
end
-- In the next example, ℤ should be ℝ in maths, but I don't want to import real numbers
-- for testing only
local notation `|` x `|` := abs x
example (a : ℕ → ℤ) (l : ℤ) (h : ¬ ∀ ε > 0, ∃ N, ∀ n ≥ N, | a n - l | < ε) : true :=
begin
push_neg at h,
guard_hyp_strict h := ∃ (ε : ℤ), ε > 0 ∧ ∀ (N : ℕ), ∃ (n : ℕ), n ≥ N ∧ ε ≤ |a n - l|,
trivial
end
example (f : ℤ → ℤ) (x₀ y₀) (h : ¬ ∀ ε > 0, ∃ δ > 0, ∀ x, |x - x₀| ≤ δ → |f x - y₀| ≤ ε) : true :=
begin
push_neg at h,
guard_hyp_strict h := ∃ (ε : ℤ), ε > 0 ∧ ∀ δ > 0, (∃ (x : ℤ), |x - x₀| ≤ δ ∧ ε < |f x - y₀| ),
trivial
end
example (n) : n*n ≠ 1 → n ≠ 1 :=
begin
contrapose,
rw [not_not, not_not],
intro h,
rw [h, one_mul]
end
example (n) : n*n ≠ 1 → n ≠ 1 :=
begin
contrapose!,
intro h,
rw [h, one_mul]
end
example (n) (h : n*n ≠ 1) : n ≠ 1 :=
begin
contrapose h,
rw not_not at *,
rw [h, one_mul]
end
example (n) (h : n*n ≠ 1) : n ≠ 1 :=
begin
contrapose! h,
rw [h, one_mul]
end
example (n) (h : n*n ≠ 1) : n ≠ 1 :=
begin
contrapose! h with newh,
rw [newh, one_mul]
end
example : 0 = 0 :=
begin
success_if_fail_with_msg { contrapose }
"The goal is not an implication, and you didn't specify an assumption",
refl
end
-- Remember that ∀ is the same as Π which is a generalization of → so we need to make sure
-- `contrapose` fails with a helpful error message in the next example.
example : ∀ x : ℕ, x = x :=
begin
success_if_fail_with_msg { contrapose }
"contrapose only applies to nondependent arrows between decidable props",
intro, refl
end
|
8b7ac355da90971593887af36b1bec65bbc59c5d | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/adjunction/opposites.lean | 496d3e8668605f08a08180ea1f23935ff70e3532 | [] | 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,996 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Thomas Read
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.adjunction.basic
import Mathlib.category_theory.yoneda
import Mathlib.category_theory.opposites
import Mathlib.PostPort
universes u₁ u₂ v₁ v₂
namespace Mathlib
/-!
# Opposite adjunctions
This file contains constructions to relate adjunctions of functors to adjunctions of their
opposites.
These constructions are used to show uniqueness of adjoints (up to natural isomorphism).
## Tags
adjunction, opposite, uniqueness
-/
namespace adjunction
/-- If `G.op` is adjoint to `F.op` then `F` is adjoint to `G`. -/
def adjoint_of_op_adjoint_op {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (F : C ⥤ D) (G : D ⥤ C) (h : category_theory.functor.op G ⊣ category_theory.functor.op F) : F ⊣ G :=
category_theory.adjunction.mk_of_hom_equiv
(category_theory.adjunction.core_hom_equiv.mk
fun (X : C) (Y : D) =>
equiv.trans
(equiv.symm
(equiv.trans (category_theory.adjunction.hom_equiv h (opposite.op Y) (opposite.op X))
(category_theory.op_equiv (opposite.op Y)
(category_theory.functor.obj (category_theory.functor.op F) (opposite.op X)))))
(category_theory.op_equiv (category_theory.functor.obj (category_theory.functor.op G) (opposite.op Y))
(opposite.op X)))
/-- If `G` is adjoint to `F.op` then `F` is adjoint to `G.unop`. -/
def adjoint_unop_of_adjoint_op {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (F : C ⥤ D) (G : Dᵒᵖ ⥤ (Cᵒᵖ)) (h : G ⊣ category_theory.functor.op F) : F ⊣ category_theory.functor.unop G :=
adjoint_of_op_adjoint_op F (category_theory.functor.unop G)
(category_theory.adjunction.of_nat_iso_left h (category_theory.iso.symm (category_theory.functor.op_unop_iso G)))
/-- If `G.op` is adjoint to `F` then `F.unop` is adjoint to `G`. -/
def unop_adjoint_of_op_adjoint {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (F : Cᵒᵖ ⥤ (Dᵒᵖ)) (G : D ⥤ C) (h : category_theory.functor.op G ⊣ F) : category_theory.functor.unop F ⊣ G :=
adjoint_of_op_adjoint_op (category_theory.functor.unop F) G
(category_theory.adjunction.of_nat_iso_right h (category_theory.iso.symm (category_theory.functor.op_unop_iso F)))
/-- If `G` is adjoint to `F` then `F.unop` is adjoint to `G.unop`. -/
def unop_adjoint_unop_of_adjoint {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (F : Cᵒᵖ ⥤ (Dᵒᵖ)) (G : Dᵒᵖ ⥤ (Cᵒᵖ)) (h : G ⊣ F) : category_theory.functor.unop F ⊣ category_theory.functor.unop G :=
adjoint_unop_of_adjoint_op (category_theory.functor.unop F) G
(category_theory.adjunction.of_nat_iso_right h (category_theory.iso.symm (category_theory.functor.op_unop_iso F)))
/-- If `G` is adjoint to `F` then `F.op` is adjoint to `G.op`. -/
def op_adjoint_op_of_adjoint {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (F : C ⥤ D) (G : D ⥤ C) (h : G ⊣ F) : category_theory.functor.op F ⊣ category_theory.functor.op G :=
category_theory.adjunction.mk_of_hom_equiv
(category_theory.adjunction.core_hom_equiv.mk
fun (X : Cᵒᵖ) (Y : Dᵒᵖ) =>
equiv.trans (category_theory.op_equiv (category_theory.functor.obj (category_theory.functor.op F) X) Y)
(equiv.trans (equiv.symm (category_theory.adjunction.hom_equiv h (opposite.unop Y) (opposite.unop X)))
(equiv.symm (category_theory.op_equiv X (opposite.op (category_theory.functor.obj G (opposite.unop Y)))))))
/-- If `G` is adjoint to `F.unop` then `F` is adjoint to `G.op`. -/
def adjoint_op_of_adjoint_unop {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (F : Cᵒᵖ ⥤ (Dᵒᵖ)) (G : D ⥤ C) (h : G ⊣ category_theory.functor.unop F) : F ⊣ category_theory.functor.op G :=
category_theory.adjunction.of_nat_iso_left (op_adjoint_op_of_adjoint (category_theory.functor.unop F) G h)
(category_theory.functor.op_unop_iso F)
/-- If `G.unop` is adjoint to `F` then `F.op` is adjoint to `G`. -/
def op_adjoint_of_unop_adjoint {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (F : C ⥤ D) (G : Dᵒᵖ ⥤ (Cᵒᵖ)) (h : category_theory.functor.unop G ⊣ F) : category_theory.functor.op F ⊣ G :=
category_theory.adjunction.of_nat_iso_right (op_adjoint_op_of_adjoint F (category_theory.functor.unop G) h)
(category_theory.functor.op_unop_iso G)
/-- If `G.unop` is adjoint to `F.unop` then `F` is adjoint to `G`. -/
def adjoint_of_unop_adjoint_unop {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (F : Cᵒᵖ ⥤ (Dᵒᵖ)) (G : Dᵒᵖ ⥤ (Cᵒᵖ)) (h : category_theory.functor.unop G ⊣ category_theory.functor.unop F) : F ⊣ G :=
category_theory.adjunction.of_nat_iso_right (adjoint_op_of_adjoint_unop F (category_theory.functor.unop G) h)
(category_theory.functor.op_unop_iso G)
/--
If `F` and `F'` are both adjoint to `G`, there is a natural isomorphism
`F.op ⋙ coyoneda ≅ F'.op ⋙ coyoneda`.
We use this in combination with `fully_faithful_cancel_right` to show left adjoints are unique.
-/
def left_adjoints_coyoneda_equiv {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] {F : C ⥤ D} {F' : C ⥤ D} {G : D ⥤ C} (adj1 : F ⊣ G) (adj2 : F' ⊣ G) : category_theory.functor.op F ⋙ category_theory.coyoneda ≅ category_theory.functor.op F' ⋙ category_theory.coyoneda :=
category_theory.nat_iso.of_components
(fun (X : Cᵒᵖ) =>
category_theory.nat_iso.of_components
(fun (Y : D) =>
equiv.to_iso
(equiv.trans (category_theory.adjunction.hom_equiv adj1 (opposite.unop X) Y)
(equiv.symm (category_theory.adjunction.hom_equiv adj2 (opposite.unop X) Y))))
sorry)
sorry
/-- If `F` and `F'` are both left adjoint to `G`, then they are naturally isomorphic. -/
def left_adjoint_uniq {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] {F : C ⥤ D} {F' : C ⥤ D} {G : D ⥤ C} (adj1 : F ⊣ G) (adj2 : F' ⊣ G) : F ≅ F' :=
category_theory.nat_iso.remove_op
(category_theory.fully_faithful_cancel_right category_theory.coyoneda (left_adjoints_coyoneda_equiv adj2 adj1))
/-- If `G` and `G'` are both right adjoint to `F`, then they are naturally isomorphic. -/
def right_adjoint_uniq {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] {F : C ⥤ D} {G : D ⥤ C} {G' : D ⥤ C} (adj1 : F ⊣ G) (adj2 : F ⊣ G') : G ≅ G' :=
category_theory.nat_iso.remove_op
(left_adjoint_uniq (op_adjoint_op_of_adjoint G' F adj2) (op_adjoint_op_of_adjoint G F adj1))
/--
Given two adjunctions, if the left adjoints are naturally isomorphic, then so are the right
adjoints.
-/
def nat_iso_of_left_adjoint_nat_iso {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] {F : C ⥤ D} {F' : C ⥤ D} {G : D ⥤ C} {G' : D ⥤ C} (adj1 : F ⊣ G) (adj2 : F' ⊣ G') (l : F ≅ F') : G ≅ G' :=
right_adjoint_uniq adj1 (category_theory.adjunction.of_nat_iso_left adj2 (category_theory.iso.symm l))
/--
Given two adjunctions, if the right adjoints are naturally isomorphic, then so are the left
adjoints.
-/
def nat_iso_of_right_adjoint_nat_iso {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] {F : C ⥤ D} {F' : C ⥤ D} {G : D ⥤ C} {G' : D ⥤ C} (adj1 : F ⊣ G) (adj2 : F' ⊣ G') (r : G ≅ G') : F ≅ F' :=
left_adjoint_uniq adj1 (category_theory.adjunction.of_nat_iso_right adj2 (category_theory.iso.symm r))
|
a73cf97c16b78691593582be6ba2e39b85d39cb4 | 6b45072eb2b3db3ecaace2a7a0241ce81f815787 | /tools/super/intuit.lean | da8dc02c3032b030eb40470101a87082a37761b0 | [] | no_license | avigad/library_dev | 27b47257382667b5eb7e6476c4f5b0d685dd3ddc | 9d8ac7c7798ca550874e90fed585caad030bbfac | refs/heads/master | 1,610,452,468,791 | 1,500,712,839,000 | 1,500,713,478,000 | 69,311,142 | 1 | 0 | null | 1,474,942,903,000 | 1,474,942,902,000 | null | UTF-8 | Lean | false | false | 2,560 | lean | import super.clausifier super.cdcl super.trim
open tactic super expr monad
-- Intuitionistic propositional prover based on
-- SAT Modulo Intuitionistic Implications, Claessen and Rosen, LPAR 2015
namespace intuit
meta def check_model (intuit : tactic unit) : cdcl.solver (option cdcl.proof_term) :=
do s ← state_t.read, monad_lift $ do
hyps ← return $ s^.trail^.for (λe, e^.hyp),
subgoal ← mk_meta_var s^.local_false,
goals ← get_goals,
set_goals [subgoal],
for' s^.trail (λe,
if e^.phase then do
name ← get_unused_name `model (some 1),
assertv name e^.hyp^.local_type e^.hyp,
return ()
else
return ()),
is_solved ← first (do
e ← s^.trail,
guard ¬e^.phase,
guard e^.var^.is_pi,
a ← option.to_monad $ s^.vars^.find e^.var^.binding_domain,
b ← option.to_monad $ s^.vars^.find e^.var^.binding_body,
guard $ a^.phase = ff ∧ b^.phase = ff,
return $ do
apply e^.hyp,
intuit,
done, return tt) <|> return ff,
set_goals goals,
if is_solved then do
proof ← instantiate_mvars subgoal,
proof' ← trim proof, -- gets rid of the unnecessary asserts
return $ some proof'
else
return none
lemma imp1 {F a b} : b → ((a → b) → F) → F := λhb habf, habf (λha, hb)
lemma imp2 {a b} : a → (a → b) → b := λha hab, hab ha
meta def solve : unit → tactic unit | () := with_trim $ do
as_refutation,
local_false ← target, clauses ← clauses_of_context,
clauses ← get_clauses_intuit clauses,
vars ← return $ list.nub (do c ← clauses, l ← c^.get_lits, [l^.formula]),
imp_axs ← sequence (do
v ← vars, guard v^.is_pi,
a ← return v^.binding_domain, b ← return v^.binding_body,
pr ← [mk_mapp ``intuit.imp1 [some local_false, some a, some b],
mk_mapp ``intuit.imp2 [some a, some b]],
[pr >>= clause.of_proof local_false]),
clauses ← return $ imp_axs ++ clauses,
result ← cdcl.solve (check_model (solve ())) local_false clauses,
match result with
| (cdcl.result.sat interp) :=
let interp' := do e ← interp^.to_list, [if e^.2 = tt then e^.1 else `(not %%(e^.1)) ] in
do pp_interp ← pp interp',
fail (to_fmt "satisfying assignment: " ++ pp_interp)
| (cdcl.result.unsat proof) := exact proof
end
end intuit
meta def intuit : tactic unit := _root_.intuit.solve ()
example (a b) : a → (a → b) → b := by intuit
example (a b c) : (a → c) → (c → b) → ((a → b) → a) → a := by intuit
example (a b) : a ∨ ¬a → ((a → b) → a) → a := by intuit
def compose {a b c} : (a → b) → (b → c) → (a → c) := by intuit
|
fc4c9254b7fe1d48588b38abe03e7ba16474ec37 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/univ_of_instances.lean | ae52ba7577fd4a6059ddddc9ec58e14356be5226 | [
"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 | 191 | lean | section
universes v u
class category (C : Type u) := (hom : C → C → Type v)
end
section
universes v u
variables (C : Type u) [category.{v} C]
def End (X : C) := category.hom X X
end
|
7aa76ef1107a523f4bf724b653f1b019ac96d465 | 3863d2564418bccb1859e057bf5a4ef240e75fd7 | /hott/init/equiv.hlean | 18fba5ff1685ef3ce9f4ab511678ac5930b0bcd0 | [
"Apache-2.0"
] | permissive | JacobGross/lean | 118bbb067ff4d4af48a266face2c7eb9868fa91c | eb26087df940c54337cb807b4bc6d345d1fc1085 | refs/heads/master | 1,582,735,011,532 | 1,462,557,826,000 | 1,462,557,826,000 | 46,451,196 | 0 | 0 | null | 1,462,557,826,000 | 1,447,885,161,000 | C++ | UTF-8 | Lean | false | false | 17,168 | hlean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad, Jakob von Raumer, Floris van Doorn
Ported from Coq HoTT
-/
prelude
import .path .function
open eq function lift
/- Equivalences -/
-- This is our definition of equivalence. In the HoTT-book it's called
-- ihae (half-adjoint equivalence).
structure is_equiv [class] {A B : Type} (f : A → B) :=
mk' ::
(inv : B → A)
(right_inv : Πb, f (inv b) = b)
(left_inv : Πa, inv (f a) = a)
(adj : Πx, right_inv (f x) = ap f (left_inv x))
attribute is_equiv.inv [reducible]
-- A more bundled version of equivalence
structure equiv (A B : Type) :=
(to_fun : A → B)
(to_is_equiv : is_equiv to_fun)
namespace is_equiv
/- Some instances and closure properties of equivalences -/
postfix ⁻¹ := inv
/- a second notation for the inverse, which is not overloaded -/
postfix [parsing_only] `⁻¹ᶠ`:std.prec.max_plus := inv
section
variables {A B C : Type} (f : A → B) (g : B → C) {f' : A → B}
-- The variant of mk' where f is explicit.
protected abbreviation mk [constructor] := @is_equiv.mk' A B f
-- The identity function is an equivalence.
definition is_equiv_id [instance] [constructor] (A : Type) : (is_equiv (id : A → A)) :=
is_equiv.mk id id (λa, idp) (λa, idp) (λa, idp)
-- The composition of two equivalences is, again, an equivalence.
definition is_equiv_compose [constructor] [Hf : is_equiv f] [Hg : is_equiv g]
: is_equiv (g ∘ f) :=
is_equiv.mk (g ∘ f) (f⁻¹ ∘ g⁻¹)
abstract (λc, ap g (right_inv f (g⁻¹ c)) ⬝ right_inv g c) end
abstract (λa, ap (inv f) (left_inv g (f a)) ⬝ left_inv f a) end
abstract (λa, (whisker_left _ (adj g (f a))) ⬝
(ap_con g _ _)⁻¹ ⬝
ap02 g ((ap_con_eq_con (right_inv f) (left_inv g (f a)))⁻¹ ⬝
(ap_compose f (inv f) _ ◾ adj f a) ⬝
(ap_con f _ _)⁻¹
) ⬝
(ap_compose g f _)⁻¹) end
-- Any function equal to an equivalence is an equivlance as well.
variable {f}
definition is_equiv_eq_closed [Hf : is_equiv f] (Heq : f = f') : is_equiv f' :=
eq.rec_on Heq Hf
end
section
parameters {A B : Type} (f : A → B) (g : B → A)
(ret : Πb, f (g b) = b) (sec : Πa, g (f a) = a)
definition adjointify_left_inv' (a : A) : g (f a) = a :=
ap g (ap f (inverse (sec a))) ⬝ ap g (ret (f a)) ⬝ sec a
theorem adjointify_adj' (a : A) : ret (f a) = ap f (adjointify_left_inv' a) :=
let fgretrfa := ap f (ap g (ret (f a))) in
let fgfinvsect := ap f (ap g (ap f (sec a)⁻¹)) in
let fgfa := f (g (f a)) in
let retrfa := ret (f a) in
have eq1 : ap f (sec a) = _,
from calc ap f (sec a)
= idp ⬝ ap f (sec a) : by rewrite idp_con
... = (ret (f a) ⬝ (ret (f a))⁻¹) ⬝ ap f (sec a) : by rewrite con.right_inv
... = ((ret fgfa)⁻¹ ⬝ ap (f ∘ g) (ret (f a))) ⬝ ap f (sec a) : by rewrite con_ap_eq_con
... = ((ret fgfa)⁻¹ ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose
... = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc,
have eq2 : ap f (sec a) ⬝ idp = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)),
from !con_idp ⬝ eq1,
have eq3 : idp = _,
from calc idp
= (ap f (sec a))⁻¹ ⬝ ((ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a))) : eq_inv_con_of_con_eq eq2
... = ((ap f (sec a))⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc'
... = (ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite ap_inv
... = ((ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con.assoc'
... = ((retrfa⁻¹ ⬝ ap (f ∘ g) (ap f (sec a)⁻¹)) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con_ap_eq_con
... = ((retrfa⁻¹ ⬝ fgfinvsect) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose
... = (retrfa⁻¹ ⬝ (fgfinvsect ⬝ fgretrfa)) ⬝ ap f (sec a) : by rewrite con.assoc'
... = retrfa⁻¹ ⬝ ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a) : by rewrite ap_con
... = retrfa⁻¹ ⬝ (ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a)) : by rewrite con.assoc'
... = retrfa⁻¹ ⬝ ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a) : by rewrite -ap_con,
show ret (f a) = ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a),
from eq_of_idp_eq_inv_con eq3
definition adjointify [constructor] : is_equiv f :=
is_equiv.mk f g ret adjointify_left_inv' adjointify_adj'
end
-- Any function pointwise equal to an equivalence is an equivalence as well.
definition homotopy_closed [constructor] {A B : Type} (f : A → B) {f' : A → B} [Hf : is_equiv f]
(Hty : f ~ f') : is_equiv f' :=
adjointify f'
(inv f)
(λ b, (Hty (inv f b))⁻¹ ⬝ right_inv f b)
(λ a, (ap (inv f) (Hty a))⁻¹ ⬝ left_inv f a)
definition inv_homotopy_closed [constructor] {A B : Type} {f : A → B} {f' : B → A}
[Hf : is_equiv f] (Hty : f⁻¹ ~ f') : is_equiv f :=
adjointify f
f'
(λ b, ap f !Hty⁻¹ ⬝ right_inv f b)
(λ a, !Hty⁻¹ ⬝ left_inv f a)
definition is_equiv_up [instance] [constructor] (A : Type)
: is_equiv (up : A → lift A) :=
adjointify up down (λa, by induction a;reflexivity) (λa, idp)
section
variables {A B C : Type} (f : A → B) {f' : A → B} [Hf : is_equiv f] (g : B → C)
include Hf
--The inverse of an equivalence is, again, an equivalence.
definition is_equiv_inv [instance] [constructor] : is_equiv f⁻¹ :=
adjointify f⁻¹ f (left_inv f) (right_inv f)
definition cancel_right (g : B → C) [Hgf : is_equiv (g ∘ f)] : (is_equiv g) :=
have Hfinv : is_equiv f⁻¹, from is_equiv_inv f,
@homotopy_closed _ _ _ _ (is_equiv_compose f⁻¹ (g ∘ f)) (λb, ap g (@right_inv _ _ f _ b))
definition cancel_left (g : C → A) [Hgf : is_equiv (f ∘ g)] : (is_equiv g) :=
have Hfinv : is_equiv f⁻¹, from is_equiv_inv f,
@homotopy_closed _ _ _ _ (is_equiv_compose (f ∘ g) f⁻¹) (λa, left_inv f (g a))
definition eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : x = y :=
(left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y
theorem ap_eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : ap f (eq_of_fn_eq_fn' f q) = q :=
begin
rewrite [↑eq_of_fn_eq_fn',+ap_con,ap_inv,-+adj,-ap_compose,con.assoc,
ap_con_eq_con_ap (right_inv f) q,inv_con_cancel_left,ap_id],
end
definition is_equiv_ap [instance] [constructor] (x y : A) : is_equiv (ap f : x = y → f x = f y) :=
adjointify
(ap f)
(eq_of_fn_eq_fn' f)
abstract (λq, !ap_con
⬝ whisker_right !ap_con _
⬝ ((!ap_inv ⬝ inverse2 (adj f _)⁻¹)
◾ (inverse (ap_compose f f⁻¹ _))
◾ (adj f _)⁻¹)
⬝ con_ap_con_eq_con_con (right_inv f) _ _
⬝ whisker_right !con.left_inv _
⬝ !idp_con) end
abstract (λp, whisker_right (whisker_left _ (ap_compose f⁻¹ f _)⁻¹) _
⬝ con_ap_con_eq_con_con (left_inv f) _ _
⬝ whisker_right !con.left_inv _
⬝ !idp_con) end
-- The function equiv_rect says that given an equivalence f : A → B,
-- and a hypothesis from B, one may always assume that the hypothesis
-- is in the image of e.
-- In fibrational terms, if we have a fibration over B which has a section
-- once pulled back along an equivalence f : A → B, then it has a section
-- over all of B.
definition is_equiv_rect (P : B → Type) (g : Πa, P (f a)) (b : B) : P b :=
right_inv f b ▸ g (f⁻¹ b)
definition is_equiv_rect' (P : A → B → Type) (g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) :=
left_inv f a ▸ g (f a)
definition is_equiv_rect_comp (P : B → Type)
(df : Π (x : A), P (f x)) (x : A) : is_equiv_rect f P df (f x) = df x :=
calc
is_equiv_rect f P df (f x)
= right_inv f (f x) ▸ df (f⁻¹ (f x)) : by esimp
... = ap f (left_inv f x) ▸ df (f⁻¹ (f x)) : by rewrite -adj
... = left_inv f x ▸ df (f⁻¹ (f x)) : by rewrite -tr_compose
... = df x : by rewrite (apdt df (left_inv f x))
theorem adj_inv (b : B) : left_inv f (f⁻¹ b) = ap f⁻¹ (right_inv f b) :=
is_equiv_rect f _
(λa, eq.cancel_right (left_inv f (id a))
(whisker_left _ !ap_id⁻¹ ⬝ (ap_con_eq_con_ap (left_inv f) (left_inv f a))⁻¹) ⬝
!ap_compose ⬝ ap02 f⁻¹ (adj f a)⁻¹)
b
end
section
variables {A B C : Type} {f : A → B} [Hf : is_equiv f]
include Hf
section rewrite_rules
variables {a : A} {b : B}
definition eq_of_eq_inv (p : a = f⁻¹ b) : f a = b :=
ap f p ⬝ right_inv f b
definition eq_of_inv_eq (p : f⁻¹ b = a) : b = f a :=
(eq_of_eq_inv p⁻¹)⁻¹
definition inv_eq_of_eq (p : b = f a) : f⁻¹ b = a :=
ap f⁻¹ p ⬝ left_inv f a
definition eq_inv_of_eq (p : f a = b) : a = f⁻¹ b :=
(inv_eq_of_eq p⁻¹)⁻¹
end rewrite_rules
variable (f)
section pre_compose
variables (α : A → C) (β : B → C)
definition homotopy_of_homotopy_inv_pre (p : β ~ α ∘ f⁻¹) : β ∘ f ~ α :=
λ a, p (f a) ⬝ ap α (left_inv f a)
definition homotopy_of_inv_homotopy_pre (p : α ∘ f⁻¹ ~ β) : α ~ β ∘ f :=
λ a, (ap α (left_inv f a))⁻¹ ⬝ p (f a)
definition inv_homotopy_of_homotopy_pre (p : α ~ β ∘ f) : α ∘ f⁻¹ ~ β :=
λ b, p (f⁻¹ b) ⬝ ap β (right_inv f b)
definition homotopy_inv_of_homotopy_pre (p : β ∘ f ~ α) : β ~ α ∘ f⁻¹ :=
λ b, (ap β (right_inv f b))⁻¹ ⬝ p (f⁻¹ b)
end pre_compose
section post_compose
variables (α : C → A) (β : C → B)
definition homotopy_of_homotopy_inv_post (p : α ~ f⁻¹ ∘ β) : f ∘ α ~ β :=
λ c, ap f (p c) ⬝ (right_inv f (β c))
definition homotopy_of_inv_homotopy_post (p : f⁻¹ ∘ β ~ α) : β ~ f ∘ α :=
λ c, (right_inv f (β c))⁻¹ ⬝ ap f (p c)
definition inv_homotopy_of_homotopy_post (p : β ~ f ∘ α) : f⁻¹ ∘ β ~ α :=
λ c, ap f⁻¹ (p c) ⬝ (left_inv f (α c))
definition homotopy_inv_of_homotopy_post (p : f ∘ α ~ β) : α ~ f⁻¹ ∘ β :=
λ c, (left_inv f (α c))⁻¹ ⬝ ap f⁻¹ (p c)
end post_compose
end
--Transporting is an equivalence
definition is_equiv_tr [constructor] {A : Type} (P : A → Type) {x y : A}
(p : x = y) : (is_equiv (transport P p)) :=
is_equiv.mk _ (transport P p⁻¹) (tr_inv_tr p) (inv_tr_tr p) (tr_inv_tr_lemma p)
section
variables {A : Type} {B C : A → Type} (f : Π{a}, B a → C a) [H : Πa, is_equiv (@f a)]
{g : A → A} {g' : A → A} (h : Π{a}, B (g' a) → B (g a)) (h' : Π{a}, C (g' a) → C (g a))
include H
definition inv_commute' (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A}
(c : C (g' a)) : f⁻¹ (h' c) = h (f⁻¹ c) :=
eq_of_fn_eq_fn' f (right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹)
definition fun_commute_of_inv_commute' (p : Π⦃a : A⦄ (c : C (g' a)), f⁻¹ (h' c) = h (f⁻¹ c))
{a : A} (b : B (g' a)) : f (h b) = h' (f b) :=
eq_of_fn_eq_fn' f⁻¹ (left_inv f (h b) ⬝ ap h (left_inv f b)⁻¹ ⬝ (p (f b))⁻¹)
definition ap_inv_commute' (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A}
(c : C (g' a)) : ap f (inv_commute' @f @h @h' p c)
= right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹ :=
!ap_eq_of_fn_eq_fn'
end
end is_equiv
open is_equiv
namespace eq
local attribute is_equiv_tr [instance]
definition tr_inv_fn {A : Type} {B : A → Type} {a a' : A} (p : a = a') :
transport B p⁻¹ = (transport B p)⁻¹ := idp
definition tr_inv {A : Type} {B : A → Type} {a a' : A} (p : a = a') (b : B a') :
p⁻¹ ▸ b = (transport B p)⁻¹ b := idp
definition cast_inv_fn {A B : Type} (p : A = B) : cast p⁻¹ = (cast p)⁻¹ := idp
definition cast_inv {A B : Type} (p : A = B) (b : B) : cast p⁻¹ b = (cast p)⁻¹ b := idp
end eq
infix ` ≃ `:25 := equiv
attribute equiv.to_is_equiv [instance]
namespace equiv
attribute to_fun [coercion]
section
variables {A B C : Type}
protected definition MK [reducible] [constructor] (f : A → B) (g : B → A)
(right_inv : Πb, f (g b) = b) (left_inv : Πa, g (f a) = a) : A ≃ B :=
equiv.mk f (adjointify f g right_inv left_inv)
definition to_inv [reducible] [unfold 3] (f : A ≃ B) : B → A := f⁻¹
definition to_right_inv [reducible] [unfold 3] (f : A ≃ B) (b : B) : f (f⁻¹ b) = b :=
right_inv f b
definition to_left_inv [reducible] [unfold 3] (f : A ≃ B) (a : A) : f⁻¹ (f a) = a :=
left_inv f a
protected definition refl [refl] [constructor] : A ≃ A :=
equiv.mk id !is_equiv_id
protected definition symm [symm] [constructor] (f : A ≃ B) : B ≃ A :=
equiv.mk f⁻¹ !is_equiv_inv
protected definition trans [trans] [constructor] (f : A ≃ B) (g : B ≃ C) : A ≃ C :=
equiv.mk (g ∘ f) !is_equiv_compose
infixl ` ⬝e `:75 := equiv.trans
postfix `⁻¹ᵉ`:(max + 1) := equiv.symm
-- notation for inverse which is not overloaded
abbreviation erfl [constructor] := @equiv.refl
definition to_inv_trans [reducible] [unfold_full] (f : A ≃ B) (g : B ≃ C)
: to_inv (f ⬝e g) = to_fun (g⁻¹ᵉ ⬝e f⁻¹ᵉ) :=
idp
definition equiv_change_fun [constructor] (f : A ≃ B) {f' : A → B} (Heq : f ~ f') : A ≃ B :=
equiv.mk f' (is_equiv.homotopy_closed f Heq)
definition equiv_change_inv [constructor] (f : A ≃ B) {f' : B → A} (Heq : f⁻¹ ~ f')
: A ≃ B :=
equiv.mk f (inv_homotopy_closed Heq)
--rename: eq_equiv_fn_eq_of_is_equiv
definition eq_equiv_fn_eq [constructor] (f : A → B) [H : is_equiv f] (a b : A) : (a = b) ≃ (f a = f b) :=
equiv.mk (ap f) !is_equiv_ap
--rename: eq_equiv_fn_eq
definition eq_equiv_fn_eq_of_equiv [constructor] (f : A ≃ B) (a b : A) : (a = b) ≃ (f a = f b) :=
equiv.mk (ap f) !is_equiv_ap
definition equiv_ap [constructor] (P : A → Type) {a b : A} (p : a = b) : P a ≃ P b :=
equiv.mk (transport P p) !is_equiv_tr
definition equiv_of_eq [constructor] {A B : Type} (p : A = B) : A ≃ B :=
equiv.mk (cast p) !is_equiv_tr
definition eq_of_fn_eq_fn (f : A ≃ B) {x y : A} (q : f x = f y) : x = y :=
(left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y
definition eq_of_fn_eq_fn_inv (f : A ≃ B) {x y : B} (q : f⁻¹ x = f⁻¹ y) : x = y :=
(right_inv f x)⁻¹ ⬝ ap f q ⬝ right_inv f y
--we need this theorem for the funext_of_ua proof
theorem inv_eq {A B : Type} (eqf eqg : A ≃ B) (p : eqf = eqg) : (to_fun eqf)⁻¹ = (to_fun eqg)⁻¹ :=
eq.rec_on p idp
definition equiv_of_equiv_of_eq [trans] {A B C : Type} (p : A = B) (q : B ≃ C) : A ≃ C :=
equiv_of_eq p ⬝e q
definition equiv_of_eq_of_equiv [trans] {A B C : Type} (p : A ≃ B) (q : B = C) : A ≃ C :=
p ⬝e equiv_of_eq q
definition equiv_lift [constructor] (A : Type) : A ≃ lift A := equiv.mk up _
definition equiv_rect (f : A ≃ B) (P : B → Type) (g : Πa, P (f a)) (b : B) : P b :=
right_inv f b ▸ g (f⁻¹ b)
definition equiv_rect' (f : A ≃ B) (P : A → B → Type) (g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) :=
left_inv f a ▸ g (f a)
definition equiv_rect_comp (f : A ≃ B) (P : B → Type)
(df : Π (x : A), P (f x)) (x : A) : equiv_rect f P df (f x) = df x :=
calc
equiv_rect f P df (f x)
= right_inv f (f x) ▸ df (f⁻¹ (f x)) : by esimp
... = ap f (left_inv f x) ▸ df (f⁻¹ (f x)) : by rewrite -adj
... = left_inv f x ▸ df (f⁻¹ (f x)) : by rewrite -tr_compose
... = df x : by rewrite (apdt df (left_inv f x))
end
section
variables {A : Type} {B C : A → Type} (f : Π{a}, B a ≃ C a)
{g : A → A} {g' : A → A} (h : Π{a}, B (g' a) → B (g a)) (h' : Π{a}, C (g' a) → C (g a))
definition inv_commute (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A}
(c : C (g' a)) : f⁻¹ (h' c) = h (f⁻¹ c) :=
inv_commute' @f @h @h' p c
definition fun_commute_of_inv_commute (p : Π⦃a : A⦄ (c : C (g' a)), f⁻¹ (h' c) = h (f⁻¹ c))
{a : A} (b : B (g' a)) : f (h b) = h' (f b) :=
fun_commute_of_inv_commute' @f @h @h' p b
end
infixl ` ⬝pe `:75 := equiv_of_equiv_of_eq
infixl ` ⬝ep `:75 := equiv_of_eq_of_equiv
end equiv
open equiv
namespace is_equiv
definition is_equiv_of_equiv_of_homotopy [constructor] {A B : Type} (f : A ≃ B)
{f' : A → B} (Hty : f ~ f') : is_equiv f' :=
homotopy_closed f Hty
end is_equiv
export [unfold] equiv
export [unfold] is_equiv
|
c50572b0df823c2f4c9a63b305665a48a3124099 | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/t14.lean | 916cae8b544ba29d9d01243843194eb086baa2d2 | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 676 | lean |
namespace foo
variable A : Type.{1}
variable a : A
variable x : A
variable c : A
end
section
using foo (renaming a->b x->y) (hiding c)
check b
check y
check c -- Error
end
section
using foo (a x)
check a
check x
check c -- Error
end
section
using foo (a x) (hiding c) -- Error
end
section
using foo
check a
check c
check A
end
namespace foo
variable f : A → A → A
infix `*`:75 := f
end
section
using foo
check a * c
end
section
using [notation] foo -- use only the notation
check foo.a * foo.c
check a * c -- Error
end
section
using [decls] foo -- use only the declarations
check f a c
check a*c -- Error
end
|
f374a26534eaf6808feafb48cc2fc791529fa6cd | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/analysis/special_functions/exp_log.lean | 4c0575ecc9d8089cebc68701126e248a6098ef4e | [
"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 | 34,883 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne
-/
import analysis.calculus.inverse
import analysis.complex.real_deriv
import data.complex.exponential
/-!
# Complex and real exponential, real logarithm
## Main statements
This file establishes the basic analytical properties of the complex and real exponential functions
(continuity, differentiability, computation of the derivative).
It also contains the definition of the real logarithm function (as the inverse of the
exponential on `(0, +∞)`, extended to `ℝ` by setting `log (-x) = log x`) and its basic
properties (continuity, differentiability, formula for the derivative).
The complex logarithm is *not* defined in this file as it relies on trigonometric functions. See
instead `trigonometric.lean`.
## Tags
exp, log
-/
noncomputable theory
open finset filter metric asymptotics set function
open_locale classical topological_space
namespace complex
/-- The complex exponential is everywhere differentiable, with the derivative `exp x`. -/
lemma has_deriv_at_exp (x : ℂ) : has_deriv_at exp (exp x) x :=
begin
rw has_deriv_at_iff_is_o_nhds_zero,
have : (1 : ℕ) < 2 := by norm_num,
refine (is_O.of_bound (∥exp x∥) _).trans_is_o (is_o_pow_id this),
filter_upwards [metric.ball_mem_nhds (0 : ℂ) zero_lt_one],
simp only [metric.mem_ball, dist_zero_right, normed_field.norm_pow],
intros z hz,
calc ∥exp (x + z) - exp x - z * exp x∥
= ∥exp x * (exp z - 1 - z)∥ : by { congr, rw [exp_add], ring }
... = ∥exp x∥ * ∥exp z - 1 - z∥ : normed_field.norm_mul _ _
... ≤ ∥exp x∥ * ∥z∥^2 :
mul_le_mul_of_nonneg_left (abs_exp_sub_one_sub_id_le (le_of_lt hz)) (norm_nonneg _)
end
lemma differentiable_exp : differentiable ℂ exp :=
λx, (has_deriv_at_exp x).differentiable_at
lemma differentiable_at_exp {x : ℂ} : differentiable_at ℂ exp x :=
differentiable_exp x
@[simp] lemma deriv_exp : deriv exp = exp :=
funext $ λ x, (has_deriv_at_exp x).deriv
@[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp
| 0 := rfl
| (n+1) := by rw [iterate_succ_apply, deriv_exp, iter_deriv_exp n]
@[continuity] lemma continuous_exp : continuous exp :=
differentiable_exp.continuous
lemma continuous_on_exp {s : set ℂ} : continuous_on exp s :=
continuous_exp.continuous_on
lemma times_cont_diff_exp : ∀ {n}, times_cont_diff ℂ n exp :=
begin
refine times_cont_diff_all_iff_nat.2 (λ n, _),
induction n with n ihn,
{ exact times_cont_diff_zero.2 continuous_exp },
{ rw times_cont_diff_succ_iff_deriv,
use differentiable_exp,
rwa deriv_exp }
end
lemma has_strict_deriv_at_exp (x : ℂ) : has_strict_deriv_at exp (exp x) x :=
times_cont_diff_exp.times_cont_diff_at.has_strict_deriv_at' (has_deriv_at_exp x) le_rfl
lemma is_open_map_exp : is_open_map exp :=
open_map_of_strict_deriv has_strict_deriv_at_exp exp_ne_zero
end complex
section
variables {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ}
lemma has_strict_deriv_at.cexp (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, complex.exp (f x)) (complex.exp (f x) * f') x :=
(complex.has_strict_deriv_at_exp (f x)).comp x hf
lemma has_deriv_at.cexp (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, complex.exp (f x)) (complex.exp (f x) * f') x :=
(complex.has_deriv_at_exp (f x)).comp x hf
lemma has_deriv_within_at.cexp (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, complex.exp (f x)) (complex.exp (f x) * f') s x :=
(complex.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_cexp (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
deriv_within (λx, complex.exp (f x)) s x = complex.exp (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.cexp.deriv_within hxs
@[simp] lemma deriv_cexp (hc : differentiable_at ℂ f x) :
deriv (λx, complex.exp (f x)) x = complex.exp (f x) * (deriv f x) :=
hc.has_deriv_at.cexp.deriv
end
section
variables {E : Type*} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {f' : E →L[ℂ] ℂ}
{x : E} {s : set E}
lemma has_strict_fderiv_at.cexp (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ x, complex.exp (f x)) (complex.exp (f x) • f') x :=
(complex.has_strict_deriv_at_exp (f x)).comp_has_strict_fderiv_at x hf
lemma has_fderiv_within_at.cexp (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, complex.exp (f x)) (complex.exp (f x) • f') s x :=
(complex.has_deriv_at_exp (f x)).comp_has_fderiv_within_at x hf
lemma has_fderiv_at.cexp (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, complex.exp (f x)) (complex.exp (f x) • f') x :=
has_fderiv_within_at_univ.1 $ hf.has_fderiv_within_at.cexp
lemma differentiable_within_at.cexp (hf : differentiable_within_at ℂ f s x) :
differentiable_within_at ℂ (λ x, complex.exp (f x)) s x :=
hf.has_fderiv_within_at.cexp.differentiable_within_at
@[simp] lemma differentiable_at.cexp (hc : differentiable_at ℂ f x) :
differentiable_at ℂ (λx, complex.exp (f x)) x :=
hc.has_fderiv_at.cexp.differentiable_at
lemma differentiable_on.cexp (hc : differentiable_on ℂ f s) :
differentiable_on ℂ (λx, complex.exp (f x)) s :=
λx h, (hc x h).cexp
@[simp] lemma differentiable.cexp (hc : differentiable ℂ f) :
differentiable ℂ (λx, complex.exp (f x)) :=
λx, (hc x).cexp
lemma times_cont_diff.cexp {n} (h : times_cont_diff ℂ n f) :
times_cont_diff ℂ n (λ x, complex.exp (f x)) :=
complex.times_cont_diff_exp.comp h
lemma times_cont_diff_at.cexp {n} (hf : times_cont_diff_at ℂ n f x) :
times_cont_diff_at ℂ n (λ x, complex.exp (f x)) x :=
complex.times_cont_diff_exp.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.cexp {n} (hf : times_cont_diff_on ℂ n f s) :
times_cont_diff_on ℂ n (λ x, complex.exp (f x)) s :=
complex.times_cont_diff_exp.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.cexp {n} (hf : times_cont_diff_within_at ℂ n f s x) :
times_cont_diff_within_at ℂ n (λ x, complex.exp (f x)) s x :=
complex.times_cont_diff_exp.times_cont_diff_at.comp_times_cont_diff_within_at x hf
end
namespace real
variables {x y z : ℝ}
lemma has_strict_deriv_at_exp (x : ℝ) : has_strict_deriv_at exp (exp x) x :=
(complex.has_strict_deriv_at_exp x).real_of_complex
lemma has_deriv_at_exp (x : ℝ) : has_deriv_at exp (exp x) x :=
(complex.has_deriv_at_exp x).real_of_complex
lemma times_cont_diff_exp {n} : times_cont_diff ℝ n exp :=
complex.times_cont_diff_exp.real_of_complex
lemma differentiable_exp : differentiable ℝ exp :=
λx, (has_deriv_at_exp x).differentiable_at
lemma differentiable_at_exp : differentiable_at ℝ exp x :=
differentiable_exp x
@[simp] lemma deriv_exp : deriv exp = exp :=
funext $ λ x, (has_deriv_at_exp x).deriv
@[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp
| 0 := rfl
| (n+1) := by rw [iterate_succ_apply, deriv_exp, iter_deriv_exp n]
@[continuity] lemma continuous_exp : continuous exp :=
differentiable_exp.continuous
lemma continuous_on_exp {s : set ℝ} : continuous_on exp s :=
continuous_exp.continuous_on
end real
section
/-! Register lemmas for the derivatives of the composition of `real.exp` with a differentiable
function, for standalone use and use with `simp`. -/
variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ}
lemma has_strict_deriv_at.exp (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, real.exp (f x)) (real.exp (f x) * f') x :=
(real.has_strict_deriv_at_exp (f x)).comp x hf
lemma has_deriv_at.exp (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, real.exp (f x)) (real.exp (f x) * f') x :=
(real.has_deriv_at_exp (f x)).comp x hf
lemma has_deriv_within_at.exp (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, real.exp (f x)) (real.exp (f x) * f') s x :=
(real.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_exp (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, real.exp (f x)) s x = real.exp (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.exp.deriv_within hxs
@[simp] lemma deriv_exp (hc : differentiable_at ℝ f x) :
deriv (λx, real.exp (f x)) x = real.exp (f x) * (deriv f x) :=
hc.has_deriv_at.exp.deriv
end
section
/-! Register lemmas for the derivatives of the composition of `real.exp` with a differentiable
function, for standalone use and use with `simp`. -/
variables {E : Type*} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : E →L[ℝ] ℝ}
{x : E} {s : set E}
lemma times_cont_diff.exp {n} (hf : times_cont_diff ℝ n f) :
times_cont_diff ℝ n (λ x, real.exp (f x)) :=
real.times_cont_diff_exp.comp hf
lemma times_cont_diff_at.exp {n} (hf : times_cont_diff_at ℝ n f x) :
times_cont_diff_at ℝ n (λ x, real.exp (f x)) x :=
real.times_cont_diff_exp.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.exp {n} (hf : times_cont_diff_on ℝ n f s) :
times_cont_diff_on ℝ n (λ x, real.exp (f x)) s :=
real.times_cont_diff_exp.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.exp {n} (hf : times_cont_diff_within_at ℝ n f s x) :
times_cont_diff_within_at ℝ n (λ x, real.exp (f x)) s x :=
real.times_cont_diff_exp.times_cont_diff_at.comp_times_cont_diff_within_at x hf
lemma has_fderiv_within_at.exp (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, real.exp (f x)) (real.exp (f x) • f') s x :=
(real.has_deriv_at_exp (f x)).comp_has_fderiv_within_at x hf
lemma has_fderiv_at.exp (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, real.exp (f x)) (real.exp (f x) • f') x :=
(real.has_deriv_at_exp (f x)).comp_has_fderiv_at x hf
lemma has_strict_fderiv_at.exp (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ x, real.exp (f x)) (real.exp (f x) • f') x :=
(real.has_strict_deriv_at_exp (f x)).comp_has_strict_fderiv_at x hf
lemma differentiable_within_at.exp (hf : differentiable_within_at ℝ f s x) :
differentiable_within_at ℝ (λ x, real.exp (f x)) s x :=
hf.has_fderiv_within_at.exp.differentiable_within_at
@[simp] lemma differentiable_at.exp (hc : differentiable_at ℝ f x) :
differentiable_at ℝ (λx, real.exp (f x)) x :=
hc.has_fderiv_at.exp.differentiable_at
lemma differentiable_on.exp (hc : differentiable_on ℝ f s) :
differentiable_on ℝ (λx, real.exp (f x)) s :=
λ x h, (hc x h).exp
@[simp] lemma differentiable.exp (hc : differentiable ℝ f) :
differentiable ℝ (λx, real.exp (f x)) :=
λ x, (hc x).exp
lemma fderiv_within_exp (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
fderiv_within ℝ (λx, real.exp (f x)) s x = real.exp (f x) • (fderiv_within ℝ f s x) :=
hf.has_fderiv_within_at.exp.fderiv_within hxs
@[simp] lemma fderiv_exp (hc : differentiable_at ℝ f x) :
fderiv ℝ (λx, real.exp (f x)) x = real.exp (f x) • (fderiv ℝ f x) :=
hc.has_fderiv_at.exp.fderiv
end
namespace real
variables {x y z : ℝ}
/-- The real exponential function tends to `+∞` at `+∞`. -/
lemma tendsto_exp_at_top : tendsto exp at_top at_top :=
begin
have A : tendsto (λx:ℝ, x + 1) at_top at_top :=
tendsto_at_top_add_const_right at_top 1 tendsto_id,
have B : ∀ᶠ x in at_top, x + 1 ≤ exp x :=
eventually_at_top.2 ⟨0, λx hx, add_one_le_exp_of_nonneg hx⟩,
exact tendsto_at_top_mono' at_top B A
end
/-- The real exponential function tends to `0` at `-∞` or, equivalently, `exp(-x)` tends to `0`
at `+∞` -/
lemma tendsto_exp_neg_at_top_nhds_0 : tendsto (λx, exp (-x)) at_top (𝓝 0) :=
(tendsto_inv_at_top_zero.comp tendsto_exp_at_top).congr (λx, (exp_neg x).symm)
/-- The real exponential function tends to `1` at `0`. -/
lemma tendsto_exp_nhds_0_nhds_1 : tendsto exp (𝓝 0) (𝓝 1) :=
by { convert continuous_exp.tendsto 0, simp }
lemma tendsto_exp_at_bot : tendsto exp at_bot (𝓝 0) :=
(tendsto_exp_neg_at_top_nhds_0.comp tendsto_neg_at_bot_at_top).congr $
λ x, congr_arg exp $ neg_neg x
lemma tendsto_exp_at_bot_nhds_within : tendsto exp at_bot (𝓝[Ioi 0] 0) :=
tendsto_inf.2 ⟨tendsto_exp_at_bot, tendsto_principal.2 $ eventually_of_forall exp_pos⟩
/-- `real.exp` as an order isomorphism between `ℝ` and `(0, +∞)`. -/
def exp_order_iso : ℝ ≃o Ioi (0 : ℝ) :=
strict_mono.order_iso_of_surjective _ (exp_strict_mono.cod_restrict exp_pos) $
(continuous_subtype_mk _ continuous_exp).surjective
(by simp only [tendsto_Ioi_at_top, subtype.coe_mk, tendsto_exp_at_top])
(by simp [tendsto_exp_at_bot_nhds_within])
@[simp] lemma coe_exp_order_iso_apply (x : ℝ) : (exp_order_iso x : ℝ) = exp x := rfl
@[simp] lemma coe_comp_exp_order_iso : coe ∘ exp_order_iso = exp := rfl
@[simp] lemma range_exp : range exp = Ioi 0 :=
by rw [← coe_comp_exp_order_iso, range_comp, exp_order_iso.range_eq, image_univ, subtype.range_coe]
@[simp] lemma map_exp_at_top : map exp at_top = at_top :=
by rw [← coe_comp_exp_order_iso, ← filter.map_map, order_iso.map_at_top, map_coe_Ioi_at_top]
@[simp] lemma comap_exp_at_top : comap exp at_top = at_top :=
by rw [← map_exp_at_top, comap_map exp_injective, map_exp_at_top]
@[simp] lemma tendsto_exp_comp_at_top {α : Type*} {l : filter α} {f : α → ℝ} :
tendsto (λ x, exp (f x)) l at_top ↔ tendsto f l at_top :=
by rw [← tendsto_comap_iff, comap_exp_at_top]
lemma tendsto_comp_exp_at_top {α : Type*} {l : filter α} {f : ℝ → α} :
tendsto (λ x, f (exp x)) at_top l ↔ tendsto f at_top l :=
by rw [← tendsto_map'_iff, map_exp_at_top]
@[simp] lemma map_exp_at_bot : map exp at_bot = 𝓝[Ioi 0] 0 :=
by rw [← coe_comp_exp_order_iso, ← filter.map_map, exp_order_iso.map_at_bot, ← map_coe_Ioi_at_bot]
lemma comap_exp_nhds_within_Ioi_zero : comap exp (𝓝[Ioi 0] 0) = at_bot :=
by rw [← map_exp_at_bot, comap_map exp_injective]
lemma tendsto_comp_exp_at_bot {α : Type*} {l : filter α} {f : ℝ → α} :
tendsto (λ x, f (exp x)) at_bot l ↔ tendsto f (𝓝[Ioi 0] 0) l :=
by rw [← map_exp_at_bot, tendsto_map'_iff]
/-- The real logarithm function, equal to the inverse of the exponential for `x > 0`,
to `log |x|` for `x < 0`, and to `0` for `0`. We use this unconventional extension to
`(-∞, 0]` as it gives the formula `log (x * y) = log x + log y` for all nonzero `x` and `y`, and
the derivative of `log` is `1/x` away from `0`. -/
@[pp_nodot] noncomputable def log (x : ℝ) : ℝ :=
if hx : x = 0 then 0 else exp_order_iso.symm ⟨abs x, abs_pos.2 hx⟩
lemma log_of_ne_zero (hx : x ≠ 0) : log x = exp_order_iso.symm ⟨abs x, abs_pos.2 hx⟩ := dif_neg hx
lemma log_of_pos (hx : 0 < x) : log x = exp_order_iso.symm ⟨x, hx⟩ :=
by { rw [log_of_ne_zero hx.ne'], congr, exact abs_of_pos hx }
lemma exp_log_eq_abs (hx : x ≠ 0) : exp (log x) = abs x :=
by rw [log_of_ne_zero hx, ← coe_exp_order_iso_apply, order_iso.apply_symm_apply, subtype.coe_mk]
lemma exp_log (hx : 0 < x) : exp (log x) = x :=
by { rw exp_log_eq_abs hx.ne', exact abs_of_pos hx }
lemma exp_log_of_neg (hx : x < 0) : exp (log x) = -x :=
by { rw exp_log_eq_abs (ne_of_lt hx), exact abs_of_neg hx }
@[simp] lemma log_exp (x : ℝ) : log (exp x) = x :=
exp_injective $ exp_log (exp_pos x)
lemma surj_on_log : surj_on log (Ioi 0) univ :=
λ x _, ⟨exp x, exp_pos x, log_exp x⟩
lemma log_surjective : surjective log :=
λ x, ⟨exp x, log_exp x⟩
@[simp] lemma range_log : range log = univ :=
log_surjective.range_eq
@[simp] lemma log_zero : log 0 = 0 := dif_pos rfl
@[simp] lemma log_one : log 1 = 0 :=
exp_injective $ by rw [exp_log zero_lt_one, exp_zero]
@[simp] lemma log_abs (x : ℝ) : log (abs x) = log x :=
begin
by_cases h : x = 0,
{ simp [h] },
{ rw [← exp_eq_exp, exp_log_eq_abs h, exp_log_eq_abs (abs_pos.2 h).ne', abs_abs] }
end
@[simp] lemma log_neg_eq_log (x : ℝ) : log (-x) = log x :=
by rw [← log_abs x, ← log_abs (-x), abs_neg]
lemma surj_on_log' : surj_on log (Iio 0) univ :=
λ x _, ⟨-exp x, neg_lt_zero.2 $ exp_pos x, by rw [log_neg_eq_log, log_exp]⟩
lemma log_mul (hx : x ≠ 0) (hy : y ≠ 0) : log (x * y) = log x + log y :=
exp_injective $
by rw [exp_log_eq_abs (mul_ne_zero hx hy), exp_add, exp_log_eq_abs hx, exp_log_eq_abs hy, abs_mul]
lemma log_div (hx : x ≠ 0) (hy : y ≠ 0) : log (x / y) = log x - log y :=
exp_injective $
by rw [exp_log_eq_abs (div_ne_zero hx hy), exp_sub, exp_log_eq_abs hx, exp_log_eq_abs hy, abs_div]
@[simp] lemma log_inv (x : ℝ) : log (x⁻¹) = -log x :=
begin
by_cases hx : x = 0, { simp [hx] },
rw [← exp_eq_exp, exp_log_eq_abs (inv_ne_zero hx), exp_neg, exp_log_eq_abs hx, abs_inv]
end
lemma log_le_log (h : 0 < x) (h₁ : 0 < y) : real.log x ≤ real.log y ↔ x ≤ y :=
by rw [← exp_le_exp, exp_log h, exp_log h₁]
lemma log_lt_log (hx : 0 < x) : x < y → log x < log y :=
by { intro h, rwa [← exp_lt_exp, exp_log hx, exp_log (lt_trans hx h)] }
lemma log_lt_log_iff (hx : 0 < x) (hy : 0 < y) : log x < log y ↔ x < y :=
by { rw [← exp_lt_exp, exp_log hx, exp_log hy] }
lemma log_pos_iff (hx : 0 < x) : 0 < log x ↔ 1 < x :=
by { rw ← log_one, exact log_lt_log_iff zero_lt_one hx }
lemma log_pos (hx : 1 < x) : 0 < log x :=
(log_pos_iff (lt_trans zero_lt_one hx)).2 hx
lemma log_neg_iff (h : 0 < x) : log x < 0 ↔ x < 1 :=
by { rw ← log_one, exact log_lt_log_iff h zero_lt_one }
lemma log_neg (h0 : 0 < x) (h1 : x < 1) : log x < 0 := (log_neg_iff h0).2 h1
lemma log_nonneg_iff (hx : 0 < x) : 0 ≤ log x ↔ 1 ≤ x :=
by rw [← not_lt, log_neg_iff hx, not_lt]
lemma log_nonneg (hx : 1 ≤ x) : 0 ≤ log x :=
(log_nonneg_iff (zero_lt_one.trans_le hx)).2 hx
lemma log_nonpos_iff (hx : 0 < x) : log x ≤ 0 ↔ x ≤ 1 :=
by rw [← not_lt, log_pos_iff hx, not_lt]
lemma log_nonpos_iff' (hx : 0 ≤ x) : log x ≤ 0 ↔ x ≤ 1 :=
begin
rcases hx.eq_or_lt with (rfl|hx),
{ simp [le_refl, zero_le_one] },
exact log_nonpos_iff hx
end
lemma log_nonpos (hx : 0 ≤ x) (h'x : x ≤ 1) : log x ≤ 0 :=
(log_nonpos_iff' hx).2 h'x
lemma strict_mono_incr_on_log : strict_mono_incr_on log (set.Ioi 0) :=
λ x hx y hy hxy, log_lt_log hx hxy
lemma strict_mono_decr_on_log : strict_mono_decr_on log (set.Iio 0) :=
begin
rintros x (hx : x < 0) y (hy : y < 0) hxy,
rw [← log_abs y, ← log_abs x],
refine log_lt_log (abs_pos.2 hy.ne) _,
rwa [abs_of_neg hy, abs_of_neg hx, neg_lt_neg_iff]
end
lemma log_inj_on_pos : set.inj_on log (set.Ioi 0) :=
strict_mono_incr_on_log.inj_on
lemma eq_one_of_pos_of_log_eq_zero {x : ℝ} (h₁ : 0 < x) (h₂ : log x = 0) : x = 1 :=
log_inj_on_pos (set.mem_Ioi.2 h₁) (set.mem_Ioi.2 zero_lt_one) (h₂.trans real.log_one.symm)
lemma log_ne_zero_of_pos_of_ne_one {x : ℝ} (hx_pos : 0 < x) (hx : x ≠ 1) : log x ≠ 0 :=
mt (eq_one_of_pos_of_log_eq_zero hx_pos) hx
/-- The real logarithm function tends to `+∞` at `+∞`. -/
lemma tendsto_log_at_top : tendsto log at_top at_top :=
tendsto_comp_exp_at_top.1 $ by simpa only [log_exp] using tendsto_id
lemma tendsto_log_nhds_within_zero : tendsto log (𝓝[{0}ᶜ] 0) at_bot :=
begin
rw [← (show _ = log, from funext log_abs)],
refine tendsto.comp _ tendsto_abs_nhds_within_zero,
simpa [← tendsto_comp_exp_at_bot] using tendsto_id
end
lemma continuous_on_log : continuous_on log {0}ᶜ :=
begin
rw [continuous_on_iff_continuous_restrict, restrict],
conv in (log _) { rw [log_of_ne_zero (show (x : ℝ) ≠ 0, from x.2)] },
exact exp_order_iso.symm.continuous.comp (continuous_subtype_mk _ continuous_subtype_coe.norm)
end
@[continuity] lemma continuous_log : continuous (λ x : {x : ℝ // x ≠ 0}, log x) :=
continuous_on_iff_continuous_restrict.1 $ continuous_on_log.mono $ λ x hx, hx
@[continuity] lemma continuous_log' : continuous (λ x : {x : ℝ // 0 < x}, log x) :=
continuous_on_iff_continuous_restrict.1 $ continuous_on_log.mono $ λ x hx, ne_of_gt hx
lemma continuous_at_log (hx : x ≠ 0) : continuous_at log x :=
(continuous_on_log x hx).continuous_at $ is_open.mem_nhds is_open_compl_singleton hx
@[simp] lemma continuous_at_log_iff : continuous_at log x ↔ x ≠ 0 :=
begin
refine ⟨_, continuous_at_log⟩,
rintros h rfl,
exact not_tendsto_nhds_of_tendsto_at_bot tendsto_log_nhds_within_zero _
(h.tendsto.mono_left inf_le_left)
end
lemma has_strict_deriv_at_log_of_pos (hx : 0 < x) : has_strict_deriv_at log x⁻¹ x :=
have has_strict_deriv_at log (exp $ log x)⁻¹ x,
from (has_strict_deriv_at_exp $ log x).of_local_left_inverse (continuous_at_log hx.ne')
(ne_of_gt $ exp_pos _) $ eventually.mono (lt_mem_nhds hx) @exp_log,
by rwa [exp_log hx] at this
lemma has_strict_deriv_at_log (hx : x ≠ 0) : has_strict_deriv_at log x⁻¹ x :=
begin
cases hx.lt_or_lt with hx hx,
{ convert (has_strict_deriv_at_log_of_pos (neg_pos.mpr hx)).comp x (has_strict_deriv_at_neg x),
{ ext y, exact (log_neg_eq_log y).symm },
{ field_simp [hx.ne] } },
{ exact has_strict_deriv_at_log_of_pos hx }
end
lemma has_deriv_at_log (hx : x ≠ 0) : has_deriv_at log x⁻¹ x :=
(has_strict_deriv_at_log hx).has_deriv_at
lemma differentiable_at_log (hx : x ≠ 0) : differentiable_at ℝ log x :=
(has_deriv_at_log hx).differentiable_at
lemma differentiable_on_log : differentiable_on ℝ log {0}ᶜ :=
λ x hx, (differentiable_at_log hx).differentiable_within_at
@[simp] lemma differentiable_at_log_iff : differentiable_at ℝ log x ↔ x ≠ 0 :=
⟨λ h, continuous_at_log_iff.1 h.continuous_at, differentiable_at_log⟩
lemma deriv_log (x : ℝ) : deriv log x = x⁻¹ :=
if hx : x = 0 then
by rw [deriv_zero_of_not_differentiable_at (mt differentiable_at_log_iff.1 (not_not.2 hx)), hx,
inv_zero]
else (has_deriv_at_log hx).deriv
@[simp] lemma deriv_log' : deriv log = has_inv.inv := funext deriv_log
lemma times_cont_diff_on_log {n : with_top ℕ} : times_cont_diff_on ℝ n log {0}ᶜ :=
begin
suffices : times_cont_diff_on ℝ ⊤ log {0}ᶜ, from this.of_le le_top,
refine (times_cont_diff_on_top_iff_deriv_of_open is_open_compl_singleton).2 _,
simp [differentiable_on_log, times_cont_diff_on_inv]
end
lemma times_cont_diff_at_log {n : with_top ℕ} : times_cont_diff_at ℝ n log x ↔ x ≠ 0 :=
⟨λ h, continuous_at_log_iff.1 h.continuous_at,
λ hx, (times_cont_diff_on_log x hx).times_cont_diff_at $
is_open.mem_nhds is_open_compl_singleton hx⟩
end real
section log_differentiable
open real
section continuity
variables {α : Type*}
lemma filter.tendsto.log {f : α → ℝ} {l : filter α} {x : ℝ} (h : tendsto f l (𝓝 x)) (hx : x ≠ 0) :
tendsto (λ x, log (f x)) l (𝓝 (log x)) :=
(continuous_at_log hx).tendsto.comp h
variables [topological_space α] {f : α → ℝ} {s : set α} {a : α}
lemma continuous.log (hf : continuous f) (h₀ : ∀ x, f x ≠ 0) : continuous (λ x, log (f x)) :=
continuous_on_log.comp_continuous hf h₀
lemma continuous_at.log (hf : continuous_at f a) (h₀ : f a ≠ 0) :
continuous_at (λ x, log (f x)) a :=
hf.log h₀
lemma continuous_within_at.log (hf : continuous_within_at f s a) (h₀ : f a ≠ 0) :
continuous_within_at (λ x, log (f x)) s a :=
hf.log h₀
lemma continuous_on.log (hf : continuous_on f s) (h₀ : ∀ x ∈ s, f x ≠ 0) :
continuous_on (λ x, log (f x)) s :=
λ x hx, (hf x hx).log (h₀ x hx)
end continuity
section deriv
variables {f : ℝ → ℝ} {x f' : ℝ} {s : set ℝ}
lemma has_deriv_within_at.log (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) :
has_deriv_within_at (λ y, log (f y)) (f' / (f x)) s x :=
begin
rw div_eq_inv_mul,
exact (has_deriv_at_log hx).comp_has_deriv_within_at x hf
end
lemma has_deriv_at.log (hf : has_deriv_at f f' x) (hx : f x ≠ 0) :
has_deriv_at (λ y, log (f y)) (f' / f x) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hf.log hx
end
lemma has_strict_deriv_at.log (hf : has_strict_deriv_at f f' x) (hx : f x ≠ 0) :
has_strict_deriv_at (λ y, log (f y)) (f' / f x) x :=
begin
rw div_eq_inv_mul,
exact (has_strict_deriv_at_log hx).comp x hf
end
lemma deriv_within.log (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, log (f x)) s x = (deriv_within f s x) / (f x) :=
(hf.has_deriv_within_at.log hx).deriv_within hxs
@[simp] lemma deriv.log (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) :
deriv (λx, log (f x)) x = (deriv f x) / (f x) :=
(hf.has_deriv_at.log hx).deriv
end deriv
section fderiv
variables {E : Type*} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {x : E} {f' : E →L[ℝ] ℝ}
{s : set E}
lemma has_fderiv_within_at.log (hf : has_fderiv_within_at f f' s x) (hx : f x ≠ 0) :
has_fderiv_within_at (λ x, log (f x)) ((f x)⁻¹ • f') s x :=
(has_deriv_at_log hx).comp_has_fderiv_within_at x hf
lemma has_fderiv_at.log (hf : has_fderiv_at f f' x) (hx : f x ≠ 0) :
has_fderiv_at (λ x, log (f x)) ((f x)⁻¹ • f') x :=
(has_deriv_at_log hx).comp_has_fderiv_at x hf
lemma has_strict_fderiv_at.log (hf : has_strict_fderiv_at f f' x) (hx : f x ≠ 0) :
has_strict_fderiv_at (λ x, log (f x)) ((f x)⁻¹ • f') x :=
(has_strict_deriv_at_log hx).comp_has_strict_fderiv_at x hf
lemma differentiable_within_at.log (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) :
differentiable_within_at ℝ (λx, log (f x)) s x :=
(hf.has_fderiv_within_at.log hx).differentiable_within_at
@[simp] lemma differentiable_at.log (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) :
differentiable_at ℝ (λx, log (f x)) x :=
(hf.has_fderiv_at.log hx).differentiable_at
lemma times_cont_diff_at.log {n} (hf : times_cont_diff_at ℝ n f x) (hx : f x ≠ 0) :
times_cont_diff_at ℝ n (λ x, log (f x)) x :=
(times_cont_diff_at_log.2 hx).comp x hf
lemma times_cont_diff_within_at.log {n} (hf : times_cont_diff_within_at ℝ n f s x) (hx : f x ≠ 0) :
times_cont_diff_within_at ℝ n (λ x, log (f x)) s x :=
(times_cont_diff_at_log.2 hx).comp_times_cont_diff_within_at x hf
lemma times_cont_diff_on.log {n} (hf : times_cont_diff_on ℝ n f s) (hs : ∀ x ∈ s, f x ≠ 0) :
times_cont_diff_on ℝ n (λ x, log (f x)) s :=
λ x hx, (hf x hx).log (hs x hx)
lemma times_cont_diff.log {n} (hf : times_cont_diff ℝ n f) (h : ∀ x, f x ≠ 0) :
times_cont_diff ℝ n (λ x, log (f x)) :=
times_cont_diff_iff_times_cont_diff_at.2 $ λ x, hf.times_cont_diff_at.log (h x)
lemma differentiable_on.log (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) :
differentiable_on ℝ (λx, log (f x)) s :=
λx h, (hf x h).log (hx x h)
@[simp] lemma differentiable.log (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) :
differentiable ℝ (λx, log (f x)) :=
λx, (hf x).log (hx x)
lemma fderiv_within.log (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0)
(hxs : unique_diff_within_at ℝ s x) :
fderiv_within ℝ (λx, log (f x)) s x = (f x)⁻¹ • fderiv_within ℝ f s x :=
(hf.has_fderiv_within_at.log hx).fderiv_within hxs
@[simp] lemma fderiv.log (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) :
fderiv ℝ (λx, log (f x)) x = (f x)⁻¹ • fderiv ℝ f x :=
(hf.has_fderiv_at.log hx).fderiv
end fderiv
end log_differentiable
namespace real
/-- The function `exp(x)/x^n` tends to `+∞` at `+∞`, for any natural number `n` -/
lemma tendsto_exp_div_pow_at_top (n : ℕ) : tendsto (λx, exp x / x^n) at_top at_top :=
begin
refine (at_top_basis_Ioi.tendsto_iff (at_top_basis' 1)).2 (λ C hC₁, _),
have hC₀ : 0 < C, from zero_lt_one.trans_le hC₁,
have : 0 < (exp 1 * C)⁻¹ := inv_pos.2 (mul_pos (exp_pos _) hC₀),
obtain ⟨N, hN⟩ : ∃ N, ∀ k ≥ N, (↑k ^ n : ℝ) / exp 1 ^ k < (exp 1 * C)⁻¹ :=
eventually_at_top.1 ((tendsto_pow_const_div_const_pow_of_one_lt n
(one_lt_exp_iff.2 zero_lt_one)).eventually (gt_mem_nhds this)),
simp only [← exp_nat_mul, mul_one, div_lt_iff, exp_pos, ← div_eq_inv_mul] at hN,
refine ⟨N, trivial, λ x hx, _⟩, rw mem_Ioi at hx,
have hx₀ : 0 < x, from N.cast_nonneg.trans_lt hx,
rw [mem_Ici, le_div_iff (pow_pos hx₀ _), ← le_div_iff' hC₀],
calc x ^ n ≤ ⌈x⌉₊ ^ n : pow_le_pow_of_le_left hx₀.le (le_nat_ceil _) _
... ≤ exp ⌈x⌉₊ / (exp 1 * C) : (hN _ (lt_nat_ceil.2 hx).le).le
... ≤ exp (x + 1) / (exp 1 * C) : div_le_div_of_le (mul_pos (exp_pos _) hC₀).le
(exp_le_exp.2 $ (nat_ceil_lt_add_one hx₀.le).le)
... = exp x / C : by rw [add_comm, exp_add, mul_div_mul_left _ _ (exp_pos _).ne']
end
/-- The function `x^n * exp(-x)` tends to `0` at `+∞`, for any natural number `n`. -/
lemma tendsto_pow_mul_exp_neg_at_top_nhds_0 (n : ℕ) : tendsto (λx, x^n * exp (-x)) at_top (𝓝 0) :=
(tendsto_inv_at_top_zero.comp (tendsto_exp_div_pow_at_top n)).congr $ λx,
by rw [comp_app, inv_eq_one_div, div_div_eq_mul_div, one_mul, div_eq_mul_inv, exp_neg]
/-- The function `(b * exp x + c) / (x ^ n)` tends to `+∞` at `+∞`, for any positive natural number
`n` and any real numbers `b` and `c` such that `b` is positive. -/
lemma tendsto_mul_exp_add_div_pow_at_top (b c : ℝ) (n : ℕ) (hb : 0 < b) (hn : 1 ≤ n) :
tendsto (λ x, (b * (exp x) + c) / (x^n)) at_top at_top :=
begin
refine tendsto.congr' (eventually_eq_of_mem (Ioi_mem_at_top 0) _)
(((tendsto_exp_div_pow_at_top n).const_mul_at_top hb).at_top_add
((tendsto_pow_neg_at_top hn).mul (@tendsto_const_nhds _ _ _ c _))),
intros x hx,
simp only [fpow_neg x n],
ring,
end
/-- The function `(x ^ n) / (b * exp x + c)` tends to `0` at `+∞`, for any positive natural number
`n` and any real numbers `b` and `c` such that `b` is nonzero. -/
lemma tendsto_div_pow_mul_exp_add_at_top (b c : ℝ) (n : ℕ) (hb : 0 ≠ b) (hn : 1 ≤ n) :
tendsto (λ x, x^n / (b * (exp x) + c)) at_top (𝓝 0) :=
begin
have H : ∀ d e, 0 < d → tendsto (λ (x:ℝ), x^n / (d * (exp x) + e)) at_top (𝓝 0),
{ intros b' c' h,
convert (tendsto_mul_exp_add_div_pow_at_top b' c' n h hn).inv_tendsto_at_top ,
ext x,
simpa only [pi.inv_apply] using inv_div.symm },
cases lt_or_gt_of_ne hb,
{ exact H b c h },
{ convert (H (-b) (-c) (neg_pos.mpr h)).neg,
{ ext x,
field_simp,
rw [← neg_add (b * exp x) c, neg_div_neg_eq] },
{ exact neg_zero.symm } },
end
/-- The function `x * log (1 + t / x)` tends to `t` at `+∞`. -/
lemma tendsto_mul_log_one_plus_div_at_top (t : ℝ) :
tendsto (λ x, x * log (1 + t / x)) at_top (𝓝 t) :=
begin
have h₁ : tendsto (λ h, h⁻¹ * log (1 + t * h)) (𝓝[{0}ᶜ] 0) (𝓝 t),
{ simpa [has_deriv_at_iff_tendsto_slope] using
((has_deriv_at_const _ 1).add ((has_deriv_at_id (0 : ℝ)).const_mul t)).log (by simp) },
have h₂ : tendsto (λ x : ℝ, x⁻¹) at_top (𝓝[{0}ᶜ] 0) :=
tendsto_inv_at_top_zero'.mono_right (nhds_within_mono _ (λ x hx, (set.mem_Ioi.mp hx).ne')),
convert h₁.comp h₂,
ext,
field_simp [mul_comm],
end
open_locale big_operators
/-- A crude lemma estimating the difference between `log (1-x)` and its Taylor series at `0`,
where the main point of the bound is that it tends to `0`. The goal is to deduce the series
expansion of the logarithm, in `has_sum_pow_div_log_of_abs_lt_1`.
-/
lemma abs_log_sub_add_sum_range_le {x : ℝ} (h : abs x < 1) (n : ℕ) :
abs ((∑ i in range n, x^(i+1)/(i+1)) + log (1-x)) ≤ (abs x)^(n+1) / (1 - abs x) :=
begin
/- For the proof, we show that the derivative of the function to be estimated is small,
and then apply the mean value inequality. -/
let F : ℝ → ℝ := λ x, ∑ i in range n, x^(i+1)/(i+1) + log (1-x),
-- First step: compute the derivative of `F`
have A : ∀ y ∈ Ioo (-1 : ℝ) 1, deriv F y = - (y^n) / (1 - y),
{ assume y hy,
have : (∑ i in range n, (↑i + 1) * y ^ i / (↑i + 1)) = (∑ i in range n, y ^ i),
{ congr' with i,
have : (i : ℝ) + 1 ≠ 0 := ne_of_gt (nat.cast_add_one_pos i),
field_simp [this, mul_comm] },
field_simp [F, this, ← geom_sum_def, geom_sum_eq (ne_of_lt hy.2),
sub_ne_zero_of_ne (ne_of_gt hy.2), sub_ne_zero_of_ne (ne_of_lt hy.2)],
ring },
-- second step: show that the derivative of `F` is small
have B : ∀ y ∈ Icc (-abs x) (abs x), abs (deriv F y) ≤ (abs x)^n / (1 - abs x),
{ assume y hy,
have : y ∈ Ioo (-(1 : ℝ)) 1 := ⟨lt_of_lt_of_le (neg_lt_neg h) hy.1, lt_of_le_of_lt hy.2 h⟩,
calc abs (deriv F y) = abs (-(y^n) / (1 - y)) : by rw [A y this]
... ≤ (abs x)^n / (1 - abs x) :
begin
have : abs y ≤ abs x := abs_le.2 hy,
have : 0 < 1 - abs x, by linarith,
have : 1 - abs x ≤ abs (1 - y) := le_trans (by linarith [hy.2]) (le_abs_self _),
simp only [← pow_abs, abs_div, abs_neg],
apply_rules [div_le_div, pow_nonneg, abs_nonneg, pow_le_pow_of_le_left]
end },
-- third step: apply the mean value inequality
have C : ∥F x - F 0∥ ≤ ((abs x)^n / (1 - abs x)) * ∥x - 0∥,
{ have : ∀ y ∈ Icc (- abs x) (abs x), differentiable_at ℝ F y,
{ assume y hy,
have : 1 - y ≠ 0 := sub_ne_zero_of_ne (ne_of_gt (lt_of_le_of_lt hy.2 h)),
simp [F, this] },
apply convex.norm_image_sub_le_of_norm_deriv_le this B (convex_Icc _ _) _ _,
{ simpa using abs_nonneg x },
{ simp [le_abs_self x, neg_le.mp (neg_le_abs_self x)] } },
-- fourth step: conclude by massaging the inequality of the third step
simpa [F, norm_eq_abs, div_mul_eq_mul_div, pow_succ'] using C
end
/-- Power series expansion of the logarithm around `1`. -/
theorem has_sum_pow_div_log_of_abs_lt_1 {x : ℝ} (h : abs x < 1) :
has_sum (λ (n : ℕ), x ^ (n + 1) / (n + 1)) (-log (1 - x)) :=
begin
rw summable.has_sum_iff_tendsto_nat,
show tendsto (λ (n : ℕ), ∑ (i : ℕ) in range n, x ^ (i + 1) / (i + 1)) at_top (𝓝 (-log (1 - x))),
{ rw [tendsto_iff_norm_tendsto_zero],
simp only [norm_eq_abs, sub_neg_eq_add],
refine squeeze_zero (λ n, abs_nonneg _) (abs_log_sub_add_sum_range_le h) _,
suffices : tendsto (λ (t : ℕ), abs x ^ (t + 1) / (1 - abs x)) at_top
(𝓝 (abs x * 0 / (1 - abs x))), by simpa,
simp only [pow_succ],
refine (tendsto_const_nhds.mul _).div_const,
exact tendsto_pow_at_top_nhds_0_of_lt_1 (abs_nonneg _) h },
show summable (λ (n : ℕ), x ^ (n + 1) / (n + 1)),
{ refine summable_of_norm_bounded _ (summable_geometric_of_lt_1 (abs_nonneg _) h) (λ i, _),
calc ∥x ^ (i + 1) / (i + 1)∥
= abs x ^ (i+1) / (i+1) :
begin
have : (0 : ℝ) ≤ i + 1 := le_of_lt (nat.cast_add_one_pos i),
rw [norm_eq_abs, abs_div, ← pow_abs, abs_of_nonneg this],
end
... ≤ abs x ^ (i+1) / (0 + 1) :
begin
apply_rules [div_le_div_of_le_left, pow_nonneg, abs_nonneg, add_le_add_right,
i.cast_nonneg],
norm_num,
end
... ≤ abs x ^ i :
by simpa [pow_succ'] using mul_le_of_le_one_right (pow_nonneg (abs_nonneg x) i) (le_of_lt h) }
end
end real
|
70c4b0aa4040739d4b200c875903550229d89cdc | ad0c7d243dc1bd563419e2767ed42fb323d7beea | /analysis/ennreal.lean | 430a5bbefb85f8a8a384087848f536e499d4da37 | [
"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 | 17,293 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
Extended non-negative reals
-/
import analysis.nnreal data.real.ennreal
noncomputable theory
open classical set lattice filter
local attribute [instance] prop_decidable
variables {α : Type*} {β : Type*} {γ : Type*}
local notation `∞` := ennreal.infinity
namespace ennreal
variables {a b c d : ennreal} {r p q : nnreal}
section topological_space
open topological_space
instance : topological_space ennreal :=
topological_space.generate_from {s | ∃a, s = {b | a < b} ∨ s = {b | b < a}}
instance : orderable_topology ennreal := ⟨rfl⟩
instance : t2_space ennreal := by apply_instance
instance : second_countable_topology ennreal :=
⟨⟨⋃q ≥ (0:ℚ), {{a : ennreal | a < nnreal.of_real q}, {a : ennreal | ↑(nnreal.of_real q) < a}},
countable_bUnion (countable_encodable _) $ assume a ha, countable_insert (countable_singleton _),
le_antisymm
(generate_from_le $ λ s h, begin
rcases h with ⟨a, hs | hs⟩;
[ rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ a < nnreal.of_real q}, {b | ↑(nnreal.of_real q) < b},
from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn a b, and_assoc]),
rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ ↑(nnreal.of_real q) < a}, {b | b < ↑(nnreal.of_real q)},
from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn b a, and_comm, and_assoc])];
{ apply is_open_Union, intro q,
apply is_open_Union, intro hq,
exact generate_open.basic _ (mem_bUnion hq.1 $ by simp) }
end)
(generate_from_le $ by simp [or_imp_distrib, is_open_lt', is_open_gt'] {contextual := tt})⟩⟩
lemma embedding_coe : embedding (coe : nnreal → ennreal) :=
and.intro (assume a b, coe_eq_coe.1) $
begin
refine le_antisymm _ _,
{ rw [orderable_topology.topology_eq_generate_intervals nnreal],
refine generate_from_le (assume s ha, _),
rcases ha with ⟨a, rfl | rfl⟩,
exact ⟨{b : ennreal | ↑a < b}, @is_open_lt' ennreal ennreal.topological_space _ _ _, by simp⟩,
exact ⟨{b : ennreal | b < ↑a}, @is_open_gt' ennreal ennreal.topological_space _ _ _, by simp⟩, },
{ rw [orderable_topology.topology_eq_generate_intervals ennreal,
induced_le_iff_le_coinduced],
refine generate_from_le (assume s ha, _),
rcases ha with ⟨a, rfl | rfl⟩,
show is_open {b : nnreal | a < ↑b},
{ cases a; simp [none_eq_top, some_eq_coe, is_open_lt'] },
show is_open {b : nnreal | ↑b < a},
{ cases a; simp [none_eq_top, some_eq_coe, is_open_gt', is_open_const] } }
end
lemma is_open_ne_top : is_open {a : ennreal | a ≠ ⊤} :=
is_open_neg (is_closed_eq continuous_id continuous_const)
lemma coe_image_univ_mem_nhds : (coe : nnreal → ennreal) '' univ ∈ (nhds (r : ennreal)).sets :=
have {a : ennreal | a ≠ ⊤} = (coe : nnreal → ennreal) '' univ,
from set.ext $ assume a, by cases a; simp [none_eq_top, some_eq_coe],
this ▸ mem_nhds_sets is_open_ne_top coe_ne_top
lemma tendsto_coe {f : filter α} {m : α → nnreal} {a : nnreal} :
tendsto (λa, (m a : ennreal)) f (nhds ↑a) ↔ tendsto m f (nhds a) :=
embedding_coe.tendsto_nhds_iff.symm
lemma continuous_coe {α} [topological_space α] {f : α → nnreal} :
continuous (λa, (f a : ennreal)) ↔ continuous f :=
embedding_coe.continuous_iff.symm
lemma nhds_coe {r : nnreal} : nhds (r : ennreal) = (nhds r).map coe :=
by rw [embedding_coe.2, map_nhds_induced_eq coe_image_univ_mem_nhds]
lemma nhds_coe_coe {r p : nnreal} : nhds ((r : ennreal), (p : ennreal)) =
(nhds (r, p)).map (λp:nnreal×nnreal, (p.1, p.2)) :=
begin
rw [(embedding_prod_mk embedding_coe embedding_coe).map_nhds_eq],
rw [← univ_prod_univ, ← prod_image_image_eq],
exact prod_mem_nhds_sets coe_image_univ_mem_nhds coe_image_univ_mem_nhds
end
lemma tendsto_to_nnreal {a : ennreal} : a ≠ ⊤ →
tendsto (ennreal.to_nnreal) (nhds a) (nhds a.to_nnreal) :=
begin
cases a; simp [some_eq_coe, none_eq_top, nhds_coe, tendsto_map'_iff, (∘)],
exact tendsto_id
end
lemma coe_nat : ∀n:ℕ, (n : ennreal) = (n : nnreal)
| 0 := rfl
| (n + 1) := by simp [coe_nat n]
lemma tendsto_nhds_top {m : α → ennreal} {f : filter α}
(h : ∀n:ℕ, {a | ↑n < m a} ∈ f.sets) : tendsto m f (nhds ⊤) :=
tendsto_nhds_generate_from $ assume s hs,
match s, hs with
| _, ⟨none, or.inl rfl⟩, hr := (lt_irrefl ⊤ hr).elim
| _, ⟨some r, or.inl rfl⟩, hr :=
let ⟨n, hrn⟩ := exists_nat_gt r in
mem_sets_of_superset (h n) $ assume a hnma, show ↑r < m a, from
lt_trans (show (r : ennreal) < n, from (coe_nat n).symm ▸ coe_lt_coe.2 hrn) hnma
| _, ⟨a, or.inr rfl⟩, hr := (not_top_lt $ show ⊤ < a, from hr).elim
end
/-
lemma nhds_top : nhds (⊤ : ennreal) = (⨅i:ℕ, principal {e : ennreal | ↑i < e}) :=
_
-/
/- MOVE TO nnreal
lemma nhds_of_real_eq_map_of_real_nhds_nonneg {r : ℝ} :
nhds (of_real r) = (nhds r ⊓ principal {x | 0 ≤ x}).map of_real :=
by rw [nhds_of_real_eq_map_of_real_nhds hr];
from by_cases
(assume : r = 0,
le_antisymm
(assume s (hs : {a | of_real a ∈ s} ∈ (nhds r ⊓ principal {x | 0 ≤ x}).sets),
let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := mem_inf_sets.mp hs in
show {a | of_real a ∈ s} ∈ (nhds r).sets,
from (nhds r).sets_of_superset ht₁ $ assume a ha,
match le_total 0 a with
| or.inl h := have a ∈ t₂, from ht₂ h, ht ⟨ha, this⟩
| or.inr h :=
have r ∈ t₁ ∩ t₂, from ⟨mem_of_nhds ht₁, ht₂ (le_of_eq ‹r = 0›.symm)⟩,
have of_real 0 ∈ s, from ‹r = 0› ▸ ht this,
by simp [of_real_of_nonpos h]; assumption
end)
(map_mono inf_le_left))
(assume : r ≠ 0,
have 0 < r, from lt_of_le_of_ne hr this.symm,
have nhds r ⊓ principal {x : ℝ | 0 ≤ x} = nhds r,
from inf_of_le_left $ le_principal_iff.mpr $ le_mem_nhds this,
by simp [*])
-/
instance : topological_add_monoid ennreal :=
⟨ continuous_iff_tendsto.2 $
have hl : ∀a:ennreal, tendsto (λ (p : ennreal × ennreal), p.fst + p.snd) (nhds (⊤, a)) (nhds ⊤), from
assume a, tendsto_nhds_top $ assume n,
have set.prod {a | ↑n < a } univ ∈ (nhds ((⊤:ennreal), a)).sets, from
prod_mem_nhds_sets (lt_mem_nhds $ (coe_nat n).symm ▸ coe_lt_top) univ_mem_sets,
begin filter_upwards [this] assume ⟨a₁, a₂⟩ ⟨h₁, h₂⟩, lt_of_lt_of_le h₁ (le_add_right $ le_refl _) end,
begin
rintro ⟨a₁, a₂⟩,
cases a₁, { simp [none_eq_top, hl a₂], },
cases a₂, { simp [none_eq_top, some_eq_coe, nhds_swap (a₁ : ennreal) ⊤, tendsto_map'_iff, (∘), hl ↑a₁] },
simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)],
simp only [coe_add.symm, tendsto_coe, tendsto_add']
end ⟩
protected lemma tendsto_mul' (ha : a ≠ 0) (hb : b ≠ 0) :
tendsto (λp:ennreal×ennreal, p.1 * p.2) (nhds (a, b)) (nhds (a * b)) :=
have ht : ∀b:ennreal, b ≠ 0 → tendsto (λp:ennreal×ennreal, p.1 * p.2) (nhds ((⊤:ennreal), b)) (nhds ⊤),
begin
refine assume b hb, tendsto_nhds_top $ assume n, _,
rcases dense (zero_lt_iff_ne_zero.2 hb) with ⟨ε', hε', hεb'⟩,
rcases ennreal.lt_iff_exists_coe.1 hεb' with ⟨ε, rfl, h⟩,
rcases exists_nat_gt (↑n / ε) with ⟨m, hm⟩,
have hε : ε > 0, from coe_lt_coe.1 hε',
refine mem_sets_of_superset (prod_mem_nhds_sets (lt_mem_nhds $ @coe_lt_top m) (lt_mem_nhds $ h)) _,
rintros ⟨a₁, a₂⟩ ⟨h₁, h₂⟩,
dsimp at h₁ h₂ ⊢,
calc (n:ennreal) = ↑(((n:nnreal) / ε) * ε) :
begin
simp [nnreal.div_def],
rw [mul_assoc, ← coe_mul, nnreal.inv_mul_cancel, coe_one, coe_nat, mul_one],
exact zero_lt_iff_ne_zero.1 hε
end
... < (↑m * ε : nnreal) : coe_lt_coe.2 $ mul_lt_mul hm (le_refl _) hε (nat.cast_nonneg _)
... ≤ a₁ * a₂ : by rw [coe_mul]; exact canonically_ordered_semiring.mul_le_mul
(le_of_lt h₁)
(le_of_lt h₂)
end,
begin
cases a, { simp [none_eq_top, ht b hb, top_mul, hb] },
cases b, {
have ha' : a ≠ 0, from mt coe_eq_coe.2 ha,
simp [*, nhds_swap (a : ennreal) ⊤, none_eq_top, some_eq_coe, top_mul, tendsto_map'_iff, (∘), mul_comm] },
simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)],
simp only [coe_mul.symm, tendsto_coe, tendsto_mul']
end
protected lemma tendsto_mul {f : filter α} {ma : α → ennreal} {mb : α → ennreal} {a b : ennreal}
(hma : tendsto ma f (nhds a)) (ha : a ≠ 0) (hmb : tendsto mb f (nhds b)) (hb : b ≠ 0) :
tendsto (λa, ma a * mb a) f (nhds (a * b)) :=
show tendsto ((λp:ennreal×ennreal, p.1 * p.2) ∘ (λa, (ma a, mb a))) f (nhds (a * b)), from
tendsto.comp (tendsto_prod_mk_nhds hma hmb) (ennreal.tendsto_mul' ha hb)
protected lemma tendsto_mul_right {f : filter α} {m : α → ennreal} {a b : ennreal}
(hm : tendsto m f (nhds b)) (hb : b ≠ 0) : tendsto (λb, a * m b) f (nhds (a * b)) :=
by_cases
(assume : a = 0, by simp [this, tendsto_const_nhds])
(assume ha : a ≠ 0, ennreal.tendsto_mul tendsto_const_nhds ha hm hb)
lemma Sup_add {s : set ennreal} (hs : s ≠ ∅) : Sup s + a = ⨆b∈s, b + a :=
have Sup ((λb, b + a) '' s) = Sup s + a,
from is_lub_iff_Sup_eq.mp $ is_lub_of_is_lub_of_tendsto
(assume x _ y _ h, add_le_add' h (le_refl _))
is_lub_Sup
hs
(tendsto_add (tendsto_id' inf_le_left) tendsto_const_nhds),
by simp [Sup_image, -add_comm] at this; exact this.symm
lemma supr_add {ι : Sort*} {s : ι → ennreal} [h : nonempty ι] : supr s + a = ⨆b, s b + a :=
let ⟨x⟩ := h in
calc supr s + a = Sup (range s) + a : by simp [Sup_range]
... = (⨆b∈range s, b + a) : Sup_add $ ne_empty_iff_exists_mem.mpr ⟨s x, x, rfl⟩
... = _ : by simp [supr_range, -mem_range]
lemma add_supr {ι : Sort*} {s : ι → ennreal} [h : nonempty ι] : a + supr s = ⨆b, a + s b :=
by rw [add_comm, supr_add]; simp
lemma supr_add_supr {ι : Sort*} [nonempty ι]
{f g : ι → ennreal} (h : ∀i j, ∃k, f i + g j ≤ f k + g k) :
supr f + supr g = (⨆ a, f a + g a) :=
begin
refine le_antisymm _ (supr_le $ λ a, add_le_add' (le_supr _ _) (le_supr _ _)),
simpa [add_supr, supr_add] using
λ i j, show f i + g j ≤ ⨆ a, f a + g a, from
let ⟨k, hk⟩ := h i j in le_supr_of_le k hk,
end
protected lemma tendsto_coe_sub : ∀{b:ennreal}, tendsto (λb:ennreal, ↑r - b) (nhds b) (nhds (↑r - b)) :=
begin
refine (forall_ennreal.2 $ and.intro (assume a, _) _),
{ simp [@nhds_coe a, tendsto_map'_iff, (∘), tendsto_coe, coe_sub.symm],
exact nnreal.tendsto_sub tendsto_const_nhds tendsto_id },
simp,
exact (tendsto_cong tendsto_const_nhds $ mem_sets_of_superset (lt_mem_nhds $ @coe_lt_top r) $
by simp [le_of_lt] {contextual := tt})
end
lemma sub_supr {ι : Sort*} [hι : nonempty ι] {b : ι → ennreal} (hr : a < ⊤) :
a - (⨆i, b i) = (⨅i, a - b i) :=
let ⟨i⟩ := hι in
let ⟨r, eq, _⟩ := lt_iff_exists_coe.mp hr in
have Inf ((λb, ↑r - b) '' range b) = ↑r - (⨆i, b i),
from is_glb_iff_Inf_eq.mp $ is_glb_of_is_lub_of_tendsto
(assume x _ y _, sub_le_sub (le_refl _))
is_lub_supr
(ne_empty_of_mem ⟨i, rfl⟩)
(tendsto.comp (tendsto_id' inf_le_left) ennreal.tendsto_coe_sub),
by rw [eq, ←this]; simp [Inf_image, infi_range, -mem_range]; exact le_refl _
end topological_space
section tsum
variables {f g : α → ennreal}
protected lemma is_sum_coe {f : α → nnreal} {r : nnreal} :
is_sum (λa, (f a : ennreal)) ↑r ↔ is_sum f r :=
have (λs:finset α, s.sum (coe ∘ f)) = (coe : nnreal → ennreal) ∘ (λs:finset α, s.sum f),
from funext $ assume s, ennreal.coe_finset_sum.symm,
by unfold is_sum; rw [this, tendsto_coe]
protected lemma tsum_coe_eq {f : α → nnreal} (h : is_sum f r) : (∑a, (f a : ennreal)) = r :=
tsum_eq_is_sum $ ennreal.is_sum_coe.2 $ h
protected lemma tsum_coe {f : α → nnreal} : has_sum f → (∑a, (f a : ennreal)) = ↑(tsum f)
| ⟨r, hr⟩ := by rw [tsum_eq_is_sum hr, ennreal.tsum_coe_eq hr]
protected lemma is_sum : is_sum f (⨆s:finset α, s.sum f) :=
tendsto_orderable.2
⟨assume a' ha',
let ⟨s, hs⟩ := lt_supr_iff.mp ha' in
mem_at_top_sets.mpr ⟨s, assume t ht, lt_of_lt_of_le hs $ finset.sum_le_sum_of_subset ht⟩,
assume a' ha',
univ_mem_sets' $ assume s,
have s.sum f ≤ ⨆(s : finset α), s.sum f,
from le_supr (λ(s : finset α), s.sum f) s,
lt_of_le_of_lt this ha'⟩
@[simp] protected lemma has_sum : has_sum f := ⟨_, ennreal.is_sum⟩
protected lemma tsum_eq_supr_sum : (∑a, f a) = (⨆s:finset α, s.sum f) :=
tsum_eq_is_sum ennreal.is_sum
protected lemma tsum_sigma {β : α → Type*} (f : Πa, β a → ennreal) :
(∑p:Σa, β a, f p.1 p.2) = (∑a b, f a b) :=
tsum_sigma (assume b, ennreal.has_sum) ennreal.has_sum
protected lemma tsum_prod {f : α → β → ennreal} : (∑p:α×β, f p.1 p.2) = (∑a, ∑b, f a b) :=
let j : α × β → (Σa:α, β) := λp, sigma.mk p.1 p.2 in
let i : (Σa:α, β) → α × β := λp, (p.1, p.2) in
let f' : (Σa:α, β) → ennreal := λp, f p.1 p.2 in
calc (∑p:α×β, f' (j p)) = (∑p:Σa:α, β, f p.1 p.2) :
tsum_eq_tsum_of_iso j i (assume ⟨a, b⟩, rfl) (assume ⟨a, b⟩, rfl)
... = (∑a, ∑b, f a b) : ennreal.tsum_sigma f
protected lemma tsum_comm {f : α → β → ennreal} : (∑a, ∑b, f a b) = (∑b, ∑a, f a b) :=
let f' : α×β → ennreal := λp, f p.1 p.2 in
calc (∑a, ∑b, f a b) = (∑p:α×β, f' p) : ennreal.tsum_prod.symm
... = (∑p:β×α, f' (prod.swap p)) :
(tsum_eq_tsum_of_iso prod.swap (@prod.swap α β) (assume ⟨a, b⟩, rfl) (assume ⟨a, b⟩, rfl)).symm
... = (∑b, ∑a, f' (prod.swap (b, a))) : @ennreal.tsum_prod β α (λb a, f' (prod.swap (b, a)))
protected lemma tsum_add : (∑a, f a + g a) = (∑a, f a) + (∑a, g a) :=
tsum_add ennreal.has_sum ennreal.has_sum
protected lemma tsum_le_tsum (h : ∀a, f a ≤ g a) : (∑a, f a) ≤ (∑a, g a) :=
tsum_le_tsum h ennreal.has_sum ennreal.has_sum
protected lemma tsum_eq_supr_nat {f : ℕ → ennreal} :
(∑i:ℕ, f i) = (⨆i:ℕ, (finset.range i).sum f) :=
calc _ = (⨆s:finset ℕ, s.sum f) : ennreal.tsum_eq_supr_sum
... = (⨆i:ℕ, (finset.range i).sum f) : le_antisymm
(supr_le_supr2 $ assume s,
let ⟨n, hn⟩ := finset.exists_nat_subset_range s in
⟨n, finset.sum_le_sum_of_subset hn⟩)
(supr_le_supr2 $ assume i, ⟨finset.range i, le_refl _⟩)
protected lemma le_tsum (a : α) : f a ≤ (∑a, f a) :=
calc f a = ({a} : finset α).sum f : by simp
... ≤ (⨆s:finset α, s.sum f) : le_supr (λs:finset α, s.sum f) _
... = (∑a, f a) : by rw [ennreal.tsum_eq_supr_sum]
protected lemma mul_tsum : (∑i, a * f i) = a * (∑i, f i) :=
if h : ∀i, f i = 0 then by simp [h] else
let ⟨i, (hi : f i ≠ 0)⟩ := classical.not_forall.mp h in
have sum_ne_0 : (∑i, f i) ≠ 0, from ne_of_gt $
calc 0 < f i : lt_of_le_of_ne (zero_le _) hi.symm
... ≤ (∑i, f i) : ennreal.le_tsum _,
have tendsto (λs:finset α, s.sum ((*) a ∘ f)) at_top (nhds (a * (∑i, f i))),
by rw [← show (*) a ∘ (λs:finset α, s.sum f) = λs, s.sum ((*) a ∘ f),
from funext $ λ s, finset.mul_sum];
exact ennreal.tendsto_mul_right (is_sum_tsum ennreal.has_sum) sum_ne_0,
tsum_eq_is_sum this
protected lemma tsum_mul : (∑i, f i * a) = (∑i, f i) * a :=
by simp [mul_comm, ennreal.mul_tsum]
@[simp] lemma tsum_supr_eq {α : Type*} (a : α) {f : α → ennreal} :
(∑b:α, ⨆ (h : a = b), f b) = f a :=
le_antisymm
(by rw [ennreal.tsum_eq_supr_sum]; exact supr_le (assume s,
calc s.sum (λb, ⨆ (h : a = b), f b) ≤ (finset.singleton a).sum (λb, ⨆ (h : a = b), f b) :
finset.sum_le_sum_of_ne_zero $ assume b _ hb,
suffices a = b, by simpa using this.symm,
classical.by_contradiction $ assume h,
by simpa [h] using hb
... = f a : by simp))
(calc f a ≤ (⨆ (h : a = a), f a) : le_supr (λh:a=a, f a) rfl
... ≤ (∑b:α, ⨆ (h : a = b), f b) : ennreal.le_tsum _)
end tsum
end ennreal
namespace nnreal
lemma exists_le_is_sum_of_le {f g : β → nnreal} {r : nnreal} (hgf : ∀b, g b ≤ f b) (hfr : is_sum f r) :
∃p≤r, is_sum g p :=
have (∑b, (g b : ennreal)) ≤ r,
begin
refine is_sum_le (assume b, _) (is_sum_tsum ennreal.has_sum) (ennreal.is_sum_coe.2 hfr),
exact ennreal.coe_le_coe.2 (hgf _)
end,
let ⟨p, eq, hpr⟩ := ennreal.le_coe_iff.1 this in
⟨p, hpr, ennreal.is_sum_coe.1 $ eq ▸ is_sum_tsum ennreal.has_sum⟩
lemma has_sum_of_le {f g : β → nnreal} (hgf : ∀b, g b ≤ f b) : has_sum f → has_sum g
| ⟨r, hfr⟩ := let ⟨p, _, hp⟩ := exists_le_is_sum_of_le hgf hfr in has_sum_spec hp
end nnreal
lemma has_sum_of_nonneg_of_le {f g : β → ℝ} (hg : ∀b, 0 ≤ g b) (hgf : ∀b, g b ≤ f b) (hf : has_sum f) :
has_sum g :=
let f' (b : β) : nnreal := ⟨f b, le_trans (hg b) (hgf b)⟩ in
let g' (b : β) : nnreal := ⟨g b, hg b⟩ in
have has_sum f', from nnreal.has_sum_coe.1 hf,
have has_sum g', from nnreal.has_sum_of_le (assume b, (nnreal.coe_le (g' b) (f' b)).2 $ hgf b) this,
show has_sum (λb, g' b : β → ℝ), from nnreal.has_sum_coe.2 this
|
f18c0b64c2d6813782708550ecc9b7c23ec644ca | c777c32c8e484e195053731103c5e52af26a25d1 | /src/ring_theory/polynomial/cyclotomic/eval.lean | 77a8f285d4c511e3c3ba29a7482270ba05bb26d2 | [
"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 | 16,312 | lean | /-
Copyright (c) 2021 Eric Rodriguez. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Rodriguez
-/
import ring_theory.polynomial.cyclotomic.basic
import tactic.by_contra
import topology.algebra.polynomial
import number_theory.padics.padic_val
import analysis.complex.arg
/-!
# Evaluating cyclotomic polynomials
This file states some results about evaluating cyclotomic polynomials in various different ways.
## Main definitions
* `polynomial.eval(₂)_one_cyclotomic_prime(_pow)`: `eval 1 (cyclotomic p^k R) = p`.
* `polynomial.eval_one_cyclotomic_not_prime_pow`: Otherwise, `eval 1 (cyclotomic n R) = 1`.
* `polynomial.cyclotomic_pos` : `∀ x, 0 < eval x (cyclotomic n R)` if `2 < n`.
-/
namespace polynomial
open finset nat
open_locale big_operators
@[simp] lemma eval_one_cyclotomic_prime {R : Type*} [comm_ring R] {p : ℕ} [hn : fact p.prime] :
eval 1 (cyclotomic p R) = p :=
by simp only [cyclotomic_prime, eval_X, one_pow, finset.sum_const, eval_pow,
eval_finset_sum, finset.card_range, smul_one_eq_coe]
@[simp] lemma eval₂_one_cyclotomic_prime {R S : Type*} [comm_ring R] [semiring S] (f : R →+* S)
{p : ℕ} [fact p.prime] : eval₂ f 1 (cyclotomic p R) = p :=
by simp
@[simp] lemma eval_one_cyclotomic_prime_pow {R : Type*} [comm_ring R] {p : ℕ} (k : ℕ)
[hn : fact p.prime] : eval 1 (cyclotomic (p ^ (k + 1)) R) = p :=
by simp only [cyclotomic_prime_pow_eq_geom_sum hn.out, eval_X, one_pow, finset.sum_const,
eval_pow, eval_finset_sum, finset.card_range, smul_one_eq_coe]
@[simp] lemma eval₂_one_cyclotomic_prime_pow {R S : Type*} [comm_ring R] [semiring S] (f : R →+* S)
{p : ℕ} (k : ℕ) [fact p.prime] : eval₂ f 1 (cyclotomic (p ^ (k + 1)) R) = p :=
by simp
private lemma cyclotomic_neg_one_pos {n : ℕ} (hn : 2 < n) {R} [linear_ordered_comm_ring R] :
0 < eval (-1 : R) (cyclotomic n R) :=
begin
haveI := ne_zero.of_gt hn,
rw [←map_cyclotomic_int, ←int.cast_one, ←int.cast_neg, eval_int_cast_map,
int.coe_cast_ring_hom, int.cast_pos],
suffices : 0 < eval ↑(-1 : ℤ) (cyclotomic n ℝ),
{ rw [←map_cyclotomic_int n ℝ, eval_int_cast_map, int.coe_cast_ring_hom] at this,
exact_mod_cast this },
simp only [int.cast_one, int.cast_neg],
have h0 := cyclotomic_coeff_zero ℝ hn.le,
rw coeff_zero_eq_eval_zero at h0,
by_contra' hx,
have := intermediate_value_univ (-1) 0 (cyclotomic n ℝ).continuous,
obtain ⟨y, hy : is_root _ y⟩ := this (show (0 : ℝ) ∈ set.Icc _ _, by simpa [h0] using hx),
rw is_root_cyclotomic_iff at hy,
rw hy.eq_order_of at hn,
exact hn.not_le linear_ordered_ring.order_of_le_two,
end
lemma cyclotomic_pos {n : ℕ} (hn : 2 < n) {R} [linear_ordered_comm_ring R] (x : R) :
0 < eval x (cyclotomic n R) :=
begin
induction n using nat.strong_induction_on with n ih,
have hn' : 0 < n := pos_of_gt hn,
have hn'' : 1 < n := one_lt_two.trans hn,
dsimp at ih,
have := prod_cyclotomic_eq_geom_sum hn' R,
apply_fun eval x at this,
rw [← cons_self_proper_divisors hn'.ne', finset.erase_cons_of_ne _ hn''.ne',
finset.prod_cons, eval_mul, eval_geom_sum] at this,
rcases lt_trichotomy 0 (∑ i in finset.range n, x ^ i) with h | h | h,
{ apply pos_of_mul_pos_left,
{ rwa this },
rw eval_prod,
refine finset.prod_nonneg (λ i hi, _),
simp only [finset.mem_erase, mem_proper_divisors] at hi,
rw geom_sum_pos_iff hn'.ne' at h,
cases h with hk hx,
{ refine (ih _ hi.2.2 (nat.two_lt_of_ne _ hi.1 _)).le; rintro rfl,
{ exact hn'.ne' (zero_dvd_iff.mp hi.2.1) },
{ exact even_iff_not_odd.mp (even_iff_two_dvd.mpr hi.2.1) hk } },
{ rcases eq_or_ne i 2 with rfl | hk,
{ simpa only [eval_X, eval_one, cyclotomic_two, eval_add] using hx.le },
refine (ih _ hi.2.2 (nat.two_lt_of_ne _ hi.1 hk)).le,
rintro rfl,
exact (hn'.ne' $ zero_dvd_iff.mp hi.2.1) } },
{ rw [eq_comm, geom_sum_eq_zero_iff_neg_one hn'.ne'] at h,
exact h.1.symm ▸ cyclotomic_neg_one_pos hn },
{ apply pos_of_mul_neg_left,
{ rwa this },
rw geom_sum_neg_iff hn'.ne' at h,
have h2 : 2 ∈ n.proper_divisors.erase 1,
{ rw [finset.mem_erase, mem_proper_divisors],
exact ⟨dec_trivial, even_iff_two_dvd.mp h.1, hn⟩ },
rw [eval_prod, ← finset.prod_erase_mul _ _ h2],
apply mul_nonpos_of_nonneg_of_nonpos,
{ refine finset.prod_nonneg (λ i hi, le_of_lt _),
simp only [finset.mem_erase, mem_proper_divisors] at hi,
refine ih _ hi.2.2.2 (nat.two_lt_of_ne _ hi.2.1 hi.1),
rintro rfl,
rw zero_dvd_iff at hi,
exact hn'.ne' hi.2.2.1 },
{ simpa only [eval_X, eval_one, cyclotomic_two, eval_add] using h.right.le } }
end
lemma cyclotomic_pos_and_nonneg (n : ℕ) {R} [linear_ordered_comm_ring R] (x : R) :
(1 < x → 0 < eval x (cyclotomic n R)) ∧ (1 ≤ x → 0 ≤ eval x (cyclotomic n R)) :=
begin
rcases n with _ | _ | _ | n;
simp only [cyclotomic_zero, cyclotomic_one, cyclotomic_two, succ_eq_add_one,
eval_X, eval_one, eval_add, eval_sub, sub_nonneg, sub_pos,
zero_lt_one, zero_le_one, implies_true_iff, imp_self, and_self],
{ split; intro; linarith, },
{ have : 2 < n + 3 := dec_trivial,
split; intro; [skip, apply le_of_lt]; apply cyclotomic_pos this, },
end
/-- Cyclotomic polynomials are always positive on inputs larger than one.
Similar to `cyclotomic_pos` but with the condition on the input rather than index of the
cyclotomic polynomial. -/
lemma cyclotomic_pos' (n : ℕ) {R} [linear_ordered_comm_ring R] {x : R} (hx : 1 < x) :
0 < eval x (cyclotomic n R) :=
(cyclotomic_pos_and_nonneg n x).1 hx
/-- Cyclotomic polynomials are always nonnegative on inputs one or more. -/
lemma cyclotomic_nonneg (n : ℕ) {R} [linear_ordered_comm_ring R] {x : R} (hx : 1 ≤ x) :
0 ≤ eval x (cyclotomic n R) :=
(cyclotomic_pos_and_nonneg n x).2 hx
lemma eval_one_cyclotomic_not_prime_pow {R : Type*} [ring R] {n : ℕ}
(h : ∀ {p : ℕ}, p.prime → ∀ k : ℕ, p ^ k ≠ n) : eval 1 (cyclotomic n R) = 1 :=
begin
rcases n.eq_zero_or_pos with rfl | hn',
{ simp },
have hn : 1 < n := one_lt_iff_ne_zero_and_ne_one.mpr ⟨hn'.ne', (h nat.prime_two 0).symm⟩,
rsuffices (h | h) : eval 1 (cyclotomic n ℤ) = 1 ∨ eval 1 (cyclotomic n ℤ) = -1,
{ have := eval_int_cast_map (int.cast_ring_hom R) (cyclotomic n ℤ) 1,
simpa only [map_cyclotomic, int.cast_one, h, eq_int_cast] using this },
{ exfalso,
linarith [cyclotomic_nonneg n (le_refl (1 : ℤ))] },
rw [←int.nat_abs_eq_nat_abs_iff, int.nat_abs_one, nat.eq_one_iff_not_exists_prime_dvd],
intros p hp hpe,
haveI := fact.mk hp,
have hpn : p ∣ n,
{ apply hpe.trans,
nth_rewrite 1 ←int.nat_abs_of_nat n,
rw [int.nat_abs_dvd_iff_dvd, ←one_geom_sum, ←eval_geom_sum, ←prod_cyclotomic_eq_geom_sum hn'],
apply eval_dvd,
apply finset.dvd_prod_of_mem,
simp [hn'.ne', hn.ne'] },
have := prod_cyclotomic_eq_geom_sum hn' ℤ,
apply_fun eval 1 at this,
rw [eval_geom_sum, one_geom_sum, eval_prod, eq_comm, ←finset.prod_sdiff $
@range_pow_padic_val_nat_subset_divisors' p _ _, finset.prod_image] at this,
simp_rw [eval_one_cyclotomic_prime_pow, finset.prod_const, finset.card_range, mul_comm] at this,
rw [←finset.prod_sdiff $ show {n} ⊆ _, from _] at this,
any_goals {apply_instance},
swap,
{ simp only [singleton_subset_iff, mem_sdiff, mem_erase, ne.def, mem_divisors, dvd_refl,
true_and, mem_image, mem_range, exists_prop, not_exists, not_and],
exact ⟨⟨hn.ne', hn'.ne'⟩, λ t _, h hp _⟩ },
rw [←int.nat_abs_of_nat p, int.nat_abs_dvd_iff_dvd] at hpe,
obtain ⟨t, ht⟩ := hpe,
rw [finset.prod_singleton, ht, mul_left_comm, mul_comm, ←mul_assoc, mul_assoc] at this,
have : (p ^ (padic_val_nat p n) * p : ℤ) ∣ n := ⟨_, this⟩,
simp only [←pow_succ', ←int.nat_abs_dvd_iff_dvd, int.nat_abs_of_nat, int.nat_abs_pow] at this,
exact pow_succ_padic_val_nat_not_dvd hn'.ne' this,
{ rintro x - y - hxy,
apply nat.succ_injective,
exact nat.pow_right_injective hp.two_le hxy }
end
lemma sub_one_pow_totient_lt_cyclotomic_eval {n : ℕ} {q : ℝ} (hn' : 2 ≤ n) (hq' : 1 < q) :
(q - 1) ^ totient n < (cyclotomic n ℝ).eval q :=
begin
have hn : 0 < n := pos_of_gt hn',
have hq := zero_lt_one.trans hq',
have hfor : ∀ ζ' ∈ primitive_roots n ℂ, q - 1 ≤ ‖↑q - ζ'‖,
{ intros ζ' hζ',
rw mem_primitive_roots hn at hζ',
convert norm_sub_norm_le (↑q) ζ',
{ rw [complex.norm_real, real.norm_of_nonneg hq.le], },
{ rw [hζ'.norm'_eq_one hn.ne'] } },
let ζ := complex.exp (2 * ↑real.pi * complex.I / ↑n),
have hζ : is_primitive_root ζ n := complex.is_primitive_root_exp n hn.ne',
have hex : ∃ ζ' ∈ primitive_roots n ℂ, q - 1 < ‖↑q - ζ'‖,
{ refine ⟨ζ, (mem_primitive_roots hn).mpr hζ, _⟩,
suffices : ¬ same_ray ℝ (q : ℂ) ζ,
{ convert lt_norm_sub_of_not_same_ray this;
simp only [hζ.norm'_eq_one hn.ne', real.norm_of_nonneg hq.le, complex.norm_real] },
rw complex.same_ray_iff,
push_neg,
refine ⟨by exact_mod_cast hq.ne', hζ.ne_zero hn.ne', _⟩,
rw [complex.arg_of_real_of_nonneg hq.le, ne.def, eq_comm, hζ.arg_eq_zero_iff hn.ne'],
clear_value ζ,
rintro rfl,
linarith [hζ.unique is_primitive_root.one] },
have : ¬eval ↑q (cyclotomic n ℂ) = 0,
{ erw cyclotomic.eval_apply q n (algebra_map ℝ ℂ),
simpa only [complex.coe_algebra_map, complex.of_real_eq_zero]
using (cyclotomic_pos' n hq').ne' },
suffices : (units.mk0 (real.to_nnreal (q - 1)) (by simp [hq'])) ^ totient n
< units.mk0 (‖(cyclotomic n ℂ).eval q‖₊) (by simp [this]),
{ simp only [←units.coe_lt_coe, units.coe_pow, units.coe_mk0, ← nnreal.coe_lt_coe, hq'.le,
real.to_nnreal_lt_to_nnreal_iff_of_nonneg, coe_nnnorm, complex.norm_eq_abs,
nnreal.coe_pow, real.coe_to_nnreal', max_eq_left, sub_nonneg] at this,
convert this,
erw [(cyclotomic.eval_apply q n (algebra_map ℝ ℂ)), eq_comm],
simp only [cyclotomic_nonneg n hq'.le, complex.coe_algebra_map,
complex.abs_of_real, abs_eq_self], },
simp only [cyclotomic_eq_prod_X_sub_primitive_roots hζ, eval_prod, eval_C,
eval_X, eval_sub, nnnorm_prod, units.mk0_prod],
convert finset.prod_lt_prod' _ _,
swap, { exact λ _, units.mk0 (real.to_nnreal (q - 1)) (by simp [hq']) },
{ simp only [complex.card_primitive_roots, prod_const, card_attach] },
{ simp only [subtype.coe_mk, finset.mem_attach, forall_true_left, subtype.forall,
←units.coe_le_coe, ← nnreal.coe_le_coe, complex.abs.nonneg, hq'.le, units.coe_mk0,
real.coe_to_nnreal', coe_nnnorm, complex.norm_eq_abs, max_le_iff, tsub_le_iff_right],
intros x hx,
simpa only [and_true, tsub_le_iff_right] using hfor x hx, },
{ simp only [subtype.coe_mk, finset.mem_attach, exists_true_left, subtype.exists,
← nnreal.coe_lt_coe, ← units.coe_lt_coe, units.coe_mk0 _, coe_nnnorm],
simpa only [hq'.le, real.coe_to_nnreal', max_eq_left, sub_nonneg] using hex },
end
lemma sub_one_pow_totient_le_cyclotomic_eval {q : ℝ} (hq' : 1 < q) :
∀ n, (q - 1) ^ totient n ≤ (cyclotomic n ℝ).eval q
| 0 := by simp only [totient_zero, pow_zero, cyclotomic_zero, eval_one]
| 1 := by simp only [totient_one, pow_one, cyclotomic_one, eval_sub, eval_X, eval_one]
| (n + 2) := (sub_one_pow_totient_lt_cyclotomic_eval dec_trivial hq').le
lemma cyclotomic_eval_lt_add_one_pow_totient {n : ℕ} {q : ℝ} (hn' : 3 ≤ n) (hq' : 1 < q) :
(cyclotomic n ℝ).eval q < (q + 1) ^ totient n :=
begin
have hn : 0 < n := pos_of_gt hn',
have hq := zero_lt_one.trans hq',
have hfor : ∀ ζ' ∈ primitive_roots n ℂ, ‖↑q - ζ'‖ ≤ q + 1,
{ intros ζ' hζ',
rw mem_primitive_roots hn at hζ',
convert norm_sub_le (↑q) ζ',
{ rw [complex.norm_real, real.norm_of_nonneg (zero_le_one.trans_lt hq').le], },
{ rw [hζ'.norm'_eq_one hn.ne'] }, },
let ζ := complex.exp (2 * ↑real.pi * complex.I / ↑n),
have hζ : is_primitive_root ζ n := complex.is_primitive_root_exp n hn.ne',
have hex : ∃ ζ' ∈ primitive_roots n ℂ, ‖↑q - ζ'‖ < q + 1,
{ refine ⟨ζ, (mem_primitive_roots hn).mpr hζ, _⟩,
suffices : ¬ same_ray ℝ (q : ℂ) (-ζ),
{ convert norm_add_lt_of_not_same_ray this;
simp [abs_of_pos hq, hζ.norm'_eq_one hn.ne', -complex.norm_eq_abs] },
rw complex.same_ray_iff,
push_neg,
refine ⟨by exact_mod_cast hq.ne', neg_ne_zero.mpr $ hζ.ne_zero hn.ne', _⟩,
rw [complex.arg_of_real_of_nonneg hq.le, ne.def, eq_comm],
intro h,
rw [complex.arg_eq_zero_iff, complex.neg_re, neg_nonneg, complex.neg_im, neg_eq_zero] at h,
have hζ₀ : ζ ≠ 0,
{ clear_value ζ,
rintro rfl,
exact hn.ne' (hζ.unique is_primitive_root.zero) },
have : ζ.re < 0 ∧ ζ.im = 0 := ⟨h.1.lt_of_ne _, h.2⟩,
rw [←complex.arg_eq_pi_iff, hζ.arg_eq_pi_iff hn.ne'] at this,
rw this at hζ,
linarith [hζ.unique $ is_primitive_root.neg_one 0 two_ne_zero.symm],
{ contrapose! hζ₀,
ext; simp [hζ₀, h.2] } },
have : ¬eval ↑q (cyclotomic n ℂ) = 0,
{ erw cyclotomic.eval_apply q n (algebra_map ℝ ℂ),
simp only [complex.coe_algebra_map, complex.of_real_eq_zero],
exact (cyclotomic_pos' n hq').ne.symm, },
suffices : units.mk0 (‖(cyclotomic n ℂ).eval q‖₊) (by simp [this])
< (units.mk0 (real.to_nnreal (q + 1)) (by simp; linarith)) ^ totient n,
{ simp only [←units.coe_lt_coe, units.coe_pow, units.coe_mk0, ← nnreal.coe_lt_coe, hq'.le,
real.to_nnreal_lt_to_nnreal_iff_of_nonneg, coe_nnnorm, complex.norm_eq_abs,
nnreal.coe_pow, real.coe_to_nnreal', max_eq_left, sub_nonneg] at this,
convert this,
{ erw [(cyclotomic.eval_apply q n (algebra_map ℝ ℂ)), eq_comm],
simp [cyclotomic_nonneg n hq'.le] },
rw [eq_comm, max_eq_left_iff],
linarith },
simp only [cyclotomic_eq_prod_X_sub_primitive_roots hζ, eval_prod, eval_C,
eval_X, eval_sub, nnnorm_prod, units.mk0_prod],
convert finset.prod_lt_prod' _ _,
swap, { exact λ _, units.mk0 (real.to_nnreal (q + 1)) (by simp; linarith only [hq']) },
{ simp [complex.card_primitive_roots], },
{ simp only [subtype.coe_mk, finset.mem_attach, forall_true_left, subtype.forall,
←units.coe_le_coe, ← nnreal.coe_le_coe, complex.abs.nonneg, hq'.le, units.coe_mk0,
real.coe_to_nnreal, coe_nnnorm, complex.norm_eq_abs, max_le_iff],
intros x hx,
have : complex.abs _ ≤ _ := hfor x hx,
simp [this], },
{ simp only [subtype.coe_mk, finset.mem_attach, exists_true_left, subtype.exists,
← nnreal.coe_lt_coe, ← units.coe_lt_coe, units.coe_mk0 _, coe_nnnorm],
obtain ⟨ζ, hζ, hhζ : complex.abs _ < _⟩ := hex,
exact ⟨ζ, hζ, by simp [hhζ]⟩ },
end
lemma cyclotomic_eval_le_add_one_pow_totient {q : ℝ} (hq' : 1 < q) :
∀ n, (cyclotomic n ℝ).eval q ≤ (q + 1) ^ totient n
| 0 := by simp
| 1 := by simp [add_assoc, add_nonneg, zero_le_one]
| 2 := by simp
| (n + 3) := (cyclotomic_eval_lt_add_one_pow_totient dec_trivial hq').le
lemma sub_one_pow_totient_lt_nat_abs_cyclotomic_eval {n : ℕ} {q : ℕ} (hn' : 1 < n) (hq : q ≠ 1) :
(q - 1) ^ totient n < ((cyclotomic n ℤ).eval ↑q).nat_abs :=
begin
rcases hq.lt_or_lt.imp_left nat.lt_one_iff.mp with rfl | hq',
{ rw [zero_tsub, zero_pow (nat.totient_pos (pos_of_gt hn')), pos_iff_ne_zero, int.nat_abs_ne_zero,
nat.cast_zero, ← coeff_zero_eq_eval_zero, cyclotomic_coeff_zero _ hn'],
exact one_ne_zero },
rw [← @nat.cast_lt ℝ, nat.cast_pow, nat.cast_sub hq'.le, nat.cast_one, int.cast_nat_abs],
refine (sub_one_pow_totient_lt_cyclotomic_eval hn' (nat.one_lt_cast.2 hq')).trans_le _,
exact (cyclotomic.eval_apply (q : ℤ) n (algebra_map ℤ ℝ)).trans_le (le_abs_self _)
end
lemma sub_one_lt_nat_abs_cyclotomic_eval {n : ℕ} {q : ℕ} (hn' : 1 < n) (hq : q ≠ 1) :
q - 1 < ((cyclotomic n ℤ).eval ↑q).nat_abs :=
calc q - 1 ≤ (q - 1) ^ totient n : nat.le_self_pow (nat.totient_pos $ pos_of_gt hn').ne' _
... < ((cyclotomic n ℤ).eval ↑q).nat_abs : sub_one_pow_totient_lt_nat_abs_cyclotomic_eval hn' hq
end polynomial
|
9fdb82490eac9b96b6de6b3b75f65787a9dca6ad | 49ffcd4736fa3bdcc1cdbb546d4c855d67c0f28a | /library/init/data/list/instances.lean | db76c8e261cffb584ad4d65f2e959cb741b559e3 | [
"Apache-2.0"
] | permissive | black13/lean | 979e24d09e17b2fdf8ec74aac160583000086bc8 | 1a80ea9c8e28902cadbfb612896bcd45ba4ce697 | refs/heads/master | 1,626,839,620,164 | 1,509,113,016,000 | 1,509,122,889,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,420 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import init.data.list.lemmas
import init.meta.mk_dec_eq_instance
open list
universes u v
local attribute [simp] join ret
instance : monad list :=
{pure := @list.ret, bind := @list.bind,
id_map := begin
intros _ xs, induction xs with x xs ih,
{ refl },
{ dsimp [function.comp] at ih, dsimp [function.comp], simp [*] }
end,
pure_bind := by simp_intros,
bind_assoc := begin
intros _ _ _ xs _ _, induction xs,
{ refl },
{ simp [*] }
end}
instance : alternative list :=
{ list.monad with
failure := @list.nil,
orelse := @list.append }
instance {α : Type u} [decidable_eq α] : decidable_eq (list α) :=
by tactic.mk_dec_eq_instance
namespace list
variables {α β : Type u} (p : α → Prop) [decidable_pred p]
instance bin_tree_to_list : has_coe (bin_tree α) (list α) :=
⟨bin_tree.to_list⟩
instance decidable_bex : ∀ (l : list α), decidable (∃ x ∈ l, p x)
| [] := is_false (by simp)
| (x::xs) := by simp; have := decidable_bex xs; apply_instance
instance decidable_ball (l : list α) : decidable (∀ x ∈ l, p x) :=
if h : ∃ x ∈ l, ¬ p x then
is_false $ let ⟨x, h, np⟩ := h in λ al, np (al x h)
else
is_true $ λ x hx, if h' : p x then h' else false.elim $ h ⟨x, hx, h'⟩
end list
|
cb248cf80571f69127c4f0fde19aeac46b14be5b | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/Lake/DSL/Attributes.lean | 3f0ec39945e054a5588c593324f7e52c0417722d | [
"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 | 2,438 | lean | /-
Copyright (c) 2021 Mac Malone. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mac Malone
-/
import Lake.Util.OrderedTagAttribute
open Lean
namespace Lake
initialize packageAttr : OrderedTagAttribute ←
registerOrderedTagAttribute `package "mark a definition as a Lake package configuration"
initialize packageDepAttr : OrderedTagAttribute ←
registerOrderedTagAttribute `package_dep "mark a definition as a Lake package dependency"
initialize scriptAttr : OrderedTagAttribute ←
registerOrderedTagAttribute `script "mark a definition as a Lake script"
initialize defaultScriptAttr : OrderedTagAttribute ←
registerOrderedTagAttribute `default_script "mark a Lake script as the package's default"
fun name => do
unless (← getEnv <&> (scriptAttr.hasTag · name)) do
throwError "attribute `default_script` can only be used on a `script`"
initialize leanLibAttr : OrderedTagAttribute ←
registerOrderedTagAttribute `lean_lib "mark a definition as a Lake Lean library target configuration"
initialize leanExeAttr : OrderedTagAttribute ←
registerOrderedTagAttribute `lean_exe "mark a definition as a Lake Lean executable target configuration"
initialize externLibAttr : OrderedTagAttribute ←
registerOrderedTagAttribute `extern_lib "mark a definition as a Lake external library target"
initialize targetAttr : OrderedTagAttribute ←
registerOrderedTagAttribute `target "mark a definition as a custom Lake target"
initialize defaultTargetAttr : OrderedTagAttribute ←
registerOrderedTagAttribute `default_target "mark a Lake target as the package's default"
fun name => do
let valid ← getEnv <&> fun env =>
leanLibAttr.hasTag env name ||
leanExeAttr.hasTag env name ||
externLibAttr.hasTag env name ||
targetAttr.hasTag env name
unless valid do
throwError "attribute `default_target` can only be used on a target (e.g., `lean_lib`, `lean_exe`)"
initialize moduleFacetAttr : OrderedTagAttribute ←
registerOrderedTagAttribute `module_facet "mark a definition as a Lake module facet"
initialize packageFacetAttr : OrderedTagAttribute ←
registerOrderedTagAttribute `package_facet "mark a definition as a Lake package facet"
initialize libraryFacetAttr : OrderedTagAttribute ←
registerOrderedTagAttribute `library_facet "mark a definition as a Lake library facet"
|
ff5937c881e47c52bdb5e4b8a696391c815e4202 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/deprecated/subring.lean | 019839500077124069e77adc069b8b0490107406 | [
"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 | 8,811 | lean | /-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import deprecated.subgroup
import deprecated.group
import ring_theory.subring.basic
/-!
# Unbundled subrings (deprecated)
This file is deprecated, and is no longer imported by anything in mathlib other than other
deprecated files, and test files. You should not need to import it.
This file defines predicates for unbundled subrings. Instead of using this file, please use
`subring`, defined in `ring_theory.subring.basic`, for subrings of rings.
## Main definitions
`is_subring (S : set R) : Prop` : the predicate that `S` is the underlying set of a subring
of the ring `R`. The bundled variant `subring R` should be used in preference to this.
## Tags
is_subring
-/
universes u v
open group
variables {R : Type u} [ring R]
/-- `S` is a subring: a set containing 1 and closed under multiplication, addition and additive
inverse. -/
structure is_subring (S : set R) extends is_add_subgroup S, is_submonoid S : Prop.
/-- Construct a `subring` from a set satisfying `is_subring`. -/
def is_subring.subring {S : set R} (hs : is_subring S) : subring R :=
{ carrier := S,
one_mem' := hs.one_mem,
mul_mem' := hs.mul_mem,
zero_mem' := hs.zero_mem,
add_mem' := hs.add_mem,
neg_mem' := hs.neg_mem }
namespace ring_hom
lemma is_subring_preimage {R : Type u} {S : Type v} [ring R] [ring S]
(f : R →+* S) {s : set S} (hs : is_subring s) : is_subring (f ⁻¹' s) :=
{ ..is_add_group_hom.preimage f.to_is_add_group_hom hs.to_is_add_subgroup,
..is_submonoid.preimage f.to_is_monoid_hom hs.to_is_submonoid, }
lemma is_subring_image {R : Type u} {S : Type v} [ring R] [ring S]
(f : R →+* S) {s : set R} (hs : is_subring s) : is_subring (f '' s) :=
{ ..is_add_group_hom.image_add_subgroup f.to_is_add_group_hom hs.to_is_add_subgroup,
..is_submonoid.image f.to_is_monoid_hom hs.to_is_submonoid, }
lemma is_subring_set_range {R : Type u} {S : Type v} [ring R] [ring S]
(f : R →+* S) : is_subring (set.range f) :=
{ ..is_add_group_hom.range_add_subgroup f.to_is_add_group_hom,
..range.is_submonoid f.to_is_monoid_hom, }
end ring_hom
variables {cR : Type u} [comm_ring cR]
lemma is_subring.inter {S₁ S₂ : set R} (hS₁ : is_subring S₁) (hS₂ : is_subring S₂) :
is_subring (S₁ ∩ S₂) :=
{ ..is_add_subgroup.inter hS₁.to_is_add_subgroup hS₂.to_is_add_subgroup,
..is_submonoid.inter hS₁.to_is_submonoid hS₂.to_is_submonoid }
lemma is_subring.Inter {ι : Sort*} {S : ι → set R} (h : ∀ y : ι, is_subring (S y)) :
is_subring (set.Inter S) :=
{ ..is_add_subgroup.Inter (λ i, (h i).to_is_add_subgroup),
..is_submonoid.Inter (λ i, (h i).to_is_submonoid) }
lemma is_subring_Union_of_directed {ι : Type*} [hι : nonempty ι]
{s : ι → set R} (h : ∀ i, is_subring (s i))
(directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) :
is_subring (⋃i, s i) :=
{ to_is_add_subgroup := is_add_subgroup_Union_of_directed
(λ i, (h i).to_is_add_subgroup) directed,
to_is_submonoid := is_submonoid_Union_of_directed (λ i, (h i).to_is_submonoid) directed }
namespace ring
/-- The smallest subring containing a given subset of a ring, considered as a set. This function
is deprecated; use `subring.closure`. -/
def closure (s : set R) := add_group.closure (monoid.closure s)
variable {s : set R}
local attribute [reducible] closure
theorem exists_list_of_mem_closure {a : R} (h : a ∈ closure s) :
(∃ L : list (list R), (∀ l ∈ L, ∀ x ∈ l, x ∈ s ∨ x = (-1:R)) ∧ (L.map list.prod).sum = a) :=
add_group.in_closure.rec_on h
(λ x hx, match x, monoid.exists_list_of_mem_closure hx with
| _, ⟨L, h1, rfl⟩ := ⟨[L], list.forall_mem_singleton.2 (λ r hr, or.inl (h1 r hr)), zero_add _⟩
end)
⟨[], list.forall_mem_nil _, rfl⟩
(λ b _ ih, match b, ih with
| _, ⟨L1, h1, rfl⟩ := ⟨L1.map (list.cons (-1)),
λ L2 h2, match L2, list.mem_map.1 h2 with
| _, ⟨L3, h3, rfl⟩ := list.forall_mem_cons.2 ⟨or.inr rfl, h1 L3 h3⟩
end,
by simp only [list.map_map, (∘), list.prod_cons, neg_one_mul];
exact list.rec_on L1 neg_zero.symm (λ hd tl ih,
by rw [list.map_cons, list.sum_cons, ih, list.map_cons, list.sum_cons, neg_add])⟩
end)
(λ r1 r2 hr1 hr2 ih1 ih2, match r1, r2, ih1, ih2 with
| _, _, ⟨L1, h1, rfl⟩, ⟨L2, h2, rfl⟩ := ⟨L1 ++ L2, list.forall_mem_append.2 ⟨h1, h2⟩,
by rw [list.map_append, list.sum_append]⟩
end)
@[elab_as_eliminator]
protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s)
(h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n))
(ha : ∀ {x y}, C x → C y → C (x + y)) : C x :=
begin
have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1,
rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx,
induction L with hd tl ih, { exact h0 },
rw list.forall_mem_cons at HL,
suffices : C (list.prod hd),
{ rw [list.map_cons, list.sum_cons],
exact ha this (ih HL.2) },
replace HL := HL.1, clear ih tl,
suffices : ∃ L : list R,
(∀ x ∈ L, x ∈ s) ∧ (list.prod hd = list.prod L ∨ list.prod hd = -list.prod L),
{ rcases this with ⟨L, HL', HP | HP⟩,
{ rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 },
rw list.forall_mem_cons at HL',
rw list.prod_cons,
exact hs _ HL'.1 _ (ih HL'.2) },
rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 },
rw [list.prod_cons, neg_mul_eq_mul_neg],
rw list.forall_mem_cons at HL',
exact hs _ HL'.1 _ (ih HL'.2) },
induction hd with hd tl ih,
{ exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ },
rw list.forall_mem_cons at HL,
rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd,
{ exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $
by rw [list.prod_cons, list.prod_cons, HP]⟩ },
{ exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ },
{ exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $
by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ },
{ exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ }
end
lemma closure.is_subring : is_subring (closure s) :=
{ one_mem := add_group.mem_closure $ is_submonoid.one_mem $ monoid.closure.is_submonoid _,
mul_mem := λ a b ha hb, add_group.in_closure.rec_on hb
( λ c hc, add_group.in_closure.rec_on ha
( λ d hd, add_group.subset_closure ((monoid.closure.is_submonoid _).mul_mem hd hc))
( (zero_mul c).symm ▸ (add_group.closure.is_add_subgroup _).zero_mem)
( λ d hd hdc, neg_mul_eq_neg_mul d c ▸ (add_group.closure.is_add_subgroup _).neg_mem hdc)
( λ d e hd he hdc hec, (add_mul d e c).symm ▸
((add_group.closure.is_add_subgroup _).add_mem hdc hec)))
( (mul_zero a).symm ▸ (add_group.closure.is_add_subgroup _).zero_mem)
( λ c hc hac, neg_mul_eq_mul_neg a c ▸ (add_group.closure.is_add_subgroup _).neg_mem hac)
( λ c d hc hd hac had, (mul_add a c d).symm ▸
(add_group.closure.is_add_subgroup _).add_mem hac had),
..add_group.closure.is_add_subgroup _}
theorem mem_closure {a : R} : a ∈ s → a ∈ closure s :=
add_group.mem_closure ∘ @monoid.subset_closure _ _ _ _
theorem subset_closure : s ⊆ closure s :=
λ _, mem_closure
theorem closure_subset {t : set R} (ht : is_subring t) : s ⊆ t → closure s ⊆ t :=
(add_group.closure_subset ht.to_is_add_subgroup) ∘ (monoid.closure_subset ht.to_is_submonoid)
theorem closure_subset_iff {s t : set R} (ht : is_subring t) : closure s ⊆ t ↔ s ⊆ t :=
(add_group.closure_subset_iff ht.to_is_add_subgroup).trans
⟨set.subset.trans monoid.subset_closure, monoid.closure_subset ht.to_is_submonoid⟩
theorem closure_mono {s t : set R} (H : s ⊆ t) : closure s ⊆ closure t :=
closure_subset closure.is_subring $ set.subset.trans H subset_closure
lemma image_closure {S : Type*} [ring S] (f : R →+* S) (s : set R) :
f '' closure s = closure (f '' s) :=
le_antisymm
begin
rintros _ ⟨x, hx, rfl⟩,
apply in_closure.rec_on hx; intros,
{ rw [f.map_one], apply closure.is_subring.to_is_submonoid.one_mem },
{ rw [f.map_neg, f.map_one],
apply closure.is_subring.to_is_add_subgroup.neg_mem,
apply closure.is_subring.to_is_submonoid.one_mem },
{ rw [f.map_mul],
apply closure.is_subring.to_is_submonoid.mul_mem;
solve_by_elim [subset_closure, set.mem_image_of_mem] },
{ rw [f.map_add], apply closure.is_subring.to_is_add_submonoid.add_mem, assumption' },
end
(closure_subset (ring_hom.is_subring_image _ closure.is_subring) $
set.image_subset _ subset_closure)
end ring
|
8be6854195b11cd141d29fbd94cfe97e24d3823d | 94e33a31faa76775069b071adea97e86e218a8ee | /src/topology/sheaves/presheaf.lean | d892a09e2471dcf4f671dad7f86290579f4a3cb7 | [
"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 | 11,962 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Mario Carneiro, Reid Barton, Andrew Yang
-/
import category_theory.limits.kan_extension
import category_theory.adjunction
import topology.category.Top.opens
/-!
# Presheaves on a topological space
We define `presheaf C X` simply as `(opens X)ᵒᵖ ⥤ C`,
and inherit the category structure with natural transformations as morphisms.
We define
* `pushforward_obj {X Y : Top.{w}} (f : X ⟶ Y) (ℱ : X.presheaf C) : Y.presheaf C`
with notation `f _* ℱ`
and for `ℱ : X.presheaf C` provide the natural isomorphisms
* `pushforward.id : (𝟙 X) _* ℱ ≅ ℱ`
* `pushforward.comp : (f ≫ g) _* ℱ ≅ g _* (f _* ℱ)`
along with their `@[simp]` lemmas.
We also define the functors `pushforward` and `pullback` between the categories
`X.presheaf C` and `Y.presheaf C`, and provide their adjunction at
`pushforward_pullback_adjunction`.
-/
universes w v u
open category_theory
open topological_space
open opposite
variables (C : Type u) [category.{v} C]
namespace Top
/-- The category of `C`-valued presheaves on a (bundled) topological space `X`. -/
@[derive category, nolint has_inhabited_instance]
def presheaf (X : Top.{w}) := (opens X)ᵒᵖ ⥤ C
variables {C}
namespace presheaf
/-- Pushforward a presheaf on `X` along a continuous map `f : X ⟶ Y`, obtaining a presheaf
on `Y`. -/
def pushforward_obj {X Y : Top.{w}} (f : X ⟶ Y) (ℱ : X.presheaf C) : Y.presheaf C :=
(opens.map f).op ⋙ ℱ
infix ` _* `: 80 := pushforward_obj
@[simp] lemma pushforward_obj_obj {X Y : Top.{w}} (f : X ⟶ Y) (ℱ : X.presheaf C) (U : (opens Y)ᵒᵖ) :
(f _* ℱ).obj U = ℱ.obj ((opens.map f).op.obj U) := rfl
@[simp] lemma pushforward_obj_map {X Y : Top.{w}} (f : X ⟶ Y) (ℱ : X.presheaf C)
{U V : (opens Y)ᵒᵖ} (i : U ⟶ V) :
(f _* ℱ).map i = ℱ.map ((opens.map f).op.map i) := rfl
/--
An equality of continuous maps induces a natural isomorphism between the pushforwards of a presheaf
along those maps.
-/
def pushforward_eq {X Y : Top.{w}} {f g : X ⟶ Y} (h : f = g) (ℱ : X.presheaf C) :
f _* ℱ ≅ g _* ℱ :=
iso_whisker_right (nat_iso.op (opens.map_iso f g h).symm) ℱ
lemma pushforward_eq' {X Y : Top.{w}} {f g : X ⟶ Y} (h : f = g) (ℱ : X.presheaf C) :
f _* ℱ = g _* ℱ :=
by rw h
@[simp] lemma pushforward_eq_hom_app
{X Y : Top.{w}} {f g : X ⟶ Y} (h : f = g) (ℱ : X.presheaf C) (U) :
(pushforward_eq h ℱ).hom.app U =
ℱ.map (begin dsimp [functor.op], apply quiver.hom.op, apply eq_to_hom, rw h, end) :=
by simp [pushforward_eq]
lemma pushforward_eq'_hom_app
{X Y : Top.{w}} {f g : X ⟶ Y} (h : f = g) (ℱ : X.presheaf C) (U) :
nat_trans.app (eq_to_hom (pushforward_eq' h ℱ)) U = ℱ.map (eq_to_hom (by rw h)) :=
by simpa [eq_to_hom_map]
@[simp]
lemma pushforward_eq_rfl {X Y : Top.{w}} (f : X ⟶ Y) (ℱ : X.presheaf C) (U) :
(pushforward_eq (rfl : f = f) ℱ).hom.app (op U) = 𝟙 _ :=
begin
dsimp [pushforward_eq],
simp,
end
lemma pushforward_eq_eq {X Y : Top.{w}} {f g : X ⟶ Y} (h₁ h₂ : f = g) (ℱ : X.presheaf C) :
ℱ.pushforward_eq h₁ = ℱ.pushforward_eq h₂ :=
rfl
namespace pushforward
variables {X : Top.{w}} (ℱ : X.presheaf C)
/-- The natural isomorphism between the pushforward of a presheaf along the identity continuous map
and the original presheaf. -/
def id : (𝟙 X) _* ℱ ≅ ℱ :=
(iso_whisker_right (nat_iso.op (opens.map_id X).symm) ℱ) ≪≫ functor.left_unitor _
lemma id_eq : (𝟙 X) _* ℱ = ℱ :=
by { unfold pushforward_obj, rw opens.map_id_eq, erw functor.id_comp }
@[simp] lemma id_hom_app' (U) (p) :
(id ℱ).hom.app (op ⟨U, p⟩) = ℱ.map (𝟙 (op ⟨U, p⟩)) :=
by { dsimp [id], simp, }
local attribute [tidy] tactic.op_induction'
@[simp, priority 990] lemma id_hom_app (U) :
(id ℱ).hom.app U = ℱ.map (eq_to_hom (opens.op_map_id_obj U)) := by tidy
@[simp] lemma id_inv_app' (U) (p) : (id ℱ).inv.app (op ⟨U, p⟩) = ℱ.map (𝟙 (op ⟨U, p⟩)) :=
by { dsimp [id], simp, }
/-- The natural isomorphism between
the pushforward of a presheaf along the composition of two continuous maps and
the corresponding pushforward of a pushforward. -/
def comp {Y Z : Top.{w}} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g) _* ℱ ≅ g _* (f _* ℱ) :=
iso_whisker_right (nat_iso.op (opens.map_comp f g).symm) ℱ
lemma comp_eq {Y Z : Top.{w}} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g) _* ℱ = g _* (f _* ℱ) :=
rfl
@[simp] lemma comp_hom_app {Y Z : Top.{w}} (f : X ⟶ Y) (g : Y ⟶ Z) (U) :
(comp ℱ f g).hom.app U = 𝟙 _ :=
by { dsimp [comp], tidy, }
@[simp] lemma comp_inv_app {Y Z : Top.{w}} (f : X ⟶ Y) (g : Y ⟶ Z) (U) :
(comp ℱ f g).inv.app U = 𝟙 _ :=
by { dsimp [comp], tidy, }
end pushforward
/--
A morphism of presheaves gives rise to a morphisms of the pushforwards of those presheaves.
-/
@[simps]
def pushforward_map {X Y : Top.{w}} (f : X ⟶ Y) {ℱ 𝒢 : X.presheaf C} (α : ℱ ⟶ 𝒢) :
f _* ℱ ⟶ f _* 𝒢 :=
{ app := λ U, α.app _,
naturality' := λ U V i, by { erw α.naturality, refl, } }
open category_theory.limits
section pullback
variable [has_colimits C]
noncomputable theory
/--
Pullback a presheaf on `Y` along a continuous map `f : X ⟶ Y`, obtaining a presheaf on `X`.
This is defined in terms of left Kan extensions, which is just a fancy way of saying
"take the colimits over the open sets whose preimage contains U".
-/
@[simps]
def pullback_obj {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : Y.presheaf C) : X.presheaf C :=
(Lan (opens.map f).op).obj ℱ
/-- Pulling back along continuous maps is functorial. -/
def pullback_map {X Y : Top.{v}} (f : X ⟶ Y) {ℱ 𝒢 : Y.presheaf C} (α : ℱ ⟶ 𝒢) :
pullback_obj f ℱ ⟶ pullback_obj f 𝒢 :=
(Lan (opens.map f).op).map α
/-- If `f '' U` is open, then `f⁻¹ℱ U ≅ ℱ (f '' U)`. -/
@[simps]
def pullback_obj_obj_of_image_open {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : Y.presheaf C) (U : opens X)
(H : is_open (f '' U)) : (pullback_obj f ℱ).obj (op U) ≅ ℱ.obj (op ⟨_, H⟩) :=
begin
let x : costructured_arrow (opens.map f).op (op U) :=
{ left := op ⟨f '' U, H⟩,
hom := ((@hom_of_le _ _ _ ((opens.map f).obj ⟨_, H⟩) (set.image_preimage.le_u_l _)).op :
op ((opens.map f).obj (⟨⇑f '' ↑U, H⟩)) ⟶ op U) },
have hx : is_terminal x :=
{ lift := λ s,
begin
fapply costructured_arrow.hom_mk,
change op (unop _) ⟶ op (⟨_, H⟩ : opens _),
refine (hom_of_le _).op,
exact (set.image_subset f s.X.hom.unop.le).trans (set.image_preimage.l_u_le ↑(unop s.X.left)),
simp
end },
exact is_colimit.cocone_point_unique_up_to_iso
(colimit.is_colimit _)
(colimit_of_diagram_terminal hx _),
end
namespace pullback
variables {X Y : Top.{v}} (ℱ : Y.presheaf C)
/-- The pullback along the identity is isomorphic to the original presheaf. -/
def id : pullback_obj (𝟙 _) ℱ ≅ ℱ :=
nat_iso.of_components
(λ U, pullback_obj_obj_of_image_open (𝟙 _) ℱ (unop U) (by simpa using U.unop.2) ≪≫
ℱ.map_iso (eq_to_iso (by simp)))
(λ U V i,
begin
ext, simp,
erw colimit.pre_desc_assoc,
erw colimit.ι_desc_assoc,
erw colimit.ι_desc_assoc,
dsimp, simp only [←ℱ.map_comp], congr
end)
lemma id_inv_app (U : opens Y) :
(id ℱ).inv.app (op U) = colimit.ι (Lan.diagram (opens.map (𝟙 Y)).op ℱ (op U))
(@costructured_arrow.mk _ _ _ _ _ (op U) _ (eq_to_hom (by simp))) :=
begin
dsimp[id], simp, dsimp[colimit_of_diagram_terminal],
delta Lan.diagram,
refine eq.trans _ (category.id_comp _),
rw ← ℱ.map_id,
congr,
any_goals { apply subsingleton.helim },
all_goals { simp }
end
end pullback
end pullback
variable (C)
/--
The pushforward functor.
-/
def pushforward {X Y : Top.{v}} (f : X ⟶ Y) : X.presheaf C ⥤ Y.presheaf C :=
{ obj := pushforward_obj f,
map := @pushforward_map _ _ X Y f }
@[simp]
lemma pushforward_map_app' {X Y : Top.{v}} (f : X ⟶ Y)
{ℱ 𝒢 : X.presheaf C} (α : ℱ ⟶ 𝒢) {U : (opens Y)ᵒᵖ} :
((pushforward C f).map α).app U = α.app (op $ (opens.map f).obj U.unop) := rfl
lemma id_pushforward {X : Top.{v}} : pushforward C (𝟙 X) = 𝟭 (X.presheaf C) :=
begin
apply category_theory.functor.ext,
{ intros,
ext U,
have h := f.congr, erw h (opens.op_map_id_obj U),
simpa [eq_to_hom_map], },
{ intros, apply pushforward.id_eq },
end
section iso
/-- A homeomorphism of spaces gives an equivalence of categories of presheaves. -/
@[simps] def presheaf_equiv_of_iso {X Y : Top} (H : X ≅ Y) :
X.presheaf C ≌ Y.presheaf C :=
equivalence.congr_left (opens.map_map_iso H).symm.op
variable {C}
/--
If `H : X ≅ Y` is a homeomorphism,
then given an `H _* ℱ ⟶ 𝒢`, we may obtain an `ℱ ⟶ H ⁻¹ _* 𝒢`.
-/
def to_pushforward_of_iso {X Y : Top} (H : X ≅ Y) {ℱ : X.presheaf C} {𝒢 : Y.presheaf C}
(α : H.hom _* ℱ ⟶ 𝒢) : ℱ ⟶ H.inv _* 𝒢 :=
(presheaf_equiv_of_iso _ H).to_adjunction.hom_equiv ℱ 𝒢 α
@[simp]
lemma to_pushforward_of_iso_app {X Y : Top} (H₁ : X ≅ Y) {ℱ : X.presheaf C} {𝒢 : Y.presheaf C}
(H₂ : H₁.hom _* ℱ ⟶ 𝒢) (U : (opens X)ᵒᵖ) :
(to_pushforward_of_iso H₁ H₂).app U =
ℱ.map (eq_to_hom (by simp [opens.map, set.preimage_preimage])) ≫
H₂.app (op ((opens.map H₁.inv).obj (unop U))) :=
begin
delta to_pushforward_of_iso,
simp only [equiv.to_fun_as_coe, nat_trans.comp_app, equivalence.equivalence_mk'_unit,
eq_to_hom_map, eq_to_hom_op, eq_to_hom_trans, presheaf_equiv_of_iso_unit_iso_hom_app_app,
equivalence.to_adjunction, equivalence.equivalence_mk'_counit,
presheaf_equiv_of_iso_inverse_map_app, adjunction.mk_of_unit_counit_hom_equiv_apply],
congr,
end
/--
If `H : X ≅ Y` is a homeomorphism,
then given an `H _* ℱ ⟶ 𝒢`, we may obtain an `ℱ ⟶ H ⁻¹ _* 𝒢`.
-/
def pushforward_to_of_iso {X Y : Top} (H₁ : X ≅ Y) {ℱ : Y.presheaf C} {𝒢 : X.presheaf C}
(H₂ : ℱ ⟶ H₁.hom _* 𝒢) : H₁.inv _* ℱ ⟶ 𝒢 :=
((presheaf_equiv_of_iso _ H₁.symm).to_adjunction.hom_equiv ℱ 𝒢).symm H₂
@[simp]
lemma pushforward_to_of_iso_app {X Y : Top} (H₁ : X ≅ Y) {ℱ : Y.presheaf C} {𝒢 : X.presheaf C}
(H₂ : ℱ ⟶ H₁.hom _* 𝒢) (U : (opens X)ᵒᵖ) :
(pushforward_to_of_iso H₁ H₂).app U =
H₂.app (op ((opens.map H₁.inv).obj (unop U))) ≫
𝒢.map (eq_to_hom (by simp [opens.map, set.preimage_preimage])) :=
by simpa [pushforward_to_of_iso, equivalence.to_adjunction]
end iso
variables (C) [has_colimits C]
/-- Pullback a presheaf on `Y` along a continuous map `f : X ⟶ Y`, obtaining a presheaf
on `X`. -/
@[simps map_app]
def pullback {X Y : Top.{v}} (f : X ⟶ Y) : Y.presheaf C ⥤ X.presheaf C := Lan (opens.map f).op
@[simp] lemma pullback_obj_eq_pullback_obj {C} [category C] [has_colimits C] {X Y : Top.{w}}
(f : X ⟶ Y) (ℱ : Y.presheaf C) : (pullback C f).obj ℱ = pullback_obj f ℱ := rfl
/-- The pullback and pushforward along a continuous map are adjoint to each other. -/
@[simps unit_app_app counit_app_app]
def pushforward_pullback_adjunction {X Y : Top.{v}} (f : X ⟶ Y) :
pullback C f ⊣ pushforward C f := Lan.adjunction _ _
/-- Pulling back along a homeomorphism is the same as pushing forward along its inverse. -/
def pullback_hom_iso_pushforward_inv {X Y : Top.{v}} (H : X ≅ Y) :
pullback C H.hom ≅ pushforward C H.inv :=
adjunction.left_adjoint_uniq
(pushforward_pullback_adjunction C H.hom)
(presheaf_equiv_of_iso C H.symm).to_adjunction
/-- Pulling back along the inverse of a homeomorphism is the same as pushing forward along it. -/
def pullback_inv_iso_pushforward_hom {X Y : Top.{v}} (H : X ≅ Y) :
pullback C H.inv ≅ pushforward C H.hom :=
adjunction.left_adjoint_uniq
(pushforward_pullback_adjunction C H.inv)
(presheaf_equiv_of_iso C H).to_adjunction
end presheaf
end Top
|
7ebe489a1a5b69e84bc938226bd3cfdc67074e9e | abd85493667895c57a7507870867b28124b3998f | /src/data/opposite.lean | 18f8bc0f5a271b24a956042cd1dc86fa05356eda | [
"Apache-2.0"
] | permissive | pechersky/mathlib | d56eef16bddb0bfc8bc552b05b7270aff5944393 | f1df14c2214ee114c9738e733efd5de174deb95d | refs/heads/master | 1,666,714,392,571 | 1,591,747,567,000 | 1,591,747,567,000 | 270,557,274 | 0 | 0 | Apache-2.0 | 1,591,597,975,000 | 1,591,597,974,000 | null | UTF-8 | Lean | false | false | 3,997 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Reid Barton, Simon Hudon, Kenny Lau
Opposites.
-/
import data.list.defs
import data.equiv.basic
universes v u -- declare the `v` first; see `category_theory.category` for an explanation
variable (α : Sort u)
/-- The type of objects of the opposite of `α`; used to defined opposite category/group/...
In order to avoid confusion between `α` and its opposite type, we
set up the type of objects `opposite α` using the following pattern,
which will be repeated later for the morphisms.
1. Define `opposite α := α`.
2. Define the isomorphisms `op : α → opposite α`, `unop : opposite α → α`.
3. Make the definition `opposite` irreducible.
This has the following consequences.
* `opposite α` and `α` are distinct types in the elaborator, so you
must use `op` and `unop` explicitly to convert between them.
* Both `unop (op X) = X` and `op (unop X) = X` are definitional
equalities. Notably, every object of the opposite category is
definitionally of the form `op X`, which greatly simplifies the
definition of the structure of the opposite category, for example.
(If Lean supported definitional eta equality for records, we could
achieve the same goals using a structure with one field.)
-/
def opposite : Sort u := α
-- Use a high right binding power (like that of postfix ⁻¹) so that, for example,
-- `presheaf Cᵒᵖ` parses as `presheaf (Cᵒᵖ)` and not `(presheaf C)ᵒᵖ`.
notation α `ᵒᵖ`:std.prec.max_plus := opposite α
namespace opposite
variables {α}
def op : α → αᵒᵖ := id
def unop : αᵒᵖ → α := id
lemma op_inj : function.injective (op : α → αᵒᵖ) := λ _ _, id
lemma unop_inj : function.injective (unop : αᵒᵖ → α) := λ _ _, id
@[simp] lemma op_inj_iff (x y : α) : op x = op y ↔ x = y := iff.rfl
@[simp] lemma unop_inj_iff (x y : αᵒᵖ) : unop x = unop y ↔ x = y := iff.rfl
@[simp] lemma op_unop (x : αᵒᵖ) : op (unop x) = x := rfl
@[simp] lemma unop_op (x : α) : unop (op x) = x := rfl
attribute [irreducible] opposite
/-- The type-level equivalence between a type and its opposite. -/
def equiv_to_opposite : α ≃ αᵒᵖ :=
{ to_fun := op,
inv_fun := unop,
left_inv := λ a, by simp,
right_inv := λ a, by simp, }
@[simp]
lemma equiv_to_opposite_apply (a : α) : equiv_to_opposite a = op a := rfl
@[simp]
lemma equiv_to_opposite_symm_apply (a : αᵒᵖ) : equiv_to_opposite.symm a = unop a := rfl
lemma op_eq_iff_eq_unop {x : α} {y} : op x = y ↔ x = unop y :=
equiv_to_opposite.apply_eq_iff_eq_symm_apply _ _
lemma unop_eq_iff_eq_op {x} {y : α} : unop x = y ↔ x = op y :=
equiv_to_opposite.symm.apply_eq_iff_eq_symm_apply _ _
instance [inhabited α] : inhabited αᵒᵖ := ⟨op (default _)⟩
def op_induction {F : Π (X : αᵒᵖ), Sort v} (h : Π X, F (op X)) : Π X, F X :=
λ X, h (unop X)
end opposite
namespace tactic
open opposite
open interactive interactive.types lean.parser tactic
local postfix `?`:9001 := optional
namespace op_induction
meta def is_opposite (e : expr) : tactic bool :=
do t ← infer_type e,
`(opposite _) ← whnf t | return ff,
return tt
meta def find_opposite_hyp : tactic name :=
do lc ← local_context,
h :: _ ← lc.mfilter $ is_opposite | fail "No hypotheses of the form Xᵒᵖ",
return h.local_pp_name
end op_induction
open op_induction
meta def op_induction (h : option name) : tactic unit :=
do h ← match h with
| (some h) := pure h
| none := find_opposite_hyp
end,
h' ← tactic.get_local h,
revert_lst [h'],
applyc `opposite.op_induction,
tactic.intro h,
skip
-- For use with `local attribute [tidy] op_induction`
meta def op_induction' := op_induction none
namespace interactive
meta def op_induction (h : parse ident?) : tactic unit :=
tactic.op_induction h
end interactive
end tactic
|
c4a4f3fead48089bf40adfd9b0b3ca185d21af32 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/order/monoid/basic.lean | 50bd75e3cf7535ec5200b3c9e17ba1c0ce1fcdbc | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 3,079 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl
-/
import algebra.order.monoid.defs
import algebra.group.inj_surj
import order.hom.basic
/-!
# Ordered monoids
This file develops some additional material on ordered monoids.
-/
set_option old_structure_cmd true
open function
universe u
variables {α : Type u} {β : Type*}
/-- Pullback an `ordered_comm_monoid` under an injective map.
See note [reducible non-instances]. -/
@[reducible, to_additive function.injective.ordered_add_comm_monoid
"Pullback an `ordered_add_comm_monoid` under an injective map."]
def function.injective.ordered_comm_monoid [ordered_comm_monoid α] {β : Type*}
[has_one β] [has_mul β] [has_pow β ℕ]
(f : β → α) (hf : function.injective f) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) :
ordered_comm_monoid β :=
{ mul_le_mul_left := λ a b ab c, show f (c * a) ≤ f (c * b), by
{ rw [mul, mul], apply mul_le_mul_left', exact ab },
..partial_order.lift f hf,
..hf.comm_monoid f one mul npow }
/-- Pullback a `linear_ordered_comm_monoid` under an injective map.
See note [reducible non-instances]. -/
@[reducible, to_additive function.injective.linear_ordered_add_comm_monoid
"Pullback an `ordered_add_comm_monoid` under an injective map."]
def function.injective.linear_ordered_comm_monoid [linear_ordered_comm_monoid α] {β : Type*}
[has_one β] [has_mul β] [has_pow β ℕ] [has_sup β] [has_inf β]
(f : β → α) (hf : function.injective f) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n)
(hsup : ∀ x y, f (x ⊔ y) = max (f x) (f y)) (hinf : ∀ x y, f (x ⊓ y) = min (f x) (f y)) :
linear_ordered_comm_monoid β :=
{ .. hf.ordered_comm_monoid f one mul npow,
.. linear_order.lift f hf hsup hinf }
-- TODO find a better home for the next two constructions.
/-- The order embedding sending `b` to `a * b`, for some fixed `a`.
See also `order_iso.mul_left` when working in an ordered group. -/
@[to_additive "The order embedding sending `b` to `a + b`, for some fixed `a`.
See also `order_iso.add_left` when working in an additive ordered group.", simps]
def order_embedding.mul_left
{α : Type*} [has_mul α] [linear_order α] [covariant_class α α (*) (<)] (m : α) : α ↪o α :=
order_embedding.of_strict_mono (λ n, m * n) (λ a b w, mul_lt_mul_left' w m)
/-- The order embedding sending `b` to `b * a`, for some fixed `a`.
See also `order_iso.mul_right` when working in an ordered group. -/
@[to_additive "The order embedding sending `b` to `b + a`, for some fixed `a`.
See also `order_iso.add_right` when working in an additive ordered group.", simps]
def order_embedding.mul_right
{α : Type*} [has_mul α] [linear_order α] [covariant_class α α (swap (*)) (<)] (m : α) :
α ↪o α :=
order_embedding.of_strict_mono (λ n, n * m) (λ a b w, mul_lt_mul_right' w m)
|
fdcf4d65ce22af9a455524c8a54dc944f5e89827 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/1986.lean | 68cf03faabab03c5269c0a50b8120442fae28436 | [
"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 | 7,380 | lean | instance {ι : Type u} {α : ι → Type v} [∀ i, LE (α i)] : LE (∀ i, α i) where
le x y := ∀ i, x i ≤ y i
class Top (α : Type u) where
top : α
class Bot (α : Type u) where
bot : α
notation "⊤" => Top.top
notation "⊥" => Bot.bot
class Preorder (α : Type u) extends LE α, LT α where
le_refl : ∀ a : α, a ≤ a
le_trans : ∀ a b c : α, a ≤ b → b ≤ c → a ≤ c
lt := λ a b => a ≤ b ∧ ¬ b ≤ a
lt_iff_le_not_le : ∀ a b : α, a < b ↔ (a ≤ b ∧ ¬ b ≤ a)
class PartialOrder (α : Type u) extends Preorder α :=
(le_antisymm : ∀ a b : α, a ≤ b → b ≤ a → a = b)
def Set (α : Type u) := α → Prop
def setOf {α : Type u} (p : α → Prop) : Set α :=
p
namespace Set
protected def Mem (a : α) (s : Set α) : Prop :=
s a
instance : Membership α (Set α) :=
⟨Set.Mem⟩
def range (f : ι → α) : Set α :=
setOf (λ x => ∃ y, f y = x)
end Set
class InfSet (α : Type _) where
infₛ : Set α → α
class SupSet (α : Type _) where
supₛ : Set α → α
export SupSet (supₛ)
export InfSet (infₛ)
open Set
def supᵢ {α : Type _} [SupSet α] {ι} (s : ι → α) : α :=
supₛ (range s)
def infᵢ {α : Type _} [InfSet α] {ι} (s : ι → α) : α :=
infₛ (range s)
class HasSup (α : Type u) where
sup : α → α → α
class HasInf (α : Type u) where
inf : α → α → α
@[inherit_doc]
infixl:68 " ⊔ " => HasSup.sup
@[inherit_doc]
infixl:69 " ⊓ " => HasInf.inf
class SemilatticeSup (α : Type u) extends HasSup α, PartialOrder α where
protected le_sup_left : ∀ a b : α, a ≤ a ⊔ b
protected le_sup_right : ∀ a b : α, b ≤ a ⊔ b
protected sup_le : ∀ a b c : α, a ≤ c → b ≤ c → a ⊔ b ≤ c
class SemilatticeInf (α : Type u) extends HasInf α, PartialOrder α where
protected inf_le_left : ∀ a b : α, a ⊓ b ≤ a
protected inf_le_right : ∀ a b : α, a ⊓ b ≤ b
protected le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c
class Lattice (α : Type u) extends SemilatticeSup α, SemilatticeInf α
class CompleteSemilatticeInf (α : Type _) extends PartialOrder α, InfSet α where
infₛ_le : ∀ s, ∀ a, a ∈ s → infₛ s ≤ a
le_infₛ : ∀ s a, (∀ b, b ∈ s → a ≤ b) → a ≤ infₛ s
class CompleteSemilatticeSup (α : Type _) extends PartialOrder α, SupSet α where
le_supₛ : ∀ s, ∀ a, a ∈ s → a ≤ supₛ s
supₛ_le : ∀ s a, (∀ b, b ∈ s → b ≤ a) → supₛ s ≤ a
class CompleteLattice (α : Type _) extends Lattice α, CompleteSemilatticeSup α,
CompleteSemilatticeInf α, Top α, Bot α where
protected le_top : ∀ x : α, x ≤ ⊤
protected bot_le : ∀ x : α, ⊥ ≤ x
class Frame (α : Type _) extends CompleteLattice α where
class Coframe (α : Type _) extends CompleteLattice α where
infᵢ_sup_le_sup_infₛ (a : α) (s : Set α) : (infᵢ (λ b => a ⊔ b)) ≤ a ⊔ infₛ s
-- should be ⨅ b ∈ s but I had problems with notation
class CompleteDistribLattice (α : Type _) extends Frame α where
infᵢ_sup_le_sup_infₛ : ∀ a s, (infᵢ (λ b => a ⊔ b)) ≤ a ⊔ infₛ s
-- similarly this is not quite right mathematically but this doesn't matter
-- See note [lower instance priority]
instance (priority := 100) CompleteDistribLattice.toCoframe {α : Type _} [CompleteDistribLattice α] :
Coframe α :=
{ ‹CompleteDistribLattice α› with }
class OrderTop (α : Type u) [LE α] extends Top α where
le_top : ∀ a : α, a ≤ ⊤
class OrderBot (α : Type u) [LE α] extends Bot α where
bot_le : ∀ a : α, ⊥ ≤ a
class BoundedOrder (α : Type u) [LE α] extends OrderTop α, OrderBot α
instance(priority := 100) CompleteLattice.toBoundedOrder {α : Type _} [h : CompleteLattice α] :
BoundedOrder α :=
{ h with }
namespace Pi
variable {ι : Type _} {α' : ι → Type _}
instance [∀ i, Bot (α' i)] : Bot (∀ i, α' i) :=
⟨fun _ => ⊥⟩
instance [∀ i, Top (α' i)] : Top (∀ i, α' i) :=
⟨fun _ => ⊤⟩
protected instance LE {ι : Type u} {α : ι → Type v} [∀ i, LE (α i)] : LE (∀ i, α i) where
le x y := ∀ i, x i ≤ y i
instance Preorder {ι : Type u} {α : ι → Type v} [∀ i, Preorder (α i)] : Preorder (∀ i, α i) :=
{ Pi.LE with
le_refl := sorry
le_trans := sorry
lt_iff_le_not_le := sorry }
instance PartialOrder {ι : Type u} {α : ι → Type v} [∀ i, PartialOrder (α i)] :
PartialOrder (∀ i, α i) :=
{ Pi.Preorder with
le_antisymm := sorry }
instance semilatticeSup [∀ i, SemilatticeSup (α' i)] : SemilatticeSup (∀ i, α' i) where
le_sup_left _ _ _ := SemilatticeSup.le_sup_left _ _
le_sup_right _ _ _ := SemilatticeSup.le_sup_right _ _
sup_le _ _ _ ac bc i := SemilatticeSup.sup_le _ _ _ (ac i) (bc i)
instance semilatticeInf [∀ i, SemilatticeInf (α' i)] : SemilatticeInf (∀ i, α' i) where
inf_le_left _ _ _ := SemilatticeInf.inf_le_left _ _
inf_le_right _ _ _ := SemilatticeInf.inf_le_right _ _
le_inf _ _ _ ac bc i := SemilatticeInf.le_inf _ _ _ (ac i) (bc i)
instance lattice [∀ i, Lattice (α' i)] : Lattice (∀ i, α' i) :=
{ Pi.semilatticeSup, Pi.semilatticeInf with }
instance orderTop [∀ i, LE (α' i)] [∀ i, OrderTop (α' i)] : OrderTop (∀ i, α' i) :=
{ inferInstanceAs (Top (∀ i, α' i)) with le_top := sorry }
instance orderBot [∀ i, LE (α' i)] [∀ i, OrderBot (α' i)] : OrderBot (∀ i, α' i) :=
{ inferInstanceAs (Bot (∀ i, α' i)) with bot_le := sorry }
instance boundedOrder [∀ i, LE (α' i)] [∀ i, BoundedOrder (α' i)] : BoundedOrder (∀ i, α' i) :=
{ Pi.orderTop, Pi.orderBot with }
instance SupSet {α : Type _} {β : α → Type _} [∀ i, SupSet (β i)] : SupSet (∀ i, β i) :=
⟨fun s i => supᵢ (λ (f : {f : ∀ i, β i // f ∈ s}) => f.1 i)⟩
instance InfSet {α : Type _} {β : α → Type _} [∀ i, InfSet (β i)] : InfSet (∀ i, β i) :=
⟨fun s i => infᵢ (λ (f : {f : ∀ i, β i // f ∈ s}) => f.1 i)⟩
instance completeLattice {α : Type _} {β : α → Type _} [∀ i, CompleteLattice (β i)] :
CompleteLattice (∀ i, β i) :=
{ Pi.boundedOrder, Pi.lattice with
le_supₛ := sorry
infₛ_le := sorry
supₛ_le := sorry
le_infₛ := sorry
}
instance frame {ι : Type _} {π : ι → Type _} [∀ i, Frame (π i)] : Frame (∀ i, π i) :=
{ Pi.completeLattice with }
instance coframe {ι : Type _} {π : ι → Type _} [∀ i, Coframe (π i)] : Coframe (∀ i, π i) :=
{ Pi.completeLattice with infᵢ_sup_le_sup_infₛ := sorry }
end Pi
-- very quick (instantaneous) in Lean 4
instance Pi.completeDistribLattice' {ι : Type _} {π : ι → Type _}
[∀ i, CompleteDistribLattice (π i)] : CompleteDistribLattice (∀ i, π i) :=
CompleteDistribLattice.mk (Pi.coframe.infᵢ_sup_le_sup_infₛ)
-- takes around 2 seconds wall clock time on my PC (but very quick in Lean 3)
set_option maxHeartbeats 400 -- make sure it stays fast
set_option synthInstance.maxHeartbeats 400
instance Pi.completeDistribLattice'' {ι : Type _} {π : ι → Type _}
[∀ i, CompleteDistribLattice (π i)] : CompleteDistribLattice (∀ i, π i) :=
{ Pi.frame, Pi.coframe with }
-- quick Lean 3 version:
-- https://github.com/leanprover-community/mathlib/blob/b26e15a46f1a713ce7410e016d50575bb0bc3aa4/src/order/complete_boolean_algebra.lean#L210
|
0d48eaa24cdc1a91243d860243f66412e6a32c9b | 2a70b774d16dbdf5a533432ee0ebab6838df0948 | /_target/deps/mathlib/src/algebra/archimedean.lean | 10df326163e484adc4a936ebe87e3fe36cc3ac3b | [
"Apache-2.0"
] | permissive | hjvromen/lewis | 40b035973df7c77ebf927afab7878c76d05ff758 | 105b675f73630f028ad5d890897a51b3c1146fb0 | refs/heads/master | 1,677,944,636,343 | 1,676,555,301,000 | 1,676,555,301,000 | 327,553,599 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,818 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
Archimedean groups and fields.
-/
import algebra.field_power
import data.rat
variables {α : Type*}
/-- An ordered additive commutative monoid is called `archimedean` if for any two elements `x`, `y`
such that `0 < y` there exists a natural number `n` such that `x ≤ n •ℕ y`. -/
class archimedean (α) [ordered_add_comm_monoid α] : Prop :=
(arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n •ℕ y)
namespace linear_ordered_add_comm_group
variables [linear_ordered_add_comm_group α] [archimedean α]
/-- An archimedean decidable linearly ordered `add_comm_group` has a version of the floor: for
`a > 0`, any `g` in the group lies between some two consecutive multiples of `a`. -/
lemma exists_int_smul_near_of_pos {a : α} (ha : 0 < a) (g : α) :
∃ k, k •ℤ a ≤ g ∧ g < (k + 1) •ℤ a :=
begin
let s : set ℤ := {n : ℤ | n •ℤ a ≤ g},
obtain ⟨k, hk : -g ≤ k •ℕ a⟩ := archimedean.arch (-g) ha,
have h_ne : s.nonempty := ⟨-k, by simpa using neg_le_neg hk⟩,
obtain ⟨k, hk⟩ := archimedean.arch g ha,
have h_bdd : ∀ n ∈ s, n ≤ (k : ℤ) :=
λ n hn, (gsmul_le_gsmul_iff ha).mp (le_trans hn hk : n •ℤ a ≤ k •ℤ a),
obtain ⟨m, hm, hm'⟩ := int.exists_greatest_of_bdd ⟨k, h_bdd⟩ h_ne,
refine ⟨m, hm, _⟩,
by_contra H,
linarith [hm' _ $ not_lt.mp H]
end
lemma exists_int_smul_near_of_pos' {a : α} (ha : 0 < a) (g : α) :
∃ k, 0 ≤ g - k •ℤ a ∧ g - k •ℤ a < a :=
begin
obtain ⟨k, h1, h2⟩ := exists_int_smul_near_of_pos ha g,
refine ⟨k, sub_nonneg.mpr h1, _⟩,
have : g < k •ℤ a + 1 •ℤ a, by rwa ← add_gsmul a k 1,
simpa [sub_lt_iff_lt_add']
end
end linear_ordered_add_comm_group
theorem exists_nat_gt [ordered_semiring α] [nontrivial α] [archimedean α]
(x : α) : ∃ n : ℕ, x < n :=
let ⟨n, h⟩ := archimedean.arch x zero_lt_one in
⟨n+1, lt_of_le_of_lt (by rwa ← nsmul_one)
(nat.cast_lt.2 (nat.lt_succ_self _))⟩
theorem exists_nat_ge [ordered_semiring α] [archimedean α] (x : α) :
∃ n : ℕ, x ≤ n :=
begin
nontriviality α,
exact (exists_nat_gt x).imp (λ n, le_of_lt)
end
lemma add_one_pow_unbounded_of_pos [ordered_semiring α] [nontrivial α] [archimedean α]
(x : α) {y : α} (hy : 0 < y) :
∃ n : ℕ, x < (y + 1) ^ n :=
let ⟨n, h⟩ := archimedean.arch x hy in
⟨n, calc x ≤ n •ℕ y : h
... < 1 + n •ℕ y : lt_one_add _
... ≤ (1 + y) ^ n : one_add_mul_le_pow' (mul_nonneg (le_of_lt hy) (le_of_lt hy))
(le_of_lt $ lt_trans hy (lt_one_add y)) _
... = (y + 1) ^ n : by rw [add_comm]⟩
section linear_ordered_ring
variables [linear_ordered_ring α] [archimedean α]
lemma pow_unbounded_of_one_lt (x : α) {y : α} (hy1 : 1 < y) :
∃ n : ℕ, x < y ^ n :=
sub_add_cancel y 1 ▸ add_one_pow_unbounded_of_pos _ (sub_pos.2 hy1)
/-- Every x greater than or equal to 1 is between two successive
natural-number powers of every y greater than one. -/
lemma exists_nat_pow_near {x : α} {y : α} (hx : 1 ≤ x) (hy : 1 < y) :
∃ n : ℕ, y ^ n ≤ x ∧ x < y ^ (n + 1) :=
have h : ∃ n : ℕ, x < y ^ n, from pow_unbounded_of_one_lt _ hy,
by classical; exact let n := nat.find h in
have hn : x < y ^ n, from nat.find_spec h,
have hnp : 0 < n, from pos_iff_ne_zero.2 (λ hn0,
by rw [hn0, pow_zero] at hn; exact (not_le_of_gt hn hx)),
have hnsp : nat.pred n + 1 = n, from nat.succ_pred_eq_of_pos hnp,
have hltn : nat.pred n < n, from nat.pred_lt (ne_of_gt hnp),
⟨nat.pred n, le_of_not_lt (nat.find_min h hltn), by rwa hnsp⟩
theorem exists_int_gt (x : α) : ∃ n : ℤ, x < n :=
let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa ← coe_coe⟩
theorem exists_int_lt (x : α) : ∃ n : ℤ, (n : α) < x :=
let ⟨n, h⟩ := exists_int_gt (-x) in ⟨-n, by rw int.cast_neg; exact neg_lt.1 h⟩
theorem exists_floor (x : α) :
∃ (fl : ℤ), ∀ (z : ℤ), z ≤ fl ↔ (z : α) ≤ x :=
begin
haveI := classical.prop_decidable,
have : ∃ (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⟩),
refine this.imp (λ fl h z, _),
cases h with h₁ h₂,
exact ⟨λ h, le_trans (int.cast_le.2 h) h₁, h₂ z⟩,
end
end linear_ordered_ring
section linear_ordered_field
variables [linear_ordered_field α]
/-- Every positive `x` is between two successive integer powers of
another `y` greater than one. This is the same as `exists_int_pow_near'`,
but with ≤ and < the other way around. -/
lemma exists_int_pow_near [archimedean α]
{x : α} {y : α} (hx : 0 < x) (hy : 1 < y) :
∃ n : ℤ, y ^ n ≤ x ∧ x < y ^ (n + 1) :=
by classical; exact
let ⟨N, hN⟩ := pow_unbounded_of_one_lt x⁻¹ hy in
have he: ∃ m : ℤ, y ^ m ≤ x, from
⟨-N, le_of_lt (by rw [(fpow_neg y (↑N))];
exact (inv_lt hx (lt_trans (inv_pos.2 hx) hN)).1 hN)⟩,
let ⟨M, hM⟩ := pow_unbounded_of_one_lt x hy in
have hb: ∃ b : ℤ, ∀ m, y ^ m ≤ x → m ≤ b, from
⟨M, λ m hm, le_of_not_lt (λ hlt, not_lt_of_ge
(fpow_le_of_le (le_of_lt hy) (le_of_lt hlt)) (lt_of_le_of_lt hm hM))⟩,
let ⟨n, hn₁, hn₂⟩ := int.exists_greatest_of_bdd hb he in
⟨n, hn₁, lt_of_not_ge (λ hge, not_le_of_gt (int.lt_succ _) (hn₂ _ hge))⟩
/-- Every positive `x` is between two successive integer powers of
another `y` greater than one. This is the same as `exists_int_pow_near`,
but with ≤ and < the other way around. -/
lemma exists_int_pow_near' [archimedean α]
{x : α} {y : α} (hx : 0 < x) (hy : 1 < y) :
∃ n : ℤ, y ^ n < x ∧ x ≤ y ^ (n + 1) :=
let ⟨m, hle, hlt⟩ := exists_int_pow_near (inv_pos.2 hx) hy in
have hyp : 0 < y, from lt_trans zero_lt_one hy,
⟨-(m+1),
by rwa [fpow_neg, inv_lt (fpow_pos_of_pos hyp _) hx],
by rwa [neg_add, neg_add_cancel_right, fpow_neg,
le_inv hx (fpow_pos_of_pos hyp _)]⟩
/-- For any `y < 1` and any positive `x`, there exists `n : ℕ` with `y ^ n < x`. -/
lemma exists_pow_lt_of_lt_one [archimedean α] {x y : α} (hx : 0 < x) (hy : y < 1) :
∃ n : ℕ, y ^ n < x :=
begin
by_cases y_pos : y ≤ 0,
{ use 1, simp only [pow_one], linarith, },
rw [not_le] at y_pos,
rcases pow_unbounded_of_one_lt (x⁻¹) (one_lt_inv y_pos hy) with ⟨q, hq⟩,
exact ⟨q, by rwa [inv_pow', inv_lt_inv hx (pow_pos y_pos _)] at hq⟩
end
/-- Given `x` and `y` between `0` and `1`, `x` is between two successive powers of `y`.
This is the same as `exists_nat_pow_near`, but for elements between `0` and `1` -/
lemma exists_nat_pow_near_of_lt_one [archimedean α]
{x : α} {y : α} (xpos : 0 < x) (hx : x ≤ 1) (ypos : 0 < y) (hy : y < 1) :
∃ n : ℕ, y ^ (n + 1) < x ∧ x ≤ y ^ n :=
begin
rcases exists_nat_pow_near (one_le_inv_iff.2 ⟨xpos, hx⟩) (one_lt_inv_iff.2 ⟨ypos, hy⟩)
with ⟨n, hn, h'n⟩,
refine ⟨n, _, _⟩,
{ rwa [inv_pow', inv_lt_inv xpos (pow_pos ypos _)] at h'n },
{ rwa [inv_pow', inv_le_inv (pow_pos ypos _) xpos] at hn }
end
variables [floor_ring α]
lemma sub_floor_div_mul_nonneg (x : α) {y : α} (hy : 0 < y) :
0 ≤ x - ⌊x / y⌋ * y :=
begin
conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm},
rw ← sub_mul,
exact mul_nonneg (sub_nonneg.2 (floor_le _)) (le_of_lt hy)
end
lemma sub_floor_div_mul_lt (x : α) {y : α} (hy : 0 < y) :
x - ⌊x / y⌋ * y < y :=
sub_lt_iff_lt_add.2 begin
conv in y {rw ← one_mul y},
conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm},
rw ← add_mul,
exact (mul_lt_mul_right hy).2 (by rw add_comm; exact lt_floor_add_one _),
end
end linear_ordered_field
instance : archimedean ℕ :=
⟨λ n m m0, ⟨n, by simpa only [mul_one, nat.nsmul_eq_mul] using nat.mul_le_mul_left n m0⟩⟩
instance : archimedean ℤ :=
⟨λ n m m0, ⟨n.to_nat, le_trans (int.le_to_nat _) $
by simpa only [nsmul_eq_mul, int.nat_cast_eq_coe_nat, zero_add, mul_one]
using mul_le_mul_of_nonneg_left (int.add_one_le_iff.2 m0) (int.coe_zero_le n.to_nat)⟩⟩
/-- A linear ordered archimedean ring is a floor ring. This is not an `instance` because in some
cases we have a computable `floor` function. -/
noncomputable def archimedean.floor_ring (α)
[linear_ordered_ring α] [archimedean α] : floor_ring α :=
{ floor := λ x, classical.some (exists_floor x),
le_floor := λ z x, classical.some_spec (exists_floor x) z }
section linear_ordered_field
variables [linear_ordered_field α]
theorem archimedean_iff_nat_lt :
archimedean α ↔ ∀ x : α, ∃ n : ℕ, x < n :=
⟨@exists_nat_gt α _ _, λ H, ⟨λ x y y0,
(H (x / y)).imp $ λ n h, le_of_lt $
by rwa [div_lt_iff y0, ← nsmul_eq_mul] at h⟩⟩
theorem archimedean_iff_nat_le :
archimedean α ↔ ∀ x : α, ∃ n : ℕ, x ≤ n :=
archimedean_iff_nat_lt.trans
⟨λ H x, (H x).imp $ λ _, le_of_lt,
λ H x, let ⟨n, h⟩ := H x in ⟨n+1,
lt_of_le_of_lt h (nat.cast_lt.2 (lt_add_one _))⟩⟩
theorem exists_rat_gt [archimedean α] (x : α) : ∃ q : ℚ, x < q :=
let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa rat.cast_coe_nat⟩
theorem archimedean_iff_rat_lt :
archimedean α ↔ ∀ x : α, ∃ q : ℚ, x < q :=
⟨@exists_rat_gt α _,
λ H, archimedean_iff_nat_lt.2 $ λ x,
let ⟨q, h⟩ := H x in
⟨nat_ceil q, lt_of_lt_of_le h $
by simpa only [rat.cast_coe_nat] using (@rat.cast_le α _ _ _).2 (le_nat_ceil _)⟩⟩
theorem archimedean_iff_rat_le :
archimedean α ↔ ∀ x : α, ∃ q : ℚ, x ≤ q :=
archimedean_iff_rat_lt.trans
⟨λ H x, (H x).imp $ λ _, le_of_lt,
λ H x, let ⟨n, h⟩ := H x in ⟨n+1,
lt_of_le_of_lt h (rat.cast_lt.2 (lt_add_one _))⟩⟩
variable [archimedean α]
theorem exists_rat_lt (x : α) : ∃ q : ℚ, (q : α) < x :=
let ⟨n, h⟩ := exists_int_lt x in ⟨n, by rwa rat.cast_coe_int⟩
theorem exists_rat_btwn {x y : α} (h : x < y) : ∃ q : ℚ, x < q ∧ (q:α) < y :=
begin
cases exists_nat_gt (y - x)⁻¹ with n nh,
cases exists_floor (x * n) with z zh,
refine ⟨(z + 1 : ℤ) / n, _⟩,
have n0' := (inv_pos.2 (sub_pos.2 h)).trans nh,
have n0 := nat.cast_pos.1 n0',
rw [rat.cast_div_of_ne_zero, rat.cast_coe_nat, rat.cast_coe_int, div_lt_iff n0'],
refine ⟨(lt_div_iff n0').2 $
(lt_iff_lt_of_le_iff_le (zh _)).1 (lt_add_one _), _⟩,
rw [int.cast_add, int.cast_one],
refine lt_of_le_of_lt (add_le_add_right ((zh _).1 (le_refl _)) _) _,
rwa [← lt_sub_iff_add_lt', ← sub_mul,
← div_lt_iff' (sub_pos.2 h), one_div],
{ rw [rat.coe_int_denom, nat.cast_one], exact one_ne_zero },
{ intro H, rw [rat.coe_nat_num, ← coe_coe, nat.cast_eq_zero] at H, subst H, cases n0 },
{ rw [rat.coe_nat_denom, nat.cast_one], exact one_ne_zero }
end
theorem exists_nat_one_div_lt {ε : α} (hε : 0 < ε) : ∃ n : ℕ, 1 / (n + 1: α) < ε :=
begin
cases exists_nat_gt (1/ε) with n hn,
use n,
rw [div_lt_iff, ← div_lt_iff' hε],
{ apply hn.trans,
simp [zero_lt_one] },
{ exact n.cast_add_one_pos }
end
theorem exists_pos_rat_lt {x : α} (x0 : 0 < x) : ∃ q : ℚ, 0 < q ∧ (q : α) < x :=
by simpa only [rat.cast_pos] using exists_rat_btwn x0
include α
@[simp] theorem rat.cast_floor (x : ℚ) :
by haveI := archimedean.floor_ring α; exact ⌊(x:α)⌋ = ⌊x⌋ :=
begin
haveI := archimedean.floor_ring α,
apply le_antisymm,
{ rw [le_floor, ← @rat.cast_le α, rat.cast_coe_int],
apply floor_le },
{ rw [le_floor, ← rat.cast_coe_int, rat.cast_le],
apply floor_le }
end
end linear_ordered_field
section
variables [linear_ordered_field α]
/-- `round` rounds a number to the nearest integer. `round (1 / 2) = 1` -/
def round [floor_ring α] (x : α) : ℤ := ⌊x + 1 / 2⌋
lemma abs_sub_round [floor_ring α] (x : α) : abs (x - round x) ≤ 1 / 2 :=
begin
rw [round, abs_sub_le_iff],
have := floor_le (x + 1 / 2),
have := lt_floor_add_one (x + 1 / 2),
split; linarith
end
variable [archimedean α]
theorem exists_rat_near (x : α) {ε : α} (ε0 : 0 < ε) :
∃ q : ℚ, abs (x - q) < ε :=
let ⟨q, h₁, h₂⟩ := exists_rat_btwn $
lt_trans ((sub_lt_self_iff x).2 ε0) ((lt_add_iff_pos_left x).2 ε0) in
⟨q, abs_sub_lt_iff.2 ⟨sub_lt.1 h₁, sub_lt_iff_lt_add.2 h₂⟩⟩
instance : archimedean ℚ :=
archimedean_iff_rat_le.2 $ λ q, ⟨q, by rw rat.cast_id⟩
@[simp] theorem rat.cast_round (x : ℚ) : by haveI := archimedean.floor_ring α;
exact round (x:α) = round x :=
have ((x + (1 : ℚ) / (2 : ℚ) : ℚ) : α) = x + 1 / 2, by simp,
by rw [round, round, ← this, rat.cast_floor]
end
|
423499b76032f3eb3bb41455a9f3bdefd482856a | 367134ba5a65885e863bdc4507601606690974c1 | /src/combinatorics/simple_graph/matching.lean | f2453f016b07042d82ce8bd8e26d79fd01301542 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 2,010 | lean | /-
Copyright (c) 2020 Alena Gusakov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Alena Gusakov.
-/
import data.fintype.basic
import data.sym2
import combinatorics.simple_graph.basic
/-!
# Matchings
## Main definitions
* a `matching` on a simple graph is a subset of its edge set such that
no two edges share an endpoint.
* a `perfect_matching` on a simple graph is a matching in which every
vertex belongs to an edge.
TODO:
- Lemma stating that the existence of a perfect matching on `G` implies that
the cardinality of `V` is even (assuming it's finite)
- Hall's Marriage Theorem
- Tutte's Theorem
- consider coercions instead of type definition for `matching`:
https://github.com/leanprover-community/mathlib/pull/5156#discussion_r532935457
- consider expressing `matching_verts` as union:
https://github.com/leanprover-community/mathlib/pull/5156#discussion_r532906131
TODO: Tutte and Hall require a definition of subgraphs.
-/
open finset
universe u
namespace simple_graph
variables {V : Type u} (G : simple_graph V)
/--
A matching on `G` is a subset of its edges such that no two edges share a vertex.
-/
structure matching :=
(edges : set (sym2 V))
(sub_edges : edges ⊆ G.edge_set)
(disjoint : ∀ (x y ∈ edges) (v : V), v ∈ x ∧ v ∈ y → x = y)
instance : inhabited (matching G) :=
⟨⟨∅, set.empty_subset _, λ _ _ hx, false.elim (set.not_mem_empty _ hx)⟩⟩
variables {G}
/--
`M.support` is the set of vertices of `G` that are
contained in some edge of matching `M`
-/
def matching.support (M : G.matching) : set V :=
{v : V | ∃ x ∈ M.edges, v ∈ x}
/--
A perfect matching `M` on graph `G` is a matching such that
every vertex is contained in an edge of `M`.
-/
def matching.is_perfect (M : G.matching) : Prop :=
M.support = set.univ
lemma matching.is_perfect_iff (M : G.matching) :
M.is_perfect ↔ ∀ (v : V), ∃ e ∈ M.edges, v ∈ e :=
set.eq_univ_iff_forall
end simple_graph
|
84b100400878b73d8c1e83017a3efadddeda90a9 | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /library/data/list/comb.lean | 030b4c937d5a1cda1e904ee32c8349281c7a6ada | [
"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 | 21,031 | lean | /-
Copyright (c) 2015 Leonardo de Moura. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Haitao Zhang
List combinators.
-/
import data.list.basic data.equiv
open nat prod decidable function helper_tactics
namespace list
variables {A B C : Type}
/- map -/
definition map (f : A → B) : list A → list B
| [] := []
| (a :: l) := f a :: map l
theorem map_nil (f : A → B) : map f [] = []
theorem map_cons (f : A → B) (a : A) (l : list A) : map f (a :: l) = f a :: map f l
lemma map_append (f : A → B) : ∀ l₁ l₂, map f (l₁++l₂) = (map f l₁)++(map f l₂)
| nil := take l, rfl
| (a::l) := take l', begin rewrite [append_cons, *map_cons, append_cons, map_append] end
lemma map_singleton (f : A → B) (a : A) : map f [a] = [f a] := rfl
theorem map_id [simp] : ∀ l : list A, map id l = l
| [] := rfl
| (x::xs) := begin rewrite [map_cons, map_id] end
theorem map_id' {f : A → A} (H : ∀x, f x = x) : ∀ l : list A, map f l = l
| [] := rfl
| (x::xs) := begin rewrite [map_cons, H, map_id'] end
theorem map_map [simp] (g : B → C) (f : A → B) : ∀ l, map g (map f l) = map (g ∘ f) l
| [] := rfl
| (a :: l) :=
show (g ∘ f) a :: map g (map f l) = map (g ∘ f) (a :: l),
by rewrite (map_map l)
theorem length_map [simp] (f : A → B) : ∀ l : list A, length (map f l) = length l
| [] := by esimp
| (a :: l) :=
show length (map f l) + 1 = length l + 1,
by rewrite (length_map l)
theorem mem_map {A B : Type} (f : A → B) : ∀ {a l}, a ∈ l → f a ∈ map f l
| a [] i := absurd i !not_mem_nil
| a (x::xs) i := or.elim (eq_or_mem_of_mem_cons i)
(suppose a = x, by rewrite [this, map_cons]; apply mem_cons)
(suppose a ∈ xs, or.inr (mem_map this))
theorem exists_of_mem_map {A B : Type} {f : A → B} {b : B} :
∀{l}, b ∈ map f l → ∃a, a ∈ l ∧ f a = b
| [] H := false.elim H
| (c::l) H := or.elim (iff.mp !mem_cons_iff H)
(suppose b = f c,
exists.intro c (and.intro !mem_cons (eq.symm this)))
(suppose b ∈ map f l,
obtain a (Hl : a ∈ l) (Hr : f a = b), from exists_of_mem_map this,
exists.intro a (and.intro (mem_cons_of_mem _ Hl) Hr))
theorem eq_of_map_const {A B : Type} {b₁ b₂ : B} : ∀ {l : list A}, b₁ ∈ map (const A b₂) l → b₁ = b₂
| [] h := absurd h !not_mem_nil
| (a::l) h :=
or.elim (eq_or_mem_of_mem_cons h)
(suppose b₁ = b₂, this)
(suppose b₁ ∈ map (const A b₂) l, eq_of_map_const this)
definition map₂ (f : A → B → C) : list A → list B → list C
| [] _ := []
| _ [] := []
| (x::xs) (y::ys) := f x y :: map₂ xs ys
/- filter -/
definition filter (p : A → Prop) [h : decidable_pred p] : list A → list A
| [] := []
| (a::l) := if p a then a :: filter l else filter l
theorem filter_nil [simp] (p : A → Prop) [h : decidable_pred p] : filter p [] = []
theorem filter_cons_of_pos [simp] {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ l, p a → filter p (a::l) = a :: filter p l :=
λ l pa, if_pos pa
theorem filter_cons_of_neg [simp] {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ l, ¬ p a → filter p (a::l) = filter p l :=
λ l pa, if_neg pa
theorem of_mem_filter {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ {l}, a ∈ filter p l → p a
| [] ain := absurd ain !not_mem_nil
| (b::l) ain := by_cases
(assume pb : p b,
have a ∈ b :: filter p l, by rewrite [filter_cons_of_pos _ pb at ain]; exact ain,
or.elim (eq_or_mem_of_mem_cons this)
(suppose a = b, by rewrite [-this at pb]; exact pb)
(suppose a ∈ filter p l, of_mem_filter this))
(suppose ¬ p b, by rewrite [filter_cons_of_neg _ this at ain]; exact (of_mem_filter ain))
theorem mem_of_mem_filter {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ {l}, a ∈ filter p l → a ∈ l
| [] ain := absurd ain !not_mem_nil
| (b::l) ain := by_cases
(λ pb : p b,
have a ∈ b :: filter p l, by rewrite [filter_cons_of_pos _ pb at ain]; exact ain,
or.elim (eq_or_mem_of_mem_cons this)
(suppose a = b, by rewrite this; exact !mem_cons)
(suppose a ∈ filter p l, mem_cons_of_mem _ (mem_of_mem_filter this)))
(suppose ¬ p b, by rewrite [filter_cons_of_neg _ this at ain]; exact (mem_cons_of_mem _ (mem_of_mem_filter ain)))
theorem mem_filter_of_mem {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ {l}, a ∈ l → p a → a ∈ filter p l
| [] ain pa := absurd ain !not_mem_nil
| (b::l) ain pa := by_cases
(λ pb : p b, or.elim (eq_or_mem_of_mem_cons ain)
(λ aeqb : a = b, by rewrite [filter_cons_of_pos _ pb, aeqb]; exact !mem_cons)
(λ ainl : a ∈ l, by rewrite [filter_cons_of_pos _ pb]; exact (mem_cons_of_mem _ (mem_filter_of_mem ainl pa))))
(λ npb : ¬ p b, or.elim (eq_or_mem_of_mem_cons ain)
(λ aeqb : a = b, absurd (eq.rec_on aeqb pa) npb)
(λ ainl : a ∈ l, by rewrite [filter_cons_of_neg _ npb]; exact (mem_filter_of_mem ainl pa)))
theorem filter_sub [simp] {p : A → Prop} [h : decidable_pred p] (l : list A) : filter p l ⊆ l :=
λ a ain, mem_of_mem_filter ain
theorem filter_append {p : A → Prop} [h : decidable_pred p] : ∀ (l₁ l₂ : list A), filter p (l₁++l₂) = filter p l₁ ++ filter p l₂
| [] l₂ := rfl
| (a::l₁) l₂ := by_cases
(suppose p a, by rewrite [append_cons, *filter_cons_of_pos _ this, filter_append])
(suppose ¬ p a, by rewrite [append_cons, *filter_cons_of_neg _ this, filter_append])
/- foldl & foldr -/
definition foldl (f : A → B → A) : A → list B → A
| a [] := a
| a (b :: l) := foldl (f a b) l
theorem foldl_nil [simp] (f : A → B → A) (a : A) : foldl f a [] = a
theorem foldl_cons [simp] (f : A → B → A) (a : A) (b : B) (l : list B) : foldl f a (b::l) = foldl f (f a b) l
definition foldr (f : A → B → B) : B → list A → B
| b [] := b
| b (a :: l) := f a (foldr b l)
theorem foldr_nil [simp] (f : A → B → B) (b : B) : foldr f b [] = b
theorem foldr_cons [simp] (f : A → B → B) (b : B) (a : A) (l : list A) : foldr f b (a::l) = f a (foldr f b l)
section foldl_eq_foldr
-- foldl and foldr coincide when f is commutative and associative
parameters {α : Type} {f : α → α → α}
hypothesis (Hcomm : ∀ a b, f a b = f b a)
hypothesis (Hassoc : ∀ a b c, f (f a b) c = f a (f b c))
include Hcomm Hassoc
theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l)
| a b nil := Hcomm a b
| a b (c::l) :=
begin
change foldl f (f (f a b) c) l = f b (foldl f (f a c) l),
rewrite -foldl_eq_of_comm_of_assoc,
change foldl f (f (f a b) c) l = foldl f (f (f a c) b) l,
have H₁ : f (f a b) c = f (f a c) b, by rewrite [Hassoc, Hassoc, Hcomm b c],
rewrite H₁
end
theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l
| a nil := rfl
| a (b :: l) :=
begin
rewrite foldl_eq_of_comm_of_assoc,
esimp,
change f b (foldl f a l) = f b (foldr f a l),
rewrite foldl_eq_foldr
end
end foldl_eq_foldr
theorem foldl_append [simp] (f : B → A → B) : ∀ (b : B) (l₁ l₂ : list A), foldl f b (l₁++l₂) = foldl f (foldl f b l₁) l₂
| b [] l₂ := rfl
| b (a::l₁) l₂ := by rewrite [append_cons, *foldl_cons, foldl_append]
theorem foldr_append [simp] (f : A → B → B) : ∀ (b : B) (l₁ l₂ : list A), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁
| b [] l₂ := rfl
| b (a::l₁) l₂ := by rewrite [append_cons, *foldr_cons, foldr_append]
/- all & any -/
definition all (l : list A) (p : A → Prop) : Prop :=
foldr (λ a r, p a ∧ r) true l
definition any (l : list A) (p : A → Prop) : Prop :=
foldr (λ a r, p a ∨ r) false l
theorem all_nil_eq [simp] (p : A → Prop) : all [] p = true
theorem all_nil (p : A → Prop) : all [] p := trivial
theorem all_cons_eq (p : A → Prop) (a : A) (l : list A) : all (a::l) p = (p a ∧ all l p)
theorem all_cons {p : A → Prop} {a : A} {l : list A} (H1 : p a) (H2 : all l p) : all (a::l) p :=
and.intro H1 H2
theorem all_of_all_cons {p : A → Prop} {a : A} {l : list A} : all (a::l) p → all l p :=
assume h, by rewrite [all_cons_eq at h]; exact (and.elim_right h)
theorem of_all_cons {p : A → Prop} {a : A} {l : list A} : all (a::l) p → p a :=
assume h, by rewrite [all_cons_eq at h]; exact (and.elim_left h)
theorem all_cons_of_all {p : A → Prop} {a : A} {l : list A} : p a → all l p → all (a::l) p :=
assume pa alllp, and.intro pa alllp
theorem all_implies {p q : A → Prop} : ∀ {l}, all l p → (∀ x, p x → q x) → all l q
| [] h₁ h₂ := trivial
| (a::l) h₁ h₂ :=
have all l q, from all_implies (all_of_all_cons h₁) h₂,
have q a, from h₂ a (of_all_cons h₁),
all_cons_of_all this `all l q`
theorem of_mem_of_all {p : A → Prop} {a : A} : ∀ {l}, a ∈ l → all l p → p a
| [] h₁ h₂ := absurd h₁ !not_mem_nil
| (b::l) h₁ h₂ :=
or.elim (eq_or_mem_of_mem_cons h₁)
(suppose a = b,
by rewrite [all_cons_eq at h₂, -this at h₂]; exact (and.elim_left h₂))
(suppose a ∈ l,
have all l p, by rewrite [all_cons_eq at h₂]; exact (and.elim_right h₂),
of_mem_of_all `a ∈ l` this)
theorem all_of_forall {p : A → Prop} : ∀ {l}, (∀a, a ∈ l → p a) → all l p
| [] H := !all_nil
| (a::l) H := all_cons (H a !mem_cons)
(all_of_forall (λ a' H', H a' (mem_cons_of_mem _ H')))
theorem any_nil [simp] (p : A → Prop) : any [] p = false
theorem any_cons [simp] (p : A → Prop) (a : A) (l : list A) : any (a::l) p = (p a ∨ any l p)
theorem any_of_mem {p : A → Prop} {a : A} : ∀ {l}, a ∈ l → p a → any l p
| [] i h := absurd i !not_mem_nil
| (b::l) i h :=
or.elim (eq_or_mem_of_mem_cons i)
(suppose a = b, by rewrite [-this]; exact (or.inl h))
(suppose a ∈ l,
have any l p, from any_of_mem this h,
or.inr this)
theorem exists_of_any {p : A → Prop} : ∀{l : list A}, any l p → ∃a, a ∈ l ∧ p a
| [] H := false.elim H
| (b::l) H := or.elim H
(assume H1 : p b, exists.intro b (and.intro !mem_cons H1))
(assume H1 : any l p,
obtain a (H2l : a ∈ l) (H2r : p a), from exists_of_any H1,
exists.intro a (and.intro (mem_cons_of_mem b H2l) H2r))
definition decidable_all (p : A → Prop) [H : decidable_pred p] : ∀ l, decidable (all l p)
| [] := decidable_true
| (a :: l) :=
match H a with
| inl Hp₁ :=
match decidable_all l with
| inl Hp₂ := inl (and.intro Hp₁ Hp₂)
| inr Hn₂ := inr (not_and_of_not_right (p a) Hn₂)
end
| inr Hn := inr (not_and_of_not_left (all l p) Hn)
end
definition decidable_any (p : A → Prop) [H : decidable_pred p] : ∀ l, decidable (any l p)
| [] := decidable_false
| (a :: l) :=
match H a with
| inl Hp := inl (or.inl Hp)
| inr Hn₁ :=
match decidable_any l with
| inl Hp₂ := inl (or.inr Hp₂)
| inr Hn₂ := inr (not_or Hn₁ Hn₂)
end
end
/- zip & unzip -/
definition zip (l₁ : list A) (l₂ : list B) : list (A × B) :=
map₂ (λ a b, (a, b)) l₁ l₂
definition unzip : list (A × B) → list A × list B
| [] := ([], [])
| ((a, b) :: l) :=
match unzip l with
| (la, lb) := (a :: la, b :: lb)
end
theorem unzip_nil [simp] : unzip (@nil (A × B)) = ([], [])
theorem unzip_cons [simp] (a : A) (b : B) (l : list (A × B)) :
unzip ((a, b) :: l) = match unzip l with (la, lb) := (a :: la, b :: lb) end :=
rfl
theorem zip_unzip : ∀ (l : list (A × B)), zip (pr₁ (unzip l)) (pr₂ (unzip l)) = l
| [] := rfl
| ((a, b) :: l) :=
begin
rewrite unzip_cons,
have r : zip (pr₁ (unzip l)) (pr₂ (unzip l)) = l, from zip_unzip l,
revert r,
eapply prod.cases_on (unzip l),
intro la lb r,
rewrite -r
end
/- flat -/
definition flat (l : list (list A)) : list A :=
foldl append nil l
/- product -/
section product
definition product : list A → list B → list (A × B)
| [] l₂ := []
| (a::l₁) l₂ := map (λ b, (a, b)) l₂ ++ product l₁ l₂
theorem nil_product (l : list B) : product (@nil A) l = []
theorem product_cons (a : A) (l₁ : list A) (l₂ : list B)
: product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂
theorem product_nil : ∀ (l : list A), product l (@nil B) = []
| [] := rfl
| (a::l) := by rewrite [product_cons, map_nil, product_nil]
theorem eq_of_mem_map_pair₁ {a₁ a : A} {b₁ : B} {l : list B} : (a₁, b₁) ∈ map (λ b, (a, b)) l → a₁ = a :=
assume ain,
assert pr1 (a₁, b₁) ∈ map pr1 (map (λ b, (a, b)) l), from mem_map pr1 ain,
assert a₁ ∈ map (λb, a) l, by revert this; rewrite [map_map, ↑pr1]; intro this; assumption,
eq_of_map_const this
theorem mem_of_mem_map_pair₁ {a₁ a : A} {b₁ : B} {l : list B} : (a₁, b₁) ∈ map (λ b, (a, b)) l → b₁ ∈ l :=
assume ain,
assert pr2 (a₁, b₁) ∈ map pr2 (map (λ b, (a, b)) l), from mem_map pr2 ain,
assert b₁ ∈ map (λx, x) l, by rewrite [map_map at this, ↑pr2 at this]; exact this,
by rewrite [map_id at this]; exact this
theorem mem_product {a : A} {b : B} : ∀ {l₁ l₂}, a ∈ l₁ → b ∈ l₂ → (a, b) ∈ product l₁ l₂
| [] l₂ h₁ h₂ := absurd h₁ !not_mem_nil
| (x::l₁) l₂ h₁ h₂ :=
or.elim (eq_or_mem_of_mem_cons h₁)
(assume aeqx : a = x,
assert (a, b) ∈ map (λ b, (a, b)) l₂, from mem_map _ h₂,
begin rewrite [-aeqx, product_cons], exact mem_append_left _ this end)
(assume ainl₁ : a ∈ l₁,
assert (a, b) ∈ product l₁ l₂, from mem_product ainl₁ h₂,
begin rewrite [product_cons], exact mem_append_right _ this end)
theorem mem_of_mem_product_left {a : A} {b : B} : ∀ {l₁ l₂}, (a, b) ∈ product l₁ l₂ → a ∈ l₁
| [] l₂ h := absurd h !not_mem_nil
| (x::l₁) l₂ h :=
or.elim (mem_or_mem_of_mem_append h)
(suppose (a, b) ∈ map (λ b, (x, b)) l₂,
assert a = x, from eq_of_mem_map_pair₁ this,
by rewrite this; exact !mem_cons)
(suppose (a, b) ∈ product l₁ l₂,
have a ∈ l₁, from mem_of_mem_product_left this,
mem_cons_of_mem _ this)
theorem mem_of_mem_product_right {a : A} {b : B} : ∀ {l₁ l₂}, (a, b) ∈ product l₁ l₂ → b ∈ l₂
| [] l₂ h := absurd h !not_mem_nil
| (x::l₁) l₂ h :=
or.elim (mem_or_mem_of_mem_append h)
(suppose (a, b) ∈ map (λ b, (x, b)) l₂,
mem_of_mem_map_pair₁ this)
(suppose (a, b) ∈ product l₁ l₂,
mem_of_mem_product_right this)
theorem length_product : ∀ (l₁ : list A) (l₂ : list B), length (product l₁ l₂) = length l₁ * length l₂
| [] l₂ := by rewrite [length_nil, zero_mul]
| (x::l₁) l₂ :=
assert length (product l₁ l₂) = length l₁ * length l₂, from length_product l₁ l₂,
by rewrite [product_cons, length_append, length_cons,
length_map, this, mul.right_distrib, one_mul, add.comm]
end product
-- new for list/comb dependent map theory
definition dinj₁ (p : A → Prop) (f : Π a, p a → B) := ∀ ⦃a1 a2⦄ (h1 : p a1) (h2 : p a2), a1 ≠ a2 → (f a1 h1) ≠ (f a2 h2)
definition dinj (p : A → Prop) (f : Π a, p a → B) := ∀ ⦃a1 a2⦄ (h1 : p a1) (h2 : p a2), (f a1 h1) = (f a2 h2) → a1 = a2
definition dmap (p : A → Prop) [h : decidable_pred p] (f : Π a, p a → B) : list A → list B
| [] := []
| (a::l) := if P : (p a) then cons (f a P) (dmap l) else (dmap l)
-- properties of dmap
section dmap
variable {p : A → Prop}
variable [h : decidable_pred p]
include h
variable {f : Π a, p a → B}
lemma dmap_nil : dmap p f [] = [] := rfl
lemma dmap_cons_of_pos {a : A} (P : p a) : ∀ l, dmap p f (a::l) = (f a P) :: dmap p f l :=
λ l, dif_pos P
lemma dmap_cons_of_neg {a : A} (P : ¬ p a) : ∀ l, dmap p f (a::l) = dmap p f l :=
λ l, dif_neg P
lemma mem_dmap : ∀ {l : list A} {a} (Pa : p a), a ∈ l → (f a Pa) ∈ dmap p f l
| [] := take a Pa Pinnil, by contradiction
| (a::l) := take b Pb Pbin, or.elim (eq_or_mem_of_mem_cons Pbin)
(assume Pbeqa, begin
rewrite [eq.symm Pbeqa, dmap_cons_of_pos Pb],
exact !mem_cons
end)
(assume Pbinl,
decidable.rec_on (h a)
(assume Pa, begin
rewrite [dmap_cons_of_pos Pa],
apply mem_cons_of_mem,
exact mem_dmap Pb Pbinl
end)
(assume nPa, begin
rewrite [dmap_cons_of_neg nPa],
exact mem_dmap Pb Pbinl
end))
lemma exists_of_mem_dmap : ∀ {l : list A} {b : B}, b ∈ dmap p f l → ∃ a P, a ∈ l ∧ b = f a P
| [] := take b, by rewrite dmap_nil; contradiction
| (a::l) := take b, decidable.rec_on (h a)
(assume Pa, begin
rewrite [dmap_cons_of_pos Pa, mem_cons_iff],
intro Pb, cases Pb with Peq Pin,
exact exists.intro a (exists.intro Pa (and.intro !mem_cons Peq)),
assert Pex : ∃ (a : A) (P : p a), a ∈ l ∧ b = f a P, exact exists_of_mem_dmap Pin,
cases Pex with a' Pex', cases Pex' with Pa' P',
exact exists.intro a' (exists.intro Pa' (and.intro (mem_cons_of_mem a (and.left P')) (and.right P')))
end)
(assume nPa, begin
rewrite [dmap_cons_of_neg nPa],
intro Pin,
assert Pex : ∃ (a : A) (P : p a), a ∈ l ∧ b = f a P, exact exists_of_mem_dmap Pin,
cases Pex with a' Pex', cases Pex' with Pa' P',
exact exists.intro a' (exists.intro Pa' (and.intro (mem_cons_of_mem a (and.left P')) (and.right P')))
end)
lemma map_dmap_of_inv_of_pos {g : B → A} (Pinv : ∀ a (Pa : p a), g (f a Pa) = a) :
∀ {l : list A}, (∀ ⦃a⦄, a ∈ l → p a) → map g (dmap p f l) = l
| [] := assume Pl, by rewrite [dmap_nil, map_nil]
| (a::l) := assume Pal,
assert Pa : p a, from Pal a !mem_cons,
assert Pl : ∀ a, a ∈ l → p a,
from take x Pxin, Pal x (mem_cons_of_mem a Pxin),
by rewrite [dmap_cons_of_pos Pa, map_cons, Pinv, map_dmap_of_inv_of_pos Pl]
lemma mem_of_dinj_of_mem_dmap (Pdi : dinj p f) :
∀ {l : list A} {a} (Pa : p a), (f a Pa) ∈ dmap p f l → a ∈ l
| [] := take a Pa Pinnil, by contradiction
| (b::l) := take a Pa Pmap,
decidable.rec_on (h b)
(λ Pb, begin
rewrite (dmap_cons_of_pos Pb) at Pmap,
rewrite mem_cons_iff at Pmap,
rewrite mem_cons_iff,
apply (or_of_or_of_imp_of_imp Pmap),
apply Pdi,
apply mem_of_dinj_of_mem_dmap Pa
end)
(λ nPb, begin
rewrite (dmap_cons_of_neg nPb) at Pmap,
apply mem_cons_of_mem,
exact mem_of_dinj_of_mem_dmap Pa Pmap
end)
lemma not_mem_dmap_of_dinj_of_not_mem (Pdi : dinj p f) {l : list A} {a} (Pa : p a) :
a ∉ l → (f a Pa) ∉ dmap p f l :=
not.mto (mem_of_dinj_of_mem_dmap Pdi Pa)
end dmap
section
open equiv
definition list_equiv_of_equiv {A B : Type} : A ≃ B → list A ≃ list B
| (mk f g l r) :=
mk (map f) (map g)
begin intros, rewrite [map_map, id_of_left_inverse l, map_id], try reflexivity end
begin intros, rewrite [map_map, id_of_righ_inverse r, map_id], try reflexivity end
private definition to_nat : list nat → nat
| [] := 0
| (x::xs) := succ (mkpair (to_nat xs) x)
open prod.ops
private definition of_nat.F : Π (n : nat), (Π m, m < n → list nat) → list nat
| 0 f := []
| (succ n) f := (unpair n).2 :: f (unpair n).1 (unpair_lt n)
private definition of_nat : nat → list nat :=
well_founded.fix of_nat.F
private lemma of_nat_zero : of_nat 0 = [] :=
well_founded.fix_eq of_nat.F 0
private lemma of_nat_succ (n : nat)
: of_nat (succ n) = (unpair n).2 :: of_nat (unpair n).1 :=
well_founded.fix_eq of_nat.F (succ n)
private lemma to_nat_of_nat (n : nat) : to_nat (of_nat n) = n :=
nat.case_strong_induction_on n
_
(λ n ih,
begin
rewrite of_nat_succ, unfold to_nat,
have to_nat (of_nat (unpair n).1) = (unpair n).1, from ih _ (le_of_lt_succ (unpair_lt n)),
rewrite this, rewrite mkpair_unpair
end)
private lemma of_nat_to_nat : ∀ (l : list nat), of_nat (to_nat l) = l
| [] := rfl
| (x::xs) := begin unfold to_nat, rewrite of_nat_succ, rewrite *unpair_mkpair, esimp, congruence, apply of_nat_to_nat end
definition list_nat_equiv_nat : list nat ≃ nat :=
mk to_nat of_nat of_nat_to_nat to_nat_of_nat
definition list_equiv_self_of_equiv_nat {A : Type} : A ≃ nat → list A ≃ A :=
suppose A ≃ nat, calc
list A ≃ list nat : list_equiv_of_equiv this
... ≃ nat : list_nat_equiv_nat
... ≃ A : this
end
end list
attribute list.decidable_any [instance]
attribute list.decidable_all [instance]
|
73a3f2be5ca2e8b528691669ca44cdbd7faaaab6 | a4673261e60b025e2c8c825dfa4ab9108246c32e | /src/Lean/Parser/Basic.lean | 12fd483dbe75065d45adc1c4e647a75b1e8aaea4 | [
"Apache-2.0"
] | permissive | jcommelin/lean4 | c02dec0cc32c4bccab009285475f265f17d73228 | 2909313475588cc20ac0436e55548a4502050d0a | refs/heads/master | 1,674,129,550,893 | 1,606,415,348,000 | 1,606,415,348,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 64,327 | 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
-/
/-!
# Basic Lean parser infrastructure
The Lean parser was developed with the following primary goals in mind:
* flexibility: Lean's grammar is complex and includes indentation and other whitespace sensitivity. It should be
possible to introduce such custom "tweaks" locally without having to adjust the fundamental parsing approach.
* extensibility: Lean's grammar can be extended on the fly within a Lean file, and with Lean 4 we want to extend this
to cover embedding domain-specific languages that may look nothing like Lean, down to using a separate set of tokens.
* losslessness: The parser should produce a concrete syntax tree that preserves all whitespace and other "sub-token"
information for the use in tooling.
* performance: The overhead of the parser building blocks, and the overall parser performance on average-complexity
input, should be comparable with that of the previous parser hand-written in C++. No fancy optimizations should be
necessary for this.
Given these constraints, we decided to implement a combinatoric, non-monadic, lexer-less, memoizing recursive-descent
parser. Using combinators instead of some more formal and introspectible grammar representation ensures ultimate
flexibility as well as efficient extensibility: there is (almost) no pre-processing necessary when extending the grammar
with a new parser. However, because the all results the combinators produce are of the homogeneous `Syntax` type, the
basic parser type is not actually a monad but a monomorphic linear function `ParserState → ParserState`, avoiding
constructing and deconstructing countless monadic return values. Instead of explicitly returning syntax objects, parsers
push (zero or more of) them onto a syntax stack inside the linear state. Chaining parsers via `>>` accumulates their
output on the stack. Combinators such as `node` then pop off all syntax objects produced during their invocation and
wrap them in a single `Syntax.node` object that is again pushed on this stack. Instead of calling `node` directly, we
usually use the macro `parser! p`, which unfolds to `node k p` where the new syntax node kind `k` is the name of the
declaration being defined.
The lack of a dedicated lexer ensures we can modify and replace the lexical grammar at any point, and simplifies
detecting and propagating whitespace. The parser still has a concept of "tokens", however, and caches the most recent
one for performance: when `tokenFn` is called twice at the same position in the input, it will reuse the result of the
first call. `tokenFn` recognizes some built-in variable-length tokens such as identifiers as well as any fixed token in
the `ParserContext`'s `TokenTable` (a trie); however, the same cache field and strategy could be reused by custom token
parsers. Tokens also play a central role in the `prattParser` combinator, which selects a *leading* parser followed by
zero or more *trailing* parsers based on the current token (via `peekToken`); see the documentation of `prattParser`
for more details. Tokens are specified via the `symbol` parser, or with `symbolNoWs` for tokens that should not be preceded by whitespace.
The `Parser` type is extended with additional metadata over the mere parsing function to propagate token information:
`collectTokens` collects all tokens within a parser for registering. `firstTokens` holds information about the "FIRST"
token set used to speed up parser selection in `prattParser`. This approach of combining static and dynamic information
in the parser type is inspired by the paper "Deterministic, Error-Correcting Combinator Parsers" by Swierstra and Duponcheel.
If multiple parsers accept the same current token, `prattParser` tries all of them using the backtracking `longestMatchFn` combinator.
This is the only case where standard parsers might execute arbitrary backtracking. At the moment there is no memoization shared by these
parallel parsers apart from the first token, though we might change this in the future if the need arises.
Finally, error reporting follows the standard combinatoric approach of collecting a single unexpected token/... and zero
or more expected tokens (see `Error` below). Expected tokens are e.g. set by `symbol` and merged by `<|>`. Combinators
running multiple parsers should check if an error message is set in the parser state (`hasError`) and act accordingly.
Error recovery is left to the designer of the specific language; for example, Lean's top-level `parseCommand` loop skips
tokens until the next command keyword on error.
-/
import Lean.Data.Trie
import Lean.Data.Position
import Lean.Syntax
import Lean.ToExpr
import Lean.Environment
import Lean.Attributes
import Lean.Message
import Lean.Compiler.InitAttr
namespace Lean
namespace Parser
def isLitKind (k : SyntaxNodeKind) : Bool :=
k == strLitKind || k == numLitKind || k == charLitKind || k == nameLitKind
abbrev mkAtom (info : SourceInfo) (val : String) : Syntax :=
Syntax.atom info val
abbrev mkIdent (info : SourceInfo) (rawVal : Substring) (val : Name) : Syntax :=
Syntax.ident info rawVal val []
/- Return character after position `pos` -/
def getNext (input : String) (pos : Nat) : Char :=
input.get (input.next pos)
/- Maximal (and function application) precedence.
In the standard lean language, no parser has precedence higher than `maxPrec`.
Note that nothing prevents users from using a higher precedence, but we strongly
discourage them from doing it. -/
def maxPrec : Nat := 1024
def leadPrec := maxPrec - 1
abbrev Token := String
structure TokenCacheEntry :=
(startPos stopPos : String.Pos := 0)
(token : Syntax := Syntax.missing)
structure ParserCache :=
(tokenCache : TokenCacheEntry)
def initCacheForInput (input : String) : ParserCache := {
tokenCache := { startPos := input.bsize + 1 /- make sure it is not a valid position -/}
}
abbrev TokenTable := Trie Token
abbrev SyntaxNodeKindSet := Std.PersistentHashMap SyntaxNodeKind Unit
def SyntaxNodeKindSet.insert (s : SyntaxNodeKindSet) (k : SyntaxNodeKind) : SyntaxNodeKindSet :=
Std.PersistentHashMap.insert s k ()
/-
Input string and related data. Recall that the `FileMap` is a helper structure for mapping
`String.Pos` in the input string to line/column information. -/
structure InputContext :=
(input : String)
(fileName : String)
(fileMap : FileMap)
instance : Inhabited InputContext := ⟨{
input := "", fileName := "", fileMap := arbitrary
}⟩
structure ParserContext extends InputContext :=
(prec : Nat)
(env : Environment)
(tokens : TokenTable)
(insideQuot : Bool := false)
(suppressInsideQuot : Bool := false)
(savedPos? : Option String.Pos := none)
(forbiddenTk? : Option Token := none)
structure Error :=
(unexpected : String := "")
(expected : List String := [])
namespace Error
instance : Inhabited Error := ⟨{}⟩
private def expectedToString : List String → String
| [] => ""
| [e] => e
| [e1, e2] => e1 ++ " or " ++ e2
| e::es => e ++ ", " ++ expectedToString es
protected def toString (e : Error) : String :=
let unexpected := if e.unexpected == "" then [] else [e.unexpected]
let expected := if e.expected == [] then [] else
let expected := e.expected.toArray.qsort (fun e e' => e < e')
let expected := expected.toList.eraseReps
["expected " ++ expectedToString expected]
"; ".intercalate $ unexpected ++ expected
instance : ToString Error := ⟨Error.toString⟩
protected def beq (e₁ e₂ : Error) : Bool :=
e₁.unexpected == e₂.unexpected && e₁.expected == e₂.expected
instance : BEq Error := ⟨Error.beq⟩
def merge (e₁ e₂ : Error) : Error :=
match e₂ with
| { unexpected := u, .. } => { unexpected := if u == "" then e₁.unexpected else u, expected := e₁.expected ++ e₂.expected }
end Error
structure ParserState :=
(stxStack : Array Syntax := #[])
(pos : String.Pos := 0)
(cache : ParserCache)
(errorMsg : Option Error := none)
namespace ParserState
@[inline] def hasError (s : ParserState) : Bool :=
s.errorMsg != none
@[inline] def stackSize (s : ParserState) : Nat :=
s.stxStack.size
def restore (s : ParserState) (iniStackSz : Nat) (iniPos : Nat) : ParserState :=
{ s with stxStack := s.stxStack.shrink iniStackSz, errorMsg := none, pos := iniPos }
def setPos (s : ParserState) (pos : Nat) : ParserState :=
{ s with pos := pos }
def setCache (s : ParserState) (cache : ParserCache) : ParserState :=
{ s with cache := cache }
def pushSyntax (s : ParserState) (n : Syntax) : ParserState :=
{ s with stxStack := s.stxStack.push n }
def popSyntax (s : ParserState) : ParserState :=
{ s with stxStack := s.stxStack.pop }
def shrinkStack (s : ParserState) (iniStackSz : Nat) : ParserState :=
{ s with stxStack := s.stxStack.shrink iniStackSz }
def next (s : ParserState) (input : String) (pos : Nat) : ParserState :=
{ s with pos := input.next pos }
def toErrorMsg (ctx : ParserContext) (s : ParserState) : String :=
match s.errorMsg with
| none => ""
| some msg =>
let pos := ctx.fileMap.toPosition s.pos
mkErrorStringWithPos ctx.fileName pos.line pos.column (toString msg)
def mkNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, err⟩ =>
if err != none && stack.size == iniStackSz then
-- If there is an error but there are no new nodes on the stack, we just return `s`
s
else
let newNode := Syntax.node k (stack.extract iniStackSz stack.size)
let stack := stack.shrink iniStackSz
let stack := stack.push newNode
⟨stack, pos, cache, err⟩
def mkTrailingNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, err⟩ =>
let newNode := Syntax.node k (stack.extract (iniStackSz - 1) stack.size)
let stack := stack.shrink iniStackSz
let stack := stack.push newNode
⟨stack, pos, cache, err⟩
def mkError (s : ParserState) (msg : String) : ParserState :=
match s with
| ⟨stack, pos, cache, _⟩ => ⟨stack, pos, cache, some { expected := [ msg ] }⟩
def mkUnexpectedError (s : ParserState) (msg : String) : ParserState :=
match s with
| ⟨stack, pos, cache, _⟩ => ⟨stack, pos, cache, some { unexpected := msg }⟩
def mkEOIError (s : ParserState) : ParserState :=
s.mkUnexpectedError "end of input"
def mkErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { expected := [ msg ] }⟩
def mkErrorsAt (s : ParserState) (ex : List String) (pos : String.Pos) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { expected := ex }⟩
def mkUnexpectedErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { unexpected := msg }⟩
end ParserState
def ParserFn := ParserContext → ParserState → ParserState
instance : Inhabited ParserFn := ⟨fun _ => id⟩
inductive FirstTokens :=
| epsilon : FirstTokens
| unknown : FirstTokens
| tokens : List Token → FirstTokens
| optTokens : List Token → FirstTokens
namespace FirstTokens
def seq : FirstTokens → FirstTokens → FirstTokens
| epsilon, tks => tks
| optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| optTokens s₁, tokens s₂ => tokens (s₁ ++ s₂)
| tks, _ => tks
def toOptional : FirstTokens → FirstTokens
| tokens tks => optTokens tks
| tks => tks
def merge : FirstTokens → FirstTokens → FirstTokens
| epsilon, tks => toOptional tks
| tks, epsilon => toOptional tks
| tokens s₁, tokens s₂ => tokens (s₁ ++ s₂)
| optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| tokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| optTokens s₁, tokens s₂ => optTokens (s₁ ++ s₂)
| _, _ => unknown
def toStr : FirstTokens → String
| epsilon => "epsilon"
| unknown => "unknown"
| tokens tks => toString tks
| optTokens tks => "?" ++ toString tks
instance : ToString FirstTokens := ⟨toStr⟩
end FirstTokens
structure ParserInfo :=
(collectTokens : List Token → List Token := id)
(collectKinds : SyntaxNodeKindSet → SyntaxNodeKindSet := id)
(firstTokens : FirstTokens := FirstTokens.unknown)
structure Parser :=
(info : ParserInfo := {})
(fn : ParserFn)
instance : Inhabited Parser :=
⟨{ fn := fun _ s => s }⟩
abbrev TrailingParser := Parser
@[noinline] def epsilonInfo : ParserInfo :=
{ firstTokens := FirstTokens.epsilon }
@[inline] def checkStackTopFn (p : Syntax → Bool) (msg : String) : ParserFn := fun c s =>
if p s.stxStack.back then s
else s.mkUnexpectedError msg
@[inline] def checkStackTop (p : Syntax → Bool) (msg : String) : Parser := {
info := epsilonInfo,
fn := checkStackTopFn p msg
}
@[inline] def andthenFn (p q : ParserFn) : ParserFn := fun c s =>
let s := p c s
if s.hasError then s else q c s
@[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens ∘ q.collectTokens,
collectKinds := p.collectKinds ∘ q.collectKinds,
firstTokens := p.firstTokens.seq q.firstTokens
}
@[inline] def andthen (p q : Parser) : Parser := {
info := andthenInfo p.info q.info,
fn := andthenFn p.fn q.fn
}
instance : AndThen Parser := ⟨andthen⟩
@[inline] def nodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let s := p c s
s.mkNode n iniSz
@[inline] def trailingNodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let s := p c s
s.mkTrailingNode n iniSz
@[noinline] def nodeInfo (n : SyntaxNodeKind) (p : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens,
collectKinds := fun s => (p.collectKinds s).insert n,
firstTokens := p.firstTokens
}
@[inline] def node (n : SyntaxNodeKind) (p : Parser) : Parser := {
info := nodeInfo n p.info,
fn := nodeFn n p.fn
}
def errorFn (msg : String) : ParserFn := fun _ s =>
s.mkUnexpectedError msg
@[inline] def error (msg : String) : Parser := {
info := epsilonInfo,
fn := errorFn msg
}
def errorAtSavedPosFn (msg : String) (delta : Bool) : ParserFn := fun c s =>
match c.savedPos? with
| none => s
| some pos =>
let pos := if delta then c.input.next pos else pos
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { unexpected := msg }⟩
/- Generate an error at the position saved with the `withPosition` combinator.
If `delta == true`, then it reports at saved position+1.
This useful to make sure a parser consumed at least one character. -/
@[inline] def errorAtSavedPos (msg : String) (delta : Bool) : Parser := {
fn := errorAtSavedPosFn msg delta
}
/- Succeeds if `c.prec <= prec` -/
def checkPrecFn (prec : Nat) : ParserFn := fun c s =>
if c.prec <= prec then s
else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term"
@[inline] def checkPrec (prec : Nat) : Parser := {
info := epsilonInfo,
fn := checkPrecFn prec
}
def checkInsideQuotFn : ParserFn := fun c s =>
if c.insideQuot then s
else s.mkUnexpectedError "unexpected syntax outside syntax quotation"
@[inline] def checkInsideQuot : Parser := {
info := epsilonInfo,
fn := checkInsideQuotFn
}
def checkOutsideQuotFn : ParserFn := fun c s =>
if !c.insideQuot then s
else s.mkUnexpectedError "unexpected syntax inside syntax quotation"
@[inline] def checkOutsideQuot : Parser := {
info := epsilonInfo,
fn := checkOutsideQuotFn
}
def toggleInsideQuotFn (p : ParserFn) : ParserFn := fun c s =>
if c.suppressInsideQuot then p c s
else p { c with insideQuot := !c.insideQuot } s
@[inline] def toggleInsideQuot (p : Parser) : Parser := {
info := p.info,
fn := toggleInsideQuotFn p.fn
}
def suppressInsideQuotFn (p : ParserFn) : ParserFn := fun c s =>
p { c with suppressInsideQuot := true } s
@[inline] def suppressInsideQuot (p : Parser) : Parser := {
info := p.info,
fn := suppressInsideQuotFn p.fn
}
@[inline] def leadingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : Parser :=
checkPrec prec >> node n p
@[inline] def trailingNodeAux (n : SyntaxNodeKind) (p : Parser) : TrailingParser := {
info := nodeInfo n p.info,
fn := trailingNodeFn n p.fn
}
@[inline] def trailingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : TrailingParser :=
checkPrec prec >> trailingNodeAux n p
def mergeOrElseErrors (s : ParserState) (error1 : Error) (iniPos : Nat) (mergeErrors : Bool) : ParserState :=
match s with
| ⟨stack, pos, cache, some error2⟩ =>
if pos == iniPos then ⟨stack, pos, cache, some (if mergeErrors then error1.merge error2 else error2)⟩
else s
| other => other
def orelseFnCore (p q : ParserFn) (mergeErrors : Bool) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := p c s
match s.errorMsg with
| some errorMsg =>
if s.pos == iniPos then
mergeOrElseErrors (q c (s.restore iniSz iniPos)) errorMsg iniPos mergeErrors
else
s
| none => s
@[inline] def orelseFn (p q : ParserFn) : ParserFn :=
orelseFnCore p q true
@[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens ∘ q.collectTokens,
collectKinds := p.collectKinds ∘ q.collectKinds,
firstTokens := p.firstTokens.merge q.firstTokens
}
/--
Run `p`, falling back to `q` if `p` failed without consuming any input.
NOTE: In order for the pretty printer to retrace an `orelse`, `p` must be a call to `node` or some other parser
producing a single node kind. Nested `orelse` calls are flattened for this, i.e. `(node k1 p1 <|> node k2 p2) <|> ...`
is fine as well. -/
@[inline] def orelse (p q : Parser) : Parser := {
info := orelseInfo p.info q.info,
fn := orelseFn p.fn q.fn
}
instance : OrElse Parser := ⟨orelse⟩
@[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo := {
collectTokens := info.collectTokens,
collectKinds := info.collectKinds
}
def atomicFn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
match p c s with
| ⟨stack, _, cache, some msg⟩ => ⟨stack.shrink iniSz, iniPos, cache, some msg⟩
| other => other
@[inline] def atomic (p : Parser) : Parser := {
info := p.info,
fn := atomicFn p.fn
}
def optionalFn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := p c s
let s := if s.hasError && s.pos == iniPos then s.restore iniSz iniPos else s
s.mkNode nullKind iniSz
@[noinline] def optionaInfo (p : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens,
collectKinds := p.collectKinds,
firstTokens := p.firstTokens.toOptional
}
@[inline] def optional (p : Parser) : Parser := {
info := optionaInfo p.info,
fn := optionalFn p.fn
}
def lookaheadFn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := p c s
if s.hasError then s else s.restore iniSz iniPos
@[inline] def lookahead (p : Parser) : Parser := {
info := p.info,
fn := lookaheadFn p.fn
}
def notFollowedByFn (p : ParserFn) (msg : String) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := p c s
if s.hasError then
s.restore iniSz iniPos
else
let s := s.restore iniSz iniPos
s.mkUnexpectedError s!"unexpected {msg}"
@[inline] def notFollowedBy (p : Parser) (msg : String) : Parser := {
fn := notFollowedByFn p.fn msg
}
partial def manyAux (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := p c s
if s.hasError then
if iniPos == s.pos then s.restore iniSz iniPos else s
else if iniPos == s.pos then s.mkUnexpectedError "invalid 'many' parser combinator application, parser did not consume anything"
else manyAux p c s
@[inline] def manyFn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let s := manyAux p c s
s.mkNode nullKind iniSz
@[inline] def many (p : Parser) : Parser := {
info := noFirstTokenInfo p.info,
fn := manyFn p.fn
}
@[inline] def many1Fn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let s := andthenFn p (manyAux p) c s
s.mkNode nullKind iniSz
@[inline] def many1 (p : Parser) : Parser := {
info := p.info,
fn := many1Fn p.fn
}
private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool) (iniSz : Nat) (pOpt : Bool) : ParserFn :=
let rec parse (pOpt : Bool) (c s) :=
let sz := s.stackSize
let pos := s.pos
let s := p c s
if s.hasError then
if s.pos > pos then s
else if pOpt then
let s := s.restore sz pos
s.mkNode nullKind iniSz
else
-- append `Syntax.missing` to make clear that List is incomplete
let s := s.pushSyntax Syntax.missing
s.mkNode nullKind iniSz
else
let sz := s.stackSize
let pos := s.pos
let s := sep c s
if s.hasError then
let s := s.restore sz pos
s.mkNode nullKind iniSz
else
parse allowTrailingSep c s
parse pOpt
def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
sepByFnAux p sep allowTrailingSep iniSz true c s
def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
sepByFnAux p sep allowTrailingSep iniSz false c s
@[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens ∘ sep.collectTokens,
collectKinds := p.collectKinds ∘ sep.collectKinds
}
@[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens ∘ sep.collectTokens,
collectKinds := p.collectKinds ∘ sep.collectKinds,
firstTokens := p.firstTokens
}
@[inline] def sepBy (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := {
info := sepByInfo p.info sep.info,
fn := sepByFn allowTrailingSep p.fn sep.fn
}
@[inline] def sepBy1 (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := {
info := sepBy1Info p.info sep.info,
fn := sepBy1Fn allowTrailingSep p.fn sep.fn
}
/- Apply `f` to the syntax object produced by `p` -/
def withResultOfFn (p : ParserFn) (f : Syntax → Syntax) : ParserFn := fun c s =>
let s := p c s
if s.hasError then s
else
let stx := s.stxStack.back
s.popSyntax.pushSyntax (f stx)
@[noinline] def withResultOfInfo (p : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens,
collectKinds := p.collectKinds
}
@[inline] def withResultOf (p : Parser) (f : Syntax → Syntax) : Parser := {
info := withResultOfInfo p.info,
fn := withResultOfFn p.fn f
}
@[inline] def many1Unbox (p : Parser) : Parser :=
withResultOf (many1 p) fun stx => if stx.getNumArgs == 1 then stx.getArg 0 else stx
partial def satisfyFn (p : Char → Bool) (errorMsg : String := "unexpected character") : ParserFn := fun c s =>
let i := s.pos
if c.input.atEnd i then s.mkEOIError
else if p (c.input.get i) then s.next c.input i
else s.mkUnexpectedError errorMsg
partial def takeUntilFn (p : Char → Bool) : ParserFn := fun c s =>
let i := s.pos
if c.input.atEnd i then s
else if p (c.input.get i) then s
else takeUntilFn p c (s.next c.input i)
def takeWhileFn (p : Char → Bool) : ParserFn :=
takeUntilFn (fun c => !p c)
@[inline] def takeWhile1Fn (p : Char → Bool) (errorMsg : String) : ParserFn :=
andthenFn (satisfyFn p errorMsg) (takeWhileFn p)
partial def finishCommentBlock (nesting : Nat) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError
else
let curr := input.get i
let i := input.next i
if curr == '-' then
if input.atEnd i then s.mkEOIError
else
let curr := input.get i
if curr == '/' then -- "-/" end of comment
if nesting == 1 then s.next input i
else finishCommentBlock (nesting-1) c (s.next input i)
else
finishCommentBlock nesting c (s.next input i)
else if curr == '/' then
if input.atEnd i then s.mkEOIError
else
let curr := input.get i
if curr == '-' then finishCommentBlock (nesting+1) c (s.next input i)
else finishCommentBlock nesting c (s.setPos i)
else finishCommentBlock nesting c (s.setPos i)
/- Consume whitespace and comments -/
partial def whitespace : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s
else
let curr := input.get i
if curr.isWhitespace then whitespace c (s.next input i)
else if curr == '-' then
let i := input.next i
let curr := input.get i
if curr == '-' then andthenFn (takeUntilFn (fun c => c = '\n')) whitespace c (s.next input i)
else s
else if curr == '/' then
let i := input.next i
let curr := input.get i
if curr == '-' then
let i := input.next i
let curr := input.get i
if curr == '-' then s -- "/--" doc comment is an actual token
else andthenFn (finishCommentBlock 1) whitespace c (s.next input i)
else s
else s
def mkEmptySubstringAt (s : String) (p : Nat) : Substring :=
{ str := s, startPos := p, stopPos := p }
private def rawAux (startPos : Nat) (trailingWs : Bool) : ParserFn := fun c s =>
let input := c.input
let stopPos := s.pos
let leading := mkEmptySubstringAt input startPos
let val := input.extract startPos stopPos
if trailingWs then
let s := whitespace c s
let stopPos' := s.pos
let trailing := { str := input, startPos := stopPos, stopPos := stopPos' : Substring }
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } val
s.pushSyntax atom
else
let trailing := mkEmptySubstringAt input stopPos
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } val
s.pushSyntax atom
/-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/
@[inline] def rawFn (p : ParserFn) (trailingWs := false) : ParserFn := fun c s =>
let startPos := s.pos
let s := p c s
if s.hasError then s else rawAux startPos trailingWs c s
@[inline] def chFn (c : Char) (trailingWs := false) : ParserFn :=
rawFn (satisfyFn (fun d => c == d) ("'" ++ toString c ++ "'")) trailingWs
def rawCh (c : Char) (trailingWs := false) : Parser :=
{ fn := chFn c trailingWs }
def hexDigitFn : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError
else
let curr := input.get i
let i := input.next i
if curr.isDigit || ('a' <= curr && curr <= 'f') || ('A' <= curr && curr <= 'F') then s.setPos i
else s.mkUnexpectedError "invalid hexadecimal numeral"
def quotedCharCoreFn (isQuotable : Char → Bool) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError
else
let curr := input.get i
if isQuotable curr then
s.next input i
else if curr == 'x' then
andthenFn hexDigitFn hexDigitFn c (s.next input i)
else if curr == 'u' then
andthenFn hexDigitFn (andthenFn hexDigitFn (andthenFn hexDigitFn hexDigitFn)) c (s.next input i)
else
s.mkUnexpectedError "invalid escape sequence"
def isQuotableCharDefault (c : Char) : Bool :=
c == '\\' || c == '\"' || c == '\'' || c == 'r' || c == 'n' || c == 't'
def quotedCharFn : ParserFn :=
quotedCharCoreFn isQuotableCharDefault
/-- Push `(Syntax.node tk <new-atom>)` into syntax stack -/
def mkNodeToken (n : SyntaxNodeKind) (startPos : Nat) : ParserFn := fun c s =>
let input := c.input
let stopPos := s.pos
let leading := mkEmptySubstringAt input startPos
let val := input.extract startPos stopPos
let s := whitespace c s
let wsStopPos := s.pos
let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring }
let info := { leading := leading, pos := startPos, trailing := trailing : SourceInfo }
s.pushSyntax (Syntax.mkLit n val info)
def charLitFnAux (startPos : Nat) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError
else
let curr := input.get i
let s := s.setPos (input.next i)
let s := if curr == '\\' then quotedCharFn c s else s
if s.hasError then s
else
let i := s.pos
let curr := input.get i
let s := s.setPos (input.next i)
if curr == '\'' then mkNodeToken charLitKind startPos c s
else s.mkUnexpectedError "missing end of character literal"
partial def strLitFnAux (startPos : Nat) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError
else
let curr := input.get i
let s := s.setPos (input.next i)
if curr == '\"' then
mkNodeToken strLitKind startPos c s
else if curr == '\\' then andthenFn quotedCharFn (strLitFnAux startPos) c s
else strLitFnAux startPos c s
def decimalNumberFn (startPos : Nat) : ParserFn := fun c s =>
let s := takeWhileFn (fun c => c.isDigit) c s
let input := c.input
let i := s.pos
let curr := input.get i
let s :=
/- TODO(Leo): should we use a different kind for numerals containing decimal points? -/
if curr == '.' then
let i := input.next i
let curr := input.get i
if curr.isDigit then
takeWhileFn (fun c => c.isDigit) c (s.setPos i)
else s
else s
mkNodeToken numLitKind startPos c s
def binNumberFn (startPos : Nat) : ParserFn := fun c s =>
let s := takeWhile1Fn (fun c => c == '0' || c == '1') "binary number" c s
mkNodeToken numLitKind startPos c s
def octalNumberFn (startPos : Nat) : ParserFn := fun c s =>
let s := takeWhile1Fn (fun c => '0' ≤ c && c ≤ '7') "octal number" c s
mkNodeToken numLitKind startPos c s
def hexNumberFn (startPos : Nat) : ParserFn := fun c s =>
let s := takeWhile1Fn (fun c => ('0' ≤ c && c ≤ '9') || ('a' ≤ c && c ≤ 'f') || ('A' ≤ c && c ≤ 'F')) "hexadecimal number" c s
mkNodeToken numLitKind startPos c s
def numberFnAux : ParserFn := fun c s =>
let input := c.input
let startPos := s.pos
if input.atEnd startPos then s.mkEOIError
else
let curr := input.get startPos
if curr == '0' then
let i := input.next startPos
let curr := input.get i
if curr == 'b' || curr == 'B' then
binNumberFn startPos c (s.next input i)
else if curr == 'o' || curr == 'O' then
octalNumberFn startPos c (s.next input i)
else if curr == 'x' || curr == 'X' then
hexNumberFn startPos c (s.next input i)
else
decimalNumberFn startPos c (s.setPos i)
else if curr.isDigit then
decimalNumberFn startPos c (s.next input startPos)
else
s.mkError "numeral"
def isIdCont : String → ParserState → Bool := fun input s =>
let i := s.pos
let curr := input.get i
if curr == '.' then
let i := input.next i
if input.atEnd i then
false
else
let curr := input.get i
isIdFirst curr || isIdBeginEscape curr
else
false
private def isToken (idStartPos idStopPos : Nat) (tk : Option Token) : Bool :=
match tk with
| none => false
| some tk =>
-- if a token is both a symbol and a valid identifier (i.e. a keyword),
-- we want it to be recognized as a symbol
tk.bsize ≥ idStopPos - idStartPos
def mkTokenAndFixPos (startPos : Nat) (tk : Option Token) : ParserFn := fun c s =>
match tk with
| none => s.mkErrorAt "token" startPos
| some tk =>
if c.forbiddenTk? == some tk then
s.mkErrorAt "forbidden token" startPos
else
let input := c.input
let leading := mkEmptySubstringAt input startPos
let stopPos := startPos + tk.bsize
let s := s.setPos stopPos
let s := whitespace c s
let wsStopPos := s.pos
let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring }
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } tk
s.pushSyntax atom
def mkIdResult (startPos : Nat) (tk : Option Token) (val : Name) : ParserFn := fun c s =>
let stopPos := s.pos
if isToken startPos stopPos tk then
mkTokenAndFixPos startPos tk c s
else
let input := c.input
let rawVal := { str := input, startPos := startPos, stopPos := stopPos : Substring }
let s := whitespace c s
let trailingStopPos := s.pos
let leading := mkEmptySubstringAt input startPos
let trailing := { str := input, startPos := stopPos, stopPos := trailingStopPos : Substring }
let info := { leading := leading, trailing := trailing, pos := startPos : SourceInfo }
let atom := mkIdent info rawVal val
s.pushSyntax atom
partial def identFnAux (startPos : Nat) (tk : Option Token) (r : Name) : ParserFn :=
let rec parse (r : Name) (c s) :=
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError
else
let curr := input.get i
if isIdBeginEscape curr then
let startPart := input.next i
let s := takeUntilFn isIdEndEscape c (s.setPos startPart)
let stopPart := s.pos
let s := satisfyFn isIdEndEscape "missing end of escaped identifier" c s
if s.hasError then s
else
let r := Name.mkStr r (input.extract startPart stopPart)
if isIdCont input s then
let s := s.next input s.pos
parse r c s
else
mkIdResult startPos tk r c s
else if isIdFirst curr then
let startPart := i
let s := takeWhileFn isIdRest c (s.next input i)
let stopPart := s.pos
let r := Name.mkStr r (input.extract startPart stopPart)
if isIdCont input s then
let s := s.next input s.pos
parse r c s
else
mkIdResult startPos tk r c s
else
mkTokenAndFixPos startPos tk c s
parse r
private def isIdFirstOrBeginEscape (c : Char) : Bool :=
isIdFirst c || isIdBeginEscape c
private def nameLitAux (startPos : Nat) : ParserFn := fun c s =>
let input := c.input
let s := identFnAux startPos none Name.anonymous c (s.next input startPos)
if s.hasError then
s.mkErrorAt "invalid Name literal" startPos
else
let stx := s.stxStack.back
match stx with
| Syntax.ident _ rawStr _ _ =>
let s := s.popSyntax
s.pushSyntax (Syntax.node nameLitKind #[mkAtomFrom stx rawStr.toString])
| _ => s.mkError "invalid Name literal"
private def tokenFnAux : ParserFn := fun c s =>
let input := c.input
let i := s.pos
let curr := input.get i
if curr == '\"' then
strLitFnAux i c (s.next input i)
else if curr == '\'' then
charLitFnAux i c (s.next input i)
else if curr.isDigit then
numberFnAux c s
else if curr == '`' && isIdFirstOrBeginEscape (getNext input i) then
nameLitAux i c s
else
let (_, tk) := c.tokens.matchPrefix input i
identFnAux i tk Name.anonymous c s
private def updateCache (startPos : Nat) (s : ParserState) : ParserState :=
match s with
| ⟨stack, pos, cache, none⟩ =>
if stack.size == 0 then s
else
let tk := stack.back
⟨stack, pos, { tokenCache := { startPos := startPos, stopPos := pos, token := tk } }, none⟩
| other => other
def tokenFn : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError
else
let tkc := s.cache.tokenCache
if tkc.startPos == i then
let s := s.pushSyntax tkc.token
s.setPos tkc.stopPos
else
let s := tokenFnAux c s
updateCache i s
def peekTokenAux (c : ParserContext) (s : ParserState) : ParserState × Option Syntax :=
let iniSz := s.stackSize
let iniPos := s.pos
let s := tokenFn c s
if s.hasError then (s.restore iniSz iniPos, none)
else
let stx := s.stxStack.back
(s.restore iniSz iniPos, some stx)
def peekToken (c : ParserContext) (s : ParserState) : ParserState × Option Syntax :=
let tkc := s.cache.tokenCache
if tkc.startPos == s.pos then
(s, some tkc.token)
else
peekTokenAux c s
/- Treat keywords as identifiers. -/
def rawIdentFn : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError
else identFnAux i none Name.anonymous c s
@[inline] def satisfySymbolFn (p : String → Bool) (expected : List String) : ParserFn := fun c s =>
let startPos := s.pos
let s := tokenFn c s
if s.hasError then
s.mkErrorsAt expected startPos
else
match s.stxStack.back with
| Syntax.atom _ sym => if p sym then s else s.mkErrorsAt expected startPos
| _ => s.mkErrorsAt expected startPos
def symbolFnAux (sym : String) (errorMsg : String) : ParserFn :=
satisfySymbolFn (fun s => s == sym) [errorMsg]
def symbolInfo (sym : String) : ParserInfo := {
collectTokens := fun tks => sym :: tks,
firstTokens := FirstTokens.tokens [ sym ]
}
@[inline] def symbolFn (sym : String) : ParserFn :=
symbolFnAux sym ("'" ++ sym ++ "'")
@[inline] def symbol (sym : String) : Parser :=
let sym := sym.trim
{ info := symbolInfo sym,
fn := symbolFn sym }
/-- Check if the following token is the symbol _or_ identifier `sym`. Useful for
parsing local tokens that have not been added to the token table (but may have
been so by some unrelated code).
For example, the universe `max` Function is parsed using this combinator so that
it can still be used as an identifier outside of universes (but registering it
as a token in a Term Syntax would not break the universe Parser). -/
def nonReservedSymbolFnAux (sym : String) (errorMsg : String) : ParserFn := fun c s =>
let startPos := s.pos
let s := tokenFn c s
if s.hasError then s.mkErrorAt errorMsg startPos
else
match s.stxStack.back with
| Syntax.atom _ sym' =>
if sym == sym' then s else s.mkErrorAt errorMsg startPos
| Syntax.ident info rawVal _ _ =>
if sym == rawVal.toString then
let s := s.popSyntax
s.pushSyntax (Syntax.atom info sym)
else
s.mkErrorAt errorMsg startPos
| _ => s.mkErrorAt errorMsg startPos
@[inline] def nonReservedSymbolFn (sym : String) : ParserFn :=
nonReservedSymbolFnAux sym ("'" ++ sym ++ "'")
def nonReservedSymbolInfo (sym : String) (includeIdent : Bool) : ParserInfo := {
firstTokens :=
if includeIdent then
FirstTokens.tokens [ sym, "ident" ]
else
FirstTokens.tokens [ sym ]
}
@[inline] def nonReservedSymbol (sym : String) (includeIdent := false) : Parser :=
let sym := sym.trim
{ info := nonReservedSymbolInfo sym includeIdent,
fn := nonReservedSymbolFn sym }
partial def strAux (sym : String) (errorMsg : String) (j : Nat) :ParserFn :=
let rec parse (j c s) :=
if sym.atEnd j then s
else
let i := s.pos
let input := c.input
if input.atEnd i || sym.get j != input.get i then s.mkError errorMsg
else parse (sym.next j) c (s.next input i)
parse j
def checkTailWs (prev : Syntax) : Bool :=
match prev.getTailInfo with
| some { trailing := some trailing, .. } => trailing.stopPos > trailing.startPos
| _ => false
def checkWsBeforeFn (errorMsg : String) : ParserFn := fun c s =>
let prev := s.stxStack.back
if checkTailWs prev then s else s.mkError errorMsg
def checkWsBefore (errorMsg : String := "space before") : Parser := {
info := epsilonInfo,
fn := checkWsBeforeFn errorMsg
}
def checkTailNoWs (prev : Syntax) : Bool :=
match prev.getTailInfo with
| some { trailing := some trailing, .. } => trailing.stopPos == trailing.startPos
| _ => false
private def pickNonNone (stack : Array Syntax) : Syntax :=
match stack.findRev? $ fun stx => !stx.isNone with
| none => Syntax.missing
| some stx => stx
def checkNoWsBeforeFn (errorMsg : String) : ParserFn := fun c s =>
let prev := pickNonNone s.stxStack
if checkTailNoWs prev then s else s.mkError errorMsg
def checkNoWsBefore (errorMsg : String := "no space before") : Parser := {
info := epsilonInfo,
fn := checkNoWsBeforeFn errorMsg
}
def unicodeSymbolFnAux (sym asciiSym : String) (expected : List String) : ParserFn :=
satisfySymbolFn (fun s => s == sym || s == asciiSym) expected
def unicodeSymbolInfo (sym asciiSym : String) : ParserInfo := {
collectTokens := fun tks => sym :: asciiSym :: tks,
firstTokens := FirstTokens.tokens [ sym, asciiSym ]
}
@[inline] def unicodeSymbolFn (sym asciiSym : String) : ParserFn :=
unicodeSymbolFnAux sym asciiSym ["'" ++ sym ++ "', '" ++ asciiSym ++ "'"]
@[inline] def unicodeSymbol (sym asciiSym : String) : Parser :=
let sym := sym.trim
let asciiSym := asciiSym.trim
{ info := unicodeSymbolInfo sym asciiSym,
fn := unicodeSymbolFn sym asciiSym }
def mkAtomicInfo (k : String) : ParserInfo :=
{ firstTokens := FirstTokens.tokens [ k ] }
def numLitFn : ParserFn :=
fun c s =>
let iniPos := s.pos
let s := tokenFn c s
if s.hasError || !(s.stxStack.back.isOfKind numLitKind) then s.mkErrorAt "numeral" iniPos else s
@[inline] def numLitNoAntiquot : Parser := {
fn := numLitFn,
info := mkAtomicInfo "numLit"
}
def strLitFn : ParserFn := fun c s =>
let iniPos := s.pos
let s := tokenFn c s
if s.hasError || !(s.stxStack.back.isOfKind strLitKind) then s.mkErrorAt "string literal" iniPos else s
@[inline] def strLitNoAntiquot : Parser := {
fn := strLitFn,
info := mkAtomicInfo "strLit"
}
def charLitFn : ParserFn := fun c s =>
let iniPos := s.pos
let s := tokenFn c s
if s.hasError || !(s.stxStack.back.isOfKind charLitKind) then s.mkErrorAt "character literal" iniPos else s
@[inline] def charLitNoAntiquot : Parser := {
fn := charLitFn,
info := mkAtomicInfo "charLit"
}
def nameLitFn : ParserFn := fun c s =>
let iniPos := s.pos
let s := tokenFn c s
if s.hasError || !(s.stxStack.back.isOfKind nameLitKind) then s.mkErrorAt "Name literal" iniPos else s
@[inline] def nameLitNoAntiquot : Parser := {
fn := nameLitFn,
info := mkAtomicInfo "nameLit"
}
def identFn : ParserFn := fun c s =>
let iniPos := s.pos
let s := tokenFn c s
if s.hasError || !(s.stxStack.back.isIdent) then s.mkErrorAt "identifier" iniPos else s
@[inline] def identNoAntiquot : Parser := {
fn := identFn,
info := mkAtomicInfo "ident"
}
@[inline] def rawIdentNoAntiquot : Parser := {
fn := rawIdentFn
}
def identEqFn (id : Name) : ParserFn := fun c s =>
let iniPos := s.pos
let s := tokenFn c s
if s.hasError then
s.mkErrorAt "identifier" iniPos
else match s.stxStack.back with
| Syntax.ident _ _ val _ => if val != id then s.mkErrorAt ("expected identifier '" ++ toString id ++ "'") iniPos else s
| _ => s.mkErrorAt "identifier" iniPos
@[inline] def identEq (id : Name) : Parser := {
fn := identEqFn id,
info := mkAtomicInfo "ident"
}
instance : Coe String Parser := ⟨fun s => symbol s ⟩
namespace ParserState
def keepNewError (s : ParserState) (oldStackSize : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, err⟩ => ⟨stack.shrink oldStackSize, pos, cache, err⟩
def keepPrevError (s : ParserState) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option Error) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack.shrink oldStackSize, oldStopPos, cache, oldError⟩
def mergeErrors (s : ParserState) (oldStackSize : Nat) (oldError : Error) : ParserState :=
match s with
| ⟨stack, pos, cache, some err⟩ =>
if oldError == err then s
else ⟨stack.shrink oldStackSize, pos, cache, some (oldError.merge err)⟩
| other => other
def keepLatest (s : ParserState) (startStackSize : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, _⟩ =>
let node := stack.back
let stack := stack.shrink startStackSize
let stack := stack.push node
⟨stack, pos, cache, none⟩
def replaceLongest (s : ParserState) (startStackSize : Nat) : ParserState :=
s.keepLatest startStackSize
end ParserState
def invalidLongestMatchParser (s : ParserState) : ParserState :=
s.mkError "longestMatch parsers must generate exactly one Syntax node"
/--
Auxiliary function used to execute parsers provided to `longestMatchFn`.
Push `left?` into the stack if it is not `none`, and execute `p`.
After executing `p`, remove `left`.
Remark: `p` must produce exactly one syntax node.
Remark: the `left?` is not none when we are processing trailing parsers. -/
def runLongestMatchParser (left? : Option Syntax) (p : ParserFn) : ParserFn := fun c s =>
let startSize := s.stackSize
match left? with
| none =>
let s := p c s
if s.hasError then s
else
-- stack contains `[..., result ]`
if s.stackSize == startSize + 1 then
s
else
invalidLongestMatchParser s
| some left =>
let s := s.pushSyntax left
let s := p c s
if s.hasError then s
else
-- stack contains `[..., left, result ]` we must remove `left`
if s.stackSize == startSize + 2 then
-- `p` created one node, then we just remove `left` and keep it
let r := s.stxStack.back
let s := s.shrinkStack startSize -- remove `r` and `left`
s.pushSyntax r -- add `r` back
else
invalidLongestMatchParser s
def longestMatchStep (left? : Option Syntax) (startSize : Nat) (startPos : String.Pos) (prevPrio : Nat) (prio : Nat) (p : ParserFn)
: ParserContext → ParserState → ParserState × Nat := fun c s =>
let prevErrorMsg := s.errorMsg
let prevStopPos := s.pos
let prevSize := s.stackSize
let s := s.restore prevSize startPos
let s := runLongestMatchParser left? p c s
match prevErrorMsg, s.errorMsg with
| none, none => -- both succeeded
if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.replaceLongest startSize, prio)
else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then (s.restore prevSize prevStopPos, prevPrio) -- keep prev
else (s, prio)
| none, some _ => -- prev succeeded, current failed
(s.restore prevSize prevStopPos, prevPrio)
| some oldError, some _ => -- both failed
if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.keepNewError prevSize, prio)
else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then (s.keepPrevError prevSize prevStopPos prevErrorMsg, prevPrio)
else (s.mergeErrors prevSize oldError, prio)
| some _, none => -- prev failed, current succeeded
let successNode := s.stxStack.back
let s := s.shrinkStack startSize -- restore stack to initial size to make sure (failure) nodes are removed from the stack
(s.pushSyntax successNode, prio) -- put successNode back on the stack
def longestMatchMkResult (startSize : Nat) (s : ParserState) : ParserState :=
if !s.hasError && s.stackSize > startSize + 1 then s.mkNode choiceKind startSize else s
def longestMatchFnAux (left? : Option Syntax) (startSize : Nat) (startPos : String.Pos) (prevPrio : Nat) (ps : List (Parser × Nat)) : ParserFn :=
let rec parse (prevPrio : Nat) (ps : List (Parser × Nat)) :=
match ps with
| [] => fun _ s => longestMatchMkResult startSize s
| p::ps => fun c s =>
let (s, prevPrio) := longestMatchStep left? startSize startPos prevPrio p.2 p.1.fn c s
parse prevPrio ps c s
parse prevPrio ps
def longestMatchFn (left? : Option Syntax) : List (Parser × Nat) → ParserFn
| [] => fun _ s => s.mkError "longestMatch: empty list"
| [p] => runLongestMatchParser left? p.1.fn
| p::ps => fun c s =>
let startSize := s.stackSize
let startPos := s.pos
let s := runLongestMatchParser left? p.1.fn c s
if s.hasError then
let s := s.shrinkStack startSize
longestMatchFnAux left? startSize startPos p.2 ps c s
else
longestMatchFnAux left? startSize startPos p.2 ps c s
def anyOfFn : List Parser → ParserFn
| [], _, s => s.mkError "anyOf: empty list"
| [p], c, s => p.fn c s
| p::ps, c, s => orelseFn p.fn (anyOfFn ps) c s
@[inline] def checkColGeFn (errorMsg : String) : ParserFn := fun c s =>
match c.savedPos? with
| none => s
| some savedPos =>
let savedPos := c.fileMap.toPosition savedPos
let pos := c.fileMap.toPosition s.pos
if pos.column ≥ savedPos.column then s
else s.mkError errorMsg
@[inline] def checkColGe (errorMsg : String := "checkColGe") : Parser :=
{ fn := checkColGeFn errorMsg }
@[inline] def checkColGtFn (errorMsg : String) : ParserFn := fun c s =>
match c.savedPos? with
| none => s
| some savedPos =>
let savedPos := c.fileMap.toPosition savedPos
let pos := c.fileMap.toPosition s.pos
if pos.column > savedPos.column then s
else s.mkError errorMsg
@[inline] def checkColGt (errorMsg : String := "checkColGt") : Parser :=
{ fn := checkColGtFn errorMsg }
@[inline] def checkLineEqFn (errorMsg : String) : ParserFn := fun c s =>
match c.savedPos? with
| none => s
| some savedPos =>
let savedPos := c.fileMap.toPosition savedPos
let pos := c.fileMap.toPosition s.pos
if pos.line == savedPos.line then s
else s.mkError errorMsg
@[inline] def checkLineEq (errorMsg : String := "checkLineEq") : Parser :=
{ fn := checkLineEqFn errorMsg }
@[inline] def withPosition (p : Parser) : Parser := {
info := p.info,
fn := fun c s =>
p.fn { c with savedPos? := s.pos } s
}
@[inline] def withoutPosition (p : Parser) : Parser := {
info := p.info,
fn := fun c s =>
let pos := c.fileMap.toPosition s.pos
p.fn { c with savedPos? := none } s
}
@[inline] def withForbidden (tk : Token) (p : Parser) : Parser := {
info := p.info,
fn := fun c s => p.fn { c with forbiddenTk? := tk } s
}
@[inline] def withoutForbidden (p : Parser) : Parser := {
info := p.info,
fn := fun c s => p.fn { c with forbiddenTk? := none } s
}
def eoiFn : ParserFn := fun c s =>
let i := s.pos
if c.input.atEnd i then s
else s.mkError "expected end of file"
@[inline] def eoi : Parser :=
{ fn := eoiFn }
open Std (RBMap RBMap.empty)
/-- A multimap indexed by tokens. Used for indexing parsers by their leading token. -/
def TokenMap (α : Type) := RBMap Name (List α) Name.quickLt
namespace TokenMap
def insert {α : Type} (map : TokenMap α) (k : Name) (v : α) : TokenMap α :=
match map.find? k with
| none => Std.RBMap.insert map k [v]
| some vs => Std.RBMap.insert map k (v::vs)
instance {α : Type} : Inhabited (TokenMap α) := ⟨RBMap.empty⟩
instance {α : Type} : EmptyCollection (TokenMap α) := ⟨RBMap.empty⟩
end TokenMap
structure PrattParsingTables :=
(leadingTable : TokenMap (Parser × Nat) := {})
(leadingParsers : List (Parser × Nat) := []) -- for supporting parsers we cannot obtain first token
(trailingTable : TokenMap (Parser × Nat) := {})
(trailingParsers : List (Parser × Nat) := []) -- for supporting parsers such as function application
instance : Inhabited PrattParsingTables := ⟨{}⟩
/--
Each parser category is implemented using a Pratt's parser.
The system comes equipped with the following categories: `level`, `term`, `tactic`, and `command`.
Users and plugins may define extra categories.
The field `leadingIdentAsSymbol` specifies how the parsing table
lookup function behaves for identifiers. The function `prattParser`
uses two tables `leadingTable` and `trailingTable`. They map tokens
to parsers. If `leadingIdentAsSymbol == false` and the leading token
is an identifier, then `prattParser` just executes the parsers
associated with the auxiliary token "ident". If
`leadingIdentAsSymbol == true` and the leading token is an
identifier `<foo>`, then `prattParser` combines the parsers
associated with the token `<foo>` with the parsers associated with
the auxiliary token "ident". We use this feature and the
`nonReservedSymbol` parser to implement the `tactic` parsers. We
use this approach to avoid creating a reserved symbol for each
builtin tactic (e.g., `apply`, `assumption`, etc.). That is, users
may still use these symbols as identifiers (e.g., naming a
function).
The method
```
categoryParser `term prec
```
executes the Pratt's parser for category `term` with precedence `prec`.
That is, only parsers with precedence at least `prec` are considered.
The method `termParser prec` is equivalent to the method above.
-/
structure ParserCategory :=
(tables : PrattParsingTables) (leadingIdentAsSymbol : Bool)
instance : Inhabited ParserCategory := ⟨{ tables := {}, leadingIdentAsSymbol := false }⟩
abbrev ParserCategories := Std.PersistentHashMap Name ParserCategory
def indexed {α : Type} (map : TokenMap α) (c : ParserContext) (s : ParserState) (leadingIdentAsSymbol : Bool) : ParserState × List α :=
let (s, stx) := peekToken c s
let find (n : Name) : ParserState × List α :=
match map.find? n with
| some as => (s, as)
| _ => (s, [])
match stx with
| some (Syntax.atom _ sym) => find (Name.mkSimple sym)
| some (Syntax.ident _ _ val _) =>
if leadingIdentAsSymbol then
match map.find? val with
| some as => match map.find? identKind with
| some as' => (s, as ++ as')
| _ => (s, as)
| none => find identKind
else
find identKind
| some (Syntax.node k _) => find k
| _ => (s, [])
abbrev CategoryParserFn := Name → ParserFn
builtin_initialize categoryParserFnRef : IO.Ref CategoryParserFn ← IO.mkRef fun _ => whitespace
builtin_initialize categoryParserFnExtension : EnvExtension CategoryParserFn ← registerEnvExtension $ categoryParserFnRef.get
def categoryParserFn (catName : Name) : ParserFn := fun ctx s =>
categoryParserFnExtension.getState ctx.env catName ctx s
def categoryParser (catName : Name) (prec : Nat) : Parser := {
fn := fun c s => categoryParserFn catName { c with prec := prec } s
}
-- Define `termParser` here because we need it for antiquotations
@[inline] def termParser (prec : Nat := 0) : Parser :=
categoryParser `term prec
/- ============== -/
/- Antiquotations -/
/- ============== -/
/-- Fail if previous token is immediately followed by ':'. -/
def checkNoImmediateColon : Parser := {
fn := fun c s =>
let prev := s.stxStack.back
if checkTailNoWs prev then
let input := c.input
let i := s.pos
if input.atEnd i then s
else
let curr := input.get i
if curr == ':' then
s.mkUnexpectedError "unexpected ':'"
else s
else s
}
def setExpectedFn (expected : List String) (p : ParserFn) : ParserFn := fun c s =>
match p c s with
| s'@{ errorMsg := some msg, .. } => { s' with errorMsg := some { msg with expected := [] } }
| s' => s'
def setExpected (expected : List String) (p : Parser) : Parser :=
{ fn := setExpectedFn expected p.fn, info := p.info }
def pushNone : Parser :=
{ fn := fun c s => s.pushSyntax mkNullNode }
-- We support two kinds of antiquotations: `$id` and `$(t)`, where `id` is a term identifier and `t` is a term.
def antiquotNestedExpr : Parser := node `antiquotNestedExpr (symbol "(" >> toggleInsideQuot termParser >> ")")
def antiquotExpr : Parser := identNoAntiquot <|> antiquotNestedExpr
/--
Define parser for `$e` (if anonymous == true) and `$e:name`. Both
forms can also be used with an appended `*` to turn them into an
antiquotation "splice". If `kind` is given, it will additionally be checked
when evaluating `match_syntax`. Antiquotations can be escaped as in `$$e`, which
produces the syntax tree for `$e`. -/
def mkAntiquot (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Parser :=
let kind := (kind.getD Name.anonymous) ++ `antiquot
let nameP := node `antiquotName $ checkNoWsBefore ("no space before ':" ++ name ++ "'") >> symbol ":" >> nonReservedSymbol name
-- if parsing the kind fails and `anonymous` is true, check that we're not ignoring a different
-- antiquotation kind via `noImmediateColon`
let nameP := if anonymous then nameP <|> checkNoImmediateColon >> pushNone else nameP
-- antiquotations are not part of the "standard" syntax, so hide "expected '$'" on error
node kind $ atomic $
setExpected [] "$" >>
many (checkNoWsBefore "" >> "$") >>
checkNoWsBefore "no space before spliced term" >> antiquotExpr >>
nameP >>
optional (checkNoWsBefore "" >> symbol "*")
def tryAnti (c : ParserContext) (s : ParserState) : Bool :=
let (s, stx?) := peekToken c s
match stx? with
| some stx@(Syntax.atom _ sym) => sym == "$"
| _ => false
@[inline] def withAntiquotFn (antiquotP p : ParserFn) : ParserFn := fun c s =>
if tryAnti c s then orelseFn antiquotP p c s else p c s
/-- Optimized version of `mkAntiquot ... <|> p`. -/
@[inline] def withAntiquot (antiquotP p : Parser) : Parser := {
fn := withAntiquotFn antiquotP.fn p.fn,
info := orelseInfo antiquotP.info p.info
}
/- ===================== -/
/- End of Antiquotations -/
/- ===================== -/
def nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : Parser) (anonymous := false) : Parser :=
withAntiquot (mkAntiquot name kind anonymous) $ node kind p
def ident : Parser :=
withAntiquot (mkAntiquot "ident" identKind) identNoAntiquot
-- `ident` and `rawIdent` produce the same syntax tree, so we reuse the antiquotation kind name
def rawIdent : Parser :=
withAntiquot (mkAntiquot "ident" identKind) rawIdentNoAntiquot
def numLit : Parser :=
withAntiquot (mkAntiquot "numLit" numLitKind) numLitNoAntiquot
def strLit : Parser :=
withAntiquot (mkAntiquot "strLit" strLitKind) strLitNoAntiquot
def charLit : Parser :=
withAntiquot (mkAntiquot "charLit" charLitKind) charLitNoAntiquot
def nameLit : Parser :=
withAntiquot (mkAntiquot "nameLit" nameLitKind) nameLitNoAntiquot
def categoryParserOfStackFn (offset : Nat) : ParserFn := fun ctx s =>
let stack := s.stxStack
if stack.size < offset + 1 then
s.mkUnexpectedError ("failed to determine parser category using syntax stack, stack is too small")
else
match stack.get! (stack.size - offset - 1) with
| Syntax.ident _ _ catName _ => categoryParserFn catName ctx s
| _ => s.mkUnexpectedError ("failed to determine parser category using syntax stack, the specified element on the stack is not an identifier")
def categoryParserOfStack (offset : Nat) (prec : Nat := 0) : Parser :=
{ fn := fun c s => categoryParserOfStackFn offset { c with prec := prec } s }
private def mkResult (s : ParserState) (iniSz : Nat) : ParserState :=
if s.stackSize == iniSz + 1 then s
else s.mkNode nullKind iniSz -- throw error instead?
def leadingParserAux (kind : Name) (tables : PrattParsingTables) (leadingIdentAsSymbol : Bool) : ParserFn := fun c s =>
let iniSz := s.stackSize
let (s, ps) := indexed tables.leadingTable c s leadingIdentAsSymbol
let ps := tables.leadingParsers ++ ps
if ps.isEmpty then
s.mkError (toString kind)
else
let s := longestMatchFn none ps c s
mkResult s iniSz
@[inline] def leadingParser (kind : Name) (tables : PrattParsingTables) (leadingIdentAsSymbol : Bool) (antiquotParser : ParserFn) : ParserFn :=
withAntiquotFn antiquotParser (leadingParserAux kind tables leadingIdentAsSymbol)
def trailingLoopStep (tables : PrattParsingTables) (left : Syntax) (ps : List (Parser × Nat)) : ParserFn := fun c s =>
longestMatchFn left (ps ++ tables.trailingParsers) c s
private def mkTrailingResult (s : ParserState) (iniSz : Nat) : ParserState :=
let s := mkResult s iniSz
-- Stack contains `[..., left, result]`
-- We must remove `left`
let result := s.stxStack.back
let s := s.popSyntax.popSyntax
s.pushSyntax result
partial def trailingLoop (tables : PrattParsingTables) (c : ParserContext) (s : ParserState) : ParserState :=
let identAsSymbol := false
let (s, ps) := indexed tables.trailingTable c s identAsSymbol
if ps.isEmpty && tables.trailingParsers.isEmpty then
s -- no available trailing parser
else
let left := s.stxStack.back
let iniSz := s.stackSize
let iniPos := s.pos
let s := trailingLoopStep tables left ps c s
if s.hasError then
if s.pos == iniPos then s.restore iniSz iniPos else s
else
let s := mkTrailingResult s iniSz
trailingLoop tables c s
/--
Implements a variant of Pratt's algorithm. In Pratt's algorithms tokens have a right and left binding power.
In our implementation, parsers have precedence instead. This method selects a parser (or more, via
`longestMatchFn`) from `leadingTable` based on the current token. Note that the unindexed `leadingParsers` parsers
are also tried. We have the unidexed `leadingParsers` because some parsers do not have a "first token". Example:
```
syntax term:51 "≤" ident "<" term "|" term : index
```
Example, in principle, the set of first tokens for this parser is any token that can start a term, but this set
is always changing. Thus, this parsing rule is stored as an unindexed leading parser at `leadingParsers`.
After processing the leading parser, we chain with parsers from `trailingTable`/`trailingParsers` that have precedence
at least `c.prec` where `c` is the `ParsingContext`. Recall that `c.prec` is set by `categoryParser`.
Note that in the original Pratt's algorith, precedences are only checked before calling trailing parsers. In our
implementation, leading *and* trailing parsers check the precendece. We claim our algorithm is more flexible,
modular and easier to understand.
`antiquotParser` should be a `mkAntiquot` parser (or always fail) and is tried before all other parsers.
It should not be added to the regular leading parsers because it would heavily
overlap with antiquotation parsers nested inside them. -/
@[inline] def prattParser (kind : Name) (tables : PrattParsingTables) (leadingIdentAsSymbol : Bool) (antiquotParser : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := leadingParser kind tables leadingIdentAsSymbol antiquotParser c s
if s.hasError then
s
else
trailingLoop tables c s
def fieldIdxFn : ParserFn := fun c s =>
let iniPos := s.pos
let curr := c.input.get iniPos
if curr.isDigit && curr != '0' then
let s := takeWhileFn (fun c => c.isDigit) c s
mkNodeToken fieldIdxKind iniPos c s
else
s.mkErrorAt "field index" iniPos
@[inline] def fieldIdx : Parser :=
withAntiquot (mkAntiquot "fieldIdx" `fieldIdx) {
fn := fieldIdxFn,
info := mkAtomicInfo "fieldIdx"
}
@[inline] def skip : Parser := {
fn := fun c s => s,
info := epsilonInfo
}
end Parser
namespace Syntax
section
variables {β : Type} {m : Type → Type} [Monad m]
@[inline] def foldArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β :=
s.getArgs.foldlM (flip f) b
@[inline] def foldArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β :=
Id.run (s.foldArgsM f b)
@[inline] def forArgsM (s : Syntax) (f : Syntax → m Unit) : m Unit :=
s.foldArgsM (fun s _ => f s) ()
end
end Syntax
end Lean
|
3e3375187dca38780d838d6a5a0de9bba2d06778 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/topology/algebra/polynomial_auto.lean | fa9df827c19670b442d2e0084122b7e8d3291450 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,138 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Robert Y. Lewis
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.polynomial.algebra_map
import Mathlib.data.polynomial.div
import Mathlib.topology.metric_space.cau_seq_filter
import Mathlib.PostPort
universes u_1 u_2 u_3 u_4
namespace Mathlib
/-!
# Polynomials and limits
In this file we prove the following lemmas.
* `polynomial.continuous_eval₂: `polynomial.eval₂` defines a continuous function.
* `polynomial.continuous_aeval: `polynomial.aeval` defines a continuous function;
we also prove convenience lemmas `polynomial.continuous_at_aeval`,
`polynomial.continuous_within_at_aeval`, `polynomial.continuous_on_aeval`.
* `polynomial.continuous`: `polynomial.eval` defines a continuous functions;
we also prove convenience lemmas `polynomial.continuous_at`, `polynomial.continuous_within_at`,
`polynomial.continuous_on`.
* `polynomial.tendsto_norm_at_top`: `λ x, ∥polynomial.eval (z x) p∥` tends to infinity provided that
`λ x, ∥z x∥` tends to infinity and `0 < degree p`;
* `polynomial.tendsto_abv_eval₂_at_top`, `polynomial.tendsto_abv_at_top`,
`polynomial.tendsto_abv_aeval_at_top`: a few versions of the previous statement for
`is_absolute_value abv` instead of norm.
## Tags
polynomial, continuity
-/
namespace polynomial
protected theorem continuous_eval₂ {R : Type u_1} {S : Type u_2} [semiring R] [topological_space R]
[topological_semiring R] [semiring S] (p : polynomial S) (f : S →+* R) :
continuous fun (x : R) => eval₂ f x p :=
id
(continuous_finset_sum (finsupp.support p)
fun (c : ℕ) (hc : c ∈ finsupp.support p) =>
continuous.mul continuous_const (continuous_pow c))
protected theorem continuous {R : Type u_1} [semiring R] [topological_space R]
[topological_semiring R] (p : polynomial R) : continuous fun (x : R) => eval x p :=
polynomial.continuous_eval₂ p (ring_hom.id R)
protected theorem continuous_at {R : Type u_1} [semiring R] [topological_space R]
[topological_semiring R] (p : polynomial R) {a : R} :
continuous_at (fun (x : R) => eval x p) a :=
continuous.continuous_at (polynomial.continuous p)
protected theorem continuous_within_at {R : Type u_1} [semiring R] [topological_space R]
[topological_semiring R] (p : polynomial R) {s : set R} {a : R} :
continuous_within_at (fun (x : R) => eval x p) s a :=
continuous.continuous_within_at (polynomial.continuous p)
protected theorem continuous_on {R : Type u_1} [semiring R] [topological_space R]
[topological_semiring R] (p : polynomial R) {s : set R} :
continuous_on (fun (x : R) => eval x p) s :=
continuous.continuous_on (polynomial.continuous p)
protected theorem continuous_aeval {R : Type u_1} {A : Type u_2} [comm_semiring R] [semiring A]
[algebra R A] [topological_space A] [topological_semiring A] (p : polynomial R) :
continuous fun (x : A) => coe_fn (aeval x) p :=
polynomial.continuous_eval₂ p (algebra_map R A)
protected theorem continuous_at_aeval {R : Type u_1} {A : Type u_2} [comm_semiring R] [semiring A]
[algebra R A] [topological_space A] [topological_semiring A] (p : polynomial R) {a : A} :
continuous_at (fun (x : A) => coe_fn (aeval x) p) a :=
continuous.continuous_at (polynomial.continuous_aeval p)
protected theorem continuous_within_at_aeval {R : Type u_1} {A : Type u_2} [comm_semiring R]
[semiring A] [algebra R A] [topological_space A] [topological_semiring A] (p : polynomial R)
{s : set A} {a : A} : continuous_within_at (fun (x : A) => coe_fn (aeval x) p) s a :=
continuous.continuous_within_at (polynomial.continuous_aeval p)
protected theorem continuous_on_aeval {R : Type u_1} {A : Type u_2} [comm_semiring R] [semiring A]
[algebra R A] [topological_space A] [topological_semiring A] (p : polynomial R) {s : set A} :
continuous_on (fun (x : A) => coe_fn (aeval x) p) s :=
continuous.continuous_on (polynomial.continuous_aeval p)
theorem tendsto_abv_eval₂_at_top {R : Type u_1} {S : Type u_2} {k : Type u_3} {α : Type u_4}
[semiring R] [ring S] [linear_ordered_field k] (f : R →+* S) (abv : S → k)
[is_absolute_value abv] (p : polynomial R) (hd : 0 < degree p)
(hf : coe_fn f (leading_coeff p) ≠ 0) {l : filter α} {z : α → S}
(hz : filter.tendsto (abv ∘ z) l filter.at_top) :
filter.tendsto (fun (x : α) => abv (eval₂ f (z x) p)) l filter.at_top :=
sorry
theorem tendsto_abv_at_top {R : Type u_1} {k : Type u_2} {α : Type u_3} [ring R]
[linear_ordered_field k] (abv : R → k) [is_absolute_value abv] (p : polynomial R)
(h : 0 < degree p) {l : filter α} {z : α → R} (hz : filter.tendsto (abv ∘ z) l filter.at_top) :
filter.tendsto (fun (x : α) => abv (eval (z x) p)) l filter.at_top :=
tendsto_abv_eval₂_at_top (ring_hom.id R) abv p h
(mt (iff.mp leading_coeff_eq_zero) (ne_zero_of_degree_gt h)) hz
theorem tendsto_abv_aeval_at_top {R : Type u_1} {A : Type u_2} {k : Type u_3} {α : Type u_4}
[comm_semiring R] [ring A] [algebra R A] [linear_ordered_field k] (abv : A → k)
[is_absolute_value abv] (p : polynomial R) (hd : 0 < degree p)
(h₀ : coe_fn (algebra_map R A) (leading_coeff p) ≠ 0) {l : filter α} {z : α → A}
(hz : filter.tendsto (abv ∘ z) l filter.at_top) :
filter.tendsto (fun (x : α) => abv (coe_fn (aeval (z x)) p)) l filter.at_top :=
tendsto_abv_eval₂_at_top (algebra_map R A) abv p hd h₀ hz
theorem tendsto_norm_at_top {α : Type u_1} {R : Type u_2} [normed_ring R] [is_absolute_value norm]
(p : polynomial R) (h : 0 < degree p) {l : filter α} {z : α → R}
(hz : filter.tendsto (fun (x : α) => norm (z x)) l filter.at_top) :
filter.tendsto (fun (x : α) => norm (eval (z x) p)) l filter.at_top :=
tendsto_abv_at_top norm p h hz
theorem exists_forall_norm_le {R : Type u_2} [normed_ring R] [is_absolute_value norm]
[proper_space R] (p : polynomial R) : ∃ (x : R), ∀ (y : R), norm (eval x p) ≤ norm (eval y p) :=
sorry
end Mathlib |
d5f1560539032cb9690dea56f1638a8fe9525442 | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /stage0/src/Lean/Elab/PreDefinition/MkInhabitant.lean | e8509a0708206e6d26e71eb429bc49e4fd8168e7 | [
"Apache-2.0"
] | permissive | williamdemeo/lean4 | 72161c58fe65c3ad955d6a3050bb7d37c04c0d54 | 6d00fcf1d6d873e195f9220c668ef9c58e9c4a35 | refs/heads/master | 1,678,305,356,877 | 1,614,708,995,000 | 1,614,708,995,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,430 | 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.AppBuilder
namespace Lean.Elab
open Meta
private def mkInhabitant? (type : Expr) : MetaM (Option Expr) := do
try
pure $ some (← mkArbitrary type)
catch _ =>
pure none
private def findAssumption? (xs : Array Expr) (type : Expr) : MetaM (Option Expr) := do
xs.findM? fun x => do isDefEq (← inferType x) type
private def mkFnInhabitant? (xs : Array Expr) (type : Expr) : MetaM (Option Expr) :=
let rec loop
| 0, type => mkInhabitant? type
| i+1, type => do
let x := xs[i]
let type ← mkForallFVars #[x] type;
match ← mkInhabitant? type with
| none => loop i type
| some val => pure $ some (← mkLambdaFVars xs[0:i] val)
loop xs.size type
/- TODO: add a global IO.Ref to let users customize/extend this procedure -/
def mkInhabitantFor (declName : Name) (xs : Array Expr) (type : Expr) : MetaM Expr := do
match ← mkInhabitant? type with
| some val => mkLambdaFVars xs val
| none =>
match ← findAssumption? xs type with
| some x => mkLambdaFVars xs x
| none =>
match ← mkFnInhabitant? xs type with
| some val => pure val
| none => throwError! "failed to compile partial definition '{declName}', failed to show that type is inhabited"
end Lean.Elab
|
ad0e127133a2d2462324c865ac3a4ec94a06363c | f4bff2062c030df03d65e8b69c88f79b63a359d8 | /src/game/cardinality/union_finite.lean | 33638c70fa506bf9173252677e8fcf84585524e2 | [
"Apache-2.0"
] | permissive | adastra7470/real-number-game | 776606961f52db0eb824555ed2f8e16f92216ea3 | f9dcb7d9255a79b57e62038228a23346c2dc301b | refs/heads/master | 1,669,221,575,893 | 1,594,669,800,000 | 1,594,669,800,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 479 | lean | import data.real.basic
import topology.basic
open function
open set
namespace xena -- hide
/-
# Chapter 7 : Cardinality
## Level 1
A classical result about finite sets.
-/
-- begin hide
local attribute [instance] classical.prop_decidable
-- end hide
/- Lemma
If $f : X \to Y$ is an injective function and $Y$ is finite, then
$X$ is also finite.
-/
theorem union_finite (X Y : set ℝ) : finite X → finite Y → finite (X ∪ Y) :=
begin
sorry,
end
end xena -- hide
|
6fc6341595ddc99949ccdc0e00eb4744227a7678 | 78269ad0b3c342b20786f60690708b6e328132b0 | /src/library_dev/data/int/basic.lean | 10a8378febf97ca7e41611ceb9a901e51665511b | [] | no_license | dselsam/library_dev | e74f46010fee9c7b66eaa704654cad0fcd2eefca | 1b4e34e7fb067ea5211714d6d3ecef5132fc8218 | refs/heads/master | 1,610,372,841,675 | 1,497,014,421,000 | 1,497,014,421,000 | 86,526,137 | 0 | 0 | null | 1,490,752,133,000 | 1,490,752,132,000 | null | UTF-8 | Lean | false | false | 3,176 | 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.
-/
import ..nat.sub
open nat
-- TODO: where to put these?
meta def simp_coe_attr : user_attribute :=
{ name := `simp.coe,
descr := "rules for pushing coercions inwards"}
run_cmd attribute.register ``simp_coe_attr
meta def simp_coe_out_attr : user_attribute :=
{ name := `simp.coe_out,
descr := "rules for pushing coercions outwards"}
run_cmd attribute.register ``simp_coe_out_attr
instance : inhabited ℤ := ⟨0⟩
meta instance : has_to_format ℤ := ⟨λ z, int.rec_on z (λ k, ↑k) (λ k, "-("++↑k++"+1)")⟩
/-
/- nat abs -/
theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := sorry
theorem nat_abs_neg_of_nat (n : nat) : nat_abs (neg_of_nat n) = n :=
begin cases n, reflexivity, reflexivity end
section
local attribute nat_abs [reducible]
theorem nat_abs_mul : Π (a b : ℤ), nat_abs (a * b) = (nat_abs a) * (nat_abs b)
| (of_nat m) (of_nat n) := rfl
| (of_nat m) -[1+ n] := by rewrite [mul_of_nat_neg_succ_of_nat, nat_abs_neg_of_nat]
| -[1+ m] (of_nat n) := by rewrite [mul_neg_succ_of_nat_of_nat, nat_abs_neg_of_nat]
| -[1+ m] -[1+ n] := rfl
end
/- additional properties -/
theorem of_nat_sub {m n : ℕ} (H : m ≥ n) : of_nat (m - n) = of_nat m - of_nat n :=
have m - n + n = m, from nat.sub_add_cancel H,
begin
symmetry,
apply sub_eq_of_eq_add,
rewrite [-of_nat_add, this]
end
theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 :=
by rewrite [neg_succ_of_nat_eq, neg_add]
def succ (a : ℤ) := a + (succ zero)
def pred (a : ℤ) := a - (succ zero)
def nat_succ_eq_int_succ (n : ℕ) : nat.succ n = int.succ n := rfl
theorem pred_succ (a : ℤ) : pred (succ a) = a := !sub_add_cancel
theorem succ_pred (a : ℤ) : succ (pred a) = a := !add_sub_cancel
theorem neg_succ (a : ℤ) : -succ a = pred (-a) :=
by rewrite [↑succ,neg_add]
theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a :=
by rewrite [neg_succ,succ_pred]
theorem neg_pred (a : ℤ) : -pred a = succ (-a) :=
by rewrite [↑pred,neg_sub,sub_eq_add_neg,add.comm]
theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a :=
by rewrite [neg_pred,pred_succ]
theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n
theorem neg_nat_succ (n : ℕ) : -nat.succ n = pred (-n) := !neg_succ
theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := !succ_neg_succ
attribute [unfold 2]
def rec_nat_on {P : ℤ → Type} (z : ℤ) (H0 : P 0)
(Hsucc : Π⦃n : ℕ⦄, P n → P (succ n)) (Hpred : Π⦃n : ℕ⦄, P (-n) → P (-nat.succ n)) : P z :=
int.rec (nat.rec H0 Hsucc) (λn, nat.rec H0 Hpred (nat.succ n)) z
--the only computation rule of rec_nat_on which is not defintional
theorem rec_nat_on_neg {P : ℤ → Type} (n : nat) (H0 : P zero)
(Hsucc : Π⦃n : nat⦄, P n → P (succ n)) (Hpred : Π⦃n : nat⦄, P (-n) → P (-nat.succ n))
: rec_nat_on (-nat.succ n) H0 Hsucc Hpred = Hpred (rec_nat_on (-n) H0 Hsucc Hpred) :=
nat.rec rfl (λn H, rfl) n
end int
-/
|
9ae8588d32aa6e4821528737a7e5d6bbe6ebbe0f | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Lean/Elab/PreDefinition/Structural/SmartUnfolding.lean | aaf3b54563ed79cc3cc9e3acdb2d2281f4a48e23 | [
"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 | 3,202 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.PreDefinition.Basic
import Lean.Elab.PreDefinition.Structural.Basic
namespace Lean.Elab.Structural
open Meta
partial def addSmartUnfoldingDefAux (preDef : PreDefinition) (recArgPos : Nat) : MetaM PreDefinition := do
return { preDef with
declName := mkSmartUnfoldingNameFor preDef.declName
value := (← visit preDef.value)
modifiers := {}
}
where
/--
Auxiliary method for annotating `match`-alternatives with `markSmartUnfoldingMatch` and `markSmartUnfoldingMatchAlt`.
It uses the following approach:
- Whenever it finds a `match` application `e` s.t. `recArgHasLooseBVarsAt preDef.declName recArgPos e`,
it marks the `match` with `markSmartUnfoldingMatch`, and each alternative that does not contain a nested marked `match`
is marked with `markSmartUnfoldingMatchAlt`.
Recall that the condition `recArgHasLooseBVarsAt preDef.declName recArgPos e` is the one used at `mkBRecOn`.
-/
visit (e : Expr) : MetaM Expr := do
match e with
| Expr.lam .. => lambdaTelescope e fun xs b => do mkLambdaFVars xs (← visit b)
| Expr.forallE .. => forallTelescope e fun xs b => do mkForallFVars xs (← visit b)
| Expr.letE n type val body _ =>
withLetDecl n type (← visit val) fun x => do mkLetFVars #[x] (← visit (body.instantiate1 x))
| Expr.mdata d b => return mkMData d (← visit b)
| Expr.proj n i s => return mkProj n i (← visit s)
| Expr.app .. =>
let processApp (e : Expr) : MetaM Expr :=
e.withApp fun f args =>
return mkAppN (← visit f) (← args.mapM visit)
match (← matchMatcherApp? e) with
| some matcherApp =>
if !recArgHasLooseBVarsAt preDef.declName recArgPos e then
processApp e
else
let mut altsNew := #[]
for alt in matcherApp.alts, numParams in matcherApp.altNumParams do
let altNew ← lambdaTelescope alt fun xs altBody => do
unless xs.size >= numParams do
throwError "unexpected matcher application alternative{indentExpr alt}\nat application{indentExpr e}"
let altBody ← visit altBody
let containsSUnfoldMatch := Option.isSome <| altBody.find? fun e => smartUnfoldingMatch? e |>.isSome
if !containsSUnfoldMatch then
let altBody ← mkLambdaFVars xs[numParams:xs.size] altBody
let altBody := markSmartUnfoldingMatchAlt altBody
mkLambdaFVars xs[0:numParams] altBody
else
mkLambdaFVars xs altBody
altsNew := altsNew.push altNew
return markSmartUnfoldingMatch { matcherApp with alts := altsNew }.toExpr
| _ => processApp e
| _ => return e
partial def addSmartUnfoldingDef (preDef : PreDefinition) (recArgPos : Nat) : TermElabM Unit := do
if (← isProp preDef.type) then
return ()
else
let preDefSUnfold ← addSmartUnfoldingDefAux preDef recArgPos
addNonRec preDefSUnfold
end Lean.Elab.Structural
|
a91e2cdcf3b335e164c337913704b078b9bae339 | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/ring_theory/polynomial/basic.lean | 669a839d3909d63fc0c056172a3ab5d4bd284255 | [
"Apache-2.0"
] | permissive | jumpy4/mathlib | d3829e75173012833e9f15ac16e481e17596de0f | af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13 | refs/heads/master | 1,693,508,842,818 | 1,636,203,271,000 | 1,636,203,271,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 43,756 | 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 algebra.char_p.basic
import data.mv_polynomial.comm_ring
import data.mv_polynomial.equiv
import ring_theory.principal_ideal_domain
import ring_theory.polynomial.content
/-!
# Ring-theoretic supplement of data.polynomial.
## Main results
* `mv_polynomial.is_domain`:
If a ring is an integral domain, then so is its polynomial ring over finitely many variables.
* `polynomial.is_noetherian_ring`:
Hilbert basis theorem, that if a ring is noetherian then so is its polynomial ring.
* `polynomial.wf_dvd_monoid`:
If an integral domain is a `wf_dvd_monoid`, then so is its polynomial ring.
* `polynomial.unique_factorization_monoid`:
If an integral domain is a `unique_factorization_monoid`, then so is its polynomial ring.
-/
noncomputable theory
open_locale classical big_operators
universes u v w
namespace polynomial
instance {R : Type u} [semiring R] (p : ℕ) [h : char_p R p] : char_p (polynomial R) p :=
let ⟨h⟩ := h in ⟨λ n, by rw [← C.map_nat_cast, ← C_0, C_inj, h]⟩
variables (R : Type u) [comm_ring R]
/-- The `R`-submodule of `R[X]` consisting of polynomials of degree ≤ `n`. -/
def degree_le (n : with_bot ℕ) : submodule R (polynomial R) :=
⨅ k : ℕ, ⨅ h : ↑k > n, (lcoeff R k).ker
/-- The `R`-submodule of `R[X]` consisting of polynomials of degree < `n`. -/
def degree_lt (n : ℕ) : submodule R (polynomial R) :=
⨅ k : ℕ, ⨅ h : k ≥ n, (lcoeff R k).ker
variable {R}
theorem mem_degree_le {n : with_bot ℕ} {f : polynomial R} :
f ∈ degree_le R n ↔ degree f ≤ n :=
by simp only [degree_le, submodule.mem_infi, degree_le_iff_coeff_zero, linear_map.mem_ker]; refl
@[mono] theorem degree_le_mono {m n : with_bot ℕ} (H : m ≤ n) :
degree_le R m ≤ degree_le R n :=
λ f hf, mem_degree_le.2 (le_trans (mem_degree_le.1 hf) H)
theorem degree_le_eq_span_X_pow {n : ℕ} :
degree_le R n = submodule.span R ↑((finset.range (n+1)).image (λ n, (X : polynomial R)^n)) :=
begin
apply le_antisymm,
{ intros p hp, replace hp := mem_degree_le.1 hp,
rw [← polynomial.sum_monomial_eq p, polynomial.sum],
refine submodule.sum_mem _ (λ k hk, _),
show monomial _ _ ∈ _,
have := with_bot.coe_le_coe.1 (finset.sup_le_iff.1 hp k hk),
rw [monomial_eq_C_mul_X, C_mul'],
refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $
finset.mem_image.2 ⟨_, finset.mem_range.2 (nat.lt_succ_of_le this), rfl⟩) },
rw [submodule.span_le, finset.coe_image, set.image_subset_iff],
intros k hk, apply mem_degree_le.2,
exact (degree_X_pow_le _).trans
(with_bot.coe_le_coe.2 $ nat.le_of_lt_succ $ finset.mem_range.1 hk)
end
theorem mem_degree_lt {n : ℕ} {f : polynomial R} :
f ∈ degree_lt R n ↔ degree f < n :=
by { simp_rw [degree_lt, submodule.mem_infi, linear_map.mem_ker, degree,
finset.sup_lt_iff (with_bot.bot_lt_coe n), mem_support_iff, with_bot.some_eq_coe,
with_bot.coe_lt_coe, lt_iff_not_ge', ne, not_imp_not], refl }
@[mono] theorem degree_lt_mono {m n : ℕ} (H : m ≤ n) :
degree_lt R m ≤ degree_lt R n :=
λ f hf, mem_degree_lt.2 (lt_of_lt_of_le (mem_degree_lt.1 hf) $ with_bot.coe_le_coe.2 H)
theorem degree_lt_eq_span_X_pow {n : ℕ} :
degree_lt R n = submodule.span R ↑((finset.range n).image (λ n, X^n) : finset (polynomial R)) :=
begin
apply le_antisymm,
{ intros p hp, replace hp := mem_degree_lt.1 hp,
rw [← polynomial.sum_monomial_eq p, polynomial.sum],
refine submodule.sum_mem _ (λ k hk, _),
show monomial _ _ ∈ _,
have := with_bot.coe_lt_coe.1 ((finset.sup_lt_iff $ with_bot.bot_lt_coe n).1 hp k hk),
rw [monomial_eq_C_mul_X, C_mul'],
refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $
finset.mem_image.2 ⟨_, finset.mem_range.2 this, rfl⟩) },
rw [submodule.span_le, finset.coe_image, set.image_subset_iff],
intros k hk, apply mem_degree_lt.2,
exact lt_of_le_of_lt (degree_X_pow_le _) (with_bot.coe_lt_coe.2 $ finset.mem_range.1 hk)
end
/-- The first `n` coefficients on `degree_lt n` form a linear equivalence with `fin n → F`. -/
def degree_lt_equiv (F : Type*) [field F] (n : ℕ) : degree_lt F n ≃ₗ[F] (fin n → F) :=
{ to_fun := λ p n, (↑p : polynomial F).coeff n,
inv_fun := λ f, ⟨∑ i : fin n, monomial i (f i),
(degree_lt F n).sum_mem (λ i _, mem_degree_lt.mpr (lt_of_le_of_lt
(degree_monomial_le i (f i)) (with_bot.coe_lt_coe.mpr i.is_lt)))⟩,
map_add' := λ p q, by { ext, rw [submodule.coe_add, coeff_add], refl },
map_smul' := λ x p, by { ext, rw [submodule.coe_smul, coeff_smul], refl },
left_inv :=
begin
rintro ⟨p, hp⟩, ext1,
simp only [submodule.coe_mk],
by_cases hp0 : p = 0,
{ subst hp0, simp only [coeff_zero, linear_map.map_zero, finset.sum_const_zero] },
rw [mem_degree_lt, degree_eq_nat_degree hp0, with_bot.coe_lt_coe] at hp,
conv_rhs { rw [p.as_sum_range' n hp, ← fin.sum_univ_eq_sum_range] },
end,
right_inv :=
begin
intro f, ext i,
simp only [finset_sum_coeff, submodule.coe_mk],
rw [finset.sum_eq_single i, coeff_monomial, if_pos rfl],
{ rintro j - hji, rw [coeff_monomial, if_neg], rwa [← subtype.ext_iff] },
{ intro h, exact (h (finset.mem_univ _)).elim }
end }
/-- The finset of nonzero coefficients of a polynomial. -/
def frange (p : polynomial R) : finset R :=
finset.image (λ n, p.coeff n) p.support
lemma frange_zero : frange (0 : polynomial R) = ∅ :=
rfl
lemma mem_frange_iff {p : polynomial R} {c : R} :
c ∈ p.frange ↔ ∃ n ∈ p.support, c = p.coeff n :=
by simp [frange, eq_comm]
lemma frange_one : frange (1 : polynomial R) ⊆ {1} :=
begin
simp [frange, finset.image_subset_iff],
simp only [← C_1, coeff_C],
assume n hn,
simp only [exists_prop, ite_eq_right_iff, not_forall] at hn,
simp [hn],
end
lemma coeff_mem_frange (p : polynomial R) (n : ℕ) (h : p.coeff n ≠ 0) :
p.coeff n ∈ p.frange :=
begin
simp only [frange, exists_prop, mem_support_iff, finset.mem_image, ne.def],
exact ⟨n, h, rfl⟩,
end
/-- Given a polynomial, return the polynomial whose coefficients are in
the ring closure of the original coefficients. -/
def restriction (p : polynomial R) : polynomial (subring.closure (↑p.frange : set R)) :=
∑ i in p.support, monomial i (⟨p.coeff i,
if H : p.coeff i = 0 then H.symm ▸ (subring.closure _).zero_mem
else subring.subset_closure (p.coeff_mem_frange _ H)⟩ : (subring.closure (↑p.frange : set R)))
@[simp] theorem coeff_restriction {p : polynomial R} {n : ℕ} :
↑(coeff (restriction p) n) = coeff p n :=
begin
simp only [restriction, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq',
ne.def, ite_not],
split_ifs,
{ rw h, refl },
{ refl }
end
@[simp] theorem coeff_restriction' {p : polynomial R} {n : ℕ} :
(coeff (restriction p) n).1 = coeff p n :=
coeff_restriction
@[simp] lemma support_restriction (p : polynomial R) :
support (restriction p) = support p :=
begin
ext i,
simp only [mem_support_iff, not_iff_not, ne.def],
conv_rhs { rw [← coeff_restriction] },
exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩
end
@[simp] theorem map_restriction (p : polynomial R) : p.restriction.map (algebra_map _ _) = p :=
ext $ λ n, by rw [coeff_map, algebra.algebra_map_of_subring_apply, coeff_restriction]
@[simp] theorem degree_restriction {p : polynomial R} : (restriction p).degree = p.degree :=
by simp [degree]
@[simp] theorem nat_degree_restriction {p : polynomial R} :
(restriction p).nat_degree = p.nat_degree :=
by simp [nat_degree]
@[simp] theorem monic_restriction {p : polynomial R} : monic (restriction p) ↔ monic p :=
begin
simp only [monic, leading_coeff, nat_degree_restriction],
rw [←@coeff_restriction _ _ p],
exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩
end
@[simp] theorem restriction_zero : restriction (0 : polynomial R) = 0 :=
by simp only [restriction, finset.sum_empty, support_zero]
@[simp] theorem restriction_one : restriction (1 : polynomial R) = 1 :=
ext $ λ i, subtype.eq $ by rw [coeff_restriction', coeff_one, coeff_one]; split_ifs; refl
variables {S : Type v} [ring S] {f : R →+* S} {x : S}
theorem eval₂_restriction {p : polynomial R} :
eval₂ f x p = eval₂ (f.comp (subring.subtype _)) x p.restriction :=
begin
simp only [eval₂_eq_sum, sum, support_restriction, ←@coeff_restriction _ _ p],
refl,
end
section to_subring
variables (p : polynomial R) (T : subring R)
/-- Given a polynomial `p` and a subring `T` that contains the coefficients of `p`,
return the corresponding polynomial whose coefficients are in `T. -/
def to_subring (hp : (↑p.frange : set R) ⊆ T) : polynomial T :=
∑ i in p.support, monomial i (⟨p.coeff i,
if H : p.coeff i = 0 then H.symm ▸ T.zero_mem
else hp (p.coeff_mem_frange _ H)⟩ : T)
variables (hp : (↑p.frange : set R) ⊆ T)
include hp
@[simp] theorem coeff_to_subring {n : ℕ} : ↑(coeff (to_subring p T hp) n) = coeff p n :=
begin
simp only [to_subring, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq',
ne.def, ite_not],
split_ifs,
{ rw h, refl },
{ refl }
end
@[simp] theorem coeff_to_subring' {n : ℕ} : (coeff (to_subring p T hp) n).1 = coeff p n :=
coeff_to_subring _ _ hp
@[simp] lemma support_to_subring :
support (to_subring p T hp) = support p :=
begin
ext i,
simp only [mem_support_iff, not_iff_not, ne.def],
conv_rhs { rw [← coeff_to_subring p T hp] },
exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩
end
@[simp] theorem degree_to_subring : (to_subring p T hp).degree = p.degree :=
by simp [degree]
@[simp] theorem nat_degree_to_subring : (to_subring p T hp).nat_degree = p.nat_degree :=
by simp [nat_degree]
@[simp] theorem monic_to_subring : monic (to_subring p T hp) ↔ monic p :=
begin
simp_rw [monic, leading_coeff, nat_degree_to_subring, ← coeff_to_subring p T hp],
exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩
end
omit hp
@[simp] theorem to_subring_zero : to_subring (0 : polynomial R) T (by simp [frange_zero]) = 0 :=
by { ext i, simp }
@[simp] theorem to_subring_one : to_subring (1 : polynomial R) T
(set.subset.trans frange_one $finset.singleton_subset_set_iff.2 T.one_mem) = 1 :=
ext $ λ i, subtype.eq $ by rw [coeff_to_subring', coeff_one, coeff_one]; split_ifs; refl
@[simp] theorem map_to_subring : (p.to_subring T hp).map (subring.subtype T) = p :=
by { ext n, simp [coeff_map] }
end to_subring
variables (T : subring R)
/-- Given a polynomial whose coefficients are in some subring, return
the corresponding polynomial whose coefficients are in the ambient ring. -/
def of_subring (p : polynomial T) : polynomial R :=
∑ i in p.support, monomial i (p.coeff i : R)
lemma coeff_of_subring (p : polynomial T) (n : ℕ) :
coeff (of_subring T p) n = (coeff p n : T) :=
begin
simp only [of_subring, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq',
ite_eq_right_iff, ne.def, ite_not, not_not, ite_eq_left_iff],
assume h,
rw h,
refl
end
@[simp] theorem frange_of_subring {p : polynomial T} :
(↑(p.of_subring T).frange : set R) ⊆ T :=
begin
assume i hi,
simp only [frange, set.mem_image, mem_support_iff, ne.def, finset.mem_coe, finset.coe_image]
at hi,
rcases hi with ⟨n, hn, h'n⟩,
rw [← h'n, coeff_of_subring],
exact subtype.mem (coeff p n : T)
end
section mod_by_monic
variables {q : polynomial R}
lemma mem_ker_mod_by_monic [nontrivial R] (hq : q.monic) {p : polynomial R} :
p ∈ (mod_by_monic_hom hq).ker ↔ q ∣ p :=
linear_map.mem_ker.trans (dvd_iff_mod_by_monic_eq_zero hq)
@[simp] lemma ker_mod_by_monic_hom [nontrivial R] (hq : q.monic) :
(polynomial.mod_by_monic_hom hq).ker = (ideal.span {q}).restrict_scalars R :=
submodule.ext (λ f, (mem_ker_mod_by_monic hq).trans ideal.mem_span_singleton.symm)
end mod_by_monic
end polynomial
variables {R : Type u} {S : Type*} {σ : Type v} {M : Type w}
variables [comm_ring R] [comm_ring S] [add_comm_group M] [module R M]
namespace ideal
open polynomial
/-- If every coefficient of a polynomial is in an ideal `I`, then so is the polynomial itself -/
lemma polynomial_mem_ideal_of_coeff_mem_ideal (I : ideal (polynomial R)) (p : polynomial R)
(hp : ∀ (n : ℕ), (p.coeff n) ∈ I.comap C) : p ∈ I :=
sum_C_mul_X_eq p ▸ submodule.sum_mem I (λ n hn, I.mul_mem_right _ (hp n))
/-- The push-forward of an ideal `I` of `R` to `polynomial R` via inclusion
is exactly the set of polynomials whose coefficients are in `I` -/
theorem mem_map_C_iff {I : ideal R} {f : polynomial R} :
f ∈ (ideal.map C I : ideal (polynomial R)) ↔ ∀ n : ℕ, f.coeff n ∈ I :=
begin
split,
{ intros hf,
apply submodule.span_induction hf,
{ intros f hf n,
cases (set.mem_image _ _ _).mp hf with x hx,
rw [← hx.right, coeff_C],
by_cases (n = 0),
{ simpa [h] using hx.left },
{ simp [h] } },
{ simp },
{ exact λ f g hf hg n, by simp [I.add_mem (hf n) (hg n)] },
{ refine λ f g hg n, _,
rw [smul_eq_mul, coeff_mul],
exact I.sum_mem (λ c hc, I.smul_mem (f.coeff c.fst) (hg c.snd)) } },
{ intros hf,
rw ← sum_monomial_eq f,
refine (I.map C : ideal (polynomial R)).sum_mem (λ n hn, _),
simp [monomial_eq_C_mul_X],
rw mul_comm,
exact (I.map C : ideal (polynomial R)).mul_mem_left _ (mem_map_of_mem _ (hf n)) }
end
lemma _root_.polynomial.ker_map_ring_hom (f : R →+* S) :
(polynomial.map_ring_hom f).ker = f.ker.map C :=
begin
ext,
rw [mem_map_C_iff, ring_hom.mem_ker, polynomial.ext_iff],
simp_rw [coe_map_ring_hom, coeff_map, coeff_zero, ring_hom.mem_ker],
end
lemma quotient_map_C_eq_zero {I : ideal R} :
∀ a ∈ I, ((quotient.mk (map C I : ideal (polynomial R))).comp C) a = 0 :=
begin
intros a ha,
rw [ring_hom.comp_apply, quotient.eq_zero_iff_mem],
exact mem_map_of_mem _ ha,
end
lemma eval₂_C_mk_eq_zero {I : ideal R} :
∀ f ∈ (map C I : ideal (polynomial R)), eval₂_ring_hom (C.comp (quotient.mk I)) X f = 0 :=
begin
intros a ha,
rw ← sum_monomial_eq a,
dsimp,
rw eval₂_sum,
refine finset.sum_eq_zero (λ n hn, _),
dsimp,
rw eval₂_monomial (C.comp (quotient.mk I)) X,
refine mul_eq_zero_of_left (polynomial.ext (λ m, _)) (X ^ n),
erw coeff_C,
by_cases h : m = 0,
{ simpa [h] using quotient.eq_zero_iff_mem.2 ((mem_map_C_iff.1 ha) n) },
{ simp [h] }
end
/-- If `I` is an ideal of `R`, then the ring polynomials over the quotient ring `I.quotient` is
isomorphic to the quotient of `polynomial R` by the ideal `map C I`,
where `map C I` contains exactly the polynomials whose coefficients all lie in `I` -/
def polynomial_quotient_equiv_quotient_polynomial (I : ideal R) :
polynomial (I.quotient) ≃+* (map C I : ideal (polynomial R)).quotient :=
{ to_fun := eval₂_ring_hom
(quotient.lift I ((quotient.mk (map C I : ideal (polynomial R))).comp C) quotient_map_C_eq_zero)
((quotient.mk (map C I : ideal (polynomial R)) X)),
inv_fun := quotient.lift (map C I : ideal (polynomial R))
(eval₂_ring_hom (C.comp (quotient.mk I)) X) eval₂_C_mk_eq_zero,
map_mul' := λ f g, by simp only [coe_eval₂_ring_hom, eval₂_mul],
map_add' := λ f g, by simp only [eval₂_add, coe_eval₂_ring_hom],
left_inv := begin
intro f,
apply polynomial.induction_on' f,
{ intros p q hp hq,
simp only [coe_eval₂_ring_hom] at hp,
simp only [coe_eval₂_ring_hom] at hq,
simp only [coe_eval₂_ring_hom, hp, hq, ring_hom.map_add] },
{ rintros n ⟨x⟩,
simp only [monomial_eq_smul_X, C_mul', quotient.lift_mk, submodule.quotient.quot_mk_eq_mk,
quotient.mk_eq_mk, eval₂_X_pow, eval₂_smul, coe_eval₂_ring_hom, ring_hom.map_pow,
eval₂_C, ring_hom.coe_comp, ring_hom.map_mul, eval₂_X] }
end,
right_inv := begin
rintro ⟨f⟩,
apply polynomial.induction_on' f,
{ simp_intros p q hp hq,
rw [hp, hq] },
{ intros n a,
simp only [monomial_eq_smul_X, ← C_mul' a (X ^ n), quotient.lift_mk,
submodule.quotient.quot_mk_eq_mk, quotient.mk_eq_mk, eval₂_X_pow,
eval₂_smul, coe_eval₂_ring_hom, ring_hom.map_pow, eval₂_C, ring_hom.coe_comp,
ring_hom.map_mul, eval₂_X] },
end,
}
@[simp]
lemma polynomial_quotient_equiv_quotient_polynomial_symm_mk (I : ideal R) (f : polynomial R) :
I.polynomial_quotient_equiv_quotient_polynomial.symm (quotient.mk _ f) = f.map (quotient.mk I) :=
by rw [polynomial_quotient_equiv_quotient_polynomial, ring_equiv.symm_mk, ring_equiv.coe_mk,
ideal.quotient.lift_mk, coe_eval₂_ring_hom, eval₂_eq_eval_map, ←polynomial.map_map,
←eval₂_eq_eval_map, polynomial.eval₂_C_X]
@[simp]
lemma polynomial_quotient_equiv_quotient_polynomial_map_mk (I : ideal R) (f : polynomial R) :
I.polynomial_quotient_equiv_quotient_polynomial (f.map I^.quotient.mk) = quotient.mk _ f :=
begin
apply (polynomial_quotient_equiv_quotient_polynomial I).symm.injective,
rw [ring_equiv.symm_apply_apply, polynomial_quotient_equiv_quotient_polynomial_symm_mk],
end
/-- If `P` is a prime ideal of `R`, then `R[x]/(P)` is an integral domain. -/
lemma is_domain_map_C_quotient {P : ideal R} (H : is_prime P) :
is_domain (quotient (map C P : ideal (polynomial R))) :=
ring_equiv.is_domain (polynomial (quotient P))
(polynomial_quotient_equiv_quotient_polynomial P).symm
/-- If `P` is a prime ideal of `R`, then `P.R[x]` is a prime ideal of `R[x]`. -/
lemma is_prime_map_C_of_is_prime {P : ideal R} (H : is_prime P) :
is_prime (map C P : ideal (polynomial R)) :=
(quotient.is_domain_iff_prime (map C P : ideal (polynomial R))).mp
(is_domain_map_C_quotient H)
/-- Given any ring `R` and an ideal `I` of `polynomial R`, we get a map `R → R[x] → R[x]/I`.
If we let `R` be the image of `R` in `R[x]/I` then we also have a map `R[x] → R'[x]`.
In particular we can map `I` across this map, to get `I'` and a new map `R' → R'[x] → R'[x]/I`.
This theorem shows `I'` will not contain any non-zero constant polynomials
-/
lemma eq_zero_of_polynomial_mem_map_range (I : ideal (polynomial R))
(x : ((quotient.mk I).comp C).range)
(hx : C x ∈ (I.map (polynomial.map_ring_hom ((quotient.mk I).comp C).range_restrict))) :
x = 0 :=
begin
let i := ((quotient.mk I).comp C).range_restrict,
have hi' : (polynomial.map_ring_hom i).ker ≤ I,
{ refine λ f hf, polynomial_mem_ideal_of_coeff_mem_ideal I f (λ n, _),
rw [mem_comap, ← quotient.eq_zero_iff_mem, ← ring_hom.comp_apply],
rw [ring_hom.mem_ker, coe_map_ring_hom] at hf,
replace hf := congr_arg (λ (f : polynomial _), f.coeff n) hf,
simp only [coeff_map, coeff_zero] at hf,
rwa [subtype.ext_iff, ring_hom.coe_range_restrict] at hf },
obtain ⟨x, hx'⟩ := x,
obtain ⟨y, rfl⟩ := (ring_hom.mem_range).1 hx',
refine subtype.eq _,
simp only [ring_hom.comp_apply, quotient.eq_zero_iff_mem, subring.coe_zero, subtype.val_eq_coe],
suffices : C (i y) ∈ (I.map (polynomial.map_ring_hom i)),
{ obtain ⟨f, hf⟩ := mem_image_of_mem_map_of_surjective (polynomial.map_ring_hom i)
(polynomial.map_surjective _ (((quotient.mk I).comp C).range_restrict_surjective)) this,
refine sub_add_cancel (C y) f ▸ I.add_mem (hi' _ : (C y - f) ∈ I) hf.1,
rw [ring_hom.mem_ker, ring_hom.map_sub, hf.2, sub_eq_zero, coe_map_ring_hom, map_C] },
exact hx,
end
/-- `polynomial R` is never a field for any ring `R`. -/
lemma polynomial_not_is_field : ¬ is_field (polynomial R) :=
begin
by_contradiction hR,
by_cases hR' : ∃ (x y : R), x ≠ y,
{ haveI : nontrivial R := let ⟨x, y, hxy⟩ := hR' in nontrivial_of_ne x y hxy,
obtain ⟨p, hp⟩ := hR.mul_inv_cancel X_ne_zero,
by_cases hp0 : p = 0,
{ replace hp := congr_arg degree hp,
rw [hp0, mul_zero, degree_zero, degree_one] at hp,
contradiction },
{ have : p.degree < (X * p).degree := (mul_comm p X) ▸ degree_lt_degree_mul_X hp0,
rw [congr_arg degree hp, degree_one, nat.with_bot.lt_zero_iff, degree_eq_bot] at this,
exact hp0 this } },
{ push_neg at hR',
exact let ⟨x, y, hxy⟩ := hR.exists_pair_ne in hxy (polynomial.ext (λ n, hR' _ _)) }
end
/-- The only constant in a maximal ideal over a field is `0`. -/
lemma eq_zero_of_constant_mem_of_maximal (hR : is_field R)
(I : ideal (polynomial R)) [hI : I.is_maximal] (x : R) (hx : C x ∈ I) : x = 0 :=
begin
refine classical.by_contradiction (λ hx0, hI.ne_top ((eq_top_iff_one I).2 _)),
obtain ⟨y, hy⟩ := hR.mul_inv_cancel hx0,
convert I.smul_mem (C y) hx,
rw [smul_eq_mul, ← C.map_mul, mul_comm y x, hy, ring_hom.map_one],
end
/-- Transport an ideal of `R[X]` to an `R`-submodule of `R[X]`. -/
def of_polynomial (I : ideal (polynomial R)) : submodule R (polynomial R) :=
{ carrier := I.carrier,
zero_mem' := I.zero_mem,
add_mem' := λ _ _, I.add_mem,
smul_mem' := λ c x H, by { rw [← C_mul'], exact I.mul_mem_left _ H } }
variables {I : ideal (polynomial R)}
theorem mem_of_polynomial (x) : x ∈ I.of_polynomial ↔ x ∈ I := iff.rfl
variables (I)
/-- Given an ideal `I` of `R[X]`, make the `R`-submodule of `I`
consisting of polynomials of degree ≤ `n`. -/
def degree_le (n : with_bot ℕ) : submodule R (polynomial R) :=
degree_le R n ⊓ I.of_polynomial
/-- Given an ideal `I` of `R[X]`, make the ideal in `R` of
leading coefficients of polynomials in `I` with degree ≤ `n`. -/
def leading_coeff_nth (n : ℕ) : ideal R :=
(I.degree_le n).map $ lcoeff R n
theorem mem_leading_coeff_nth (n : ℕ) (x) :
x ∈ I.leading_coeff_nth n ↔ ∃ p ∈ I, degree p ≤ n ∧ leading_coeff p = x :=
begin
simp only [leading_coeff_nth, degree_le, submodule.mem_map, lcoeff_apply, submodule.mem_inf,
mem_degree_le],
split,
{ rintro ⟨p, ⟨hpdeg, hpI⟩, rfl⟩,
cases lt_or_eq_of_le hpdeg with hpdeg hpdeg,
{ refine ⟨0, I.zero_mem, bot_le, _⟩,
rw [leading_coeff_zero, eq_comm],
exact coeff_eq_zero_of_degree_lt hpdeg },
{ refine ⟨p, hpI, le_of_eq hpdeg, _⟩,
rw [leading_coeff, nat_degree, hpdeg], refl } },
{ rintro ⟨p, hpI, hpdeg, rfl⟩,
have : nat_degree p + (n - nat_degree p) = n,
{ exact add_tsub_cancel_of_le (nat_degree_le_of_degree_le hpdeg) },
refine ⟨p * X ^ (n - nat_degree p), ⟨_, I.mul_mem_right _ hpI⟩, _⟩,
{ apply le_trans (degree_mul_le _ _) _,
apply le_trans (add_le_add (degree_le_nat_degree) (degree_X_pow_le _)) _,
rw [← with_bot.coe_add, this],
exact le_refl _ },
{ rw [leading_coeff, ← coeff_mul_X_pow p (n - nat_degree p), this] } }
end
theorem mem_leading_coeff_nth_zero (x) :
x ∈ I.leading_coeff_nth 0 ↔ C x ∈ I :=
(mem_leading_coeff_nth _ _ _).trans
⟨λ ⟨p, hpI, hpdeg, hpx⟩, by rwa [← hpx, leading_coeff,
nat.eq_zero_of_le_zero (nat_degree_le_of_degree_le hpdeg),
← eq_C_of_degree_le_zero hpdeg],
λ hx, ⟨C x, hx, degree_C_le, leading_coeff_C x⟩⟩
theorem leading_coeff_nth_mono {m n : ℕ} (H : m ≤ n) :
I.leading_coeff_nth m ≤ I.leading_coeff_nth n :=
begin
intros r hr,
simp only [set_like.mem_coe, mem_leading_coeff_nth] at hr ⊢,
rcases hr with ⟨p, hpI, hpdeg, rfl⟩,
refine ⟨p * X ^ (n - m), I.mul_mem_right _ hpI, _, leading_coeff_mul_X_pow⟩,
refine le_trans (degree_mul_le _ _) _,
refine le_trans (add_le_add hpdeg (degree_X_pow_le _)) _,
rw [← with_bot.coe_add, add_tsub_cancel_of_le H],
exact le_refl _
end
/-- Given an ideal `I` in `R[X]`, make the ideal in `R` of the
leading coefficients in `I`. -/
def leading_coeff : ideal R :=
⨆ n : ℕ, I.leading_coeff_nth n
theorem mem_leading_coeff (x) :
x ∈ I.leading_coeff ↔ ∃ p ∈ I, polynomial.leading_coeff p = x :=
begin
rw [leading_coeff, submodule.mem_supr_of_directed],
simp only [mem_leading_coeff_nth],
{ split, { rintro ⟨i, p, hpI, hpdeg, rfl⟩, exact ⟨p, hpI, rfl⟩ },
rintro ⟨p, hpI, rfl⟩, exact ⟨nat_degree p, p, hpI, degree_le_nat_degree, rfl⟩ },
intros i j, exact ⟨i + j, I.leading_coeff_nth_mono (nat.le_add_right _ _),
I.leading_coeff_nth_mono (nat.le_add_left _ _)⟩
end
theorem is_fg_degree_le [is_noetherian_ring R] (n : ℕ) :
submodule.fg (I.degree_le n) :=
is_noetherian_submodule_left.1 (is_noetherian_of_fg_of_noetherian _
⟨_, degree_le_eq_span_X_pow.symm⟩) _
end ideal
namespace polynomial
@[priority 100]
instance {R : Type*} [comm_ring R] [is_domain R] [wf_dvd_monoid R] :
wf_dvd_monoid (polynomial R) :=
{ well_founded_dvd_not_unit := begin
classical,
refine rel_hom.well_founded
⟨λ p, (if p = 0 then ⊤ else ↑p.degree, p.leading_coeff), _⟩
(prod.lex_wf (with_top.well_founded_lt $ with_bot.well_founded_lt nat.lt_wf)
‹wf_dvd_monoid R›.well_founded_dvd_not_unit),
rintros a b ⟨ane0, ⟨c, ⟨not_unit_c, rfl⟩⟩⟩,
rw [polynomial.degree_mul, if_neg ane0],
split_ifs with hac,
{ rw [hac, polynomial.leading_coeff_zero],
apply prod.lex.left,
exact lt_of_le_of_ne le_top with_top.coe_ne_top },
have cne0 : c ≠ 0 := right_ne_zero_of_mul hac,
simp only [cne0, ane0, polynomial.leading_coeff_mul],
by_cases hdeg : c.degree = 0,
{ simp only [hdeg, add_zero],
refine prod.lex.right _ ⟨_, ⟨c.leading_coeff, (λ unit_c, not_unit_c _), rfl⟩⟩,
{ rwa [ne, polynomial.leading_coeff_eq_zero] },
rw [polynomial.is_unit_iff, polynomial.eq_C_of_degree_eq_zero hdeg],
use [c.leading_coeff, unit_c],
rw [polynomial.leading_coeff, polynomial.nat_degree_eq_of_degree_eq_some hdeg] },
{ apply prod.lex.left,
rw polynomial.degree_eq_nat_degree cne0 at *,
rw [with_top.coe_lt_coe, polynomial.degree_eq_nat_degree ane0,
← with_bot.coe_add, with_bot.coe_lt_coe],
exact lt_add_of_pos_right _ (nat.pos_of_ne_zero (λ h, hdeg (h.symm ▸ with_bot.coe_zero))) },
end }
end polynomial
/-- Hilbert basis theorem: a polynomial ring over a noetherian ring is a noetherian ring. -/
protected theorem polynomial.is_noetherian_ring [is_noetherian_ring R] :
is_noetherian_ring (polynomial R) :=
is_noetherian_ring_iff.2 ⟨assume I : ideal (polynomial R),
let M := well_founded.min (is_noetherian_iff_well_founded.1 (by apply_instance))
(set.range I.leading_coeff_nth) ⟨_, ⟨0, rfl⟩⟩ in
have hm : M ∈ set.range I.leading_coeff_nth := well_founded.min_mem _ _ _,
let ⟨N, HN⟩ := hm, ⟨s, hs⟩ := I.is_fg_degree_le N in
have hm2 : ∀ k, I.leading_coeff_nth k ≤ M := λ k, or.cases_on (le_or_lt k N)
(λ h, HN ▸ I.leading_coeff_nth_mono h)
(λ h x hx, classical.by_contradiction $ λ hxm,
have ¬M < I.leading_coeff_nth k, by refine well_founded.not_lt_min
(well_founded_submodule_gt _ _) _ _ _; exact ⟨k, rfl⟩,
this ⟨HN ▸ I.leading_coeff_nth_mono (le_of_lt h), λ H, hxm (H hx)⟩),
have hs2 : ∀ {x}, x ∈ I.degree_le N → x ∈ ideal.span (↑s : set (polynomial R)),
from hs ▸ λ x hx, submodule.span_induction hx (λ _ hx, ideal.subset_span hx) (ideal.zero_mem _)
(λ _ _, ideal.add_mem _) (λ c f hf, f.C_mul' c ▸ ideal.mul_mem_left _ _ hf),
⟨s, le_antisymm
(ideal.span_le.2 $ λ x hx, have x ∈ I.degree_le N, from hs ▸ submodule.subset_span hx, this.2) $
begin
have : submodule.span (polynomial R) ↑s = ideal.span ↑s, by refl,
rw this,
intros p hp, generalize hn : p.nat_degree = k,
induction k using nat.strong_induction_on with k ih generalizing p,
cases le_or_lt k N,
{ subst k, refine hs2 ⟨polynomial.mem_degree_le.2
(le_trans polynomial.degree_le_nat_degree $ with_bot.coe_le_coe.2 h), hp⟩ },
{ have hp0 : p ≠ 0,
{ rintro rfl, cases hn, exact nat.not_lt_zero _ h },
have : (0 : R) ≠ 1,
{ intro h, apply hp0, ext i, refine (mul_one _).symm.trans _,
rw [← h, mul_zero], refl },
haveI : nontrivial R := ⟨⟨0, 1, this⟩⟩,
have : p.leading_coeff ∈ I.leading_coeff_nth N,
{ rw HN, exact hm2 k ((I.mem_leading_coeff_nth _ _).2
⟨_, hp, hn ▸ polynomial.degree_le_nat_degree, rfl⟩) },
rw I.mem_leading_coeff_nth at this,
rcases this with ⟨q, hq, hdq, hlqp⟩,
have hq0 : q ≠ 0,
{ intro H, rw [← polynomial.leading_coeff_eq_zero] at H,
rw [hlqp, polynomial.leading_coeff_eq_zero] at H, exact hp0 H },
have h1 : p.degree = (q * polynomial.X ^ (k - q.nat_degree)).degree,
{ rw [polynomial.degree_mul', polynomial.degree_X_pow],
rw [polynomial.degree_eq_nat_degree hp0, polynomial.degree_eq_nat_degree hq0],
rw [← with_bot.coe_add, add_tsub_cancel_of_le, hn],
{ refine le_trans (polynomial.nat_degree_le_of_degree_le hdq) (le_of_lt h) },
rw [polynomial.leading_coeff_X_pow, mul_one],
exact mt polynomial.leading_coeff_eq_zero.1 hq0 },
have h2 : p.leading_coeff = (q * polynomial.X ^ (k - q.nat_degree)).leading_coeff,
{ rw [← hlqp, polynomial.leading_coeff_mul_X_pow] },
have := polynomial.degree_sub_lt h1 hp0 h2,
rw [polynomial.degree_eq_nat_degree hp0] at this,
rw ← sub_add_cancel p (q * polynomial.X ^ (k - q.nat_degree)),
refine (ideal.span ↑s).add_mem _ ((ideal.span ↑s).mul_mem_right _ _),
{ by_cases hpq : p - q * polynomial.X ^ (k - q.nat_degree) = 0,
{ rw hpq, exact ideal.zero_mem _ },
refine ih _ _ (I.sub_mem hp (I.mul_mem_right _ hq)) rfl,
rwa [polynomial.degree_eq_nat_degree hpq, with_bot.coe_lt_coe, hn] at this },
exact hs2 ⟨polynomial.mem_degree_le.2 hdq, hq⟩ }
end⟩⟩
attribute [instance] polynomial.is_noetherian_ring
namespace polynomial
theorem exists_irreducible_of_degree_pos
{R : Type u} [comm_ring R] [is_domain R] [wf_dvd_monoid R]
{f : polynomial R} (hf : 0 < f.degree) : ∃ g, irreducible g ∧ g ∣ f :=
wf_dvd_monoid.exists_irreducible_factor
(λ huf, ne_of_gt hf $ degree_eq_zero_of_is_unit huf)
(λ hf0, not_lt_of_lt hf $ hf0.symm ▸ (@degree_zero R _).symm ▸ with_bot.bot_lt_coe _)
theorem exists_irreducible_of_nat_degree_pos
{R : Type u} [comm_ring R] [is_domain R] [wf_dvd_monoid R]
{f : polynomial R} (hf : 0 < f.nat_degree) : ∃ g, irreducible g ∧ g ∣ f :=
exists_irreducible_of_degree_pos $ by { contrapose! hf, exact nat_degree_le_of_degree_le hf }
theorem exists_irreducible_of_nat_degree_ne_zero
{R : Type u} [comm_ring R] [is_domain R] [wf_dvd_monoid R]
{f : polynomial R} (hf : f.nat_degree ≠ 0) : ∃ g, irreducible g ∧ g ∣ f :=
exists_irreducible_of_nat_degree_pos $ nat.pos_of_ne_zero hf
lemma linear_independent_powers_iff_aeval
(f : M →ₗ[R] M) (v : M) :
linear_independent R (λ n : ℕ, (f ^ n) v)
↔ ∀ (p : polynomial R), aeval f p v = 0 → p = 0 :=
begin
rw linear_independent_iff,
simp only [finsupp.total_apply, aeval_endomorphism, forall_iff_forall_finsupp, sum, support,
coeff, ← zero_to_finsupp],
exact iff.rfl,
end
lemma disjoint_ker_aeval_of_coprime
(f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) :
disjoint (aeval f p).ker (aeval f q).ker :=
begin
intros v hv,
rcases hpq with ⟨p', q', hpq'⟩,
simpa [linear_map.mem_ker.1 (submodule.mem_inf.1 hv).1,
linear_map.mem_ker.1 (submodule.mem_inf.1 hv).2]
using congr_arg (λ p : polynomial R, aeval f p v) hpq'.symm,
end
lemma sup_aeval_range_eq_top_of_coprime
(f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) :
(aeval f p).range ⊔ (aeval f q).range = ⊤ :=
begin
rw eq_top_iff,
intros v hv,
rw submodule.mem_sup,
rcases hpq with ⟨p', q', hpq'⟩,
use aeval f (p * p') v,
use linear_map.mem_range.2 ⟨aeval f p' v, by simp only [linear_map.mul_apply, aeval_mul]⟩,
use aeval f (q * q') v,
use linear_map.mem_range.2 ⟨aeval f q' v, by simp only [linear_map.mul_apply, aeval_mul]⟩,
simpa only [mul_comm p p', mul_comm q q', aeval_one, aeval_add]
using congr_arg (λ p : polynomial R, aeval f p v) hpq'
end
lemma sup_ker_aeval_le_ker_aeval_mul {f : M →ₗ[R] M} {p q : polynomial R} :
(aeval f p).ker ⊔ (aeval f q).ker ≤ (aeval f (p * q)).ker :=
begin
intros v hv,
rcases submodule.mem_sup.1 hv with ⟨x, hx, y, hy, hxy⟩,
have h_eval_x : aeval f (p * q) x = 0,
{ rw [mul_comm, aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hx, linear_map.map_zero] },
have h_eval_y : aeval f (p * q) y = 0,
{ rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hy, linear_map.map_zero] },
rw [linear_map.mem_ker, ←hxy, linear_map.map_add, h_eval_x, h_eval_y, add_zero],
end
lemma sup_ker_aeval_eq_ker_aeval_mul_of_coprime
(f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) :
(aeval f p).ker ⊔ (aeval f q).ker = (aeval f (p * q)).ker :=
begin
apply le_antisymm sup_ker_aeval_le_ker_aeval_mul,
intros v hv,
rw submodule.mem_sup,
rcases hpq with ⟨p', q', hpq'⟩,
have h_eval₂_qpp' := calc
aeval f (q * (p * p')) v = aeval f (p' * (p * q)) v :
by rw [mul_comm, mul_assoc, mul_comm, mul_assoc, mul_comm q p]
... = 0 :
by rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hv, linear_map.map_zero],
have h_eval₂_pqq' := calc
aeval f (p * (q * q')) v = aeval f (q' * (p * q)) v :
by rw [←mul_assoc, mul_comm]
... = 0 :
by rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hv, linear_map.map_zero],
rw aeval_mul at h_eval₂_qpp' h_eval₂_pqq',
refine ⟨aeval f (q * q') v, linear_map.mem_ker.1 h_eval₂_pqq',
aeval f (p * p') v, linear_map.mem_ker.1 h_eval₂_qpp', _⟩,
rw [add_comm, mul_comm p p', mul_comm q q'],
simpa using congr_arg (λ p : polynomial R, aeval f p v) hpq'
end
end polynomial
namespace mv_polynomial
lemma is_noetherian_ring_fin_0 [is_noetherian_ring R] :
is_noetherian_ring (mv_polynomial (fin 0) R) :=
is_noetherian_ring_of_ring_equiv R
((mv_polynomial.is_empty_ring_equiv R pempty).symm.trans
(rename_equiv R fin_zero_equiv'.symm).to_ring_equiv)
theorem is_noetherian_ring_fin [is_noetherian_ring R] :
∀ {n : ℕ}, is_noetherian_ring (mv_polynomial (fin n) R)
| 0 := is_noetherian_ring_fin_0
| (n+1) :=
@is_noetherian_ring_of_ring_equiv (polynomial (mv_polynomial (fin n) R)) _ _ _
(mv_polynomial.fin_succ_equiv _ n).to_ring_equiv.symm
(@polynomial.is_noetherian_ring (mv_polynomial (fin n) R) _ (is_noetherian_ring_fin))
/-- The multivariate polynomial ring in finitely many variables over a noetherian ring
is itself a noetherian ring. -/
instance is_noetherian_ring [fintype σ] [is_noetherian_ring R] :
is_noetherian_ring (mv_polynomial σ R) :=
@is_noetherian_ring_of_ring_equiv (mv_polynomial (fin (fintype.card σ)) R) _ _ _
(rename_equiv R (fintype.equiv_fin σ).symm).to_ring_equiv is_noetherian_ring_fin
lemma is_domain_fin_zero (R : Type u) [comm_ring R] [is_domain R] :
is_domain (mv_polynomial (fin 0) R) :=
ring_equiv.is_domain R
((rename_equiv R fin_zero_equiv').to_ring_equiv.trans
(mv_polynomial.is_empty_ring_equiv R pempty))
/-- Auxiliary lemma:
Multivariate polynomials over an integral domain
with variables indexed by `fin n` form an integral domain.
This fact is proven inductively,
and then used to prove the general case without any finiteness hypotheses.
See `mv_polynomial.is_domain` for the general case. -/
lemma is_domain_fin (R : Type u) [comm_ring R] [is_domain R] :
∀ (n : ℕ), is_domain (mv_polynomial (fin n) R)
| 0 := is_domain_fin_zero R
| (n+1) :=
begin
haveI := is_domain_fin n,
exact ring_equiv.is_domain
(polynomial (mv_polynomial (fin n) R))
(mv_polynomial.fin_succ_equiv _ n).to_ring_equiv
end
/-- Auxiliary definition:
Multivariate polynomials in finitely many variables over an integral domain form an integral domain.
This fact is proven by transport of structure from the `mv_polynomial.is_domain_fin`,
and then used to prove the general case without finiteness hypotheses.
See `mv_polynomial.is_domain` for the general case. -/
lemma is_domain_fintype (R : Type u) (σ : Type v) [comm_ring R] [fintype σ]
[is_domain R] : is_domain (mv_polynomial σ R) :=
@ring_equiv.is_domain _ (mv_polynomial (fin $ fintype.card σ) R) _ _
(mv_polynomial.is_domain_fin _ _)
(rename_equiv R (fintype.equiv_fin σ)).to_ring_equiv
protected theorem eq_zero_or_eq_zero_of_mul_eq_zero
{R : Type u} [comm_ring R] [is_domain R] {σ : Type v}
(p q : mv_polynomial σ R) (h : p * q = 0) : p = 0 ∨ q = 0 :=
begin
obtain ⟨s, p, rfl⟩ := exists_finset_rename p,
obtain ⟨t, q, rfl⟩ := exists_finset_rename q,
have :
rename (subtype.map id (finset.subset_union_left s t) : {x // x ∈ s} → {x // x ∈ s ∪ t}) p *
rename (subtype.map id (finset.subset_union_right s t) : {x // x ∈ t} → {x // x ∈ s ∪ t}) q = 0,
{ apply rename_injective _ subtype.val_injective, simpa using h },
letI := mv_polynomial.is_domain_fintype R {x // x ∈ (s ∪ t)},
rw mul_eq_zero at this,
cases this; [left, right],
all_goals { simpa using congr_arg (rename subtype.val) this }
end
/-- The multivariate polynomial ring over an integral domain is an integral domain. -/
instance {R : Type u} {σ : Type v} [comm_ring R] [is_domain R] :
is_domain (mv_polynomial σ R) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := mv_polynomial.eq_zero_or_eq_zero_of_mul_eq_zero,
exists_pair_ne := ⟨0, 1, λ H,
begin
have : eval₂ (ring_hom.id _) (λ s, (0:R)) (0 : mv_polynomial σ R) =
eval₂ (ring_hom.id _) (λ s, (0:R)) (1 : mv_polynomial σ R),
{ congr, exact H },
simpa,
end⟩,
.. (by apply_instance : comm_ring (mv_polynomial σ R)) }
lemma map_mv_polynomial_eq_eval₂ {S : Type*} [comm_ring S] [fintype σ]
(ϕ : mv_polynomial σ R →+* S) (p : mv_polynomial σ R) :
ϕ p = mv_polynomial.eval₂ (ϕ.comp mv_polynomial.C) (λ s, ϕ (mv_polynomial.X s)) p :=
begin
refine trans (congr_arg ϕ (mv_polynomial.as_sum p)) _,
rw [mv_polynomial.eval₂_eq', ϕ.map_sum],
congr,
ext,
simp only [monomial_eq, ϕ.map_pow, ϕ.map_prod, ϕ.comp_apply, ϕ.map_mul, finsupp.prod_pow],
end
lemma quotient_map_C_eq_zero {I : ideal R} {i : R} (hi : i ∈ I) :
(ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R))).comp C i = 0 :=
begin
simp only [function.comp_app, ring_hom.coe_comp, ideal.quotient.eq_zero_iff_mem],
exact ideal.mem_map_of_mem _ hi
end
/-- If every coefficient of a polynomial is in an ideal `I`, then so is the polynomial itself,
multivariate version. -/
lemma mem_ideal_of_coeff_mem_ideal (I : ideal (mv_polynomial σ R)) (p : mv_polynomial σ R)
(hcoe : ∀ (m : σ →₀ ℕ), p.coeff m ∈ I.comap C) : p ∈ I :=
begin
rw as_sum p,
suffices : ∀ m ∈ p.support, monomial m (mv_polynomial.coeff m p) ∈ I,
{ exact submodule.sum_mem I this },
intros m hm,
rw [← mul_one (coeff m p), ← C_mul_monomial],
suffices : C (coeff m p) ∈ I,
{ exact I.mul_mem_right (monomial m 1) this },
simpa [ideal.mem_comap] using hcoe m
end
/-- The push-forward of an ideal `I` of `R` to `mv_polynomial σ R` via inclusion
is exactly the set of polynomials whose coefficients are in `I` -/
theorem mem_map_C_iff {I : ideal R} {f : mv_polynomial σ R} :
f ∈ (ideal.map C I : ideal (mv_polynomial σ R)) ↔ ∀ (m : σ →₀ ℕ), f.coeff m ∈ I :=
begin
split,
{ intros hf,
apply submodule.span_induction hf,
{ intros f hf n,
cases (set.mem_image _ _ _).mp hf with x hx,
rw [← hx.right, coeff_C],
by_cases (n = 0),
{ simpa [h] using hx.left },
{ simp [ne.symm h] } },
{ simp },
{ exact λ f g hf hg n, by simp [I.add_mem (hf n) (hg n)] },
{ refine λ f g hg n, _,
rw [smul_eq_mul, coeff_mul],
exact I.sum_mem (λ c hc, I.smul_mem (f.coeff c.fst) (hg c.snd)) } },
{ intros hf,
rw as_sum f,
suffices : ∀ m ∈ f.support, monomial m (coeff m f) ∈
(ideal.map C I : ideal (mv_polynomial σ R)),
{ exact submodule.sum_mem _ this },
intros m hm,
rw [← mul_one (coeff m f), ← C_mul_monomial],
suffices : C (coeff m f) ∈ (ideal.map C I : ideal (mv_polynomial σ R)),
{ exact ideal.mul_mem_right _ _ this },
apply ideal.mem_map_of_mem _,
exact hf m }
end
lemma ker_map (f : R →+* S) : (map f : mv_polynomial σ R →+* mv_polynomial σ S).ker = f.ker.map C :=
begin
ext,
rw [mv_polynomial.mem_map_C_iff, ring_hom.mem_ker, mv_polynomial.ext_iff],
simp_rw [coeff_map, coeff_zero, ring_hom.mem_ker],
end
lemma eval₂_C_mk_eq_zero {I : ideal R} {a : mv_polynomial σ R}
(ha : a ∈ (ideal.map C I : ideal (mv_polynomial σ R))) :
eval₂_hom (C.comp (ideal.quotient.mk I)) X a = 0 :=
begin
rw as_sum a,
rw [coe_eval₂_hom, eval₂_sum],
refine finset.sum_eq_zero (λ n hn, _),
simp only [eval₂_monomial, function.comp_app, ring_hom.coe_comp],
refine mul_eq_zero_of_left _ _,
suffices : coeff n a ∈ I,
{ rw [← @ideal.mk_ker R _ I, ring_hom.mem_ker] at this,
simp only [this, C_0] },
exact mem_map_C_iff.1 ha n
end
/-- If `I` is an ideal of `R`, then the ring `mv_polynomial σ I.quotient` is isomorphic as an
`R`-algebra to the quotient of `mv_polynomial σ R` by the ideal generated by `I`. -/
def quotient_equiv_quotient_mv_polynomial (I : ideal R) :
mv_polynomial σ I.quotient ≃ₐ[R] (ideal.map C I : ideal (mv_polynomial σ R)).quotient :=
{ to_fun := eval₂_hom (ideal.quotient.lift I ((ideal.quotient.mk (ideal.map C I : ideal
(mv_polynomial σ R))).comp C) (λ i hi, quotient_map_C_eq_zero hi))
(λ i, ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R)) (X i)),
inv_fun := ideal.quotient.lift (ideal.map C I : ideal (mv_polynomial σ R))
(eval₂_hom (C.comp (ideal.quotient.mk I)) X) (λ a ha, eval₂_C_mk_eq_zero ha),
map_mul' := ring_hom.map_mul _,
map_add' := ring_hom.map_add _,
left_inv := begin
intro f,
apply induction_on f,
{ rintro ⟨r⟩,
rw [coe_eval₂_hom, eval₂_C],
simp only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, ideal.quotient.lift_mk,
ideal.quotient.mk_eq_mk, bind₂_C_right, ring_hom.coe_comp] },
{ simp_intros p q hp hq only [ring_hom.map_add, mv_polynomial.coe_eval₂_hom, coe_eval₂_hom,
mv_polynomial.eval₂_add, mv_polynomial.eval₂_hom_eq_bind₂, eval₂_hom_eq_bind₂],
rw [hp, hq] },
{ simp_intros p i hp only [eval₂_hom_eq_bind₂, coe_eval₂_hom],
simp only [hp, eval₂_hom_eq_bind₂, coe_eval₂_hom, ideal.quotient.lift_mk, bind₂_X_right,
eval₂_mul, ring_hom.map_mul, eval₂_X] }
end,
right_inv := begin
rintro ⟨f⟩,
apply induction_on f,
{ intros r,
simp only [submodule.quotient.quot_mk_eq_mk, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk,
ring_hom.coe_comp, eval₂_hom_C] },
{ simp_intros p q hp hq only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, eval₂_add,
ring_hom.map_add, coe_eval₂_hom, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk],
rw [hp, hq] },
{ simp_intros p i hp only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, coe_eval₂_hom,
ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk, bind₂_X_right, eval₂_mul, ring_hom.map_mul,
eval₂_X],
simp only [hp] }
end,
commutes' := λ r, eval₂_hom_C _ _ (ideal.quotient.mk I r) }
end mv_polynomial
namespace polynomial
open unique_factorization_monoid
variables {D : Type u} [comm_ring D] [is_domain D] [unique_factorization_monoid D]
@[priority 100]
instance unique_factorization_monoid : unique_factorization_monoid (polynomial D) :=
begin
haveI := arbitrary (normalization_monoid D),
haveI := to_normalized_gcd_monoid D,
exact ufm_of_gcd_of_wf_dvd_monoid
end
end polynomial
|
212db2736966d9f22fd3eca42d2b5d07c4e15607 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/algebra/group_with_zero/basic.lean | 01eed75fad8afeb3432f11091c55d3f41d36a135 | [
"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 | 41,617 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import logic.nontrivial
import algebra.group.units_hom
import algebra.group.inj_surj
import algebra.group_with_zero.defs
/-!
# Groups with an adjoined zero element
This file describes structures that are not usually studied on their own right in mathematics,
namely a special sort of monoid: apart from a distinguished “zero element” they form a group,
or in other words, they are groups with an adjoined zero element.
Examples are:
* division rings;
* the value monoid of a multiplicative valuation;
* in particular, the non-negative real numbers.
## Main definitions
Various lemmas about `group_with_zero` and `comm_group_with_zero`.
To reduce import dependencies, the type-classes themselves are in
`algebra.group_with_zero.defs`.
## Implementation details
As is usual in mathlib, we extend the inverse function to the zero element,
and require `0⁻¹ = 0`.
-/
set_option old_structure_cmd true
open_locale classical
open function
variables {M₀ G₀ M₀' G₀' : Type*}
mk_simp_attribute field_simps "The simpset `field_simps` is used by the tactic `field_simp` to
reduce an expression in a field to an expression of the form `n / d` where `n` and `d` are
division-free."
attribute [field_simps] mul_div_assoc'
section
section mul_zero_class
variables [mul_zero_class M₀] {a b : M₀}
/-- Pullback a `mul_zero_class` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.mul_zero_class [has_mul M₀'] [has_zero M₀'] (f : M₀' → M₀)
(hf : injective f) (zero : f 0 = 0) (mul : ∀ a b, f (a * b) = f a * f b) :
mul_zero_class M₀' :=
{ mul := (*),
zero := 0,
zero_mul := λ a, hf $ by simp only [mul, zero, zero_mul],
mul_zero := λ a, hf $ by simp only [mul, zero, mul_zero] }
/-- Pushforward a `mul_zero_class` instance along an surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.mul_zero_class [has_mul M₀'] [has_zero M₀'] (f : M₀ → M₀')
(hf : surjective f) (zero : f 0 = 0) (mul : ∀ a b, f (a * b) = f a * f b) :
mul_zero_class M₀' :=
{ mul := (*),
zero := 0,
mul_zero := hf.forall.2 $ λ x, by simp only [← zero, ← mul, mul_zero],
zero_mul := hf.forall.2 $ λ x, by simp only [← zero, ← mul, zero_mul] }
lemma mul_eq_zero_of_left (h : a = 0) (b : M₀) : a * b = 0 := h.symm ▸ zero_mul b
lemma mul_eq_zero_of_right (a : M₀) (h : b = 0) : a * b = 0 := h.symm ▸ mul_zero a
lemma left_ne_zero_of_mul : a * b ≠ 0 → a ≠ 0 := mt (λ h, mul_eq_zero_of_left h b)
lemma right_ne_zero_of_mul : a * b ≠ 0 → b ≠ 0 := mt (mul_eq_zero_of_right a)
lemma ne_zero_and_ne_zero_of_mul (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 :=
⟨left_ne_zero_of_mul h, right_ne_zero_of_mul h⟩
lemma mul_eq_zero_of_ne_zero_imp_eq_zero {a b : M₀} (h : a ≠ 0 → b = 0) :
a * b = 0 :=
if ha : a = 0 then by rw [ha, zero_mul] else by rw [h ha, mul_zero]
end mul_zero_class
/-- Pushforward a `no_zero_divisors` instance along an injective function. -/
protected lemma function.injective.no_zero_divisors [has_mul M₀] [has_zero M₀]
[has_mul M₀'] [has_zero M₀'] [no_zero_divisors M₀']
(f : M₀ → M₀') (hf : injective f) (zero : f 0 = 0) (mul : ∀ x y, f (x * y) = f x * f y) :
no_zero_divisors M₀ :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ x y H,
have f x * f y = 0, by rw [← mul, H, zero],
(eq_zero_or_eq_zero_of_mul_eq_zero this).imp (λ H, hf $ by rwa zero) (λ H, hf $ by rwa zero) }
lemma eq_zero_of_mul_self_eq_zero [has_mul M₀] [has_zero M₀] [no_zero_divisors M₀]
{a : M₀} (h : a * a = 0) :
a = 0 :=
(eq_zero_or_eq_zero_of_mul_eq_zero h).elim id id
section
variables [mul_zero_class M₀] [no_zero_divisors M₀] {a b : M₀}
/-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them
equals zero. -/
@[simp] theorem mul_eq_zero : a * b = 0 ↔ a = 0 ∨ b = 0 :=
⟨eq_zero_or_eq_zero_of_mul_eq_zero,
λo, o.elim (λ h, mul_eq_zero_of_left h b) (mul_eq_zero_of_right a)⟩
/-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them
equals zero. -/
@[simp] theorem zero_eq_mul : 0 = a * b ↔ a = 0 ∨ b = 0 :=
by rw [eq_comm, mul_eq_zero]
/-- If `α` has no zero divisors, then the product of two elements is nonzero iff both of them
are nonzero. -/
theorem mul_ne_zero_iff : a * b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 :=
(not_congr mul_eq_zero).trans not_or_distrib
@[field_simps] theorem mul_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 :=
mul_ne_zero_iff.2 ⟨ha, hb⟩
/-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` equals zero iff so is
`b * a`. -/
theorem mul_eq_zero_comm : a * b = 0 ↔ b * a = 0 :=
mul_eq_zero.trans $ (or_comm _ _).trans mul_eq_zero.symm
/-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` is nonzero iff so is
`b * a`. -/
theorem mul_ne_zero_comm : a * b ≠ 0 ↔ b * a ≠ 0 :=
not_congr mul_eq_zero_comm
lemma mul_self_eq_zero : a * a = 0 ↔ a = 0 := by simp
lemma zero_eq_mul_self : 0 = a * a ↔ a = 0 := by simp
end
end
section
variables [mul_zero_one_class M₀]
/-- Pullback a `mul_zero_one_class` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.mul_zero_one_class [has_mul M₀'] [has_zero M₀'] [has_one M₀']
(f : M₀' → M₀)
(hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ a b, f (a * b) = f a * f b) :
mul_zero_one_class M₀' :=
{ ..hf.mul_zero_class f zero mul, ..hf.mul_one_class f one mul }
/-- Pushforward a `mul_zero_one_class` instance along an surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.mul_zero_one_class [has_mul M₀'] [has_zero M₀'] [has_one M₀']
(f : M₀ → M₀')
(hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ a b, f (a * b) = f a * f b) :
mul_zero_one_class M₀' :=
{ ..hf.mul_zero_class f zero mul, ..hf.mul_one_class f one mul }
/-- In a monoid with zero, if zero equals one, then zero is the only element. -/
lemma eq_zero_of_zero_eq_one (h : (0 : M₀) = 1) (a : M₀) : a = 0 :=
by rw [← mul_one a, ← h, mul_zero]
/-- In a monoid with zero, if zero equals one, then zero is the unique element.
Somewhat arbitrarily, we define the default element to be `0`.
All other elements will be provably equal to it, but not necessarily definitionally equal. -/
def unique_of_zero_eq_one (h : (0 : M₀) = 1) : unique M₀ :=
{ default := 0, uniq := eq_zero_of_zero_eq_one h }
/-- In a monoid with zero, zero equals one if and only if all elements of that semiring
are equal. -/
theorem subsingleton_iff_zero_eq_one : (0 : M₀) = 1 ↔ subsingleton M₀ :=
⟨λ h, @unique.subsingleton _ (unique_of_zero_eq_one h), λ h, @subsingleton.elim _ h _ _⟩
alias subsingleton_iff_zero_eq_one ↔ subsingleton_of_zero_eq_one _
lemma eq_of_zero_eq_one (h : (0 : M₀) = 1) (a b : M₀) : a = b :=
@subsingleton.elim _ (subsingleton_of_zero_eq_one h) a b
/-- In a monoid with zero, either zero and one are nonequal, or zero is the only element. -/
lemma zero_ne_one_or_forall_eq_0 : (0 : M₀) ≠ 1 ∨ (∀a:M₀, a = 0) :=
not_or_of_imp eq_zero_of_zero_eq_one
end
section
variables [mul_zero_one_class M₀] [nontrivial M₀] {a b : M₀}
/-- In a nontrivial monoid with zero, zero and one are different. -/
@[simp] lemma zero_ne_one : 0 ≠ (1:M₀) :=
begin
assume h,
rcases exists_pair_ne M₀ with ⟨x, y, hx⟩,
apply hx,
calc x = 1 * x : by rw [one_mul]
... = 0 : by rw [← h, zero_mul]
... = 1 * y : by rw [← h, zero_mul]
... = y : by rw [one_mul]
end
@[simp] lemma one_ne_zero : (1:M₀) ≠ 0 :=
zero_ne_one.symm
lemma ne_zero_of_eq_one {a : M₀} (h : a = 1) : a ≠ 0 :=
calc a = 1 : h
... ≠ 0 : one_ne_zero
lemma left_ne_zero_of_mul_eq_one (h : a * b = 1) : a ≠ 0 :=
left_ne_zero_of_mul $ ne_zero_of_eq_one h
lemma right_ne_zero_of_mul_eq_one (h : a * b = 1) : b ≠ 0 :=
right_ne_zero_of_mul $ ne_zero_of_eq_one h
/-- Pullback a `nontrivial` instance along a function sending `0` to `0` and `1` to `1`. -/
protected lemma pullback_nonzero [has_zero M₀'] [has_one M₀']
(f : M₀' → M₀) (zero : f 0 = 0) (one : f 1 = 1) : nontrivial M₀' :=
⟨⟨0, 1, mt (congr_arg f) $ by { rw [zero, one], exact zero_ne_one }⟩⟩
end
section semigroup_with_zero
/-- Pullback a `semigroup_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.semigroup_with_zero
[has_zero M₀'] [has_mul M₀'] [semigroup_with_zero M₀] (f : M₀' → M₀) (hf : injective f)
(zero : f 0 = 0) (mul : ∀ x y, f (x * y) = f x * f y) :
semigroup_with_zero M₀' :=
{ .. hf.mul_zero_class f zero mul,
.. ‹has_zero M₀'›,
.. hf.semigroup f mul }
/-- Pushforward a `semigroup_with_zero` class along an surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.semigroup_with_zero
[semigroup_with_zero M₀] [has_zero M₀'] [has_mul M₀'] (f : M₀ → M₀') (hf : surjective f)
(zero : f 0 = 0) (mul : ∀ x y, f (x * y) = f x * f y) :
semigroup_with_zero M₀' :=
{ .. hf.mul_zero_class f zero mul,
.. ‹has_zero M₀'›,
.. hf.semigroup f mul }
end semigroup_with_zero
section monoid_with_zero
/-- Pullback a `monoid_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
[monoid_with_zero M₀]
(f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
monoid_with_zero M₀' :=
{ .. hf.monoid f one mul, .. hf.mul_zero_class f zero mul }
/-- Pushforward a `monoid_with_zero` class along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
[monoid_with_zero M₀]
(f : M₀ → M₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
monoid_with_zero M₀' :=
{ .. hf.monoid f one mul, .. hf.mul_zero_class f zero mul }
/-- Pullback a `monoid_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.comm_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
[comm_monoid_with_zero M₀]
(f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
comm_monoid_with_zero M₀' :=
{ .. hf.comm_monoid f one mul, .. hf.mul_zero_class f zero mul }
/-- Pushforward a `monoid_with_zero` class along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.comm_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
[comm_monoid_with_zero M₀]
(f : M₀ → M₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
comm_monoid_with_zero M₀' :=
{ .. hf.comm_monoid f one mul, .. hf.mul_zero_class f zero mul }
variables [monoid_with_zero M₀]
namespace units
/-- An element of the unit group of a nonzero monoid with zero represented as an element
of the monoid is nonzero. -/
@[simp] lemma ne_zero [nontrivial M₀] (u : units M₀) :
(u : M₀) ≠ 0 :=
left_ne_zero_of_mul_eq_one u.mul_inv
-- We can't use `mul_eq_zero` + `units.ne_zero` in the next two lemmas because we don't assume
-- `nonzero M₀`.
@[simp] lemma mul_left_eq_zero (u : units M₀) {a : M₀} : a * u = 0 ↔ a = 0 :=
⟨λ h, by simpa using mul_eq_zero_of_left h ↑u⁻¹, λ h, mul_eq_zero_of_left h u⟩
@[simp] lemma mul_right_eq_zero (u : units M₀) {a : M₀} : ↑u * a = 0 ↔ a = 0 :=
⟨λ h, by simpa using mul_eq_zero_of_right ↑u⁻¹ h, mul_eq_zero_of_right u⟩
end units
namespace is_unit
lemma ne_zero [nontrivial M₀] {a : M₀} (ha : is_unit a) : a ≠ 0 := let ⟨u, hu⟩ :=
ha in hu ▸ u.ne_zero
lemma mul_right_eq_zero {a b : M₀} (ha : is_unit a) : a * b = 0 ↔ b = 0 :=
let ⟨u, hu⟩ := ha in hu ▸ u.mul_right_eq_zero
lemma mul_left_eq_zero {a b : M₀} (hb : is_unit b) : a * b = 0 ↔ a = 0 :=
let ⟨u, hu⟩ := hb in hu ▸ u.mul_left_eq_zero
end is_unit
@[simp] theorem is_unit_zero_iff : is_unit (0 : M₀) ↔ (0:M₀) = 1 :=
⟨λ ⟨⟨_, a, (a0 : 0 * a = 1), _⟩, rfl⟩, by rwa zero_mul at a0,
λ h, @is_unit_of_subsingleton _ _ (subsingleton_of_zero_eq_one h) 0⟩
@[simp] theorem not_is_unit_zero [nontrivial M₀] : ¬ is_unit (0 : M₀) :=
mt is_unit_zero_iff.1 zero_ne_one
variable (M₀)
end monoid_with_zero
section cancel_monoid_with_zero
variables [cancel_monoid_with_zero M₀] {a b c : M₀}
@[priority 10] -- see Note [lower instance priority]
instance cancel_monoid_with_zero.to_no_zero_divisors : no_zero_divisors M₀ :=
⟨λ a b ab0, by { by_cases a = 0, { left, exact h }, right,
apply cancel_monoid_with_zero.mul_left_cancel_of_ne_zero h, rw [ab0, mul_zero], }⟩
lemma mul_left_inj' (hc : c ≠ 0) : a * c = b * c ↔ a = b := ⟨mul_right_cancel' hc, λ h, h ▸ rfl⟩
lemma mul_right_inj' (ha : a ≠ 0) : a * b = a * c ↔ b = c := ⟨mul_left_cancel' ha, λ h, h ▸ rfl⟩
@[simp] lemma mul_eq_mul_right_iff : a * c = b * c ↔ a = b ∨ c = 0 :=
by by_cases hc : c = 0; [simp [hc], simp [mul_left_inj', hc]]
@[simp] lemma mul_eq_mul_left_iff : a * b = a * c ↔ b = c ∨ a = 0 :=
by by_cases ha : a = 0; [simp [ha], simp [mul_right_inj', ha]]
/-- Pullback a `monoid_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.cancel_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
(f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
cancel_monoid_with_zero M₀' :=
{ mul_left_cancel_of_ne_zero := λ x y z hx H, hf $ mul_left_cancel' ((hf.ne_iff' zero).2 hx) $
by erw [← mul, ← mul, H]; refl,
mul_right_cancel_of_ne_zero := λ x y z hx H, hf $ mul_right_cancel' ((hf.ne_iff' zero).2 hx) $
by erw [← mul, ← mul, H]; refl,
.. hf.monoid f one mul, .. hf.mul_zero_class f zero mul }
/-- An element of a `cancel_monoid_with_zero` fixed by right multiplication by an element other
than one must be zero. -/
theorem eq_zero_of_mul_eq_self_right (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 :=
classical.by_contradiction $ λ ha, h₁ $ mul_left_cancel' ha $ h₂.symm ▸ (mul_one a).symm
/-- An element of a `cancel_monoid_with_zero` fixed by left multiplication by an element other
than one must be zero. -/
theorem eq_zero_of_mul_eq_self_left (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 :=
classical.by_contradiction $ λ ha, h₁ $ mul_right_cancel' ha $ h₂.symm ▸ (one_mul a).symm
end cancel_monoid_with_zero
section comm_cancel_monoid_with_zero
variables [comm_cancel_monoid_with_zero M₀] {a b c : M₀}
/-- Pullback a `comm_cancel_monoid_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.comm_cancel_monoid_with_zero
[has_zero M₀'] [has_mul M₀'] [has_one M₀']
(f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
comm_cancel_monoid_with_zero M₀' :=
{ .. hf.comm_monoid_with_zero f zero one mul,
.. hf.cancel_monoid_with_zero f zero one mul }
end comm_cancel_monoid_with_zero
section group_with_zero
variables [group_with_zero G₀] {a b c g h x : G₀}
alias div_eq_mul_inv ← division_def
/-- Pullback a `group_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀']
[has_inv G₀'] [has_div G₀'] (f : G₀' → G₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹)
(div : ∀ x y, f (x / y) = f x / f y) :
group_with_zero G₀' :=
{ inv_zero := hf $ by erw [inv, zero, inv_zero],
mul_inv_cancel := λ x hx, hf $ by erw [one, mul, inv, mul_inv_cancel ((hf.ne_iff' zero).2 hx)],
.. hf.monoid_with_zero f zero one mul,
.. hf.div_inv_monoid f one mul inv div,
.. pullback_nonzero f zero one, }
/-- Pushforward a `group_with_zero` class along an surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀']
[has_inv G₀'] [has_div G₀'] (h01 : (0:G₀') ≠ 1) (f : G₀ → G₀') (hf : surjective f)
(zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y)
(inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) :
group_with_zero G₀' :=
{ inv_zero := by erw [← zero, ← inv, inv_zero],
mul_inv_cancel := hf.forall.2 $ λ x hx,
by erw [← inv, ← mul, mul_inv_cancel (mt (congr_arg f) $ trans_rel_left ne hx zero.symm)];
exact one,
exists_pair_ne := ⟨0, 1, h01⟩,
.. hf.monoid_with_zero f zero one mul,
.. hf.div_inv_monoid f one mul inv div }
@[simp] lemma mul_inv_cancel_right' (h : b ≠ 0) (a : G₀) :
(a * b) * b⁻¹ = a :=
calc (a * b) * b⁻¹ = a * (b * b⁻¹) : mul_assoc _ _ _
... = a : by simp [h]
@[simp] lemma mul_inv_cancel_left' (h : a ≠ 0) (b : G₀) :
a * (a⁻¹ * b) = b :=
calc a * (a⁻¹ * b) = (a * a⁻¹) * b : (mul_assoc _ _ _).symm
... = b : by simp [h]
lemma inv_ne_zero (h : a ≠ 0) : a⁻¹ ≠ 0 :=
assume a_eq_0, by simpa [a_eq_0] using mul_inv_cancel h
@[simp] lemma inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 :=
calc a⁻¹ * a = (a⁻¹ * a) * a⁻¹ * a⁻¹⁻¹ : by simp [inv_ne_zero h]
... = a⁻¹ * a⁻¹⁻¹ : by simp [h]
... = 1 : by simp [inv_ne_zero h]
lemma group_with_zero.mul_left_injective (h : x ≠ 0) :
function.injective (λ y, x * y) :=
λ y y' w, by simpa only [←mul_assoc, inv_mul_cancel h, one_mul] using congr_arg (λ y, x⁻¹ * y) w
lemma group_with_zero.mul_right_injective (h : x ≠ 0) :
function.injective (λ y, y * x) :=
λ y y' w, by simpa only [mul_assoc, mul_inv_cancel h, mul_one] using congr_arg (λ y, y * x⁻¹) w
@[simp] lemma inv_mul_cancel_right' (h : b ≠ 0) (a : G₀) :
(a * b⁻¹) * b = a :=
calc (a * b⁻¹) * b = a * (b⁻¹ * b) : mul_assoc _ _ _
... = a : by simp [h]
@[simp] lemma inv_mul_cancel_left' (h : a ≠ 0) (b : G₀) :
a⁻¹ * (a * b) = b :=
calc a⁻¹ * (a * b) = (a⁻¹ * a) * b : (mul_assoc _ _ _).symm
... = b : by simp [h]
@[simp] lemma inv_one : 1⁻¹ = (1:G₀) :=
calc 1⁻¹ = 1 * 1⁻¹ : by rw [one_mul]
... = (1:G₀) : by simp
@[simp] lemma inv_inv' (a : G₀) : a⁻¹⁻¹ = a :=
begin
by_cases h : a = 0, { simp [h] },
calc a⁻¹⁻¹ = a * (a⁻¹ * a⁻¹⁻¹) : by simp [h]
... = a : by simp [inv_ne_zero h]
end
/-- Multiplying `a` by itself and then by its inverse results in `a`
(whether or not `a` is zero). -/
@[simp] lemma mul_self_mul_inv (a : G₀) : a * a * a⁻¹ = a :=
begin
by_cases h : a = 0,
{ rw [h, inv_zero, mul_zero] },
{ rw [mul_assoc, mul_inv_cancel h, mul_one] }
end
/-- Multiplying `a` by its inverse and then by itself results in `a`
(whether or not `a` is zero). -/
@[simp] lemma mul_inv_mul_self (a : G₀) : a * a⁻¹ * a = a :=
begin
by_cases h : a = 0,
{ rw [h, inv_zero, mul_zero] },
{ rw [mul_inv_cancel h, one_mul] }
end
/-- Multiplying `a⁻¹` by `a` twice results in `a` (whether or not `a`
is zero). -/
@[simp] lemma inv_mul_mul_self (a : G₀) : a⁻¹ * a * a = a :=
begin
by_cases h : a = 0,
{ rw [h, inv_zero, mul_zero] },
{ rw [inv_mul_cancel h, one_mul] }
end
/-- Multiplying `a` by itself and then dividing by itself results in
`a` (whether or not `a` is zero). -/
@[simp] lemma mul_self_div_self (a : G₀) : a * a / a = a :=
by rw [div_eq_mul_inv, mul_self_mul_inv a]
/-- Dividing `a` by itself and then multiplying by itself results in
`a` (whether or not `a` is zero). -/
@[simp] lemma div_self_mul_self (a : G₀) : a / a * a = a :=
by rw [div_eq_mul_inv, mul_inv_mul_self a]
lemma inv_involutive' : function.involutive (has_inv.inv : G₀ → G₀) :=
inv_inv'
lemma eq_inv_of_mul_right_eq_one (h : a * b = 1) :
b = a⁻¹ :=
by rw [← inv_mul_cancel_left' (left_ne_zero_of_mul_eq_one h) b, h, mul_one]
lemma eq_inv_of_mul_left_eq_one (h : a * b = 1) :
a = b⁻¹ :=
by rw [← mul_inv_cancel_right' (right_ne_zero_of_mul_eq_one h) a, h, one_mul]
lemma inv_injective' : function.injective (@has_inv.inv G₀ _) :=
inv_involutive'.injective
@[simp] lemma inv_inj' : g⁻¹ = h⁻¹ ↔ g = h := inv_injective'.eq_iff
/-- This is the analogue of `inv_eq_iff_inv_eq` for `group_with_zero`.
It could also be named `inv_eq_iff_inv_eq'`. -/
lemma inv_eq_iff : g⁻¹ = h ↔ h⁻¹ = g :=
by rw [← inv_inj', eq_comm, inv_inv']
/-- This is the analogue of `eq_inv_iff_eq_inv` for `group_with_zero`.
It could also be named `eq_inv_iff_eq_inv'`. -/
lemma eq_inv_iff : a = b⁻¹ ↔ b = a⁻¹ :=
by rw [eq_comm, inv_eq_iff, eq_comm]
@[simp] lemma inv_eq_one' : g⁻¹ = 1 ↔ g = 1 :=
by rw [inv_eq_iff, inv_one, eq_comm]
lemma eq_mul_inv_iff_mul_eq' (hc : c ≠ 0) : a = b * c⁻¹ ↔ a * c = b :=
by split; rintro rfl; [rw inv_mul_cancel_right' hc, rw mul_inv_cancel_right' hc]
lemma eq_inv_mul_iff_mul_eq' (hb : b ≠ 0) : a = b⁻¹ * c ↔ b * a = c :=
by split; rintro rfl; [rw mul_inv_cancel_left' hb, rw inv_mul_cancel_left' hb]
lemma inv_mul_eq_iff_eq_mul' (ha : a ≠ 0) : a⁻¹ * b = c ↔ b = a * c :=
by rw [eq_comm, eq_inv_mul_iff_mul_eq' ha, eq_comm]
lemma mul_inv_eq_iff_eq_mul' (hb : b ≠ 0) : a * b⁻¹ = c ↔ a = c * b :=
by rw [eq_comm, eq_mul_inv_iff_mul_eq' hb, eq_comm]
lemma mul_inv_eq_one' (hb : b ≠ 0) : a * b⁻¹ = 1 ↔ a = b :=
by rw [mul_inv_eq_iff_eq_mul' hb, one_mul]
lemma inv_mul_eq_one' (ha : a ≠ 0) : a⁻¹ * b = 1 ↔ a = b :=
by rw [inv_mul_eq_iff_eq_mul' ha, mul_one, eq_comm]
lemma mul_eq_one_iff_eq_inv' (hb : b ≠ 0) : a * b = 1 ↔ a = b⁻¹ :=
by { convert mul_inv_eq_one' (inv_ne_zero hb), rw [inv_inv'] }
lemma mul_eq_one_iff_inv_eq' (ha : a ≠ 0) : a * b = 1 ↔ a⁻¹ = b :=
by { convert inv_mul_eq_one' (inv_ne_zero ha), rw [inv_inv'] }
end group_with_zero
namespace units
variables [group_with_zero G₀]
variables {a b : G₀}
/-- Embed a non-zero element of a `group_with_zero` into the unit group.
By combining this function with the operations on units,
or the `/ₚ` operation, it is possible to write a division
as a partial function with three arguments. -/
def mk0 (a : G₀) (ha : a ≠ 0) : units G₀ :=
⟨a, a⁻¹, mul_inv_cancel ha, inv_mul_cancel ha⟩
@[simp] lemma mk0_one (h := one_ne_zero) :
mk0 (1 : G₀) h = 1 :=
by { ext, refl }
@[simp] lemma coe_mk0 {a : G₀} (h : a ≠ 0) : (mk0 a h : G₀) = a := rfl
@[simp] lemma mk0_coe (u : units G₀) (h : (u : G₀) ≠ 0) : mk0 (u : G₀) h = u :=
units.ext rfl
@[simp, norm_cast] lemma coe_inv' (u : units G₀) : ((u⁻¹ : units G₀) : G₀) = u⁻¹ :=
eq_inv_of_mul_left_eq_one u.inv_mul
@[simp] lemma mul_inv' (u : units G₀) : (u : G₀) * u⁻¹ = 1 := mul_inv_cancel u.ne_zero
@[simp] lemma inv_mul' (u : units G₀) : (u⁻¹ : G₀) * u = 1 := inv_mul_cancel u.ne_zero
@[simp] lemma mk0_inj {a b : G₀} (ha : a ≠ 0) (hb : b ≠ 0) :
units.mk0 a ha = units.mk0 b hb ↔ a = b :=
⟨λ h, by injection h, λ h, units.ext h⟩
@[simp] lemma exists_iff_ne_zero {x : G₀} : (∃ u : units G₀, ↑u = x) ↔ x ≠ 0 :=
⟨λ ⟨u, hu⟩, hu ▸ u.ne_zero, assume hx, ⟨mk0 x hx, rfl⟩⟩
instance : can_lift G₀ (units G₀) :=
{ coe := coe,
cond := (≠ 0),
prf := λ x, exists_iff_ne_zero.mpr }
end units
section group_with_zero
variables [group_with_zero G₀]
lemma is_unit.mk0 (x : G₀) (hx : x ≠ 0) : is_unit x := (units.mk0 x hx).is_unit
lemma is_unit_iff_ne_zero {x : G₀} : is_unit x ↔ x ≠ 0 :=
units.exists_iff_ne_zero
@[priority 10] -- see Note [lower instance priority]
instance group_with_zero.no_zero_divisors : no_zero_divisors G₀ :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h,
begin
contrapose! h,
exact ((units.mk0 a h.1) * (units.mk0 b h.2)).ne_zero
end,
.. (‹_› : group_with_zero G₀) }
@[priority 10] -- see Note [lower instance priority]
instance group_with_zero.cancel_monoid_with_zero : cancel_monoid_with_zero G₀ :=
{ mul_left_cancel_of_ne_zero := λ x y z hx h,
by rw [← inv_mul_cancel_left' hx y, h, inv_mul_cancel_left' hx z],
mul_right_cancel_of_ne_zero := λ x y z hy h,
by rw [← mul_inv_cancel_right' hy x, h, mul_inv_cancel_right' hy z],
.. (‹_› : group_with_zero G₀) }
-- Can't be put next to the other `mk0` lemmas becuase it depends on the
-- `no_zero_divisors` instance, which depends on `mk0`.
@[simp] lemma units.mk0_mul (x y : G₀) (hxy) :
units.mk0 (x * y) hxy =
units.mk0 x (mul_ne_zero_iff.mp hxy).1 * units.mk0 y (mul_ne_zero_iff.mp hxy).2 :=
by { ext, refl }
lemma mul_inv_rev' (x y : G₀) : (x * y)⁻¹ = y⁻¹ * x⁻¹ :=
begin
by_cases hx : x = 0, { simp [hx] },
by_cases hy : y = 0, { simp [hy] },
symmetry,
apply eq_inv_of_mul_left_eq_one,
simp [mul_assoc, hx, hy]
end
@[simp] lemma div_self {a : G₀} (h : a ≠ 0) : a / a = 1 :=
by rw [div_eq_mul_inv, mul_inv_cancel h]
@[simp] lemma div_one (a : G₀) : a / 1 = a :=
by simp [div_eq_mul_inv a 1]
@[simp] lemma zero_div (a : G₀) : 0 / a = 0 :=
by rw [div_eq_mul_inv, zero_mul]
@[simp] lemma div_zero (a : G₀) : a / 0 = 0 :=
by rw [div_eq_mul_inv, inv_zero, mul_zero]
@[simp] lemma div_mul_cancel (a : G₀) {b : G₀} (h : b ≠ 0) : a / b * b = a :=
by rw [div_eq_mul_inv, inv_mul_cancel_right' h a]
lemma div_mul_cancel_of_imp {a b : G₀} (h : b = 0 → a = 0) : a / b * b = a :=
classical.by_cases (λ hb : b = 0, by simp [*]) (div_mul_cancel a)
@[simp] lemma mul_div_cancel (a : G₀) {b : G₀} (h : b ≠ 0) : a * b / b = a :=
by rw [div_eq_mul_inv, mul_inv_cancel_right' h a]
lemma mul_div_cancel_of_imp {a b : G₀} (h : b = 0 → a = 0) : a * b / b = a :=
classical.by_cases (λ hb : b = 0, by simp [*]) (mul_div_cancel a)
local attribute [simp] div_eq_mul_inv mul_comm mul_assoc mul_left_comm
@[simp] lemma div_self_mul_self' (a : G₀) : a / (a * a) = a⁻¹ :=
calc a / (a * a) = a⁻¹⁻¹ * a⁻¹ * a⁻¹ : by simp [mul_inv_rev']
... = a⁻¹ : inv_mul_mul_self _
lemma div_eq_mul_one_div (a b : G₀) : a / b = a * (1 / b) :=
by simp
lemma mul_one_div_cancel {a : G₀} (h : a ≠ 0) : a * (1 / a) = 1 :=
by simp [h]
lemma one_div_mul_cancel {a : G₀} (h : a ≠ 0) : (1 / a) * a = 1 :=
by simp [h]
lemma one_div_one : 1 / 1 = (1:G₀) :=
div_self (ne.symm zero_ne_one)
lemma one_div_ne_zero {a : G₀} (h : a ≠ 0) : 1 / a ≠ 0 :=
by simpa only [one_div] using inv_ne_zero h
lemma eq_one_div_of_mul_eq_one {a b : G₀} (h : a * b = 1) : b = 1 / a :=
by simpa only [one_div] using eq_inv_of_mul_right_eq_one h
lemma eq_one_div_of_mul_eq_one_left {a b : G₀} (h : b * a = 1) : b = 1 / a :=
by simpa only [one_div] using eq_inv_of_mul_left_eq_one h
@[simp] lemma one_div_div (a b : G₀) : 1 / (a / b) = b / a :=
by rw [one_div, div_eq_mul_inv, mul_inv_rev', inv_inv', div_eq_mul_inv]
lemma one_div_one_div (a : G₀) : 1 / (1 / a) = a :=
by simp
lemma eq_of_one_div_eq_one_div {a b : G₀} (h : 1 / a = 1 / b) : a = b :=
by rw [← one_div_one_div a, h, one_div_one_div]
variables {a b c : G₀}
@[simp] lemma inv_eq_zero {a : G₀} : a⁻¹ = 0 ↔ a = 0 :=
by rw [inv_eq_iff, inv_zero, eq_comm]
@[simp] lemma zero_eq_inv {a : G₀} : 0 = a⁻¹ ↔ 0 = a :=
eq_comm.trans $ inv_eq_zero.trans eq_comm
lemma one_div_mul_one_div_rev (a b : G₀) : (1 / a) * (1 / b) = 1 / (b * a) :=
by simp only [div_eq_mul_inv, one_mul, mul_inv_rev']
theorem divp_eq_div (a : G₀) (u : units G₀) : a /ₚ u = a / u :=
by simpa only [div_eq_mul_inv] using congr_arg ((*) a) u.coe_inv'
@[simp] theorem divp_mk0 (a : G₀) {b : G₀} (hb : b ≠ 0) :
a /ₚ units.mk0 b hb = a / b :=
divp_eq_div _ _
lemma inv_div : (a / b)⁻¹ = b / a :=
by rw [div_eq_mul_inv, mul_inv_rev', div_eq_mul_inv, inv_inv']
lemma inv_div_left : a⁻¹ / b = (b * a)⁻¹ :=
by rw [mul_inv_rev', div_eq_mul_inv]
lemma div_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a / b ≠ 0 :=
by { rw div_eq_mul_inv, exact mul_ne_zero ha (inv_ne_zero hb) }
@[simp] lemma div_eq_zero_iff : a / b = 0 ↔ a = 0 ∨ b = 0:=
by simp [div_eq_mul_inv]
lemma div_ne_zero_iff : a / b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 :=
(not_congr div_eq_zero_iff).trans not_or_distrib
lemma div_left_inj' (hc : c ≠ 0) : a / c = b / c ↔ a = b :=
by rw [← divp_mk0 _ hc, ← divp_mk0 _ hc, divp_left_inj]
lemma div_eq_iff_mul_eq (hb : b ≠ 0) : a / b = c ↔ c * b = a :=
⟨λ h, by rw [← h, div_mul_cancel _ hb],
λ h, by rw [← h, mul_div_cancel _ hb]⟩
lemma eq_div_iff_mul_eq (hc : c ≠ 0) : a = b / c ↔ a * c = b :=
by rw [eq_comm, div_eq_iff_mul_eq hc]
lemma div_eq_of_eq_mul {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : y = z * x) : y / x = z :=
(div_eq_iff_mul_eq hx).2 h.symm
lemma eq_div_of_mul_eq {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : z * x = y) : z = y / x :=
eq.symm $ div_eq_of_eq_mul hx h.symm
lemma eq_of_div_eq_one (h : a / b = 1) : a = b :=
begin
by_cases hb : b = 0,
{ rw [hb, div_zero] at h,
exact eq_of_zero_eq_one h a b },
{ rwa [div_eq_iff_mul_eq hb, one_mul, eq_comm] at h }
end
lemma div_eq_one_iff_eq (hb : b ≠ 0) : a / b = 1 ↔ a = b :=
⟨eq_of_div_eq_one, λ h, h.symm ▸ div_self hb⟩
lemma div_mul_left {a b : G₀} (hb : b ≠ 0) : b / (a * b) = 1 / a :=
by simp only [div_eq_mul_inv, mul_inv_rev', mul_inv_cancel_left' hb, one_mul]
lemma mul_div_mul_right (a b : G₀) {c : G₀} (hc : c ≠ 0) :
(a * c) / (b * c) = a / b :=
by simp only [div_eq_mul_inv, mul_inv_rev', mul_assoc, mul_inv_cancel_left' hc]
lemma mul_mul_div (a : G₀) {b : G₀} (hb : b ≠ 0) : a = a * b * (1 / b) :=
by simp [hb]
end group_with_zero
section comm_group_with_zero -- comm
variables [comm_group_with_zero G₀] {a b c : G₀}
@[priority 10] -- see Note [lower instance priority]
instance comm_group_with_zero.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero G₀ :=
{ ..group_with_zero.cancel_monoid_with_zero, ..comm_group_with_zero.to_comm_monoid_with_zero G₀ }
/-- Pullback a `comm_group_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.comm_group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀']
[has_inv G₀'] [has_div G₀'] (f : G₀' → G₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹)
(div : ∀ x y, f (x / y) = f x / f y) :
comm_group_with_zero G₀' :=
{ .. hf.group_with_zero f zero one mul inv div, .. hf.comm_semigroup f mul }
/-- Pushforward a `comm_group_with_zero` class along a surjective function. -/
protected def function.surjective.comm_group_with_zero [has_zero G₀'] [has_mul G₀']
[has_one G₀'] [has_inv G₀'] [has_div G₀'] (h01 : (0:G₀') ≠ 1) (f : G₀ → G₀') (hf : surjective f)
(zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹)
(div : ∀ x y, f (x / y) = f x / f y) :
comm_group_with_zero G₀' :=
{ .. hf.group_with_zero h01 f zero one mul inv div, .. hf.comm_semigroup f mul }
lemma mul_inv' : (a * b)⁻¹ = a⁻¹ * b⁻¹ :=
by rw [mul_inv_rev', mul_comm]
lemma one_div_mul_one_div (a b : G₀) : (1 / a) * (1 / b) = 1 / (a * b) :=
by rw [one_div_mul_one_div_rev, mul_comm b]
lemma div_mul_right {a : G₀} (b : G₀) (ha : a ≠ 0) : a / (a * b) = 1 / b :=
by rw [mul_comm, div_mul_left ha]
lemma mul_div_cancel_left_of_imp {a b : G₀} (h : a = 0 → b = 0) : a * b / a = b :=
by rw [mul_comm, mul_div_cancel_of_imp h]
lemma mul_div_cancel_left {a : G₀} (b : G₀) (ha : a ≠ 0) : a * b / a = b :=
mul_div_cancel_left_of_imp $ λ h, (ha h).elim
lemma mul_div_cancel_of_imp' {a b : G₀} (h : b = 0 → a = 0) : b * (a / b) = a :=
by rw [mul_comm, div_mul_cancel_of_imp h]
lemma mul_div_cancel' (a : G₀) {b : G₀} (hb : b ≠ 0) : b * (a / b) = a :=
by rw [mul_comm, (div_mul_cancel _ hb)]
local attribute [simp] mul_assoc mul_comm mul_left_comm
lemma div_mul_div (a b c d : G₀) :
(a / b) * (c / d) = (a * c) / (b * d) :=
by simp [div_eq_mul_inv, mul_inv']
lemma mul_div_mul_left (a b : G₀) {c : G₀} (hc : c ≠ 0) :
(c * a) / (c * b) = a / b :=
by rw [mul_comm c, mul_comm c, mul_div_mul_right _ _ hc]
@[field_simps] lemma div_mul_eq_mul_div (a b c : G₀) : (b / c) * a = (b * a) / c :=
by simp [div_eq_mul_inv]
lemma div_mul_eq_mul_div_comm (a b c : G₀) :
(b / c) * a = b * (a / c) :=
by rw [div_mul_eq_mul_div, ← one_mul c, ← div_mul_div, div_one, one_mul]
lemma mul_eq_mul_of_div_eq_div (a : G₀) {b : G₀} (c : G₀) {d : G₀} (hb : b ≠ 0)
(hd : d ≠ 0) (h : a / b = c / d) : a * d = c * b :=
by rw [← mul_one (a*d), mul_assoc, mul_comm d, ← mul_assoc, ← div_self hb,
← div_mul_eq_mul_div_comm, h, div_mul_eq_mul_div, div_mul_cancel _ hd]
@[field_simps] lemma div_div_eq_mul_div (a b c : G₀) :
a / (b / c) = (a * c) / b :=
by rw [div_eq_mul_one_div, one_div_div, ← mul_div_assoc]
@[field_simps] lemma div_div_eq_div_mul (a b c : G₀) :
(a / b) / c = a / (b * c) :=
by rw [div_eq_mul_one_div, div_mul_div, mul_one]
lemma div_div_div_div_eq (a : G₀) {b c d : G₀} :
(a / b) / (c / d) = (a * d) / (b * c) :=
by rw [div_div_eq_mul_div, div_mul_eq_mul_div, div_div_eq_div_mul]
lemma div_mul_eq_div_mul_one_div (a b c : G₀) :
a / (b * c) = (a / b) * (1 / c) :=
by rw [← div_div_eq_div_mul, ← div_eq_mul_one_div]
/-- Dividing `a` by the result of dividing `a` by itself results in
`a` (whether or not `a` is zero). -/
@[simp] lemma div_div_self (a : G₀) : a / (a / a) = a :=
begin
rw div_div_eq_mul_div,
exact mul_self_div_self a
end
lemma ne_zero_of_one_div_ne_zero {a : G₀} (h : 1 / a ≠ 0) : a ≠ 0 :=
assume ha : a = 0, begin rw [ha, div_zero] at h, contradiction end
lemma eq_zero_of_one_div_eq_zero {a : G₀} (h : 1 / a = 0) : a = 0 :=
classical.by_cases
(assume ha, ha)
(assume ha, ((one_div_ne_zero ha) h).elim)
lemma div_helper {a : G₀} (b : G₀) (h : a ≠ 0) : (1 / (a * b)) * a = 1 / b :=
by rw [div_mul_eq_mul_div, one_mul, div_mul_right _ h]
end comm_group_with_zero
section comm_group_with_zero
variables [comm_group_with_zero G₀] {a b c d : G₀}
lemma div_eq_inv_mul : a / b = b⁻¹ * a :=
by rw [div_eq_mul_inv, mul_comm]
lemma mul_div_right_comm (a b c : G₀) : (a * b) / c = (a / c) * b :=
by rw [div_eq_mul_inv, mul_assoc, mul_comm b, ← mul_assoc, div_eq_mul_inv]
lemma mul_comm_div' (a b c : G₀) : (a / b) * c = a * (c / b) :=
by rw [← mul_div_assoc, mul_div_right_comm]
lemma div_mul_comm' (a b c : G₀) : (a / b) * c = (c / b) * a :=
by rw [div_mul_eq_mul_div, mul_comm, mul_div_right_comm]
lemma mul_div_comm (a b c : G₀) : a * (b / c) = b * (a / c) :=
by rw [← mul_div_assoc, mul_comm, mul_div_assoc]
lemma div_right_comm (a : G₀) : (a / b) / c = (a / c) / b :=
by rw [div_div_eq_div_mul, div_div_eq_div_mul, mul_comm]
lemma div_div_div_cancel_right (a : G₀) (hc : c ≠ 0) : (a / c) / (b / c) = a / b :=
by rw [div_div_eq_mul_div, div_mul_cancel _ hc]
lemma div_mul_div_cancel (a : G₀) (hc : c ≠ 0) : (a / c) * (c / b) = a / b :=
by rw [← mul_div_assoc, div_mul_cancel _ hc]
@[field_simps] lemma div_eq_div_iff (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b :=
calc a / b = c / d ↔ a / b * (b * d) = c / d * (b * d) :
by rw [mul_left_inj' (mul_ne_zero hb hd)]
... ↔ a * d = c * b :
by rw [← mul_assoc, div_mul_cancel _ hb,
← mul_assoc, mul_right_comm, div_mul_cancel _ hd]
@[field_simps] lemma div_eq_iff (hb : b ≠ 0) : a / b = c ↔ a = c * b :=
(div_eq_iff_mul_eq hb).trans eq_comm
@[field_simps] lemma eq_div_iff (hb : b ≠ 0) : c = a / b ↔ c * b = a :=
eq_div_iff_mul_eq hb
lemma div_div_cancel' (ha : a ≠ 0) : a / (a / b) = b :=
by rw [div_eq_mul_inv, inv_div, mul_div_cancel' _ ha]
end comm_group_with_zero
namespace semiconj_by
@[simp] lemma zero_right [mul_zero_class G₀] (a : G₀) : semiconj_by a 0 0 :=
by simp only [semiconj_by, mul_zero, zero_mul]
@[simp] lemma zero_left [mul_zero_class G₀] (x y : G₀) : semiconj_by 0 x y :=
by simp only [semiconj_by, mul_zero, zero_mul]
variables [group_with_zero G₀] {a x y x' y' : G₀}
@[simp] lemma inv_symm_left_iff' : semiconj_by a⁻¹ x y ↔ semiconj_by a y x :=
classical.by_cases
(λ ha : a = 0, by simp only [ha, inv_zero, semiconj_by.zero_left])
(λ ha, @units_inv_symm_left_iff _ _ (units.mk0 a ha) _ _)
lemma inv_symm_left' (h : semiconj_by a x y) : semiconj_by a⁻¹ y x :=
semiconj_by.inv_symm_left_iff'.2 h
lemma inv_right' (h : semiconj_by a x y) : semiconj_by a x⁻¹ y⁻¹ :=
begin
by_cases ha : a = 0,
{ simp only [ha, zero_left] },
by_cases hx : x = 0,
{ subst x,
simp only [semiconj_by, mul_zero, @eq_comm _ _ (y * a), mul_eq_zero] at h,
simp [h.resolve_right ha] },
{ have := mul_ne_zero ha hx,
rw [h.eq, mul_ne_zero_iff] at this,
exact @units_inv_right _ _ _ (units.mk0 x hx) (units.mk0 y this.1) h },
end
@[simp] lemma inv_right_iff' : semiconj_by a x⁻¹ y⁻¹ ↔ semiconj_by a x y :=
⟨λ h, inv_inv' x ▸ inv_inv' y ▸ h.inv_right', inv_right'⟩
lemma div_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') :
semiconj_by a (x / x') (y / y') :=
by { rw [div_eq_mul_inv, div_eq_mul_inv], exact h.mul_right h'.inv_right' }
end semiconj_by
namespace commute
@[simp] theorem zero_right [mul_zero_class G₀] (a : G₀) :commute a 0 := semiconj_by.zero_right a
@[simp] theorem zero_left [mul_zero_class G₀] (a : G₀) : commute 0 a := semiconj_by.zero_left a a
variables [group_with_zero G₀] {a b c : G₀}
@[simp] theorem inv_left_iff' : commute a⁻¹ b ↔ commute a b :=
semiconj_by.inv_symm_left_iff'
theorem inv_left' (h : commute a b) : commute a⁻¹ b := inv_left_iff'.2 h
@[simp] theorem inv_right_iff' : commute a b⁻¹ ↔ commute a b :=
semiconj_by.inv_right_iff'
theorem inv_right' (h : commute a b) : commute a b⁻¹ := inv_right_iff'.2 h
theorem inv_inv' (h : commute a b) : commute a⁻¹ b⁻¹ := h.inv_left'.inv_right'
@[simp] theorem div_right (hab : commute a b) (hac : commute a c) :
commute a (b / c) :=
hab.div_right hac
@[simp] theorem div_left (hac : commute a c) (hbc : commute b c) :
commute (a / b) c :=
by { rw div_eq_mul_inv, exact hac.mul_left hbc.inv_left' }
end commute
namespace monoid_with_zero_hom
variables [group_with_zero G₀] [group_with_zero G₀'] [monoid_with_zero M₀] [nontrivial M₀]
section monoid_with_zero
variables (f : monoid_with_zero_hom G₀ M₀) {a : G₀}
lemma map_ne_zero : f a ≠ 0 ↔ a ≠ 0 :=
⟨λ hfa ha, hfa $ ha.symm ▸ f.map_zero, λ ha, ((is_unit.mk0 a ha).map f.to_monoid_hom).ne_zero⟩
@[simp] lemma map_eq_zero : f a = 0 ↔ a = 0 :=
not_iff_not.1 f.map_ne_zero
end monoid_with_zero
section group_with_zero
variables (f : monoid_with_zero_hom G₀ G₀') (a b : G₀)
/-- A monoid homomorphism between groups with zeros sending `0` to `0` sends `a⁻¹` to `(f a)⁻¹`. -/
@[simp] lemma map_inv' : f a⁻¹ = (f a)⁻¹ :=
begin
by_cases h : a = 0, by simp [h],
apply eq_inv_of_mul_left_eq_one,
rw [← f.map_mul, inv_mul_cancel h, f.map_one]
end
@[simp] lemma map_div : f (a / b) = f a / f b :=
by simpa only [div_eq_mul_inv] using ((f.map_mul _ _).trans $ _root_.congr_arg _ $ f.map_inv' b)
end group_with_zero
end monoid_with_zero_hom
@[simp] lemma monoid_hom.map_units_inv {M G₀ : Type*} [monoid M] [group_with_zero G₀]
(f : M →* G₀) (u : units M) : f ↑u⁻¹ = (f u)⁻¹ :=
by rw [← units.coe_map, ← units.coe_map, ← units.coe_inv', monoid_hom.map_inv]
section noncomputable_defs
variables {M : Type*} [nontrivial M]
/-- Constructs a `group_with_zero` structure on a `monoid_with_zero`
consisting only of units and 0. -/
noncomputable def group_with_zero_of_is_unit_or_eq_zero [hM : monoid_with_zero M]
(h : ∀ (a : M), is_unit a ∨ a = 0) : group_with_zero M :=
{ inv := λ a, if h0 : a = 0 then 0 else ↑((h a).resolve_right h0).unit⁻¹,
inv_zero := dif_pos rfl,
mul_inv_cancel := λ a h0, by {
change a * (if h0 : a = 0 then 0 else ↑((h a).resolve_right h0).unit⁻¹) = 1,
rw [dif_neg h0, units.mul_inv_eq_iff_eq_mul, one_mul, is_unit.unit_spec] },
exists_pair_ne := nontrivial.exists_pair_ne,
.. hM }
/-- Constructs a `comm_group_with_zero` structure on a `comm_monoid_with_zero`
consisting only of units and 0. -/
noncomputable def comm_group_with_zero_of_is_unit_or_eq_zero [hM : comm_monoid_with_zero M]
(h : ∀ (a : M), is_unit a ∨ a = 0) : comm_group_with_zero M :=
{ .. (group_with_zero_of_is_unit_or_eq_zero h), .. hM }
end noncomputable_defs
|
be1b6547c6389a845c2a4fe2c17407276ac0cc53 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/keyword_tactics.lean | 8f657ebf6fb65ba82de2e0cb35fb8741318f8426 | [
"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 | 835 | lean | example : ℕ → ℕ → ℕ :=
begin
assume n m,
apply n
end
example : ℕ → ℕ → ℕ :=
begin
assume (n m : ℕ),
apply n
end
example : ℕ → ℕ → ℕ :=
begin
assume n : ℕ × ℕ <|> assume n m : ℕ,
apply n
end
example : ¬false :=
begin
assume contr,
apply contr
end
example : Π α : Type, α → α :=
begin
assume α,
assume a : α,
apply a
end
example : ℕ → ℕ → ℕ :=
begin
assume n m : bool,
apply n
end
example : ℕ → ℕ → ℕ :=
begin
have : _ → ℕ,
{ assume m : ℕ,
have: ℕ := m,
have: ℕ, from m,
have: ℕ, by apply m,
apply this },
{ assume n, apply this },
end
example (f : ℕ → ℕ) : bool :=
begin
have : ℕ, by skip; apply f 0,
end
example (f : ℕ → ℕ) : bool :=
begin
suffices: ℕ → bool, from this 0,
end
|
5bb38959afdfb24aebbcfb0de2031ad3cb9a0936 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/measure_theory/measure/with_density_vector_measure.lean | fb74f735253003f2bc51f8cc2dac80b78ab96b1c | [
"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 | 8,622 | 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.vector_measure
import measure_theory.function.ae_eq_of_integral
/-!
# Vector measure defined by an integral
Given a measure `μ` and an integrable function `f : α → E`, we can define a vector measure `v` such
that for all measurable set `s`, `v i = ∫ x in s, f x ∂μ`. This definition is useful for
the Radon-Nikodym theorem for signed measures.
## Main definitions
* `measure_theory.measure.with_densityᵥ`: the vector measure formed by integrating a function `f`
with respect to a measure `μ` on some set if `f` is integrable, and `0` otherwise.
-/
noncomputable theory
open_locale classical measure_theory nnreal ennreal
variables {α β : Type*} {m : measurable_space α}
namespace measure_theory
open topological_space
variables {μ ν : measure α}
variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E]
/-- Given a measure `μ` and an integrable function `f`, `μ.with_densityᵥ f` is
the vector measure which maps the set `s` to `∫ₛ f ∂μ`. -/
def measure.with_densityᵥ {m : measurable_space α} (μ : measure α) (f : α → E) :
vector_measure α E :=
if hf : integrable f μ then
{ measure_of' := λ s, if measurable_set s then ∫ x in s, f x ∂μ else 0,
empty' := by simp,
not_measurable' := λ s hs, if_neg hs,
m_Union' := λ s hs₁ hs₂,
begin
convert has_sum_integral_Union hs₁ hs₂ hf.integrable_on,
{ ext n, rw if_pos (hs₁ n) },
{ rw if_pos (measurable_set.Union hs₁) }
end }
else 0
open measure
include m
variables {f g : α → E}
lemma with_densityᵥ_apply (hf : integrable f μ) {s : set α} (hs : measurable_set s) :
μ.with_densityᵥ f s = ∫ x in s, f x ∂μ :=
by { rw [with_densityᵥ, dif_pos hf], exact dif_pos hs }
@[simp] lemma with_densityᵥ_zero : μ.with_densityᵥ (0 : α → E) = 0 :=
by { ext1 s hs, erw [with_densityᵥ_apply (integrable_zero α E μ) hs], simp, }
@[simp] lemma with_densityᵥ_neg : μ.with_densityᵥ (-f) = -μ.with_densityᵥ f :=
begin
by_cases hf : integrable f μ,
{ ext1 i hi,
rw [vector_measure.neg_apply, with_densityᵥ_apply hf hi,
← integral_neg, with_densityᵥ_apply hf.neg hi],
refl },
{ rw [with_densityᵥ, with_densityᵥ, dif_neg hf, dif_neg, neg_zero],
rwa integrable_neg_iff }
end
lemma with_densityᵥ_neg' : μ.with_densityᵥ (λ x, -f x) = -μ.with_densityᵥ f :=
with_densityᵥ_neg
@[simp] lemma with_densityᵥ_add (hf : integrable f μ) (hg : integrable g μ) :
μ.with_densityᵥ (f + g) = μ.with_densityᵥ f + μ.with_densityᵥ g :=
begin
ext1 i hi,
rw [with_densityᵥ_apply (hf.add hg) hi, vector_measure.add_apply,
with_densityᵥ_apply hf hi, with_densityᵥ_apply hg hi],
simp_rw [pi.add_apply],
rw integral_add; rw ← integrable_on_univ,
{ exact hf.integrable_on.restrict measurable_set.univ },
{ exact hg.integrable_on.restrict measurable_set.univ }
end
lemma with_densityᵥ_add' (hf : integrable f μ) (hg : integrable g μ) :
μ.with_densityᵥ (λ x, f x + g x) = μ.with_densityᵥ f + μ.with_densityᵥ g :=
with_densityᵥ_add hf hg
@[simp] lemma with_densityᵥ_sub (hf : integrable f μ) (hg : integrable g μ) :
μ.with_densityᵥ (f - g) = μ.with_densityᵥ f - μ.with_densityᵥ g :=
by rw [sub_eq_add_neg, sub_eq_add_neg, with_densityᵥ_add hf hg.neg, with_densityᵥ_neg]
lemma with_densityᵥ_sub' (hf : integrable f μ) (hg : integrable g μ) :
μ.with_densityᵥ (λ x, f x - g x) = μ.with_densityᵥ f - μ.with_densityᵥ g :=
with_densityᵥ_sub hf hg
@[simp] lemma with_densityᵥ_smul {𝕜 : Type*} [nontrivially_normed_field 𝕜] [normed_space 𝕜 E]
[smul_comm_class ℝ 𝕜 E] (f : α → E) (r : 𝕜) :
μ.with_densityᵥ (r • f) = r • μ.with_densityᵥ f :=
begin
by_cases hf : integrable f μ,
{ ext1 i hi,
rw [with_densityᵥ_apply (hf.smul r) hi, vector_measure.smul_apply,
with_densityᵥ_apply hf hi, ← integral_smul r f],
refl },
{ by_cases hr : r = 0,
{ rw [hr, zero_smul, zero_smul, with_densityᵥ_zero] },
{ rw [with_densityᵥ, with_densityᵥ, dif_neg hf, dif_neg, smul_zero],
rwa integrable_smul_iff hr f } }
end
lemma with_densityᵥ_smul' {𝕜 : Type*} [nontrivially_normed_field 𝕜] [normed_space 𝕜 E]
[smul_comm_class ℝ 𝕜 E] (f : α → E) (r : 𝕜) :
μ.with_densityᵥ (λ x, r • f x) = r • μ.with_densityᵥ f :=
with_densityᵥ_smul f r
lemma measure.with_densityᵥ_absolutely_continuous (μ : measure α) (f : α → ℝ) :
μ.with_densityᵥ f ≪ᵥ μ.to_ennreal_vector_measure :=
begin
by_cases hf : integrable f μ,
{ refine vector_measure.absolutely_continuous.mk (λ i hi₁ hi₂, _),
rw to_ennreal_vector_measure_apply_measurable hi₁ at hi₂,
rw [with_densityᵥ_apply hf hi₁, measure.restrict_zero_set hi₂, integral_zero_measure] },
{ rw [with_densityᵥ, dif_neg hf],
exact vector_measure.absolutely_continuous.zero _ }
end
/-- Having the same density implies the underlying functions are equal almost everywhere. -/
lemma integrable.ae_eq_of_with_densityᵥ_eq {f g : α → E} (hf : integrable f μ) (hg : integrable g μ)
(hfg : μ.with_densityᵥ f = μ.with_densityᵥ g) :
f =ᵐ[μ] g :=
begin
refine hf.ae_eq_of_forall_set_integral_eq f g hg (λ i hi _, _),
rw [← with_densityᵥ_apply hf hi, hfg, with_densityᵥ_apply hg hi]
end
lemma with_densityᵥ_eq.congr_ae {f g : α → E} (h : f =ᵐ[μ] g) :
μ.with_densityᵥ f = μ.with_densityᵥ g :=
begin
by_cases hf : integrable f μ,
{ ext i hi,
rw [with_densityᵥ_apply hf hi, with_densityᵥ_apply (hf.congr h) hi],
exact integral_congr_ae (ae_restrict_of_ae h) },
{ have hg : ¬ integrable g μ,
{ intro hg, exact hf (hg.congr h.symm) },
rw [with_densityᵥ, with_densityᵥ, dif_neg hf, dif_neg hg] }
end
lemma integrable.with_densityᵥ_eq_iff {f g : α → E}
(hf : integrable f μ) (hg : integrable g μ) :
μ.with_densityᵥ f = μ.with_densityᵥ g ↔ f =ᵐ[μ] g :=
⟨λ hfg, hf.ae_eq_of_with_densityᵥ_eq hg hfg, λ h, with_densityᵥ_eq.congr_ae h⟩
section signed_measure
lemma with_densityᵥ_to_real {f : α → ℝ≥0∞} (hfm : ae_measurable f μ) (hf : ∫⁻ x, f x ∂μ ≠ ∞) :
μ.with_densityᵥ (λ x, (f x).to_real) =
@to_signed_measure α _ (μ.with_density f) (is_finite_measure_with_density hf) :=
begin
have hfi := integrable_to_real_of_lintegral_ne_top hfm hf,
ext i hi,
rw [with_densityᵥ_apply hfi hi, to_signed_measure_apply_measurable hi,
with_density_apply _ hi, integral_to_real hfm.restrict],
refine ae_lt_top' hfm.restrict (ne_top_of_le_ne_top hf _),
conv_rhs { rw ← set_lintegral_univ },
exact lintegral_mono_set (set.subset_univ _),
end
lemma with_densityᵥ_eq_with_density_pos_part_sub_with_density_neg_part
{f : α → ℝ} (hfi : integrable f μ) :
μ.with_densityᵥ f =
@to_signed_measure α _ (μ.with_density (λ x, ennreal.of_real $ f x))
(is_finite_measure_with_density_of_real hfi.2) -
@to_signed_measure α _ (μ.with_density (λ x, ennreal.of_real $ -f x))
(is_finite_measure_with_density_of_real hfi.neg.2) :=
begin
ext i hi,
rw [with_densityᵥ_apply hfi hi,
integral_eq_lintegral_pos_part_sub_lintegral_neg_part hfi.integrable_on,
vector_measure.sub_apply, to_signed_measure_apply_measurable hi,
to_signed_measure_apply_measurable hi, with_density_apply _ hi, with_density_apply _ hi],
end
lemma integrable.with_densityᵥ_trim_eq_integral {m m0 : measurable_space α}
{μ : measure α} (hm : m ≤ m0) {f : α → ℝ} (hf : integrable f μ)
{i : set α} (hi : measurable_set[m] i) :
(μ.with_densityᵥ f).trim hm i = ∫ x in i, f x ∂μ :=
by rw [vector_measure.trim_measurable_set_eq hm hi, with_densityᵥ_apply hf (hm _ hi)]
lemma integrable.with_densityᵥ_trim_absolutely_continuous
{m m0 : measurable_space α} {μ : measure α} (hm : m ≤ m0) (hfi : integrable f μ) :
(μ.with_densityᵥ f).trim hm ≪ᵥ (μ.trim hm).to_ennreal_vector_measure :=
begin
refine vector_measure.absolutely_continuous.mk (λ j hj₁ hj₂, _),
rw [measure.to_ennreal_vector_measure_apply_measurable hj₁, trim_measurable_set_eq hm hj₁] at hj₂,
rw [vector_measure.trim_measurable_set_eq hm hj₁, with_densityᵥ_apply hfi (hm _ hj₁)],
simp only [measure.restrict_eq_zero.mpr hj₂, integral_zero_measure]
end
end signed_measure
end measure_theory
|
c456d9ac9dd400a0f8fecfa0b86010540220fa42 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/group_theory/coset.lean | e23ab6f7a6ec94bdb3d12fda2d93691502680255 | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 11,448 | lean | /-
Copyright (c) 2018 Mitchell Rowett. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mitchell Rowett, Scott Morrison
-/
import group_theory.subgroup data.equiv.basic data.quot
open set function
variable {α : Type*}
@[to_additive left_add_coset]
def left_coset [has_mul α] (a : α) (s : set α) : set α := (λ x, a * x) '' s
attribute [to_additive left_add_coset.equations._eqn_1] left_coset.equations._eqn_1
@[to_additive right_add_coset]
def right_coset [has_mul α] (s : set α) (a : α) : set α := (λ x, x * a) '' s
attribute [to_additive right_add_coset.equations._eqn_1] right_coset.equations._eqn_1
local infix ` *l `:70 := left_coset
local infix ` +l `:70 := left_add_coset
local infix ` *r `:70 := right_coset
local infix ` +r `:70 := right_add_coset
section coset_mul
variable [has_mul α]
@[to_additive mem_left_add_coset]
lemma mem_left_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : a * x ∈ a *l s :=
mem_image_of_mem (λ b : α, a * b) hxS
@[to_additive mem_right_add_coset]
lemma mem_right_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : x * a ∈ s *r a :=
mem_image_of_mem (λ b : α, b * a) hxS
@[to_additive left_add_coset_equiv]
def left_coset_equiv (s : set α) (a b : α) := a *l s = b *l s
@[to_additive left_add_coset_equiv_rel]
lemma left_coset_equiv_rel (s : set α) : equivalence (left_coset_equiv s) :=
mk_equivalence (left_coset_equiv s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans)
end coset_mul
section coset_semigroup
variable [semigroup α]
@[simp] lemma left_coset_assoc (s : set α) (a b : α) : a *l (b *l s) = (a * b) *l s :=
by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc]
attribute [to_additive left_add_coset_assoc] left_coset_assoc
@[simp] lemma right_coset_assoc (s : set α) (a b : α) : s *r a *r b = s *r (a * b) :=
by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc]
attribute [to_additive right_add_coset_assoc] right_coset_assoc
@[to_additive left_add_coset_right_add_coset]
lemma left_coset_right_coset (s : set α) (a b : α) : a *l s *r b = a *l (s *r b) :=
by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc]
end coset_semigroup
section coset_monoid
variables [monoid α] (s : set α)
@[simp] lemma one_left_coset : 1 *l s = s :=
set.ext $ by simp [left_coset]
attribute [to_additive zero_left_add_coset] one_left_coset
@[simp] lemma right_coset_one : s *r 1 = s :=
set.ext $ by simp [right_coset]
attribute [to_additive right_add_coset_zero] right_coset_one
end coset_monoid
section coset_submonoid
open is_submonoid
variables [monoid α] (s : set α) [is_submonoid s]
@[to_additive mem_own_left_add_coset]
lemma mem_own_left_coset (a : α) : a ∈ a *l s :=
suffices a * 1 ∈ a *l s, by simpa,
mem_left_coset a (one_mem s)
@[to_additive mem_own_right_add_coset]
lemma mem_own_right_coset (a : α) : a ∈ s *r a :=
suffices 1 * a ∈ s *r a, by simpa,
mem_right_coset a (one_mem s)
@[to_additive mem_left_add_coset_left_add_coset]
lemma mem_left_coset_left_coset {a : α} (ha : a *l s = s) : a ∈ s :=
by rw [←ha]; exact mem_own_left_coset s a
@[to_additive mem_right_add_coset_right_add_coset]
lemma mem_right_coset_right_coset {a : α} (ha : s *r a = s) : a ∈ s :=
by rw [←ha]; exact mem_own_right_coset s a
end coset_submonoid
section coset_group
variables [group α] {s : set α} {x : α}
@[to_additive mem_left_add_coset_iff]
lemma mem_left_coset_iff (a : α) : x ∈ a *l s ↔ a⁻¹ * x ∈ s :=
iff.intro
(assume ⟨b, hb, eq⟩, by simp [eq.symm, hb])
(assume h, ⟨a⁻¹ * x, h, by simp⟩)
@[to_additive mem_right_add_coset_iff]
lemma mem_right_coset_iff (a : α) : x ∈ s *r a ↔ x * a⁻¹ ∈ s :=
iff.intro
(assume ⟨b, hb, eq⟩, by simp [eq.symm, hb])
(assume h, ⟨x * a⁻¹, h, by simp⟩)
end coset_group
section coset_subgroup
open is_submonoid
open is_subgroup
variables [group α] (s : set α) [is_subgroup s]
@[to_additive left_add_coset_mem_left_add_coset]
lemma left_coset_mem_left_coset {a : α} (ha : a ∈ s) : a *l s = s :=
set.ext $ by simp [mem_left_coset_iff, mul_mem_cancel_right s (inv_mem ha)]
@[to_additive right_add_coset_mem_right_add_coset]
lemma right_coset_mem_right_coset {a : α} (ha : a ∈ s) : s *r a = s :=
set.ext $ assume b, by simp [mem_right_coset_iff, mul_mem_cancel_left s (inv_mem ha)]
@[to_additive normal_of_eq_add_cosets]
theorem normal_of_eq_cosets [normal_subgroup s] (g : α) : g *l s = s *r g :=
set.ext $ assume a, by simp [mem_left_coset_iff, mem_right_coset_iff]; rw [mem_norm_comm_iff]
@[to_additive eq_add_cosets_of_normal]
theorem eq_cosets_of_normal (h : ∀ g, g *l s = s *r g) : normal_subgroup s :=
⟨assume a ha g, show g * a * g⁻¹ ∈ s,
by rw [← mem_right_coset_iff, ← h]; exact mem_left_coset g ha⟩
@[to_additive normal_iff_eq_add_cosets]
theorem normal_iff_eq_cosets : normal_subgroup s ↔ ∀ g, g *l s = s *r g :=
⟨@normal_of_eq_cosets _ _ s _, eq_cosets_of_normal s⟩
end coset_subgroup
namespace quotient_group
def left_rel [group α] (s : set α) [is_subgroup s] : setoid α :=
⟨λ x y, x⁻¹ * y ∈ s,
assume x, by simp [is_submonoid.one_mem],
assume x y hxy,
have (x⁻¹ * y)⁻¹ ∈ s, from is_subgroup.inv_mem hxy,
by simpa using this,
assume x y z hxy hyz,
have x⁻¹ * y * (y⁻¹ * z) ∈ s, from is_submonoid.mul_mem hxy hyz,
by simpa [mul_assoc] using this⟩
attribute [to_additive quotient_add_group.left_rel._proof_1] left_rel._proof_1
attribute [to_additive quotient_add_group.left_rel] left_rel
attribute [to_additive quotient_add_group.left_rel.equations._eqn_1] left_rel.equations._eqn_1
/-- `quotient s` is the quotient type representing the left cosets of `s`.
If `s` is a normal subgroup, `quotient s` is a group -/
def quotient [group α] (s : set α) [is_subgroup s] : Type* := quotient (left_rel s)
attribute [to_additive quotient_add_group.quotient] quotient
attribute [to_additive quotient_add_group.quotient.equations._eqn_1] quotient.equations._eqn_1
variables [group α] {s : set α} [is_subgroup s]
@[to_additive quotient_add_group.mk]
def mk (a : α) : quotient s :=
quotient.mk' a
attribute [to_additive quotient_add_group.mk.equations._eqn_1] mk.equations._eqn_1
@[elab_as_eliminator, to_additive quotient_add_group.induction_on]
lemma induction_on {C : quotient s → Prop} (x : quotient s)
(H : ∀ z, C (quotient_group.mk z)) : C x :=
quotient.induction_on' x H
attribute [elab_as_eliminator] quotient_add_group.induction_on
@[to_additive quotient_add_group.has_coe]
instance : has_coe α (quotient s) := ⟨mk⟩
attribute [to_additive quotient_add_group.has_coe.equations._eqn_1] has_coe.equations._eqn_1
@[elab_as_eliminator, to_additive quotient_add_group.induction_on']
lemma induction_on' {C : quotient s → Prop} (x : quotient s)
(H : ∀ z : α, C z) : C x :=
quotient.induction_on' x H
attribute [elab_as_eliminator] quotient_add_group.induction_on'
@[to_additive quotient_add_group.inhabited]
instance [group α] (s : set α) [is_subgroup s] : inhabited (quotient s) :=
⟨((1 : α) : quotient s)⟩
attribute [to_additive quotient_add_group.inhabited.equations._eqn_1] inhabited.equations._eqn_1
@[to_additive quotient_add_group.eq]
protected lemma eq {a b : α} : (a : quotient s) = b ↔ a⁻¹ * b ∈ s :=
quotient.eq'
@[to_additive quotient_add_group.eq_class_eq_left_coset]
lemma eq_class_eq_left_coset [group α] (s : set α) [is_subgroup s] (g : α) :
{x : α | (x : quotient s) = g} = left_coset g s :=
set.ext $ λ z, by rw [mem_left_coset_iff, set.mem_set_of_eq, eq_comm, quotient_group.eq]
end quotient_group
namespace is_subgroup
open quotient_group
variables [group α] {s : set α}
def left_coset_equiv_subgroup (g : α) : left_coset g s ≃ s :=
⟨λ x, ⟨g⁻¹ * x.1, (mem_left_coset_iff _).1 x.2⟩,
λ x, ⟨g * x.1, x.1, x.2, rfl⟩,
λ ⟨x, hx⟩, subtype.eq $ by simp,
λ ⟨g, hg⟩, subtype.eq $ by simp⟩
attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup._match_2] left_coset_equiv_subgroup._match_2
attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup._match_1] left_coset_equiv_subgroup._match_1
attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup._proof_4] left_coset_equiv_subgroup._proof_4
attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup._proof_3] left_coset_equiv_subgroup._proof_3
attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup._proof_2] left_coset_equiv_subgroup._proof_2
attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup._proof_1] left_coset_equiv_subgroup._proof_1
attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup] left_coset_equiv_subgroup
attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup.equations._eqn_1] left_coset_equiv_subgroup.equations._eqn_1
attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup._match_1.equations._eqn_1] left_coset_equiv_subgroup._match_1.equations._eqn_1
attribute [to_additive is_add_subgroup.left_add_coset_equiv_subgroup._match_2.equations._eqn_1] left_coset_equiv_subgroup._match_2.equations._eqn_1
noncomputable def group_equiv_quotient_times_subgroup (hs : is_subgroup s) :
α ≃ quotient s × s :=
calc α ≃ Σ L : quotient s, {x : α // (x : quotient s)= L} :
equiv.equiv_fib quotient_group.mk
... ≃ Σ L : quotient s, left_coset (quotient.out' L) s :
equiv.sigma_congr_right (λ L,
begin rw ← eq_class_eq_left_coset,
show {x // quotient.mk' x = L} ≃ {x : α // quotient.mk' x = quotient.mk' _},
simp [-quotient.eq']
end)
... ≃ Σ L : quotient s, s :
equiv.sigma_congr_right (λ L, left_coset_equiv_subgroup _)
... ≃ quotient s × s :
equiv.sigma_equiv_prod _ _
attribute [to_additive is_add_subgroup.add_group_equiv_quotient_times_subgroup._proof_2] group_equiv_quotient_times_subgroup._proof_2
attribute [to_additive is_add_subgroup.add_group_equiv_quotient_times_subgroup._proof_1] group_equiv_quotient_times_subgroup._proof_1
attribute [to_additive is_add_subgroup.add_group_equiv_quotient_times_subgroup] group_equiv_quotient_times_subgroup
attribute [to_additive is_add_subgroup.add_group_equiv_quotient_times_subgroup.equations._eqn_1] group_equiv_quotient_times_subgroup.equations._eqn_1
end is_subgroup
namespace quotient_group
variables [group α]
noncomputable def preimage_mk_equiv_subgroup_times_set
(s : set α) [is_subgroup s] (t : set (quotient s)) : quotient_group.mk ⁻¹' t ≃ s × t :=
have h : ∀ {x : quotient s} {a : α}, x ∈ t → a ∈ s →
(quotient.mk' (quotient.out' x * a) : quotient s) = quotient.mk' (quotient.out' x) :=
λ x a hx ha, quotient.sound' (show (quotient.out' x * a)⁻¹ * quotient.out' x ∈ s,
from (is_subgroup.inv_mem_iff _).1 $
by rwa [mul_inv_rev, inv_inv, ← mul_assoc, inv_mul_self, one_mul]),
{ to_fun := λ ⟨a, ha⟩, ⟨⟨(quotient.out' (quotient.mk' a))⁻¹ * a,
@quotient.exact' _ (left_rel s) _ _ $ (quotient.out_eq' _)⟩,
⟨quotient.mk' a, ha⟩⟩,
inv_fun := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, ⟨quotient.out' x * a, show quotient.mk' _ ∈ t,
by simp [h hx ha, hx]⟩,
left_inv := λ ⟨a, ha⟩, subtype.eq $ show _ * _ = a, by simp,
right_inv := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, show (_, _) = _, by simp [h hx ha] }
end quotient_group
|
e9598cb57e837b7aa00abbf07e7231e2aeef6637 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/limits/preserves/shapes/pullbacks.lean | 47d26ecc254332005f1bbd0b340a222310f168d7 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,642 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.limits.shapes.pullbacks
import Mathlib.category_theory.limits.preserves.basic
import Mathlib.PostPort
universes u₁ u₂ v
namespace Mathlib
/-!
# Preserving pullbacks
Constructions to relate the notions of preserving pullbacks and reflecting pullbacks to concrete
pullback cones.
In particular, we show that `pullback_comparison G f g` is an isomorphism iff `G` preserves
the pullback of `f` and `g`.
## TODO
* Dualise to pushouts
* Generalise to wide pullbacks
-/
namespace category_theory.limits
/--
The map of a pullback cone is a limit iff the fork consisting of the mapped morphisms is a limit.
This essentially lets us commute `pullback_cone.mk` with `functor.map_cone`.
-/
def is_limit_map_cone_pullback_cone_equiv {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {W : C} {X : C} {Y : C} {Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} {h : W ⟶ X} {k : W ⟶ Y} (comm : h ≫ f = k ≫ g) : is_limit (functor.map_cone G (pullback_cone.mk h k comm)) ≃
is_limit
(pullback_cone.mk (functor.map G h) (functor.map G k) (is_limit_map_cone_pullback_cone_equiv._proof_1 G comm)) :=
equiv.trans
(equiv.symm
(is_limit.postcompose_hom_equiv (diagram_iso_cospan (cospan f g ⋙ G))
(functor.map_cone G (pullback_cone.mk h k comm))))
(is_limit.equiv_iso_limit
(cones.ext
(iso.refl
(cone.X
(functor.obj (cones.postcompose (iso.hom (diagram_iso_cospan (cospan f g ⋙ G))))
(functor.map_cone G (pullback_cone.mk h k comm)))))
sorry))
/-- The property of preserving pullbacks expressed in terms of binary fans. -/
def is_limit_pullback_cone_map_of_is_limit {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {W : C} {X : C} {Y : C} {Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} {h : W ⟶ X} {k : W ⟶ Y} (comm : h ≫ f = k ≫ g) [preserves_limit (cospan f g) G] (l : is_limit (pullback_cone.mk h k comm)) : is_limit (pullback_cone.mk (functor.map G h) (functor.map G k) (is_limit_map_cone_pullback_cone_equiv._proof_1 G comm)) :=
coe_fn (is_limit_map_cone_pullback_cone_equiv G comm) (preserves_limit.preserves l)
/-- The property of reflecting pullbacks expressed in terms of binary fans. -/
def is_limit_of_is_limit_pullback_cone_map {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {W : C} {X : C} {Y : C} {Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} {h : W ⟶ X} {k : W ⟶ Y} (comm : h ≫ f = k ≫ g) [reflects_limit (cospan f g) G] (l : is_limit (pullback_cone.mk (functor.map G h) (functor.map G k) (is_limit_map_cone_pullback_cone_equiv._proof_1 G comm))) : is_limit (pullback_cone.mk h k comm) :=
reflects_limit.reflects (coe_fn (equiv.symm (is_limit_map_cone_pullback_cone_equiv G comm)) l)
/--
If `G` preserves pullbacks and `C` has them, then the pullback cone constructed of the mapped
morphisms of the pullback cone is a limit.
-/
def is_limit_of_has_pullback_of_preserves_limit {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} {Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [preserves_limit (cospan f g) G] : is_limit
(pullback_cone.mk (functor.map G pullback.fst) (functor.map G pullback.snd)
(is_limit_of_has_pullback_of_preserves_limit._proof_1 G f g)) :=
is_limit_pullback_cone_map_of_is_limit G pullback.condition (pullback_is_pullback f g)
/--
If the pullback comparison map for `G` at `(f,g)` is an isomorphism, then `G` preserves the
pullback of `(f,g)`.
-/
def preserves_pullback.of_iso_comparison {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} {Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_pullback (functor.map G f) (functor.map G g)] [i : is_iso (pullback_comparison G f g)] : preserves_limit (cospan f g) G :=
preserves_limit_of_preserves_limit_cone (pullback_is_pullback f g)
(coe_fn (equiv.symm (is_limit_map_cone_pullback_cone_equiv G pullback.condition))
(is_limit.of_point_iso (limit.is_limit (cospan (functor.map G f) (functor.map G g)))))
/--
If `G` preserves the pullback of `(f,g)`, then the pullback comparison map for `G` at `(f,g)` is
an isomorphism.
-/
def preserves_pullback.iso {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} {Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_pullback (functor.map G f) (functor.map G g)] [preserves_limit (cospan f g) G] : functor.obj G (pullback f g) ≅ pullback (functor.map G f) (functor.map G g) :=
is_limit.cone_point_unique_up_to_iso (is_limit_of_has_pullback_of_preserves_limit G f g)
(limit.is_limit (cospan (functor.map G f) (functor.map G g)))
@[simp] theorem preserves_pullback.iso_hom {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} {Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_pullback (functor.map G f) (functor.map G g)] [preserves_limit (cospan f g) G] : iso.hom (preserves_pullback.iso G f g) = pullback_comparison G f g :=
rfl
protected instance pullback_comparison.category_theory.is_iso {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {X : C} {Y : C} {Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_pullback (functor.map G f) (functor.map G g)] [preserves_limit (cospan f g) G] : is_iso (pullback_comparison G f g) :=
eq.mpr sorry (is_iso.of_iso (preserves_pullback.iso G f g))
|
a7c600924fc76cc72e8aad323b6f64b4720f5479 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/simp6.lean | 64f36a558c05a57b31358c17db4894630cfc07c7 | [
"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 | 737 | lean | theorem ex1 (a : α) (b : List α) : (a::b = []) = False :=
by simp
theorem ex2 (a : α) (b : List α) : (a::b = []) = False :=
by simp
theorem ex3 (x : Nat) : (if Nat.succ x = 0 then 1 else 2) = 2 :=
by simp
theorem ex4 (x : Nat) : (if 10 = 0 then 1 else 2) = 2 :=
by simp
theorem ex5 : (10 = 20) = False :=
by simp
#print ex5
theorem ex6 : (if "hello" = "world" then 1 else 2) = 2 :=
by simp
#print ex6
theorem ex7 : (if "hello" = "world" then 1 else 2) = 2 := by
fail_if_success simp (config := { decide := false })
simp
theorem ex8 : (10 + 2000 = 20) = False :=
by simp
def fact : Nat → Nat
| 0 => 1
| x+1 => (x+1) * fact x
theorem ex9 : (if fact 100 > 10 then true else false) = true :=
by simp
|
d3320ad0d0243e8b034a3607d9259ffbded56afc | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/category_theory/limits/shapes/constructions/over/products.lean | 44ecd390a1568de86a0d8cb9d0e6743a3f787176 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 5,992 | lean | /-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Reid Barton, Bhavik Mehta
-/
import category_theory.over
import category_theory.limits.shapes.pullbacks
import category_theory.limits.shapes.wide_pullbacks
import category_theory.limits.shapes.finite_products
universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation
open category_theory category_theory.limits
variables {J : Type v} [small_category J]
variables {C : Type u} [category.{v} C]
variable {X : C}
namespace category_theory.over
namespace construct_products
/-- (Impl) Given a product shape in `C/B`, construct the corresponding wide pullback diagram in `C`. -/
@[reducible]
def wide_pullback_diagram_of_diagram_over (B : C) {J : Type v} (F : discrete J ⥤ over B) : wide_pullback_shape J ⥤ C :=
wide_pullback_shape.wide_cospan B (λ j, (F.obj j).left) (λ j, (F.obj j).hom)
/-- (Impl) A preliminary definition to avoid timeouts. -/
@[simps]
def cones_equiv_inverse_obj (B : C) {J : Type v} (F : discrete J ⥤ over B) (c : cone F) :
cone (wide_pullback_diagram_of_diagram_over B F) :=
{ X := c.X.left,
π :=
{ app := λ X, option.cases_on X c.X.hom (λ (j : J), (c.π.app j).left),
-- `tidy` can do this using `case_bash`, but let's try to be a good `-T50000` citizen:
naturality' := λ X Y f,
begin
dsimp, cases X; cases Y; cases f,
{ rw [category.id_comp, category.comp_id], },
{ rw [over.w, category.id_comp], },
{ rw [category.id_comp, category.comp_id], },
end } }
/-- (Impl) A preliminary definition to avoid timeouts. -/
@[simps]
def cones_equiv_inverse (B : C) {J : Type v} (F : discrete J ⥤ over B) :
cone F ⥤ cone (wide_pullback_diagram_of_diagram_over B F) :=
{ obj := cones_equiv_inverse_obj B F,
map := λ c₁ c₂ f,
{ hom := f.hom.left,
w' := λ j,
begin
cases j,
{ simp },
{ dsimp,
rw ← f.w j,
refl }
end } }
/-- (Impl) A preliminary definition to avoid timeouts. -/
@[simps]
def cones_equiv_functor (B : C) {J : Type v} (F : discrete J ⥤ over B) :
cone (wide_pullback_diagram_of_diagram_over B F) ⥤ cone F :=
{ obj := λ c,
{ X := over.mk (c.π.app none),
π := { app := λ j, over.hom_mk (c.π.app (some j)) (by apply c.w (wide_pullback_shape.hom.term j)) } },
map := λ c₁ c₂ f,
{ hom := over.hom_mk f.hom } }
local attribute [tidy] tactic.case_bash
/-- (Impl) A preliminary definition to avoid timeouts. -/
@[simp]
def cones_equiv_unit_iso (B : C) {J : Type v} (F : discrete J ⥤ over B) :
𝟭 (cone (wide_pullback_diagram_of_diagram_over B F)) ≅
cones_equiv_functor B F ⋙ cones_equiv_inverse B F :=
nat_iso.of_components (λ _, cones.ext {hom := 𝟙 _, inv := 𝟙 _} (by tidy)) (by tidy)
/-- (Impl) A preliminary definition to avoid timeouts. -/
@[simp]
def cones_equiv_counit_iso (B : C) {J : Type v} (F : discrete J ⥤ over B) :
cones_equiv_inverse B F ⋙ cones_equiv_functor B F ≅ 𝟭 (cone F) :=
nat_iso.of_components
(λ _, cones.ext {hom := over.hom_mk (𝟙 _), inv := over.hom_mk (𝟙 _)} (by tidy)) (by tidy)
-- TODO: Can we add `. obviously` to the second arguments of `nat_iso.of_components` and `cones.ext`?
/-- (Impl) Establish an equivalence between the category of cones for `F` and for the "grown" `F`. -/
@[simps]
def cones_equiv (B : C) {J : Type v} (F : discrete J ⥤ over B) :
cone (wide_pullback_diagram_of_diagram_over B F) ≌ cone F :=
{ functor := cones_equiv_functor B F,
inverse := cones_equiv_inverse B F,
unit_iso := cones_equiv_unit_iso B F,
counit_iso := cones_equiv_counit_iso B F, }
/-- Use the above equivalence to prove we have a limit. -/
def has_over_limit_discrete_of_wide_pullback_limit {B : C} {J : Type v} (F : discrete J ⥤ over B)
[has_limit (wide_pullback_diagram_of_diagram_over B F)] :
has_limit F :=
{ cone := _,
is_limit := is_limit.of_cone_equiv
(cones_equiv B F).functor (limit.is_limit (wide_pullback_diagram_of_diagram_over B F)) }
/-- Given a wide pullback in `C`, construct a product in `C/B`. -/
def over_product_of_wide_pullback {J : Type v} [has_limits_of_shape (wide_pullback_shape J) C] {B : C} :
has_limits_of_shape (discrete J) (over B) :=
{ has_limit := λ F, has_over_limit_discrete_of_wide_pullback_limit F }
/-- Given a pullback in `C`, construct a binary product in `C/B`. -/
def over_binary_product_of_pullback [has_pullbacks C] {B : C} :
has_binary_products (over B) :=
{ has_limits_of_shape := over_product_of_wide_pullback }
/-- Given all wide pullbacks in `C`, construct products in `C/B`. -/
def over_products_of_wide_pullbacks [has_wide_pullbacks C] {B : C} :
has_products (over B) :=
{ has_limits_of_shape := λ J, over_product_of_wide_pullback }
/-- Given all finite wide pullbacks in `C`, construct finite products in `C/B`. -/
def over_finite_products_of_finite_wide_pullbacks [has_finite_wide_pullbacks C] {B : C} :
has_finite_products (over B) :=
{ has_limits_of_shape := λ J 𝒥₁ 𝒥₂, by exactI over_product_of_wide_pullback }
end construct_products
/--
Construct terminal object in the over category. This isn't an instance as it's not typically the
way we want to define terminal objects.
(For instance, this gives a terminal object which is different from the generic one given by
`over_product_of_wide_pullback` above.)
-/
def over_has_terminal (B : C) : has_terminal (over B) :=
{ has_limits_of_shape :=
{ has_limit := λ F,
{ cone :=
{ X := over.mk (𝟙 _),
π := { app := λ p, pempty.elim p } },
is_limit :=
{ lift := λ s, over.hom_mk _,
fac' := λ _ j, j.elim,
uniq' := λ s m _,
begin
ext,
rw over.hom_mk_left,
have := m.w,
dsimp at this,
rwa [category.comp_id, category.comp_id] at this
end } } } }
end category_theory.over
|
b29afc4bfd7eecd0a3d0e217f636db77fc943ae4 | 1d265c7dd8cb3d0e1d645a19fd6157a2084c3921 | /src/lessons/lesson10.lean | 28931ba0b8643d71780fe8e4303c21300faa49f3 | [
"MIT"
] | permissive | hanzhi713/lean-proofs | de432372f220d302be09b5ca4227f8986567e4fd | 4d8356a878645b9ba7cb036f87737f3f1e68ede5 | refs/heads/master | 1,585,580,245,658 | 1,553,646,623,000 | 1,553,646,623,000 | 151,342,188 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 914 | lean | def alwaysTrue : ℕ → Prop := λ n, n ≥ 0
def alwaysFalse : ℕ → Prop := λ n, n < 0
inductive day : Type
| Monday
| Tuesday
| Wednesday
| Thursday
| Friday
| Saturday
| Sunday
#check day.Tuesday
open day -- no longer need to day. prefix
#check Tuesday
-- Answer
def isWeekend : day → Prop :=
λ d, d = Saturday ∨ d = Sunday
theorem satIsWeekend : isWeekend Saturday :=
begin
unfold isWeekend,
apply or.inl,
apply rfl
end
theorem satIsWeekend' : isWeekend Saturday := or.inl (eq.refl Saturday)
def set01 : ℕ → Prop := λ n, n = 0 ∨ n = 1
def set215 : ℕ → Prop := λ n, 2 ≤ n ∧ n ≤ 15
def setpos : ℕ → Prop := λ n, n > 0
def haha : (ℕ × ℕ) → Prop := λ ⟨a, b⟩, a = b
def isSquare : ℕ → ℕ → Prop := λ a b, a ^2 = b
lemma true39 : isSquare 3 9 := eq.refl 9
def sHasLengthN : string → ℕ → Prop := λ s n, string.length s = n
|
50ee75e712536b48fc05ab9735cebc7789d7cb3d | 78269ad0b3c342b20786f60690708b6e328132b0 | /src/library_dev/data/num/lemmas.lean | 0923b3d2966ff7abaaa8856a09e57499298f2be2 | [] | no_license | dselsam/library_dev | e74f46010fee9c7b66eaa704654cad0fcd2eefca | 1b4e34e7fb067ea5211714d6d3ecef5132fc8218 | refs/heads/master | 1,610,372,841,675 | 1,497,014,421,000 | 1,497,014,421,000 | 86,526,137 | 0 | 0 | null | 1,490,752,133,000 | 1,490,752,132,000 | null | UTF-8 | Lean | false | false | 15,909 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Properties of the binary representation of integers.
-/
import .basic .bitwise
meta def unfold_coe : tactic unit :=
`[unfold coe lift_t has_lift_t.lift coe_t has_coe_t.coe coe_b has_coe.coe]
namespace pos_num
theorem one_to_nat : ((1 : pos_num) : ℕ) = 1 := rfl
theorem succ_to_nat : ∀ n, (succ n : ℕ) = n + 1
| 1 := rfl
| (bit0 p) := rfl
| (bit1 p) := (congr_arg _root_.bit0 (succ_to_nat p)).trans $
show ↑p + 1 + ↑p + 1 = ↑p + ↑p + 1 + 1, by simp
theorem add_one (n : pos_num) : n + 1 = succ n := by cases n; refl
theorem one_add (n : pos_num) : 1 + n = succ n := by cases n; refl
theorem add_to_nat : ∀ m n, ((m + n : pos_num) : ℕ) = m + n
| 1 b := by rw [one_add b, succ_to_nat, add_comm]; refl
| a 1 := by rw [add_one a, succ_to_nat]; refl
| (bit0 a) (bit0 b) := (congr_arg _root_.bit0 (add_to_nat a b)).trans $
show ((a + b) + (a + b) : ℕ) = (a + a) + (b + b), by simp
| (bit0 a) (bit1 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $
show ((a + b) + (a + b) + 1 : ℕ) = (a + a) + (b + b + 1), by simp
| (bit1 a) (bit0 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $
show ((a + b) + (a + b) + 1 : ℕ) = (a + a + 1) + (b + b), by simp
| (bit1 a) (bit1 b) :=
show (succ (a + b) + succ (a + b) : ℕ) = (a + a + 1) + (b + b + 1),
by rw [succ_to_nat, add_to_nat]; simp
theorem add_succ : ∀ (m n : pos_num), m + succ n = succ (m + n)
| 1 b := by simp [one_add]
| (bit0 a) 1 := congr_arg bit0 (add_one a)
| (bit1 a) 1 := congr_arg bit1 (add_one a)
| (bit0 a) (bit0 b) := rfl
| (bit0 a) (bit1 b) := congr_arg bit0 (add_succ a b)
| (bit1 a) (bit0 b) := rfl
| (bit1 a) (bit1 b) := congr_arg bit1 (add_succ a b)
theorem bit0_of_bit0 : Π n, _root_.bit0 n = bit0 n
| 1 := rfl
| (bit0 p) := congr_arg bit0 (bit0_of_bit0 p)
| (bit1 p) := show bit0 (succ (_root_.bit0 p)) = _, by rw bit0_of_bit0; refl
theorem bit1_of_bit1 (n : pos_num) : _root_.bit1 n = bit1 n :=
show _root_.bit0 n + 1 = bit1 n, by rw [add_one, bit0_of_bit0]; refl
theorem to_nat_pos : ∀ n : pos_num, (n : ℕ) > 0
| 1 := dec_trivial
| (bit0 p) := let h := to_nat_pos p in add_pos h h
| (bit1 p) := nat.succ_pos _
theorem pred'_to_nat : ∀ n, (option.cases_on (pred' n) ((n : ℕ) = 1) (λm, (m : ℕ) = nat.pred n) : Prop)
| 1 := rfl
| (pos_num.bit1 q) := rfl
| (pos_num.bit0 q) :=
suffices _ → ((option.cases_on (pred' q) 1 bit1 : pos_num) : ℕ) = nat.pred (bit0 q),
from this (pred'_to_nat q),
match pred' q with
| none, (IH : (q : ℕ) = 1) := show 1 = nat.pred (q + q), by rw IH; refl
| some p, (IH : ↑p = nat.pred q) :=
show _root_.bit1 ↑p = nat.pred (q + q), begin
rw [-nat.succ_pred_eq_of_pos (to_nat_pos q), IH],
generalize (nat.pred q) n, intro n,
simp [_root_.bit1, _root_.bit0]
end
end
theorem mul_to_nat (m) : ∀ n, ((m * n : pos_num) : ℕ) = m * n
| 1 := (mul_one _).symm
| (bit0 p) := show (↑(m * p) + ↑(m * p) : ℕ) = ↑m * (p + p), by rw [mul_to_nat, left_distrib]
| (bit1 p) := (add_to_nat (bit0 (m * p)) m).trans $
show (↑(m * p) + ↑(m * p) + ↑m : ℕ) = ↑m * (p + p) + m, by rw [mul_to_nat, left_distrib]
end pos_num
namespace num
open pos_num
theorem zero_to_nat : ((0 : num) : ℕ) = 0 := rfl
theorem one_to_nat : ((1 : num) : ℕ) = 1 := rfl
theorem add_to_nat : ∀ m n, ((m + n : num) : ℕ) = m + n
| 0 0 := rfl
| 0 (pos q) := (zero_add _).symm
| (pos p) 0 := rfl
| (pos p) (pos q) := pos_num.add_to_nat _ _
theorem add_zero (n : num) : n + 0 = n := by cases n; refl
theorem zero_add (n : num) : 0 + n = n := by cases n; refl
theorem add_succ : ∀ (m n : num), m + succ n = succ (m + n)
| 0 n := by simp [zero_add]
| (pos p) 0 := show pos (p + 1) = succ (pos p + 0), by rw [add_one, add_zero]; refl
| (pos p) (pos q) := congr_arg pos (pos_num.add_succ _ _)
theorem succ'_to_nat : ∀ n, (succ' n : ℕ) = n + 1
| 0 := rfl
| (pos p) := pos_num.succ_to_nat _
theorem succ_to_nat (n) : (succ n : ℕ) = n + 1 := succ'_to_nat n
@[simp] theorem to_of_nat : Π (n : ℕ), ((n : num) : ℕ) = n
| 0 := rfl
| (n+1) := (succ_to_nat (num.of_nat n)).trans (congr_arg nat.succ (to_of_nat n))
theorem of_nat_inj : ∀ {m n : ℕ}, (m : num) = n → m = n :=
function.injective_of_left_inverse to_of_nat
theorem add_of_nat (m) : ∀ n, ((m + n : ℕ) : num) = m + n
| 0 := (add_zero _).symm
| (n+1) := show succ (m + n : ℕ) = m + succ n,
by rw [add_succ, add_of_nat]
theorem mul_to_nat : ∀ m n, ((m * n : num) : ℕ) = m * n
| 0 0 := rfl
| 0 (pos q) := (zero_mul _).symm
| (pos p) 0 := rfl
| (pos p) (pos q) := pos_num.mul_to_nat _ _
end num
namespace pos_num
open num
@[simp] theorem of_to_nat : Π (n : pos_num), ((n : ℕ) : num) = pos n
| 1 := rfl
| (bit0 p) :=
show ↑(p + p : ℕ) = pos (bit0 p),
by rw [add_of_nat, of_to_nat]; exact congr_arg pos p.bit0_of_bit0
| (bit1 p) :=
show num.succ (p + p : ℕ) = pos (bit1 p),
by rw [add_of_nat, of_to_nat]; exact congr_arg (num.pos ∘ succ) p.bit0_of_bit0
theorem to_nat_inj {m n : pos_num} (h : (m : ℕ) = n) : m = n :=
by note := congr_arg (coe : ℕ → num) h; simp at this; injection this
theorem pred_to_nat {n : pos_num} (h : n > 1) : (pred n : ℕ) = nat.pred n :=
begin
unfold pred,
note := pred'_to_nat n, revert this,
cases pred' n; dsimp [option.get_or_else],
{ intro this, rw @to_nat_inj n 1 this at h,
exact absurd h dec_trivial },
{ exact id }
end
theorem cmp_swap (m) : ∀n, (cmp m n).swap = cmp n m :=
by induction m with m IH m IH; intro n;
cases n with n n; unfold cmp; try {refl}; rw -IH; cases cmp m n; refl
lemma cmp_dec_lemma {m n} : m < n → bit1 m < bit0 n :=
show (m:ℕ) < n → (m + m + 1 + 1 : ℕ) ≤ n + n,
by intro h; rw [nat.add_right_comm m m 1, add_assoc]; exact add_le_add h h
theorem cmp_dec : ∀ (m n), (ordering.cases_on (cmp m n) (m < n) (m = n) (m > n) : Prop)
| 1 1 := rfl
| (bit0 a) 1 := let h : (1:ℕ) ≤ a := to_nat_pos a in add_le_add h h
| (bit1 a) 1 := nat.succ_lt_succ $ to_nat_pos $ bit0 a
| 1 (bit0 b) := let h : (1:ℕ) ≤ b := to_nat_pos b in add_le_add h h
| 1 (bit1 b) := nat.succ_lt_succ $ to_nat_pos $ bit0 b
| (bit0 a) (bit0 b) := begin
note := cmp_dec a b, revert this, cases cmp a b; dsimp; intro,
{ exact @add_lt_add nat _ _ _ _ _ this this },
{ rw this },
{ exact @add_lt_add nat _ _ _ _ _ this this }
end
| (bit0 a) (bit1 b) := begin dsimp [cmp],
note := cmp_dec a b, revert this, cases cmp a b; dsimp; intro,
{ exact nat.le_succ_of_le (@add_lt_add nat _ _ _ _ _ this this) },
{ rw this, apply nat.lt_succ_self },
{ exact cmp_dec_lemma this }
end
| (bit1 a) (bit0 b) := begin dsimp [cmp],
note := cmp_dec a b, revert this, cases cmp a b; dsimp; intro,
{ exact cmp_dec_lemma this },
{ rw this, apply nat.lt_succ_self },
{ exact nat.le_succ_of_le (@add_lt_add nat _ _ _ _ _ this this) },
end
| (bit1 a) (bit1 b) := begin
note := cmp_dec a b, revert this, cases cmp a b; dsimp; intro,
{ exact nat.succ_lt_succ (add_lt_add this this) },
{ rw this },
{ exact nat.succ_lt_succ (add_lt_add this this) }
end
theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt :=
match cmp m n, cmp_dec m n with
| ordering.lt, (h : m < n) := ⟨λ_, rfl, λ_, h⟩
| ordering.eq, (h : m = n) :=
⟨λh', absurd h' $ by rw h; apply @lt_irrefl nat, dec_trivial⟩
| ordering.gt, (h : m > n) :=
⟨λh', absurd h' $ @not_lt_of_gt nat _ _ _ h, dec_trivial⟩
end
theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt :=
iff.trans ⟨@not_lt_of_ge nat _ _ _, le_of_not_gt⟩ $ not_congr $
lt_iff_cmp.trans $ by rw -cmp_swap; cases cmp m n; exact dec_trivial
instance decidable_lt : @decidable_rel pos_num (<) := λ m n,
decidable_of_decidable_of_iff (by apply_instance) lt_iff_cmp.symm
instance decidable_le : @decidable_rel pos_num (≤) := λ m n,
decidable_of_decidable_of_iff (by apply_instance) le_iff_cmp.symm
meta def transfer_rw : tactic unit :=
`[repeat {rw add_to_nat <|> rw mul_to_nat <|> rw one_to_nat <|> rw zero_to_nat}]
meta def transfer : tactic unit := `[intros, apply to_nat_inj, transfer_rw, try {simp}]
instance : add_comm_semigroup pos_num :=
{ add := (+),
add_assoc := by transfer,
add_comm := by transfer }
instance : comm_monoid pos_num :=
{ mul := (*),
mul_assoc := by transfer,
one := 1,
one_mul := by transfer,
mul_one := by transfer,
mul_comm := by transfer }
instance : distrib pos_num :=
{ add := (+),
mul := (*),
left_distrib := by {transfer, simp [left_distrib]},
right_distrib := by {transfer, simp [left_distrib]} }
-- TODO(Mario): Prove these using transfer tactic
instance : decidable_linear_order pos_num :=
{ lt := (<),
le := (≤),
le_refl := λa, @le_refl nat _ _,
le_trans := λa b c, @le_trans nat _ _ _ _,
le_antisymm := λa b h1 h2, to_nat_inj $ @le_antisymm nat _ _ _ h1 h2,
le_total := λa b, @le_total nat _ _ _,
le_iff_lt_or_eq := λa b, le_iff_lt_or_eq.trans $ or_congr iff.rfl ⟨to_nat_inj, congr_arg _⟩,
lt_irrefl := λ a, @lt_irrefl nat _ _,
decidable_lt := by apply_instance,
decidable_le := by apply_instance,
decidable_eq := by apply_instance }
end pos_num
namespace num
open pos_num
@[simp] theorem of_to_nat : Π (n : num), ((n : ℕ) : num) = n
| 0 := rfl
| (pos p) := p.of_to_nat
theorem to_nat_inj : ∀ {m n : num}, (m : ℕ) = n → m = n :=
function.injective_of_left_inverse of_to_nat
theorem pred_to_nat : ∀ (n : num), (pred n : ℕ) = nat.pred n
| 0 := rfl
| (pos p) :=
suffices _ → ↑(option.cases_on (pred' p) 0 pos : num) = nat.pred p,
from this (pred'_to_nat p),
by { cases pred' p; dsimp [option.get_or_else]; intro h, rw h; refl, exact h }
theorem cmp_swap (m n) : (cmp m n).swap = cmp n m :=
by cases m; cases n; unfold cmp; try {refl}; apply pos_num.cmp_swap
theorem cmp_dec : ∀ (m n), (ordering.cases_on (cmp m n) (m < n) (m = n) (m > n) : Prop)
| 0 0 := rfl
| 0 (pos b) := to_nat_pos _
| (pos a) 0 := to_nat_pos _
| (pos a) (pos b) :=
by { note := pos_num.cmp_dec a b; revert this; dsimp [cmp];
cases pos_num.cmp a b, exacts [id, congr_arg pos, id] }
theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt :=
match cmp m n, cmp_dec m n with
| ordering.lt, (h : m < n) := ⟨λ_, rfl, λ_, h⟩
| ordering.eq, (h : m = n) :=
⟨λh', absurd h' $ by rw h; apply @lt_irrefl nat, dec_trivial⟩
| ordering.gt, (h : m > n) :=
⟨λh', absurd h' $ @not_lt_of_gt nat _ _ _ h, dec_trivial⟩
end
theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt :=
iff.trans ⟨@not_lt_of_ge nat _ _ _, le_of_not_gt⟩ $ not_congr $
lt_iff_cmp.trans $ by rw -cmp_swap; cases cmp m n; exact dec_trivial
instance decidable_lt : @decidable_rel num (<) := λ m n,
decidable_of_decidable_of_iff (by apply_instance) lt_iff_cmp.symm
instance decidable_le : @decidable_rel num (≤) := λ m n,
decidable_of_decidable_of_iff (by apply_instance) le_iff_cmp.symm
meta def transfer_rw : tactic unit :=
`[repeat {rw add_to_nat <|> rw mul_to_nat <|> rw one_to_nat <|> rw zero_to_nat}]
meta def transfer : tactic unit := `[intros, apply to_nat_inj, transfer_rw, try {simp}]
instance : comm_semiring num :=
{ add := (+),
add_assoc := by transfer,
zero := 0,
zero_add := zero_add,
add_zero := add_zero,
add_comm := by transfer,
mul := (*),
mul_assoc := by transfer,
one := 1,
one_mul := by transfer,
mul_one := by transfer,
left_distrib := by {transfer, simp [left_distrib]},
right_distrib := by {transfer, simp [left_distrib]},
zero_mul := by transfer,
mul_zero := by transfer,
mul_comm := by transfer }
instance : decidable_linear_ordered_semiring num :=
{ num.comm_semiring with
add_left_cancel := λ a b c h, by { apply to_nat_inj,
note := congr_arg (coe : num → nat) h, revert this,
transfer_rw, apply add_left_cancel },
add_right_cancel := λ a b c h, by { apply to_nat_inj,
note := congr_arg (coe : num → nat) h, revert this,
transfer_rw, apply add_right_cancel },
lt := (<),
le := (≤),
le_refl := λa, @le_refl nat _ _,
le_trans := λa b c, @le_trans nat _ _ _ _,
le_antisymm := λa b h1 h2, to_nat_inj $ @le_antisymm nat _ _ _ h1 h2,
le_total := λa b, @le_total nat _ _ _,
le_iff_lt_or_eq := λa b, le_iff_lt_or_eq.trans $ or_congr iff.rfl ⟨to_nat_inj, congr_arg _⟩,
le_of_lt := λa b, @le_of_lt nat _ _ _,
lt_irrefl := λa, @lt_irrefl nat _ _,
lt_of_lt_of_le := λa b c, @lt_of_lt_of_le nat _ _ _ _,
lt_of_le_of_lt := λa b c, @lt_of_le_of_lt nat _ _ _ _,
lt_of_add_lt_add_left := λa b c, show (_:ℕ)<_→(_:ℕ)<_, by {transfer_rw, apply lt_of_add_lt_add_left},
add_lt_add_left := λa b h c, show (_:ℕ)<_, by {transfer_rw, apply @add_lt_add_left nat _ _ _ h},
add_le_add_left := λa b h c, show (_:ℕ)≤_, by {transfer_rw, apply @add_le_add_left nat _ _ _ h},
le_of_add_le_add_left := λa b c, show (_:ℕ)≤_→(_:ℕ)≤_, by {transfer_rw, apply le_of_add_le_add_left},
zero_lt_one := dec_trivial,
mul_le_mul_of_nonneg_left := λa b c h _, show (_:ℕ)≤_, by {transfer_rw, apply nat.mul_le_mul_left _ h},
mul_le_mul_of_nonneg_right := λa b c h _, show (_:ℕ)≤_, by {transfer_rw, apply nat.mul_le_mul_right _ h},
mul_lt_mul_of_pos_left := λa b c h₁ h₂, show (_:ℕ)<_, by {transfer_rw, apply nat.mul_lt_mul_of_pos_left h₁ h₂},
mul_lt_mul_of_pos_right := λa b c h₁ h₂, show (_:ℕ)<_, by {transfer_rw, apply nat.mul_lt_mul_of_pos_right h₁ h₂},
decidable_lt := num.decidable_lt,
decidable_le := num.decidable_le,
decidable_eq := num.decidable_eq }
lemma bitwise_to_nat_lemma {f : num → num → num} (m n) :
(f m n : ℕ) = (f ((m : ℕ) : num) ((n : ℕ) : num) : ℕ) := by simp
/- TODO(Jeremy): I commented these out to get library_dev to compile. Mario, should we delete
them?
@[simp] lemma lor_to_nat : ∀ m n, (lor m n : ℕ) = nat.lor m n := bitwise_to_nat_lemma
@[simp] lemma land_to_nat : ∀ m n, (land m n : ℕ) = nat.land m n := bitwise_to_nat_lemma
@[simp] lemma ldiff_to_nat : ∀ m n, (ldiff m n : ℕ) = nat.ldiff m n := bitwise_to_nat_lemma
@[simp] lemma lxor_to_nat : ∀ m n, (lxor m n : ℕ) = nat.lxor m n := bitwise_to_nat_lemma
@[simp] lemma shiftl_to_nat (m n) : (shiftl m n : ℕ) = nat.shiftl m n := by unfold nat.shiftl; simp
@[simp] lemma shiftr_to_nat (m n) : (shiftr m n : ℕ) = nat.shiftr m n := by unfold nat.shiftr; simp
-/
end num
|
11d23abf0bfb43a5c2ec2cbfaa251cea1299dfc2 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/data/fintype/basic.lean | d6caad2bc956d568940ecf0aba459d3cd8d5c9e9 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 46,146 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Finite types.
-/
import tactic.wlog
import data.finset.powerset
import data.finset.lattice
import data.finset.pi
import data.array.lemmas
universes u v
variables {α : Type*} {β : Type*} {γ : Type*}
/-- `fintype α` means that `α` is finite, i.e. there are only
finitely many distinct elements of type `α`. The evidence of this
is a finset `elems` (a list up to permutation without duplicates),
together with a proof that everything of type `α` is in the list. -/
class fintype (α : Type*) :=
(elems [] : finset α)
(complete : ∀ x : α, x ∈ elems)
namespace finset
variable [fintype α]
/-- `univ` is the universal finite set of type `finset α` implied from
the assumption `fintype α`. -/
def univ : finset α := fintype.elems α
@[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) :=
fintype.complete x
@[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ
@[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) :=
by ext; simp
theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a
instance : order_top (finset α) :=
{ top := univ,
le_top := subset_univ,
.. finset.partial_order }
instance [decidable_eq α] : boolean_algebra (finset α) :=
{ compl := λ s, univ \ s,
sdiff_eq := λ s t, by simp [ext_iff],
inf_compl_le_bot := λ s x hx, by simpa using hx,
top_le_sup_compl := λ s x hx, by simp,
..finset.distrib_lattice,
..finset.semilattice_inf_bot,
..finset.order_top,
..finset.has_sdiff }
lemma compl_eq_univ_sdiff [decidable_eq α] (s : finset α) : sᶜ = univ \ s := rfl
theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s :=
by simp [ext_iff]
@[simp] lemma univ_inter [decidable_eq α] (s : finset α) :
univ ∩ s = s := ext $ λ a, by simp
@[simp] lemma inter_univ [decidable_eq α] (s : finset α) :
s ∩ univ = s :=
by rw [inter_comm, univ_inter]
@[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (univ : finset α))]
{δ : α → Sort*} (f g : Πi, δ i) : univ.piecewise f g = f :=
by { ext i, simp [piecewise] }
lemma univ_map_equiv_to_embedding {α β : Type*} [fintype α] [fintype β] (e : α ≃ β) :
univ.map e.to_embedding = univ :=
begin
apply eq_univ_iff_forall.mpr,
intro b,
rw [mem_map],
use e.symm b,
simp,
end
end finset
open finset function
namespace fintype
instance decidable_pi_fintype {α} {β : α → Type*} [∀a, decidable_eq (β a)] [fintype α] :
decidable_eq (Πa, β a) :=
assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a)
(by simp [function.funext_iff, fintype.complete])
instance decidable_forall_fintype {p : α → Prop} [decidable_pred p] [fintype α] :
decidable (∀ a, p a) :=
decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp)
instance decidable_exists_fintype {p : α → Prop} [decidable_pred p] [fintype α] :
decidable (∃ a, p a) :=
decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp)
instance decidable_eq_equiv_fintype [decidable_eq β] [fintype α] :
decidable_eq (α ≃ β) :=
λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext (congr_fun h), congr_arg _⟩
instance decidable_injective_fintype [decidable_eq α] [decidable_eq β] [fintype α] :
decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance
instance decidable_surjective_fintype [decidable_eq β] [fintype α] [fintype β] :
decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance
instance decidable_bijective_fintype [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] :
decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance
instance decidable_left_inverse_fintype [decidable_eq α] [fintype α] (f : α → β) (g : β → α) :
decidable (function.right_inverse f g) :=
show decidable (∀ x, g (f x) = x), by apply_instance
instance decidable_right_inverse_fintype [decidable_eq β] [fintype β] (f : α → β) (g : β → α) :
decidable (function.left_inverse f g) :=
show decidable (∀ x, f (g x) = x), by apply_instance
/-- Construct a proof of `fintype α` from a universal multiset -/
def of_multiset [decidable_eq α] (s : multiset α)
(H : ∀ x : α, x ∈ s) : fintype α :=
⟨s.to_finset, by simpa using H⟩
/-- Construct a proof of `fintype α` from a universal list -/
def of_list [decidable_eq α] (l : list α)
(H : ∀ x : α, x ∈ l) : fintype α :=
⟨l.to_finset, by simpa using H⟩
theorem exists_univ_list (α) [fintype α] :
∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l :=
let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in
by have := and.intro univ.2 mem_univ_val;
exact ⟨_, by rwa ← e at this⟩
/-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/
def card (α) [fintype α] : ℕ := (@univ α _).card
/-- If `l` lists all the elements of `α` without duplicates, then `α ≃ fin (l.length)`. -/
def equiv_fin_of_forall_mem_list {α} [decidable_eq α]
{l : list α} (h : ∀ x:α, x ∈ l) (nd : l.nodup) : α ≃ fin (l.length) :=
⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩,
λ i, l.nth_le i.1 i.2,
λ a, by simp,
λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _
(list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩
/-- There is (computably) a bijection between `α` and `fin n` where
`n = card α`. Since it is not unique, and depends on which permutation
of the universe list is used, the bijection is wrapped in `trunc` to
preserve computability. -/
def equiv_fin (α) [decidable_eq α] [fintype α] : trunc (α ≃ fin (card α)) :=
by unfold card finset.card; exact
quot.rec_on_subsingleton (@univ α _).1
(λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk (equiv_fin_of_forall_mem_list h nd))
mem_univ_val univ.2
theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) :=
by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩
instance (α : Type*) : subsingleton (fintype α) :=
⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext_iff, h₁, h₂]⟩
protected def subtype {p : α → Prop} (s : finset α)
(H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} :=
⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1),
multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩,
λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩
theorem subtype_card {p : α → Prop} (s : finset α)
(H : ∀ x : α, x ∈ s ↔ p x) :
@card {x // p x} (fintype.subtype s H) = s.card :=
multiset.card_pmap _ _ _
theorem card_of_subtype {p : α → Prop} (s : finset α)
(H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] :
card {x // p x} = s.card :=
by rw ← subtype_card s H; congr
/-- Construct a fintype from a finset with the same elements. -/
def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p :=
fintype.subtype s H
@[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) :
@fintype.card p (of_finset s H) = s.card :=
fintype.subtype_card s H
theorem card_of_finset' {p : set α} (s : finset α)
(H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card :=
by rw ← card_of_finset s H; congr
/-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/
def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β :=
⟨univ.map ⟨f, H.1⟩,
λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩
/-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/
def of_surjective [decidable_eq β] [fintype α] (f : α → β) (H : function.surjective f) : fintype β :=
⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩
noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α :=
by letI := classical.dec; exact
if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα;
exact of_surjective (inv_fun f) (inv_fun_surjective H)
else ⟨∅, λ x, (hα ⟨x⟩).elim⟩
/-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/
def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective
theorem of_equiv_card [fintype α] (f : α ≃ β) :
@card β (of_equiv α f) = card α :=
multiset.card_map _ _
theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β :=
by rw ← of_equiv_card f; congr
theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) :=
⟨λ h, ⟨by classical;
calc α ≃ fin (card α) : trunc.out (equiv_fin α)
... ≃ fin (card β) : by rw h
... ≃ β : (trunc.out (equiv_fin β)).symm⟩,
λ ⟨f⟩, card_congr f⟩
def of_subsingleton (a : α) [subsingleton α] : fintype α :=
⟨{a}, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩
@[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] :
@univ _ (of_subsingleton a) = {a} := rfl
@[simp] theorem card_of_subsingleton (a : α) [subsingleton α] :
@fintype.card _ (of_subsingleton a) = 1 := rfl
end fintype
namespace set
/-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/
def to_finset (s : set α) [fintype s] : finset α :=
⟨(@finset.univ s _).1.map subtype.val,
multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩
@[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s :=
by simp [to_finset]
@[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s :=
mem_to_finset
-- We use an arbitrary `[fintype s]` instance here,
-- not necessarily coming from a `[fintype α]`.
@[simp]
lemma to_finset_card {α : Type*} (s : set α) [fintype s] :
s.to_finset.card = fintype.card s :=
multiset.card_map subtype.val finset.univ.val
@[simp] theorem coe_to_finset (s : set α) [fintype s] : (↑s.to_finset : set α) = s :=
set.ext $ λ _, mem_to_finset
@[simp] theorem to_finset_inj {s t : set α} [fintype s] [fintype t] : s.to_finset = t.to_finset ↔ s = t :=
⟨λ h, by rw [← s.coe_to_finset, h, t.coe_to_finset], λ h, by simp [h]; congr⟩
end set
lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α :=
rfl
lemma finset.eq_univ_of_card [fintype α] (s : finset α) (hs : s.card = fintype.card α) :
s = univ :=
eq_of_subset_of_card_le (subset_univ _) $ by rw [hs, finset.card_univ]
lemma finset.card_le_univ [fintype α] (s : finset α) :
s.card ≤ fintype.card α :=
card_le_of_subset (subset_univ s)
lemma finset.card_univ_diff [decidable_eq α] [fintype α] (s : finset α) :
(finset.univ \ s).card = fintype.card α - s.card :=
finset.card_sdiff (subset_univ s)
lemma finset.card_compl [decidable_eq α] [fintype α] (s : finset α) :
sᶜ.card = fintype.card α - s.card :=
finset.card_univ_diff s
instance (n : ℕ) : fintype (fin n) :=
⟨finset.fin_range n, finset.mem_fin_range⟩
@[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n :=
list.length_fin_range n
@[simp] lemma finset.card_fin (n : ℕ) : finset.card (finset.univ : finset (fin n)) = n :=
by rw [finset.card_univ, fintype.card_fin]
/-- Embed `fin n` into `fin (n + 1)` by prepending zero to the `univ` -/
lemma fin.univ_succ (n : ℕ) :
(univ : finset (fin (n + 1))) = insert 0 (univ.image fin.succ) :=
begin
ext m,
simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop],
exact fin.cases (or.inl rfl) (λ i, or.inr ⟨i, trivial, rfl⟩) m
end
/-- Embed `fin n` into `fin (n + 1)` by appending a new `fin.last n` to the `univ` -/
lemma fin.univ_cast_succ (n : ℕ) :
(univ : finset (fin (n + 1))) = insert (fin.last n) (univ.image fin.cast_succ) :=
begin
ext m,
simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop, true_and],
by_cases h : m.val < n,
{ right,
use fin.cast_lt m h,
rw fin.cast_succ_cast_lt },
{ left,
exact fin.eq_last_of_not_lt h }
end
/-- Embed `fin n` into `fin (n + 1)` by inserting
around a specified pivot `p : fin (n + 1)` into the `univ` -/
lemma fin.univ_succ_above (n : ℕ) (p : fin (n + 1)) :
(univ : finset (fin (n + 1))) = insert p (univ.image (fin.succ_above p)) :=
begin
rcases lt_or_eq_of_le (fin.le_last p) with hl|rfl,
{ ext m,
simp only [finset.mem_univ, finset.mem_insert, true_iff, finset.mem_image, exists_prop],
refine or_iff_not_imp_left.mpr _,
{ intro h,
use p.pred_above m h,
simp only [eq_self_iff_true, fin.succ_above_descend, and_self] } },
{ rw fin.succ_above_last,
exact fin.univ_cast_succ n }
end
@[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α :=
fintype.of_subsingleton (default α)
@[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} :=
by rw [subsingleton.elim f (@unique.fintype α _)]; refl
instance : fintype empty := ⟨∅, empty.rec _⟩
@[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl
@[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl
instance : fintype pempty := ⟨∅, pempty.rec _⟩
@[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl
@[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl
instance : fintype unit := fintype.of_subsingleton ()
theorem fintype.univ_unit : @univ unit _ = {()} := rfl
theorem fintype.card_unit : fintype.card unit = 1 := rfl
instance : fintype punit := fintype.of_subsingleton punit.star
@[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl
@[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl
instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩
@[simp] theorem fintype.univ_bool : @univ bool _ = {tt, ff} := rfl
instance units_int.fintype : fintype (units ℤ) :=
⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩
instance additive.fintype : Π [fintype α], fintype (additive α) := id
instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id
@[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl
noncomputable instance [monoid α] [fintype α] : fintype (units α) :=
by classical; exact fintype.of_injective units.val units.ext
@[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl
def finset.insert_none (s : finset α) : finset (option α) :=
⟨none :: s.1.map some, multiset.nodup_cons.2
⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩
@[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α},
o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s
| none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h)
| (some a) := multiset.mem_cons.trans $ by simp; refl
theorem finset.some_mem_insert_none {s : finset α} {a : α} :
some a ∈ s.insert_none ↔ a ∈ s := by simp
instance {α : Type*} [fintype α] : fintype (option α) :=
⟨univ.insert_none, λ a, by simp⟩
@[simp] theorem fintype.card_option {α : Type*} [fintype α] :
fintype.card (option α) = fintype.card α + 1 :=
(multiset.card_cons _ _).trans (by rw multiset.card_map; refl)
instance {α : Type*} (β : α → Type*)
[fintype α] [∀ a, fintype (β a)] : fintype (sigma β) :=
⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩
@[simp] lemma finset.univ_sigma_univ {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] :
(univ : finset α).sigma (λ a, (univ : finset (β a))) = univ := rfl
instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) :=
⟨univ.product univ, λ ⟨a, b⟩, by simp⟩
@[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] :
fintype.card (α × β) = fintype.card α * fintype.card β :=
card_product _ _
def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α :=
⟨(fintype.elems (α × β)).image prod.fst,
assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩
def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β :=
⟨(fintype.elems (α × β)).image prod.snd,
assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩
instance (α : Type*) [fintype α] : fintype (ulift α) :=
fintype.of_equiv _ equiv.ulift.symm
@[simp] theorem fintype.card_ulift (α : Type*) [fintype α] :
fintype.card (ulift α) = fintype.card α :=
fintype.of_equiv_card _
instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) :=
@fintype.of_equiv _ _ (@sigma.fintype _
(λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _
(λ b, by cases b; apply ulift.fintype))
((equiv.sum_equiv_sigma_bool _ _).symm.trans
(equiv.sum_congr equiv.ulift equiv.ulift))
namespace fintype
variables [fintype α] [fintype β]
lemma card_le_of_injective (f : α → β) (hf : function.injective f) : card α ≤ card β :=
finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h)
lemma card_eq_one_iff : card α = 1 ↔ (∃ x : α, ∀ y, y = x) :=
by rw [← card_unit, card_eq]; exact
⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩,
λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm,
λ _, subsingleton.elim _ _⟩⟩⟩
lemma card_eq_zero_iff : card α = 0 ↔ (α → false) :=
⟨λ h a, have e : α ≃ empty := classical.choice (card_eq.1 (by simp [h])), (e a).elim,
λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩,
by simp [card_congr e]⟩
/-- A `fintype` with cardinality zero is (constructively) equivalent to `pempty`. -/
def card_eq_zero_equiv_equiv_pempty :
card α = 0 ≃ (α ≃ pempty.{v+1}) :=
{ to_fun := λ h,
{ to_fun := λ a, false.elim (card_eq_zero_iff.1 h a),
inv_fun := λ a, pempty.elim a,
left_inv := λ a, false.elim (card_eq_zero_iff.1 h a),
right_inv := λ a, pempty.elim a, },
inv_fun := λ e,
by { simp only [←of_equiv_card e], convert card_pempty, },
left_inv := λ h, rfl,
right_inv := λ e, by { ext x, cases e x, } }
lemma card_pos_iff : 0 < card α ↔ nonempty α :=
⟨λ h, classical.by_contradiction (λ h₁,
have card α = 0 := card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩),
lt_irrefl 0 $ by rwa this at h),
λ ⟨a⟩, nat.pos_of_ne_zero (mt card_eq_zero_iff.1 (λ h, h a))⟩
lemma card_le_one_iff : card α ≤ 1 ↔ (∀ a b : α, a = b) :=
let n := card α in
have hn : n = card α := rfl,
match n, hn with
| 0 := λ ha, ⟨λ h, λ a, (card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩
| 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := card_eq_one_iff.1 ha.symm in
by rw [hx a, hx b],
λ _, ha ▸ le_refl _⟩
| (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial,
(λ h, card_unit ▸ card_le_of_injective (λ _, ())
(λ _ _ _, h _ _))⟩
end
lemma card_le_one_iff_subsingleton : card α ≤ 1 ↔ subsingleton α :=
iff.trans card_le_one_iff subsingleton_iff.symm
lemma one_lt_card_iff_nontrivial : 1 < card α ↔ nontrivial α :=
begin
classical,
rw ← not_iff_not,
push_neg,
rw [not_nontrivial_iff_subsingleton, card_le_one_iff_subsingleton]
end
lemma exists_ne_of_one_lt_card (h : 1 < card α) (a : α) : ∃ b : α, b ≠ a :=
by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_ne a }
lemma exists_pair_of_one_lt_card (h : 1 < card α) : ∃ (a b : α), a ≠ b :=
by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_pair_ne α }
lemma injective_iff_surjective {f : α → α} : injective f ↔ surjective f :=
by haveI := classical.prop_decidable; exact
have ∀ {f : α → α}, injective f → surjective f,
from λ f hinj x,
have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _)
((card_image_of_injective univ hinj).symm ▸ le_refl _),
have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _,
exists_of_bex (mem_image.1 h₂),
⟨this,
λ hsurj, has_left_inverse.injective
⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse
(this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩
lemma injective_iff_bijective {f : α → α} : injective f ↔ bijective f :=
by simp [bijective, injective_iff_surjective]
lemma surjective_iff_bijective {f : α → α} : surjective f ↔ bijective f :=
by simp [bijective, injective_iff_surjective]
lemma injective_iff_surjective_of_equiv {β : Type*} {f : α → β} (e : α ≃ β) :
injective f ↔ surjective f :=
have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from injective_iff_surjective,
⟨λ hinj, by simpa [function.comp] using
e.surjective.comp (this.1 (e.symm.injective.comp hinj)),
λ hsurj, by simpa [function.comp] using
e.injective.comp (this.2 (e.symm.surjective.comp hsurj))⟩
lemma nonempty_equiv_of_card_eq (h : card α = card β) :
nonempty (α ≃ β) :=
begin
obtain ⟨m, ⟨f⟩⟩ := exists_equiv_fin α,
obtain ⟨n, ⟨g⟩⟩ := exists_equiv_fin β,
suffices : m = n,
{ subst this, exact ⟨f.trans g.symm⟩ },
calc m = card (fin m) : (card_fin m).symm
... = card α : card_congr f.symm
... = card β : h
... = card (fin n) : card_congr g
... = n : card_fin n
end
lemma bijective_iff_injective_and_card (f : α → β) :
bijective f ↔ injective f ∧ card α = card β :=
begin
split,
{ intro h, exact ⟨h.1, card_congr (equiv.of_bijective f h)⟩ },
{ rintro ⟨hf, h⟩,
refine ⟨hf, _⟩,
obtain ⟨e⟩ : nonempty (α ≃ β) := nonempty_equiv_of_card_eq h,
rwa ← injective_iff_surjective_of_equiv e }
end
lemma bijective_iff_surjective_and_card (f : α → β) :
bijective f ↔ surjective f ∧ card α = card β :=
begin
split,
{ intro h, exact ⟨h.2, card_congr (equiv.of_bijective f h)⟩, },
{ rintro ⟨hf, h⟩,
refine ⟨_, hf⟩,
obtain ⟨e⟩ : nonempty (α ≃ β) := nonempty_equiv_of_card_eq h,
rwa injective_iff_surjective_of_equiv e }
end
end fintype
lemma fintype.coe_image_univ [fintype α] [decidable_eq β] {f : α → β} :
↑(finset.image f finset.univ) = set.range f :=
by { ext x, simp }
instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} :=
fintype.of_list l.attach l.mem_attach
instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} :=
fintype.of_multiset s.attach s.mem_attach
instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} :=
⟨s.attach, s.mem_attach⟩
instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) :=
finset.subtype.fintype s
@[simp] lemma fintype.card_coe (s : finset α) :
fintype.card (↑s : set α) = s.card := card_attach
lemma finset.attach_eq_univ {s : finset α} : s.attach = finset.univ := rfl
lemma finset.card_le_one_iff {s : finset α} :
s.card ≤ 1 ↔ ∀ {x y}, x ∈ s → y ∈ s → x = y :=
begin
let t : set α := ↑s,
letI : fintype t := finset_coe.fintype s,
have : fintype.card t = s.card := fintype.card_coe s,
rw [← this, fintype.card_le_one_iff],
split,
{ assume H x y hx hy,
exact subtype.mk.inj (H ⟨x, hx⟩ ⟨y, hy⟩) },
{ assume H x y,
exact subtype.eq (H x.2 y.2) }
end
/-- A `finset` of a subsingleton type has cardinality at most one. -/
lemma finset.card_le_one_of_subsingleton [subsingleton α] (s : finset α) : s.card ≤ 1 :=
finset.card_le_one_iff.2 $ λ _ _ _ _, subsingleton.elim _ _
lemma finset.one_lt_card_iff {s : finset α} :
1 < s.card ↔ ∃ x y, (x ∈ s) ∧ (y ∈ s) ∧ x ≠ y :=
begin
classical,
rw ← not_iff_not,
push_neg,
simpa [or_iff_not_imp_left] using finset.card_le_one_iff
end
instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) :=
⟨if h : p then {⟨h⟩} else ∅, λ ⟨h⟩, by simp [h]⟩
instance Prop.fintype : fintype Prop :=
⟨⟨true::false::0, by simp [true_ne_false]⟩,
classical.cases (by simp) (by simp)⟩
instance subtype.fintype (p : α → Prop) [decidable_pred p] [fintype α] : fintype {x // p x} :=
fintype.subtype (univ.filter p) (by simp)
def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s :=
subtype.fintype (λ x, x ∈ s)
namespace function.embedding
/-- An embedding from a `fintype` to itself can be promoted to an equivalence. -/
noncomputable def equiv_of_fintype_self_embedding {α : Type*} [fintype α] (e : α ↪ α) : α ≃ α :=
equiv.of_bijective e (fintype.injective_iff_bijective.1 e.2)
@[simp]
lemma equiv_of_fintype_self_embedding_to_embedding {α : Type*} [fintype α] (e : α ↪ α) :
e.equiv_of_fintype_self_embedding.to_embedding = e :=
by { ext, refl, }
end function.embedding
@[simp]
lemma finset.univ_map_embedding {α : Type*} [fintype α] (e : α ↪ α) :
univ.map e = univ :=
by rw [← e.equiv_of_fintype_self_embedding_to_embedding, univ_map_equiv_to_embedding]
namespace fintype
variables [decidable_eq α] [fintype α] {δ : α → Type*}
/-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the
finset `fintype.pi_finset t` of all functions taking values in `t a` for all `a`. This is the
analogue of `finset.pi` where the base finset is `univ` (but formally they are not the same, as
there is an additional condition `i ∈ finset.univ` in the `finset.pi` definition). -/
def pi_finset (t : Πa, finset (δ a)) : finset (Πa, δ a) :=
(finset.univ.pi t).map ⟨λ f a, f a (mem_univ a), λ _ _, by simp [function.funext_iff]⟩
@[simp] lemma mem_pi_finset {t : Πa, finset (δ a)} {f : Πa, δ a} :
f ∈ pi_finset t ↔ (∀a, f a ∈ t a) :=
begin
split,
{ simp only [pi_finset, mem_map, and_imp, forall_prop_of_true, exists_prop, mem_univ,
exists_imp_distrib, mem_pi],
assume g hg hgf a,
rw ← hgf,
exact hg a },
{ simp only [pi_finset, mem_map, forall_prop_of_true, exists_prop, mem_univ, mem_pi],
assume hf,
exact ⟨λ a ha, f a, hf, rfl⟩ }
end
lemma pi_finset_subset (t₁ t₂ : Πa, finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) :
pi_finset t₁ ⊆ pi_finset t₂ :=
λ g hg, mem_pi_finset.2 $ λ a, h a $ mem_pi_finset.1 hg a
lemma pi_finset_disjoint_of_disjoint [∀ a, decidable_eq (δ a)]
(t₁ t₂ : Πa, finset (δ a)) {a : α} (h : disjoint (t₁ a) (t₂ a)) :
disjoint (pi_finset t₁) (pi_finset t₂) :=
disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂,
disjoint_iff_ne.1 h (f₁ a) (mem_pi_finset.1 hf₁ a) (f₂ a) (mem_pi_finset.1 hf₂ a) (congr_fun eq₁₂ a)
end fintype
/-! ### pi -/
/-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/
instance pi.fintype {α : Type*} {β : α → Type*}
[decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype (Πa, β a) :=
⟨fintype.pi_finset (λ _, univ), by simp⟩
@[simp] lemma fintype.pi_finset_univ {α : Type*} {β : α → Type*}
[decidable_eq α] [fintype α] [∀a, fintype (β a)] :
fintype.pi_finset (λ a : α, (finset.univ : finset (β a))) = (finset.univ : finset (Π a, β a)) :=
rfl
instance d_array.fintype {n : ℕ} {α : fin n → Type*}
[∀n, fintype (α n)] : fintype (d_array n α) :=
fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm
instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) :=
d_array.fintype
instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) :=
fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm
instance quotient.fintype [fintype α] (s : setoid α)
[decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) :=
fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩))
instance finset.fintype [fintype α] : fintype (finset α) :=
⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩
@[simp] lemma fintype.card_finset [fintype α] :
fintype.card (finset α) = 2 ^ (fintype.card α) :=
finset.card_powerset finset.univ
@[simp] lemma set.to_finset_univ [fintype α] :
(set.univ : set α).to_finset = finset.univ :=
by { ext, simp only [set.mem_univ, mem_univ, set.mem_to_finset] }
@[simp] lemma set.to_finset_empty [fintype α] :
(∅ : set α).to_finset = ∅ :=
by { ext, simp only [set.mem_empty_eq, set.mem_to_finset, not_mem_empty] }
theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] :
fintype.card {x // p x} ≤ fintype.card α :=
by rw fintype.subtype_card; exact card_le_of_subset (subset_univ _)
theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p]
{x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α :=
by rw [fintype.subtype_card]; exact finset.card_lt_card
⟨subset_univ _, not_forall.2 ⟨x, by simp [hx]⟩⟩
instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] :
fintype (Σ' a, β a) :=
fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm
instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [decidable α] [∀ a, fintype (β a)] :
fintype (Σ' a, β a) :=
if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩
else ⟨∅, λ x, h x.1⟩
instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [∀ a, decidable (β a)] [fintype α] :
fintype (Σ' a, β a) :=
fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩
instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] :
fintype (Σ' a, β a) :=
if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩
instance set.fintype [fintype α] : fintype (set α) :=
⟨(@finset.univ α _).powerset.map ⟨coe, coe_injective⟩, λ s, begin
classical, refine mem_map.2 ⟨finset.univ.filter s, mem_powerset.2 (subset_univ _), _⟩,
apply (coe_filter _).trans, rw [coe_univ, set.sep_univ], refl
end⟩
instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*)
[Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) :=
if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩
else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩
lemma mem_image_univ_iff_mem_range
{α β : Type*} [fintype α] [decidable_eq β] {f : α → β} {b : β} :
b ∈ univ.image f ↔ b ∈ set.range f :=
by simp
lemma card_lt_card_of_injective_of_not_mem
{α β : Type*} [fintype α] [fintype β] (f : α → β) (h : function.injective f)
{b : β} (w : b ∉ set.range f) : fintype.card α < fintype.card β :=
begin
classical,
calc
fintype.card α = (univ : finset α).card : rfl
... = (image f univ).card : (card_image_of_injective univ h).symm
... < (insert b (image f univ)).card :
card_lt_card (ssubset_insert (mt mem_image_univ_iff_mem_range.mp w))
... ≤ (univ : finset β).card : card_le_of_subset (subset_univ _)
... = fintype.card β : rfl
end
def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)] :
∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance)
| [] f := ⟦λ i, false.elim⟧
| (i::l) f := begin
refine quotient.lift_on₂ (f i (list.mem_cons_self _ _))
(quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h)))
_ _,
exact λ a l, ⟦λ j h,
if e : j = i then by rw e; exact a else
l _ (h.resolve_left e)⟧,
refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _),
by_cases e : j = i; simp [e],
{ subst j, exact h₁ },
{ exact h₂ _ _ }
end
theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)] :
∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧
| [] f := quotient.sound (λ i h, h.elim)
| (i::l) f := begin
simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l],
refine quotient.sound (λ j h, _),
by_cases e : j = i; simp [e],
subst j, refl
end
def quotient.fin_choice {ι : Type*} [decidable_eq ι] [fintype ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)]
(f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) :=
quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι,
@quotient (Π i ∈ l, α i) (by apply_instance))
finset.univ.1
(λ l, quotient.fin_choice_aux l (λ i _, f i))
(λ a b h, begin
have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)),
simp [quotient.out_eq] at this,
simp [this],
let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧,
refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)),
congr' 1, exact quotient.sound h,
end))
(λ f, ⟦λ i, f i (finset.mem_univ _)⟧)
(λ a b h, quotient.sound $ λ i, h _ _)
theorem quotient.fin_choice_eq {ι : Type*} [decidable_eq ι] [fintype ι]
{α : ι → Type*} [∀ i, setoid (α i)]
(f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ :=
begin
let q, swap, change quotient.lift_on q _ _ = _,
have : q = ⟦λ i h, f i⟧,
{ dsimp [q],
exact quotient.induction_on
(@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) },
simp [this], exact setoid.refl _
end
section equiv
open list equiv equiv.perm
variables [decidable_eq α] [decidable_eq β]
def perms_of_list : list α → list (perm α)
| [] := [1]
| (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f))
lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length.fact
| [] := rfl
| (a :: l) :=
begin
rw [length_cons, nat.fact_succ],
simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul],
cc
end
lemma mem_perms_of_list_of_mem {l : list α} {f : perm α}
(h : ∀ x, f x ≠ x → x ∈ l) : f ∈ perms_of_list l :=
begin
induction l with a l IH generalizing f h,
{ exact list.mem_singleton.2 (equiv.ext $ λ x, decidable.by_contradiction $ h _) },
by_cases hfa : f a = a,
{ refine mem_append_left _ (IH (λ x hx, mem_of_ne_of_mem _ (h x hx))),
rintro rfl, exact hx hfa },
{ have hfa' : f (f a) ≠ f a := mt (λ h, f.injective h) hfa,
have : ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l,
{ intros x hx,
have hxa : x ≠ a,
{ rintro rfl, apply hx, simp only [mul_apply, swap_apply_right] },
refine list.mem_of_ne_of_mem hxa (h x (λ h, _)),
simp only [h, mul_apply, swap_apply_def, mul_apply, ne.def, apply_eq_iff_eq] at hx;
split_ifs at hx, exacts [hxa (h.symm.trans h_1), hx h] },
suffices : f ∈ perms_of_list l ∨ ∃ (b ∈ l) (g ∈ perms_of_list l), swap a b * g = f,
{ simpa only [perms_of_list, exists_prop, list.mem_map, mem_append, list.mem_bind] },
refine or_iff_not_imp_left.2 (λ hfl, ⟨f a, _, swap a (f a) * f, IH this, _⟩),
{ by_cases hffa : f (f a) = a,
{ exact mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa)) },
{ apply this,
simp only [mul_apply, swap_apply_def, mul_apply, ne.def, apply_eq_iff_eq],
split_ifs; cc } },
{ rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)),
swap_swap, ← equiv.perm.one_def, one_mul] } }
end
lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l
| [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp
| (a::l) f h :=
(mem_append.1 h).elim
(λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx))
(λ h x hx,
let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in
let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in
if hxa : x = a then by simp [hxa]
else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy
else mem_cons_of_mem _ $
mem_of_mem_perms_of_list hg₁ $
by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def];
split_ifs; cc)
lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l :=
⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩
lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup
| [] hl := by simp [perms_of_list]
| (a::l) hl :=
have hl' : l.nodup, from nodup_of_nodup_cons hl,
have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl',
have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a,
from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1),
by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact
⟨hln', ⟨λ _ _, nodup_map (λ _ _, mul_left_cancel) hln',
λ i j hj hij x hx₁ hx₂,
let ⟨f, hf⟩ := list.mem_map.1 hx₁ in
let ⟨g, hg⟩ := list.mem_map.1 hx₂ in
have hix : x a = nth_le l i (lt_trans hij hj),
by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left],
have hiy : x a = nth_le l j hj,
by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left],
absurd (hf.2.trans (hg.2.symm)) $
λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $
by rw [← hix, hiy]⟩,
λ f hf₁ hf₂,
let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in
let ⟨g, hg⟩ := list.mem_map.1 hx' in
have hgxa : g⁻¹ x = a, from f.injective $
by rw [hmeml hf₁, ← hg.2]; simp,
have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx),
(list.nodup_cons.1 hl).1 $
hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩
def perms_of_finset (s : finset α) : finset (perm α) :=
quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩)
(λ a b hab, hfunext (congr_arg _ (quotient.sound hab))
(λ ha hb _, heq_of_eq $ finset.ext $
by simp [mem_perms_of_list_iff, hab.mem_iff]))
s.2
lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α},
f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s :=
by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff
lemma card_perms_of_finset : ∀ (s : finset α),
(perms_of_finset s).card = s.card.fact :=
by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l
def fintype_perm [fintype α] : fintype (perm α) :=
⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩
instance [fintype α] [fintype β] : fintype (α ≃ β) :=
if h : fintype.card β = fintype.card α
then trunc.rec_on_subsingleton (fintype.equiv_fin α)
(λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β)
(λ eβ, @fintype.of_equiv _ (perm α) fintype_perm
(equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β))))
else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩
lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α).fact :=
subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸
card_perms_of_finset _
lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) :
fintype.card (α ≃ β) = (fintype.card α).fact :=
fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm
lemma univ_eq_singleton_of_card_one {α} [fintype α] (x : α) (h : fintype.card α = 1) :
(univ : finset α) = {x} :=
begin
apply symm,
apply eq_of_subset_of_card_le (subset_univ ({x})),
apply le_of_eq,
simp [h, finset.card_univ]
end
end equiv
namespace fintype
section choose
open fintype
open equiv
variables [fintype α] (p : α → Prop) [decidable_pred p]
def choose_x (hp : ∃! a : α, p a) : {a // p a} :=
⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩
def choose (hp : ∃! a, p a) : α := choose_x p hp
lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) :=
(choose_x p hp).property
end choose
section bijection_inverse
open function
variables [fintype α]
variables [decidable_eq β]
variables {f : α → β}
/-- `
`bij_inv f` is the unique inverse to a bijection `f`. This acts
as a computable alternative to `function.inv_fun`. -/
def bij_inv (f_bij : bijective f) (b : β) : α :=
fintype.choose (λ a, f a = b)
begin
rcases f_bij.right b with ⟨a', fa_eq_b⟩,
rw ← fa_eq_b,
exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩
end
lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f :=
λ a, f_bij.left (choose_spec (λ a', f a' = f a) _)
lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f :=
λ b, choose_spec (λ a', f a' = b) _
lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) :=
⟨(right_inverse_bij_inv _).injective, (left_inverse_bij_inv _).surjective⟩
end bijection_inverse
lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop)
[is_trans α r] [is_irrefl α r] : well_founded r :=
by classical; exact
have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card,
from λ x y hxy, finset.card_lt_card $
by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le,
finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy];
exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩,
subrelation.wf this (measure_wf _)
lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) :=
well_founded_of_trans_of_irrefl _
@[instance, priority 10] lemma linear_order.is_well_order [fintype α] [linear_order α] :
is_well_order α (<) :=
{ wf := preorder.well_founded }
end fintype
class infinite (α : Type*) : Prop :=
(not_fintype : fintype α → false)
@[simp] lemma not_nonempty_fintype {α : Type*} : ¬nonempty (fintype α) ↔ infinite α :=
⟨λf, ⟨λ x, f ⟨x⟩⟩, λ⟨f⟩ ⟨x⟩, f x⟩
namespace infinite
lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s :=
not_forall.1 $ λ h, not_fintype ⟨s, h⟩
@[priority 100] -- see Note [lower instance priority]
instance nonempty (α : Type*) [infinite α] : nonempty α :=
nonempty_of_exists (exists_not_mem_finset (∅ : finset α))
lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α :=
⟨λ I, by exactI not_fintype (fintype.of_injective f hf)⟩
lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α :=
⟨λ I, by classical; exactI not_fintype (fintype.of_surjective f hf)⟩
private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α
| n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset
((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m)
(λ _, multiset.mem_range.1)).to_finset)
private lemma nat_embedding_aux_injective (α : Type*) [infinite α] :
function.injective (nat_embedding_aux α) :=
begin
assume m n h,
letI := classical.dec_eq α,
wlog hmlen : m ≤ n using m n,
by_contradiction hmn,
have hmn : m < n, from lt_of_le_of_ne hmlen hmn,
refine (classical.some_spec (exists_not_mem_finset
((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m)
(λ _, multiset.mem_range.1)).to_finset)) _,
refine multiset.mem_to_finset.2 (multiset.mem_pmap.2
⟨m, multiset.mem_range.2 hmn, _⟩),
rw [h, nat_embedding_aux]
end
/-- Embedding of `ℕ` into an infinite type. -/
noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α :=
⟨_, nat_embedding_aux_injective α⟩
lemma exists_subset_card_eq (α : Type*) [infinite α] (n : ℕ) :
∃ s : finset α, s.card = n :=
⟨(range n).map (nat_embedding α), by rw [card_map, card_range]⟩
end infinite
lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) :
¬ injective f :=
assume (hf : injective f),
have H : fintype α := fintype.of_injective f hf,
infinite.not_fintype H
lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) :
¬ surjective f :=
assume (hf : surjective f),
have H : infinite α := infinite.of_surjective f hf,
@infinite.not_fintype _ H infer_instance
instance nat.infinite : infinite ℕ :=
⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩
instance int.infinite : infinite ℤ :=
infinite.of_injective int.of_nat (λ _ _, int.of_nat.inj)
section trunc
/--
For `s : multiset α`, we can lift the existential statement that `∃ x, x ∈ s` to a `trunc α`.
-/
def trunc_of_multiset_exists_mem {α} (s : multiset α) : (∃ x, x ∈ s) → trunc α :=
quotient.rec_on_subsingleton s $ λ l h,
match l, h with
| [], _ := false.elim (by tauto)
| (a :: _), _ := trunc.mk a
end
/--
A `nonempty` `fintype` constructively contains an element.
-/
def trunc_of_nonempty_fintype (α) [nonempty α] [fintype α] : trunc α :=
trunc_of_multiset_exists_mem finset.univ.val (by simp)
/--
A `fintype` with positive cardinality constructively contains an element.
-/
def trunc_of_card_pos {α} [fintype α] (h : 0 < fintype.card α) : trunc α :=
by { letI := (fintype.card_pos_iff.mp h), exact trunc_of_nonempty_fintype α }
/--
By iterating over the elements of a fintype, we can lift an existential statement `∃ a, P a`
to `trunc (Σ' a, P a)`, containing data.
-/
def trunc_sigma_of_exists {α} [fintype α] {P : α → Prop} [decidable_pred P] (h : ∃ a, P a) :
trunc (Σ' a, P a) :=
@trunc_of_nonempty_fintype (Σ' a, P a) (exists.elim h $ λ a ha, ⟨⟨a, ha⟩⟩) _
end trunc
|
4825e37ed1730931d2a68e37108727716bd591d9 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/ring_theory/complex.lean | 598d189f045c21e5db3cb43a31c706292e16f14a | [
"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 | 1,439 | lean | /-
Copyright (c) 2023 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import data.complex.module
import ring_theory.norm
import ring_theory.trace
/-! # Lemmas about `algebra.trace` and `algebra.norm` on `ℂ` -/
open complex
lemma algebra.left_mul_matrix_complex (z : ℂ) :
algebra.left_mul_matrix complex.basis_one_I z = !![z.re, -z.im; z.im, z.re] :=
begin
ext i j,
rw [algebra.left_mul_matrix_eq_repr_mul, complex.coe_basis_one_I_repr, complex.coe_basis_one_I,
mul_re, mul_im, matrix.of_apply],
fin_cases j,
{ simp_rw [matrix.cons_val_zero, one_re, one_im, mul_zero, mul_one, sub_zero, zero_add],
fin_cases i; refl },
{ simp_rw [matrix.cons_val_one, matrix.head_cons, I_re, I_im, mul_zero, mul_one, zero_sub,
add_zero],
fin_cases i; refl },
end
lemma algebra.trace_complex_apply (z : ℂ) : algebra.trace ℝ ℂ z = 2*z.re :=
begin
rw [algebra.trace_eq_matrix_trace complex.basis_one_I,
algebra.left_mul_matrix_complex, matrix.trace_fin_two],
exact (two_mul _).symm
end
lemma algebra.norm_complex_apply (z : ℂ) : algebra.norm ℝ z = z.norm_sq :=
begin
rw [algebra.norm_eq_matrix_det complex.basis_one_I,
algebra.left_mul_matrix_complex, matrix.det_fin_two, norm_sq_apply],
simp,
end
lemma algebra.norm_complex_eq : algebra.norm ℝ = norm_sq.to_monoid_hom :=
monoid_hom.ext algebra.norm_complex_apply
|
14ee6f2dbff6448e069d064217b00d35260ee76c | 74caf7451c921a8d5ab9c6e2b828c9d0a35aae95 | /library/init/meta/comp_value_tactics.lean | 3abd33963880f3abfcf21a5e4d1c3c44f1673e08 | [
"Apache-2.0"
] | permissive | sakas--/lean | f37b6fad4fd4206f2891b89f0f8135f57921fc3f | 570d9052820be1d6442a5cc58ece37397f8a9e4c | refs/heads/master | 1,586,127,145,194 | 1,480,960,018,000 | 1,480,960,635,000 | 40,137,176 | 0 | 0 | null | 1,438,621,351,000 | 1,438,621,351,000 | null | UTF-8 | Lean | false | false | 2,047 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.tactic
meta constant mk_nat_val_ne_proof : expr → expr → option expr
meta constant mk_nat_val_lt_proof : expr → expr → option expr
meta constant mk_nat_val_le_proof : expr → expr → option expr
meta constant mk_fin_val_ne_proof : expr → expr → option expr
meta constant mk_char_val_ne_proof : expr → expr → option expr
meta constant mk_string_val_ne_proof : expr → expr → option expr
namespace tactic
open expr
meta def comp_val : tactic unit :=
do t ← target,
guard (is_app t),
type ← infer_type t^.app_arg,
(do is_def_eq type (const `nat []),
(do (a, b) ← returnopt (is_ne t),
pr ← returnopt (mk_nat_val_ne_proof a b),
exact pr)
<|>
(do (a, b) ← returnopt (is_lt t),
pr ← returnopt (mk_nat_val_lt_proof a b),
exact pr)
<|>
(do (a, b) ← returnopt (is_gt t),
pr ← returnopt (mk_nat_val_lt_proof b a),
exact pr)
<|>
(do (a, b) ← returnopt (is_le t),
pr ← returnopt (mk_nat_val_le_proof a b),
exact pr)
<|>
(do (a, b) ← returnopt (is_ge t),
pr ← returnopt (mk_nat_val_le_proof b a),
exact pr))
<|>
(do is_def_eq type (const `char []),
(a, b) ← returnopt (is_ne t),
pr ← returnopt (mk_char_val_ne_proof a b),
exact pr)
<|>
(do is_def_eq type (const `string []),
(a, b) ← returnopt (is_ne t),
pr ← returnopt (mk_string_val_ne_proof a b),
exact pr)
<|>
(do type ← whnf type,
guard (is_app_of type `fin),
(a, b) ← returnopt (is_ne t),
pr ← returnopt (mk_fin_val_ne_proof a b),
exact pr)
<|>
(do (a, b) ← returnopt (is_eq t),
unify a b, to_expr `(eq.refl %%a) >>= exact)
end tactic
|
db68c18cb599c47ed4c85bbacc672881b912a1fc | 2a70b774d16dbdf5a533432ee0ebab6838df0948 | /_target/deps/mathlib/src/tactic/simps.lean | bf2e4a88f906c4c71c50a5fa6f87c8610e657667 | [
"Apache-2.0"
] | permissive | hjvromen/lewis | 40b035973df7c77ebf927afab7878c76d05ff758 | 105b675f73630f028ad5d890897a51b3c1146fb0 | refs/heads/master | 1,677,944,636,343 | 1,676,555,301,000 | 1,676,555,301,000 | 327,553,599 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 32,484 | lean | /-
Copyright (c) 2019 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import tactic.core
/-!
# simps attribute
This file defines the `@[simps]` attribute, to automatically generate simp-lemmas
reducing a definition when projections are applied to it.
## Implementation Notes
There are three attributes being defined here
* `@[simps]` is the attribute for objects of a structure or instances of a class. It will
automatically generate simplification lemmas for each projection of the object/instance that
contains data. See the doc strings for `simps_attr` and `simps_cfg` for more details and
configuration options.
* `@[_simps_str]` is automatically added to structures that have been used in `@[simps]` at least
once. This attribute contains the data of the projections used for this structure by all following
invocations of `@[simps]`.
* `@[notation_class]` should be added to all classes that define notation, like `has_mul` and
`has_zero`. This specifies that the projections that `@[simps]` used are the projections from
these notation classes instead of the projections of the superclasses.
Example: if `has_mul` is tagged with `@[notation_class]` then the projection used for `semigroup`
will be `λ α hα, @has_mul.mul α (@semigroup.to_has_mul α hα)` instead of `@semigroup.mul`.
## Tags
structures, projections, simp, simplifier, generates declarations
-/
open tactic expr
setup_tactic_parser
declare_trace simps.verbose
declare_trace simps.debug
/--
The `@[_simps_str]` attribute specifies the preferred projections of the given structure,
used by the `@[simps]` attribute.
- This will usually be tagged by the `@[simps]` tactic.
- You can also generate this with the command `initialize_simps_projections`.
- To change the default value, see Note [custom simps projection].
- You are strongly discouraged to add this attribute manually.
- The first argument is the list of names of the universe variables used in the structure
- The second argument is a list that consists of
- a custom name for each projection of the structure
- an expressions for each projections of the structure (definitionally equal to the
corresponding projection). These expressions can contain the universe parameters specified
in the first argument).
-/
@[user_attribute] meta def simps_str_attr : user_attribute unit (list name × list (name × expr)) :=
{ name := `_simps_str,
descr := "An attribute specifying the projection of the given structure.",
parser := do e ← texpr, eval_pexpr _ e }
/--
The `@[notation_class]` attribute specifies that this is a notation class,
and this notation should be used instead of projections by @[simps].
* The first argument `tt` for notation classes and `ff` for classes applied to the structure,
like `has_coe_to_sort` and `has_coe_to_fun`
* The second argument is the name of the projection (by default it is the first projection
of the structure)
-/
@[user_attribute] meta def notation_class_attr : user_attribute unit (bool × option name) :=
{ name := `notation_class,
descr := "An attribute specifying that this is a notation class. Used by @[simps].",
parser := prod.mk <$> (option.is_none <$> (tk "*")?) <*> ident? }
attribute [notation_class] has_zero has_one has_add has_mul has_inv has_neg has_sub has_div has_dvd
has_mod has_le has_lt has_append has_andthen has_union has_inter has_sdiff has_equiv has_subset
has_ssubset has_emptyc has_insert has_singleton has_sep has_mem has_pow
attribute [notation_class* coe_sort] has_coe_to_sort
attribute [notation_class* coe_fn] has_coe_to_fun
/--
Get the projections used by `simps` associated to a given structure `str`. The second component is
the list of projections, and the first component the (shared) list of universe levels used by the
projections.
The returned information is also stored in a parameter of the attribute `@[_simps_str]`, which
is given to `str`. If `str` already has this attribute, the information is read from this
attribute instead.
The returned universe levels are the universe levels of the structure. For the projections there
are three cases
* If the declaration `{structure_name}.simps.{projection_name}` has been declared, then the value
of this declaration is used (after checking that it is definitionally equal to the actual
projection
* Otherwise, for every class with the `notation_class` attribute, and the structure has an
instance of that notation class, then the projection of that notation class is used for the
projection that is definitionally equal to it (if there is such a projection).
This means in practice that coercions to function types and sorts will be used instead of
a projection, if this coercion is definitionally equal to a projection. Furthermore, for
notation classes like `has_mul` and `has_zero` those projections are used instead of the
corresponding projection
* Otherwise, the projection of the structure is chosen.
For example: ``simps_get_raw_projections env `prod`` gives the default projections
```
([u, v], [prod.fst.{u v}, prod.snd.{u v}])
```
while ``simps_get_raw_projections env `equiv`` gives
```
([u_1, u_2], [λ α β, coe_fn, λ {α β} (e : α ≃ β), ⇑(e.symm), left_inv, right_inv])
```
after declaring the coercion from `equiv` to function and adding the declaration
```
def equiv.simps.inv_fun {α β} (e : α ≃ β) : β → α := e.symm
```
Optionally, this command accepts two optional arguments
* If `trace_if_exists` the command will always generate a trace message when the structure already
has the attribute `@[_simps_str]`.
* The `name_changes` argument accepts a list of pairs `(old_name, new_name)`. This is used to
change the projection name `old_name` to the custom projection name `new_name`. Example:
for the structure `equiv` the projection `to_fun` could be renamed `apply`. This name will be
used for parsing and generating projection names. This argument is ignored if the structure
already has an existing attribute.
-/
-- if performance becomes a problem, possible heuristic: use the names of the projections to
-- skip all classes that don't have the corresponding field.
meta def simps_get_raw_projections (e : environment) (str : name) (trace_if_exists : bool := ff)
(name_changes : list (name × name) := []) : tactic (list name × list (name × expr)) := do
has_attr ← has_attribute' `_simps_str str,
if has_attr then do
data ← simps_str_attr.get_param str,
to_print ← data.2.mmap $ λ s, to_string <$> pformat!"Projection {s.1}: {s.2}",
let to_print := string.join $ to_print.intersperse "\n > ",
-- We always trace this when called by `initialize_simps_projections`,
-- because this doesn't do anything extra (so should not occur in mathlib).
-- It can be useful to find the projection names.
when (is_trace_enabled_for `simps.verbose || trace_if_exists) trace!
"[simps] > Already found projection information for structure {str}:\n > {to_print}",
return data
else do
when_tracing `simps.verbose trace!
"[simps] > generating projection information for structure {str}:",
d_str ← e.get str,
projs ← e.structure_fields_full str,
let raw_univs := d_str.univ_params,
let raw_levels := level.param <$> raw_univs,
/- Define the raw expressions for the projections, by default as the projections
(as an expression), but this can be overriden by the user. -/
raw_exprs ← projs.mmap (λ proj, let raw_expr : expr := expr.const proj raw_levels in do
custom_proj ← (do
decl ← e.get (str ++ `simps ++ proj.last),
let custom_proj := decl.value.instantiate_univ_params $ decl.univ_params.zip raw_levels,
when_tracing `simps.verbose trace!
"[simps] > found custom projection for {proj}:\n > {custom_proj}",
return custom_proj) <|> return raw_expr,
is_def_eq custom_proj raw_expr <|>
-- if the type of the expression is different, we show a different error message, because
-- that is more likely going to be helpful.
do {
custom_proj_type ← infer_type custom_proj,
raw_expr_type ← infer_type raw_expr,
b ← succeeds (is_def_eq custom_proj_type raw_expr_type),
if b then fail!"Invalid custom projection:\n {custom_proj}
Expression is not definitionally equal to {raw_expr}."
else fail!"Invalid custom projection:\n {custom_proj}
Expression has different type than {raw_expr}. Given type:\n {custom_proj_type}
Expected type:\n {raw_expr_type}" },
return custom_proj),
/- Check for other coercions and type-class arguments to use as projections instead. -/
(args, _) ← open_pis d_str.type,
let e_str := (expr.const str raw_levels).mk_app args,
automatic_projs ← attribute.get_instances `notation_class,
raw_exprs ← automatic_projs.mfoldl (λ (raw_exprs : list expr) class_nm, (do
(is_class, proj_nm) ← notation_class_attr.get_param class_nm,
proj_nm ← proj_nm <|> (e.structure_fields_full class_nm).map list.head,
/- For this class, find the projection. `raw_expr` is the projection found applied to `args`,
and `lambda_raw_expr` has the arguments `args` abstracted. -/
(raw_expr, lambda_raw_expr) ← if is_class then (do
guard $ args.length = 1,
let e_inst_type := (expr.const class_nm raw_levels).mk_app args,
(hyp, e_inst) ← try_for 1000 (mk_conditional_instance e_str e_inst_type),
raw_expr ← mk_mapp proj_nm [args.head, e_inst],
clear hyp,
-- Note: `expr.bind_lambda` doesn't give the correct type
raw_expr_lambda ← lambdas [hyp] raw_expr,
return (raw_expr, raw_expr_lambda.lambdas args))
else (do
e_inst_type ← to_expr ((expr.const class_nm []).app (pexpr.of_expr e_str)),
e_inst ← try_for 1000 (mk_instance e_inst_type),
raw_expr ← mk_mapp proj_nm [e_str, e_inst],
return (raw_expr, raw_expr.lambdas args)),
raw_expr_whnf ← whnf raw_expr,
let relevant_proj := raw_expr_whnf.binding_body.get_app_fn.const_name,
/- Use this as projection, if the function reduces to a projection, and this projection has
not been overrriden by the user. -/
guard (projs.any (= relevant_proj) ∧ ¬ e.contains (str ++ `simps ++ relevant_proj.last)),
let pos := projs.find_index (= relevant_proj),
when_tracing `simps.verbose trace!
" > using {proj_nm} instead of the default projection {relevant_proj.last}.",
return $ raw_exprs.update_nth pos lambda_raw_expr) <|> return raw_exprs) raw_exprs,
proj_names ← e.structure_fields str,
-- if we find the name in name_changes, change the name
let proj_names : list name := proj_names.map $
λ nm, (name_changes.find $ λ p : _ × _, p.1 = nm).elim nm prod.snd,
let projs := proj_names.zip raw_exprs,
when_tracing `simps.verbose $ do {
to_print ← projs.mmap $ λ s, to_string <$> pformat!"Projection {s.1}: {s.2}",
let to_print := string.join $ to_print.intersperse "\n > ",
trace!"[simps] > generated projections for {str}:\n > {to_print}" },
simps_str_attr.set str (raw_univs, projs) tt,
return (raw_univs, projs)
/--
You can specify custom projections for the `@[simps]` attribute.
To do this for the projection `my_structure.awesome_projection` by adding a declaration
`my_structure.simps.awesome_projection` that is definitionally equal to
`my_structure.awesome_projection` but has the projection in the desired (simp-normal) form.
You can initialize the projections `@[simps]` uses with `initialize_simps_projections`
(after declaring any custom projections). This is not necessary, it has the same effect
if you just add `@[simps]` to a declaration.
If you do anything to change the default projections, make sure to call either `@[simps]` or
`initialize_simps_projections` in the same file as the structure declaration. Otherwise, you might
have a file that imports the structure, but not your custom projections.
-/
library_note "custom simps projection"
/-- Specify simps projections, see Note [custom simps projection].
You can specify custom names by writing e.g.
`initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply)`.
Set `trace.simps.verbose` to true to see the generated projections.
If the projections were already specified before, you can call `initialize_simps_projections`
again to see the generated projections. -/
@[user_command] meta def initialize_simps_projections_cmd
(_ : parse $ tk "initialize_simps_projections") : parser unit := do
env ← get_env,
ns ← (prod.mk <$> ident <*> (tk "(" >>
sep_by (tk ",") (prod.mk <$> ident <*> (tk "->" >> ident)) <* tk ")")?)*,
ns.mmap' $ λ data, do
nm ← resolve_constant data.1,
simps_get_raw_projections env nm tt $ data.2.get_or_else []
/--
Get the projections of a structure used by `@[simps]` applied to the appropriate arguments.
Returns a list of quadruples
(projection expression, given projection name, original (full) projection name,
corresponding right-hand-side),
one for each projection. The given projection name is the name for the projection used by the user
used to generate (and parse) projection names. The original projection name is the actual
projection name in the structure, which is only used to check whether the expression is an
eta-expansion of some other expression. For example, in the structure
Example 1: ``simps_get_projection_exprs env `(α × β) `(⟨x, y⟩)`` will give the output
```
[(`(@prod.fst.{u v} α β), `fst, `prod.fst, `(x)),
(`(@prod.snd.{u v} α β), `snd, `prod.snd, `(y))]
```
Example 2: ``simps_get_projection_exprs env `(α ≃ α) `(⟨id, id, λ _, rfl, λ _, rfl⟩)``
will give the output
```
[(`(@equiv.to_fun.{u u} α α), `apply, `equiv.to_fun, `(id)),
(`(@equiv.inv_fun.{u u} α α), `symm_apply, `equiv.inv_fun, `(id)),
...,
...]
```
The last two fields of the list correspond to the propositional fields of the structure,
and are rarely/never used.
-/
-- This function does not use `tactic.mk_app` or `tactic.mk_mapp`, because the the given arguments
-- might not uniquely specify the universe levels yet.
meta def simps_get_projection_exprs (e : environment) (tgt : expr)
(rhs : expr) : tactic $ list $ expr × name × name × expr := do
let params := get_app_args tgt, -- the parameters of the structure
(params.zip $ (get_app_args rhs).take params.length).mmap' (λ ⟨a, b⟩, is_def_eq a b)
<|> fail "unreachable code (1)",
let str := tgt.get_app_fn.const_name,
let rhs_args := (get_app_args rhs).drop params.length, -- the fields of the object
(raw_univs, projs_and_raw_exprs) ← simps_get_raw_projections e str,
guard (rhs_args.length = projs_and_raw_exprs.length) <|> fail "unreachable code (2)",
let univs := raw_univs.zip tgt.get_app_fn.univ_levels,
let projs := projs_and_raw_exprs.map $ prod.fst,
original_projection_names ← e.structure_fields_full str,
let raw_exprs := projs_and_raw_exprs.map $ prod.snd,
let proj_exprs := raw_exprs.map $
λ raw_expr, (raw_expr.instantiate_univ_params univs).instantiate_lambdas_or_apps params,
return $ proj_exprs.zip $ projs.zip $ original_projection_names.zip rhs_args
/--
Configuration options for the `@[simps]` attribute.
* `attrs` specifies the list of attributes given to the generated lemmas. Default: ``[`simp]``.
The attributes can be either basic attributes, or user attributes without parameters.
There are two attributes which `simps` might add itself:
* If ``[`simp]`` is in the list, then ``[`_refl_lemma]`` is added automatically if appropriate.
* If the definition is marked with `@[to_additive ...]` then all generated lemmas are marked
with `@[to_additive]`
* `short_name` gives the generated lemmas a shorter name. This only has an effect when multiple
projections are applied in a lemma. When this is `ff` (default) all projection names will be
appended to the definition name to form the lemma name, and when this is `tt`, only the
last projection name will be appended.
* if `simp_rhs` is `tt` then the right-hand-side of the generated lemmas will be put in
simp-normal form. More precisely: `dsimp, simp` will be called on all these expressions.
See note [dsimp, simp].
* `type_md` specifies how aggressively definitions are unfolded in the type of expressions
for the purposes of finding out whether the type is a function type.
Default: `instances`. This will unfold coercion instances (so that a coercion to a function type
is recognized as a function type), but not declarations like `set`.
* `rhs_md` specifies how aggressively definition in the declaration are unfolded for the purposes
of finding out whether it is a constructor.
Default: `none`
Exception: `@[simps]` will automatically add the options
`{rhs_md := semireducible, simp_rhs := tt}` if the given definition is not a constructor with
the given reducibility setting for `rhs_md`.
* If `fully_applied` is `ff` then the generated simp-lemmas will be between non-fully applied
terms, i.e. equalities between functions. This does not restrict the recursive behavior of
`@[simps]`, so only the "final" projection will be non-fully applied.
However, it can be used in combination with explicit field names, to get a partially applied
intermediate projection.
* The option `not_recursive` contains the list of names of types for which `@[simps]` doesn't
recursively apply projections. For example, given an equivalence `α × β ≃ β × α` one usually
wants to only apply the projections for `equiv`, and not also those for `×`. This option is
only relevant if no explicit projection names are given as argument to `@[simps]`.
-/
@[derive [has_reflect, inhabited]] structure simps_cfg :=
(attrs := [`simp])
(short_name := ff)
(simp_rhs := ff)
(type_md := transparency.instances)
(rhs_md := transparency.none)
(fully_applied := tt)
(not_recursive := [`prod, `pprod])
/-- Add a lemma with `nm` stating that `lhs = rhs`. `type` is the type of both `lhs` and `rhs`,
`args` is the list of local constants occurring, and `univs` is the list of universe variables.
If `add_simp` then we make the resulting lemma a simp-lemma. -/
meta def simps_add_projection (nm : name) (type lhs rhs : expr) (args : list expr)
(univs : list name) (cfg : simps_cfg) : tactic unit := do
when_tracing `simps.debug trace!
"[simps] > Planning to add the equality\n > {lhs} = ({rhs} : {type})",
-- simplify `rhs` if `cfg.simp_rhs` is true
(rhs, prf) ← do { guard cfg.simp_rhs,
rhs' ← rhs.dsimp {fail_if_unchanged := ff},
when_tracing `simps.debug $ when (rhs ≠ rhs') trace!
"[simps] > `dsimp` simplified rhs to\n > {rhs'}",
rhsprf ← rhs'.simp {fail_if_unchanged := ff},
when_tracing `simps.debug $ when (rhs' ≠ rhsprf.1) trace!
"[simps] > `simp` simplified rhs to\n > {rhsprf.1}",
return rhsprf }
<|> prod.mk rhs <$> mk_app `eq.refl [type, lhs],
eq_ap ← mk_mapp `eq $ [type, lhs, rhs].map some,
decl_name ← get_unused_decl_name nm,
let decl_type := eq_ap.pis args,
let decl_value := prf.lambdas args,
let decl := declaration.thm decl_name univs decl_type (pure decl_value),
when_tracing `simps.verbose trace!
"[simps] > adding projection {decl_name}:\n > {decl_type}",
decorate_error ("failed to add projection lemma " ++ decl_name.to_string ++ ". Nested error:") $
add_decl decl,
b ← succeeds $ is_def_eq lhs rhs,
when (b ∧ `simp ∈ cfg.attrs) (set_basic_attribute `_refl_lemma decl_name tt),
cfg.attrs.mmap' $ λ nm, set_attribute nm decl_name tt
/-- Derive lemmas specifying the projections of the declaration.
If `todo` is non-empty, it will generate exactly the names in `todo`. -/
meta def simps_add_projections : ∀(e : environment) (nm : name) (suffix : string)
(type lhs rhs : expr) (args : list expr) (univs : list name) (must_be_str : bool)
(cfg : simps_cfg) (todo : list string), tactic unit
| e nm suffix type lhs rhs args univs must_be_str cfg todo := do
-- we don't want to unfold non-reducible definitions (like `set`) to apply more arguments
when_tracing `simps.debug trace!
"[simps] > Trying to add simp-lemmas for\n > {lhs}
[simps] > Type of the expression before normalizing: {type}",
(type_args, tgt) ← open_pis_whnf type cfg.type_md,
when_tracing `simps.debug trace!
"[simps] > Type after removing pi's: {tgt}",
tgt ← whnf tgt,
when_tracing `simps.debug trace!
"[simps] > Type after reduction: {tgt}",
let new_args := args ++ type_args,
let lhs_ap := lhs.mk_app type_args,
let rhs_ap := rhs.instantiate_lambdas_or_apps type_args,
let str := tgt.get_app_fn.const_name,
let new_nm := nm.append_suffix suffix,
/- We want to generate the current projection if it is in `todo` -/
let todo_next := todo.filter (≠ ""),
/- Don't recursively continue if `str` is not a structure or if the structure is in
`not_recursive`. -/
if e.is_structure str ∧ ¬(todo = [] ∧ str ∈ cfg.not_recursive ∧ ¬must_be_str) then do
[intro] ← return $ e.constructors_of str | fail "unreachable code (3)",
rhs_whnf ← whnf rhs_ap cfg.rhs_md,
(rhs_ap, todo_now) ← if h : ¬ is_constant_of rhs_ap.get_app_fn intro ∧
is_constant_of rhs_whnf.get_app_fn intro then
/- If this was a desired projection, we want to apply it before taking the whnf.
However, if the current field is an eta-expansion (see below), we first want
to eta-reduce it and only then construct the projection.
This makes the flow of this function hard to follow. -/
when ("" ∈ todo) (if cfg.fully_applied then
simps_add_projection new_nm tgt lhs_ap rhs_ap new_args univs cfg else
simps_add_projection new_nm type lhs rhs args univs cfg) >>
return (rhs_whnf, ff) else
return (rhs_ap, "" ∈ todo),
if is_constant_of (get_app_fn rhs_ap) intro then do -- if the value is a constructor application
tuples ← simps_get_projection_exprs e tgt rhs_ap,
let projs := tuples.map $ λ x, x.2.1,
let pairs := tuples.map $ λ x, x.2.2,
eta ← rhs_ap.is_eta_expansion_aux pairs, -- check whether `rhs_ap` is an eta-expansion
let rhs_ap := eta.lhoare rhs_ap, -- eta-reduce `rhs_ap`
/- As a special case, we want to automatically generate the current projection if `rhs_ap`
was an eta-expansion. Also, when this was a desired projection, we need to generate the
current projection if we haven't done it above. -/
when (todo_now ∨ (todo = [] ∧ eta.is_some)) $
if cfg.fully_applied then
simps_add_projection new_nm tgt lhs_ap rhs_ap new_args univs cfg else
simps_add_projection new_nm type lhs rhs args univs cfg,
/- We stop if no further projection is specified or if we just reduced an eta-expansion and we
automatically choose projections -/
when ¬(todo = [""] ∨ (eta.is_some ∧ todo = [])) $ do
let todo := todo_next,
-- check whether all elements in `todo` have a projection as prefix
guard (todo.all $ λ x, projs.any $ λ proj, ("_" ++ proj.last).is_prefix_of x) <|>
let x := (todo.find $ λ x, projs.all $ λ proj, ¬ ("_" ++ proj.last).is_prefix_of x).iget,
simp_lemma := nm.append_suffix $ suffix ++ x,
needed_proj := (x.split_on '_').tail.head in
fail!
"Invalid simp-lemma {simp_lemma}. Structure {str} does not have projection {needed_proj}.
The known projections are:
{projs}
You can also see this information by running
`initialize_simps_projections {str}`.
Note: the projection names used by @[simps] might not correspond to the projection names in the structure.",
tuples.mmap' $ λ ⟨proj_expr, proj, _, new_rhs⟩, do
new_type ← infer_type new_rhs,
let new_todo := todo.filter_map $ λ x, string.get_rest x $ "_" ++ proj.last,
b ← is_prop new_type,
-- we only continue with this field if it is non-propositional or mentioned in todo
when ((¬ b ∧ todo = []) ∨ new_todo ≠ []) $ do
let new_lhs := proj_expr.instantiate_lambdas_or_apps [lhs_ap],
let new_suffix := if cfg.short_name then "_" ++ proj.last else
suffix ++ "_" ++ proj.last,
simps_add_projections e nm new_suffix new_type new_lhs new_rhs new_args univs
ff cfg new_todo
-- if I'm about to run into an error, try to set the transparency for `rhs_md` higher.
else if cfg.rhs_md = transparency.none ∧ (must_be_str ∨ todo_next ≠ []) then do
when_tracing `simps.verbose trace!
"[simps] > The given definition is not a constructor application:
> {rhs_ap}
> Retrying with the options {{ rhs_md := semireducible, simp_rhs := tt}.",
simps_add_projections e nm suffix type lhs rhs args univs must_be_str
{ rhs_md := semireducible, simp_rhs := tt, ..cfg} todo
else do
when must_be_str $
fail!"Invalid `simps` attribute. The body is not a constructor application:\n {rhs_ap}",
when (todo_next ≠ []) $
fail!"Invalid simp-lemma {nm.append_suffix $ suffix ++ todo_next.head}.
The given definition is not a constructor application:\n {rhs_ap}",
if cfg.fully_applied then
simps_add_projection new_nm tgt lhs_ap rhs_ap new_args univs cfg else
simps_add_projection new_nm type lhs rhs args univs cfg
else do
when must_be_str $
fail!"Invalid `simps` attribute. Target {str} is not a structure",
when (todo_next ≠ [] ∧ str ∉ cfg.not_recursive) $
fail!"Invalid simp-lemma {nm.append_suffix $ suffix ++ todo_next.head}.
Projection {(todo_next.head.split_on '_').tail.head} doesn't exist, because target is not a structure.",
if cfg.fully_applied then
simps_add_projection new_nm tgt lhs_ap rhs_ap new_args univs cfg else
simps_add_projection new_nm type lhs rhs args univs cfg
/-- `simps_tac` derives simp-lemmas for all (nested) non-Prop projections of the declaration.
If `todo` is non-empty, it will generate exactly the names in `todo`.
If `short_nm` is true, the generated names will only use the last projection name. -/
meta def simps_tac (nm : name) (cfg : simps_cfg := {}) (todo : list string := []) :
tactic unit :=
do
e ← get_env,
d ← e.get nm,
let lhs : expr := const d.to_name (d.univ_params.map level.param),
let todo := todo.erase_dup.map $ λ proj, "_" ++ proj,
b ← has_attribute' `to_additive nm,
let cfg := if b then { attrs := cfg.attrs ++ [`to_additive], ..cfg } else cfg,
simps_add_projections e nm "" d.type lhs d.value [] d.univ_params tt cfg todo
/-- The parser for the `@[simps]` attribute. -/
meta def simps_parser : parser (list string × simps_cfg) := do
/- note: we don't check whether the user has written a nonsense namespace in an argument. -/
prod.mk <$> many (name.last <$> ident) <*>
(do some e ← parser.pexpr? | return {}, eval_pexpr simps_cfg e)
/--
The `@[simps]` attribute automatically derives lemmas specifying the projections of this
declaration.
Example:
```lean
@[simps] def foo : ℕ × ℤ := (1, 2)
```
derives two simp-lemmas:
```lean
@[simp] lemma foo_fst : foo.fst = 1
@[simp] lemma foo_snd : foo.snd = 2
```
* It does not derive simp-lemmas for the prop-valued projections.
* It will automatically reduce newly created beta-redexes, but will not unfold any definitions.
* If the structure has a coercion to either sorts or functions, and this is defined to be one
of the projections, then this coercion will be used instead of the projection.
* If the structure is a class that has an instance to a notation class, like `has_mul`, then this
notation is used instead of the corresponding projection.
* You can specify custom projections, by giving a declaration with name
`{structure_name}.simps.{projection_name}`. See Note [custom simps projection].
Example:
```lean
def equiv.simps.inv_fun (e : α ≃ β) : β → α := e.symm
@[simps] def equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ :=
⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩
```
generates
```
@[simp] lemma equiv.trans_to_fun : ∀ {α β γ} (e₁ e₂) (a : α), ⇑(e₁.trans e₂) a = (⇑e₂ ∘ ⇑e₁) a
@[simp] lemma equiv.trans_inv_fun : ∀ {α β γ} (e₁ e₂) (a : γ),
⇑((e₁.trans e₂).symm) a = (⇑(e₁.symm) ∘ ⇑(e₂.symm)) a
```
* You can specify custom projection names, by specifying the new projection names using
`initialize_simps_projections`.
Example: `initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply)`.
* If one of the fields itself is a structure, this command will recursively create
simp-lemmas for all fields in that structure.
* Exception: by default it will not recursively create simp-lemmas for fields in the structures
`prod` and `pprod`. Give explicit projection names to override this behavior.
Example:
```lean
structure my_prod (α β : Type*) := (fst : α) (snd : β)
@[simps] def foo : prod ℕ ℕ × my_prod ℕ ℕ := ⟨⟨1, 2⟩, 3, 4⟩
```
generates
```lean
@[simp] lemma foo_fst : foo.fst = (1, 2)
@[simp] lemma foo_snd_fst : foo.snd.fst = 3
@[simp] lemma foo_snd_snd : foo.snd.snd = 4
```
* You can use `@[simps proj1 proj2 ...]` to only generate the projection lemmas for the specified
projections.
* Recursive projection names can be specified using `proj1_proj2_proj3`.
This will create a lemma of the form `foo.proj1.proj2.proj3 = ...`.
Example:
```lean
structure my_prod (α β : Type*) := (fst : α) (snd : β)
@[simps fst fst_fst snd] def foo : prod ℕ ℕ × my_prod ℕ ℕ := ⟨⟨1, 2⟩, 3, 4⟩
```
generates
```lean
@[simp] lemma foo_fst : foo.fst = (1, 2)
@[simp] lemma foo_fst_fst : foo.fst.fst = 1
@[simp] lemma foo_snd : foo.snd = {fst := 3, snd := 4}
```
* If one of the values is an eta-expanded structure, we will eta-reduce this structure.
Example:
```lean
structure equiv_plus_data (α β) extends α ≃ β := (data : bool)
@[simps] def bar {α} : equiv_plus_data α α := { data := tt, ..equiv.refl α }
```
generates the following, even though Lean inserts an eta-expanded version of `equiv.refl α` in the
definition of `bar`:
```lean
@[simp] lemma bar_to_equiv : ∀ {α : Sort u_1}, bar.to_equiv = equiv.refl α
@[simp] lemma bar_data : ∀ {α : Sort u_1}, bar.data = tt
```
* For configuration options, see the doc string of `simps_cfg`.
* The precise syntax is `('simps' ident* e)`, where `e` is an expression of type `simps_cfg`.
* `@[simps]` reduces let-expressions where necessary.
* If one of the fields is a partially applied constructor, we will eta-expand it
(this likely never happens).
* When option `trace.simps.verbose` is true, `simps` will print the projections it finds and the
lemmas it generates.
* Use `@[to_additive, simps]` to apply both `to_additive` and `simps` to a definition, making sure
that `simps` comes after `to_additive`. This will also generate the additive versions of all
simp-lemmas. Note however, that the additive versions of the simp-lemmas always use the default
name generated by `to_additive`, even if a custom name is given for the additive version of the
definition.
-/
@[user_attribute] meta def simps_attr : user_attribute unit (list string × simps_cfg) :=
{ name := `simps,
descr := "Automatically derive lemmas specifying the projections of this declaration.",
parser := simps_parser,
after_set := some $
λ n _ persistent, do
guard persistent <|> fail "`simps` currently cannot be used as a local attribute",
(todo, cfg) ← simps_attr.get_param n,
simps_tac n cfg todo }
add_tactic_doc
{ name := "simps",
category := doc_category.attr,
decl_names := [`simps_attr],
tags := ["simplification"] }
|
4bc8f8bf34ba3944d31727fce19cb20b20629ec6 | 618003631150032a5676f229d13a079ac875ff77 | /src/logic/function/basic.lean | 78a5e6c05bf9d51decaa2e485b680a7832183c36 | [
"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 | 13,562 | lean | /-
Copyright (c) 2016 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import logic.basic
import data.option.defs
/-!
# Miscellaneous function constructions and lemmas
-/
universes u v w
namespace function
section
variables {α : Sort u} {β : Sort v} {f : α → β}
lemma hfunext {α α': Sort u} {β : α → Sort v} {β' : α' → Sort v} {f : Πa, β a} {f' : Πa, β' a}
(hα : α = α') (h : ∀a a', a == a' → f a == f' a') : f == f' :=
begin
subst hα,
have : ∀a, f a == f' a,
{ intro a, exact h a a (heq.refl a) },
have : β = β',
{ funext a, exact type_eq_of_heq (this a) },
subst this,
apply heq_of_eq,
funext a,
exact eq_of_heq (this a)
end
lemma funext_iff {β : α → Sort*} {f₁ f₂ : Π (x : α), β x} : f₁ = f₂ ↔ (∀a, f₁ a = f₂ a) :=
iff.intro (assume h a, h ▸ rfl) funext
lemma comp_apply {α : Sort u} {β : Sort v} {φ : Sort w} (f : β → φ) (g : α → β) (a : α) :
(f ∘ g) a = f (g a) := rfl
@[simp] theorem injective.eq_iff (I : injective f) {a b : α} :
f a = f b ↔ a = b :=
⟨@I _ _, congr_arg f⟩
lemma injective.ne (hf : function.injective f) {a₁ a₂ : α} : a₁ ≠ a₂ → f a₁ ≠ f a₂ :=
mt (assume h, hf h)
/-- If the co-domain `β` of an injective function `f : α → β` has decidable equality, then
the domain `α` also has decidable equality. -/
def injective.decidable_eq [decidable_eq β] (I : injective f) : decidable_eq α
| a b := decidable_of_iff _ I.eq_iff
lemma injective.of_comp {γ : Sort w} {g : γ → α} (I : injective (f ∘ g)) : injective g :=
λ x y h, I $ show f (g x) = f (g y), from congr_arg f h
lemma surjective.of_comp {γ : Sort w} {g : γ → α} (S : surjective (f ∘ g)) : surjective f :=
λ y, let ⟨x, h⟩ := S y in ⟨g x, h⟩
instance decidable_eq_pfun (p : Prop) [decidable p] (α : p → Type*)
[Π hp, decidable_eq (α hp)] : decidable_eq (Π hp, α hp)
| f g := decidable_of_iff (∀ hp, f hp = g hp) funext_iff.symm
/-- Cantor's diagonal argument implies that there are no surjective functions from `α`
to `set α`. -/
theorem cantor_surjective {α} (f : α → set α) : ¬ function.surjective f | h :=
let ⟨D, e⟩ := h (λ a, ¬ f a a) in
(iff_not_self (f D D)).1 $ iff_of_eq (congr_fun e D)
/-- Cantor's diagonal argument implies that there are no injective functions from `set α` to `α`. -/
theorem cantor_injective {α : Type*} (f : (set α) → α) :
¬ function.injective f | i :=
cantor_surjective (λ a b, ∀ U, a = f U → U b) $
right_inverse.surjective (λ U, funext $ λ a, propext ⟨λ h, h U rfl, λ h' U' e, i e ▸ h'⟩)
/-- `g` is a partial inverse to `f` (an injective but not necessarily
surjective function) if `g y = some x` implies `f x = y`, and `g y = none`
implies that `y` is not in the range of `f`. -/
def is_partial_inv {α β} (f : α → β) (g : β → option α) : Prop :=
∀ x y, g y = some x ↔ f x = y
theorem is_partial_inv_left {α β} {f : α → β} {g} (H : is_partial_inv f g) (x) : g (f x) = some x :=
(H _ _).2 rfl
theorem injective_of_partial_inv {α β} {f : α → β} {g} (H : is_partial_inv f g) : injective f :=
λ a b h, option.some.inj $ ((H _ _).2 h).symm.trans ((H _ _).2 rfl)
theorem injective_of_partial_inv_right {α β} {f : α → β} {g} (H : is_partial_inv f g)
(x y b) (h₁ : b ∈ g x) (h₂ : b ∈ g y) : x = y :=
((H _ _).1 h₁).symm.trans ((H _ _).1 h₂)
theorem left_inverse.comp_eq_id {f : α → β} {g : β → α} (h : left_inverse f g) : f ∘ g = id :=
funext h
theorem right_inverse.comp_eq_id {f : α → β} {g : β → α} (h : right_inverse f g) : g ∘ f = id :=
funext h
theorem left_inverse.comp {γ} {f : α → β} {g : β → α} {h : β → γ} {i : γ → β}
(hf : left_inverse f g) (hh : left_inverse h i) : left_inverse (h ∘ f) (g ∘ i) :=
assume a, show h (f (g (i a))) = a, by rw [hf (i a), hh a]
theorem right_inverse.comp {γ} {f : α → β} {g : β → α} {h : β → γ} {i : γ → β}
(hf : right_inverse f g) (hh : right_inverse h i) : right_inverse (h ∘ f) (g ∘ i) :=
left_inverse.comp hh hf
theorem left_inverse.right_inverse {f : α → β} {g : β → α} (h : left_inverse g f) :
right_inverse f g := h
theorem right_inverse.left_inverse {f : α → β} {g : β → α} (h : right_inverse g f) :
left_inverse f g := h
theorem left_inverse.surjective {f : α → β} {g : β → α} (h : left_inverse f g) :
surjective f :=
h.right_inverse.surjective
theorem right_inverse.injective {f : α → β} {g : β → α} (h : right_inverse f g) :
injective f :=
h.left_inverse.injective
theorem left_inverse.eq_right_inverse {f : α → β} {g₁ g₂ : β → α} (h₁ : left_inverse g₁ f)
(h₂ : right_inverse g₂ f) :
g₁ = g₂ :=
calc g₁ = g₁ ∘ f ∘ g₂ : by rw [h₂.comp_eq_id, comp.right_id]
... = g₂ : by rw [← comp.assoc, h₁.comp_eq_id, comp.left_id]
local attribute [instance, priority 10] classical.prop_decidable
/-- We can use choice to construct explicitly a partial inverse for
a given injective function `f`. -/
noncomputable def partial_inv {α β} (f : α → β) (b : β) : option α :=
if h : ∃ a, f a = b then some (classical.some h) else none
theorem partial_inv_of_injective {α β} {f : α → β} (I : injective f) :
is_partial_inv f (partial_inv f) | a b :=
⟨λ h, if h' : ∃ a, f a = b then begin
rw [partial_inv, dif_pos h'] at h,
injection h with h, subst h,
apply classical.some_spec h'
end else by rw [partial_inv, dif_neg h'] at h; contradiction,
λ e, e ▸ have h : ∃ a', f a' = f a, from ⟨_, rfl⟩,
(dif_pos h).trans (congr_arg _ (I $ classical.some_spec h))⟩
theorem partial_inv_left {α β} {f : α → β} (I : injective f) : ∀ x, partial_inv f (f x) = some x :=
is_partial_inv_left (partial_inv_of_injective I)
end
section inv_fun
variables {α : Type u} [n : nonempty α] {β : Sort v} {f : α → β} {s : set α} {a : α} {b : β}
include n
local attribute [instance, priority 10] classical.prop_decidable
/-- Construct the inverse for a function `f` on domain `s`. This function is a right inverse of `f`
on `f '' s`. -/
noncomputable def inv_fun_on (f : α → β) (s : set α) (b : β) : α :=
if h : ∃a, a ∈ s ∧ f a = b then classical.some h else classical.choice n
theorem inv_fun_on_pos (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b :=
by rw [bex_def] at h; rw [inv_fun_on, dif_pos h]; exact classical.some_spec h
theorem inv_fun_on_mem (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s := (inv_fun_on_pos h).left
theorem inv_fun_on_eq (h : ∃a∈s, f a = b) : f (inv_fun_on f s b) = b := (inv_fun_on_pos h).right
theorem inv_fun_on_eq' (h : ∀ x y ∈ s, f x = f y → x = y) (ha : a ∈ s) :
inv_fun_on f s (f a) = a :=
have ∃a'∈s, f a' = f a, from ⟨a, ha, rfl⟩,
h _ _ (inv_fun_on_mem this) ha (inv_fun_on_eq this)
theorem inv_fun_on_neg (h : ¬ ∃a∈s, f a = b) : inv_fun_on f s b = classical.choice n :=
by rw [bex_def] at h; rw [inv_fun_on, dif_neg h]
/-- The inverse of a function (which is a left inverse if `f` is injective
and a right inverse if `f` is surjective). -/
noncomputable def inv_fun (f : α → β) : β → α := inv_fun_on f set.univ
theorem inv_fun_eq (h : ∃a, f a = b) : f (inv_fun f b) = b :=
inv_fun_on_eq $ let ⟨a, ha⟩ := h in ⟨a, trivial, ha⟩
lemma inv_fun_neg (h : ¬ ∃ a, f a = b) : inv_fun f b = classical.choice n :=
by refine inv_fun_on_neg (mt _ h); exact assume ⟨a, _, ha⟩, ⟨a, ha⟩
theorem inv_fun_eq_of_injective_of_right_inverse {g : β → α}
(hf : injective f) (hg : right_inverse g f) : inv_fun f = g :=
funext $ assume b,
hf begin rw [hg b], exact inv_fun_eq ⟨g b, hg b⟩ end
lemma right_inverse_inv_fun (hf : surjective f) : right_inverse (inv_fun f) f :=
assume b, inv_fun_eq $ hf b
lemma left_inverse_inv_fun (hf : injective f) : left_inverse (inv_fun f) f :=
assume b,
have f (inv_fun f (f b)) = f b,
from inv_fun_eq ⟨b, rfl⟩,
hf this
lemma inv_fun_surjective (hf : injective f) : surjective (inv_fun f) :=
(left_inverse_inv_fun hf).surjective
lemma inv_fun_comp (hf : injective f) : inv_fun f ∘ f = id := funext $ left_inverse_inv_fun hf
end inv_fun
section inv_fun
variables {α : Type u} [i : nonempty α] {β : Sort v} {f : α → β}
include i
lemma injective.has_left_inverse (hf : injective f) : has_left_inverse f :=
⟨inv_fun f, left_inverse_inv_fun hf⟩
lemma injective_iff_has_left_inverse : injective f ↔ has_left_inverse f :=
⟨injective.has_left_inverse, has_left_inverse.injective⟩
end inv_fun
section surj_inv
variables {α : Sort u} {β : Sort v} {f : α → β}
/-- The inverse of a surjective function. (Unlike `inv_fun`, this does not require
`α` to be inhabited.) -/
noncomputable def surj_inv {f : α → β} (h : surjective f) (b : β) : α := classical.some (h b)
lemma surj_inv_eq (h : surjective f) (b) : f (surj_inv h b) = b := classical.some_spec (h b)
lemma right_inverse_surj_inv (hf : surjective f) : right_inverse (surj_inv hf) f :=
surj_inv_eq hf
lemma left_inverse_surj_inv (hf : bijective f) : left_inverse (surj_inv hf.2) f :=
right_inverse_of_injective_of_left_inverse hf.1 (right_inverse_surj_inv hf.2)
lemma surjective.has_right_inverse (hf : surjective f) : has_right_inverse f :=
⟨_, right_inverse_surj_inv hf⟩
lemma surjective_iff_has_right_inverse : surjective f ↔ has_right_inverse f :=
⟨surjective.has_right_inverse, has_right_inverse.surjective⟩
lemma bijective_iff_has_inverse : bijective f ↔ ∃ g, left_inverse g f ∧ right_inverse g f :=
⟨λ hf, ⟨_, left_inverse_surj_inv hf, right_inverse_surj_inv hf.2⟩,
λ ⟨g, gl, gr⟩, ⟨gl.injective, gr.surjective⟩⟩
lemma injective_surj_inv (h : surjective f) : injective (surj_inv h) :=
(right_inverse_surj_inv h).injective
end surj_inv
section update
variables {α : Sort u} {β : α → Sort v} {α' : Sort w} [decidable_eq α] [decidable_eq α']
/-- Replacing the value of a function at a given point by a given value. -/
def update (f : Πa, β a) (a' : α) (v : β a') (a : α) : β a :=
if h : a = a' then eq.rec v h.symm else f a
@[simp] lemma update_same (a : α) (v : β a) (f : Πa, β a) : update f a v a = v :=
dif_pos rfl
@[simp] lemma update_noteq {a a' : α} (h : a ≠ a') (v : β a') (f : Πa, β a) : update f a' v a = f a :=
dif_neg h
@[simp] lemma update_eq_self (a : α) (f : Πa, β a) : update f a (f a) = f :=
begin
refine funext (λi, _),
by_cases h : i = a,
{ rw h, simp },
{ simp [h] }
end
lemma update_comp {β : Sort v} (f : α → β) {g : α' → α} (hg : injective g) (a : α') (v : β) :
(update f (g a) v) ∘ g = update (f ∘ g) a v :=
begin
refine funext (λi, _),
by_cases h : i = a,
{ rw h, simp },
{ simp [h, hg.ne] }
end
lemma comp_update {α' : Sort*} {β : Sort*} (f : α' → β) (g : α → α') (i : α) (v : α') :
f ∘ (update g i v) = update (f ∘ g) i (f v) :=
begin
refine funext (λj, _),
by_cases h : j = i,
{ rw h, simp },
{ simp [h] }
end
theorem update_comm {α} [decidable_eq α] {β : α → Sort*}
{a b : α} (h : a ≠ b) (v : β a) (w : β b) (f : Πa, β a) :
update (update f a v) b w = update (update f b w) a v :=
begin
funext c, simp [update],
by_cases h₁ : c = b; by_cases h₂ : c = a; try {simp [h₁, h₂]},
cases h (h₂.symm.trans h₁),
end
@[simp] theorem update_idem {α} [decidable_eq α] {β : α → Sort*}
{a : α} (v w : β a) (f : Πa, β a) : update (update f a v) a w = update f a w :=
by {funext b, by_cases b = a; simp [update, h]}
end update
lemma uncurry_def {α β γ} (f : α → β → γ) : uncurry f = (λp, f p.1 p.2) :=
rfl
section bicomp
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ε : Type*}
/-- Compose a binary function `f` with a pair of unary functions `g` and `h`.
If both arguments of `f` have the same type and `g = h`, then `bicompl f g g = f on g`. -/
def bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) (a b) :=
f (g a) (h b)
/-- Compose an unary function `f` with a binary function `g`. -/
def bicompr (f : γ → δ) (g : α → β → γ) (a b) :=
f (g a b)
-- Suggested local notation:
local notation f `∘₂` g := bicompr f g
lemma uncurry_bicompr (f : α → β → γ) (g : γ → δ) :
uncurry (g ∘₂ f) = (g ∘ uncurry f) := rfl
lemma uncurry_bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) :
uncurry (bicompl f g h) = (uncurry f) ∘ (prod.map g h) :=
rfl
end bicomp
/-- A function is involutive, if `f ∘ f = id`. -/
def involutive {α} (f : α → α) : Prop := ∀ x, f (f x) = x
lemma involutive_iff_iter_2_eq_id {α} {f : α → α} : involutive f ↔ (f^[2] = id) :=
funext_iff.symm
namespace involutive
variables {α : Sort u} {f : α → α} (h : involutive f)
protected lemma left_inverse : left_inverse f f := h
protected lemma right_inverse : right_inverse f f := h
protected lemma injective : injective f := h.left_inverse.injective
protected lemma surjective : surjective f := λ x, ⟨f x, h x⟩
protected lemma bijective : bijective f := ⟨h.injective, h.surjective⟩
end involutive
end function
/-- `s.piecewise f g` is the function equal to `f` on the set `s`, and to `g` on its complement. -/
def set.piecewise {α : Type u} {β : α → Sort v} (s : set α) (f g : Πi, β i) [∀j, decidable (j ∈ s)] :
Πi, β i :=
λi, if i ∈ s then f i else g i
|
43504bfc562d16bda85f5057e1a36cf0e78c9335 | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/data/list/rotate.lean | 27b8dcdbd99254f112e9fc110baef75436c60b85 | [
"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 | 21,405 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Yakov Pechersky
-/
import data.list.perm
import data.list.range
/-!
# List rotation
This file proves basic results about `list.rotate`, the list rotation.
## Main declarations
* `is_rotated l₁ l₂`: States that `l₁` is a rotated version of `l₂`.
* `cyclic_permutations l`: The list of all cyclic permutants of `l`, up to the length of `l`.
## Tags
rotated, rotation, permutation, cycle
-/
universe u
variables {α : Type u}
open nat
namespace list
lemma rotate_mod (l : list α) (n : ℕ) : l.rotate (n % l.length) = l.rotate n :=
by simp [rotate]
@[simp] lemma rotate_nil (n : ℕ) : ([] : list α).rotate n = [] := by cases n; simp [rotate]
@[simp] lemma rotate_zero (l : list α) : l.rotate 0 = l := by simp [rotate]
@[simp] lemma rotate'_nil (n : ℕ) : ([] : list α).rotate' n = [] := by cases n; refl
@[simp] lemma rotate'_zero (l : list α) : l.rotate' 0 = l := by cases l; refl
lemma rotate'_cons_succ (l : list α) (a : α) (n : ℕ) :
(a :: l : list α).rotate' n.succ = (l ++ [a]).rotate' n := by simp [rotate']
@[simp] lemma length_rotate' : ∀ (l : list α) (n : ℕ), (l.rotate' n).length = l.length
| [] n := rfl
| (a::l) 0 := rfl
| (a::l) (n+1) := by rw [list.rotate', length_rotate' (l ++ [a]) n]; simp
lemma rotate'_eq_drop_append_take : ∀ {l : list α} {n : ℕ}, n ≤ l.length →
l.rotate' n = l.drop n ++ l.take n
| [] n h := by simp [drop_append_of_le_length h]
| l 0 h := by simp [take_append_of_le_length h]
| (a::l) (n+1) h :=
have hnl : n ≤ l.length, from le_of_succ_le_succ h,
have hnl' : n ≤ (l ++ [a]).length,
by rw [length_append, length_cons, list.length, zero_add];
exact (le_of_succ_le h),
by rw [rotate'_cons_succ, rotate'_eq_drop_append_take hnl', drop, take,
drop_append_of_le_length hnl, take_append_of_le_length hnl];
simp
lemma rotate'_rotate' : ∀ (l : list α) (n m : ℕ), (l.rotate' n).rotate' m = l.rotate' (n + m)
| (a::l) 0 m := by simp
| [] n m := by simp
| (a::l) (n+1) m := by rw [rotate'_cons_succ, rotate'_rotate', add_right_comm, rotate'_cons_succ]
@[simp] lemma rotate'_length (l : list α) : rotate' l l.length = l :=
by rw rotate'_eq_drop_append_take (le_refl _); simp
@[simp] lemma rotate'_length_mul (l : list α) : ∀ n : ℕ, l.rotate' (l.length * n) = l
| 0 := by simp
| (n+1) :=
calc l.rotate' (l.length * (n + 1)) =
(l.rotate' (l.length * n)).rotate' (l.rotate' (l.length * n)).length :
by simp [-rotate'_length, nat.mul_succ, rotate'_rotate']
... = l : by rw [rotate'_length, rotate'_length_mul]
lemma rotate'_mod (l : list α) (n : ℕ) : l.rotate' (n % l.length) = l.rotate' n :=
calc l.rotate' (n % l.length) = (l.rotate' (n % l.length)).rotate'
((l.rotate' (n % l.length)).length * (n / l.length)) : by rw rotate'_length_mul
... = l.rotate' n : by rw [rotate'_rotate', length_rotate', nat.mod_add_div]
lemma rotate_eq_rotate' (l : list α) (n : ℕ) : l.rotate n = l.rotate' n :=
if h : l.length = 0 then by simp [length_eq_zero, *] at *
else by
rw [← rotate'_mod, rotate'_eq_drop_append_take (le_of_lt (nat.mod_lt _ (nat.pos_of_ne_zero h)))];
simp [rotate]
lemma rotate_cons_succ (l : list α) (a : α) (n : ℕ) :
(a :: l : list α).rotate n.succ = (l ++ [a]).rotate n :=
by rw [rotate_eq_rotate', rotate_eq_rotate', rotate'_cons_succ]
@[simp] lemma mem_rotate : ∀ {l : list α} {a : α} {n : ℕ}, a ∈ l.rotate n ↔ a ∈ l
| [] _ n := by simp
| (a::l) _ 0 := by simp
| (a::l) _ (n+1) := by simp [rotate_cons_succ, mem_rotate, or.comm]
@[simp] lemma length_rotate (l : list α) (n : ℕ) : (l.rotate n).length = l.length :=
by rw [rotate_eq_rotate', length_rotate']
lemma rotate_eq_drop_append_take {l : list α} {n : ℕ} : n ≤ l.length →
l.rotate n = l.drop n ++ l.take n :=
by rw rotate_eq_rotate'; exact rotate'_eq_drop_append_take
lemma rotate_eq_drop_append_take_mod {l : list α} {n : ℕ} :
l.rotate n = l.drop (n % l.length) ++ l.take (n % l.length) :=
begin
cases l.length.zero_le.eq_or_lt with hl hl,
{ simp [eq_nil_of_length_eq_zero hl.symm ] },
rw [←rotate_eq_drop_append_take (n.mod_lt hl).le, rotate_mod]
end
lemma rotate_rotate (l : list α) (n m : ℕ) : (l.rotate n).rotate m = l.rotate (n + m) :=
by rw [rotate_eq_rotate', rotate_eq_rotate', rotate_eq_rotate', rotate'_rotate']
@[simp] lemma rotate_length (l : list α) : rotate l l.length = l :=
by rw [rotate_eq_rotate', rotate'_length]
@[simp] lemma rotate_length_mul (l : list α) (n : ℕ) : l.rotate (l.length * n) = l :=
by rw [rotate_eq_rotate', rotate'_length_mul]
lemma prod_rotate_eq_one_of_prod_eq_one [group α] : ∀ {l : list α} (hl : l.prod = 1) (n : ℕ),
(l.rotate n).prod = 1
| [] _ _ := by simp
| (a::l) hl n :=
have n % list.length (a :: l) ≤ list.length (a :: l), from le_of_lt (nat.mod_lt _ dec_trivial),
by rw ← list.take_append_drop (n % list.length (a :: l)) (a :: l) at hl;
rw [← rotate_mod, rotate_eq_drop_append_take this, list.prod_append, mul_eq_one_iff_inv_eq,
← one_mul (list.prod _)⁻¹, ← hl, list.prod_append, mul_assoc, mul_inv_self, mul_one]
lemma rotate_perm (l : list α) (n : ℕ) : l.rotate n ~ l :=
begin
rw rotate_eq_rotate',
induction n with n hn generalizing l,
{ simp },
{ cases l with hd tl,
{ simp },
{ rw rotate'_cons_succ,
exact (hn _).trans (perm_append_singleton _ _) } }
end
@[simp] lemma nodup_rotate {l : list α} {n : ℕ} : nodup (l.rotate n) ↔ nodup l :=
(rotate_perm l n).nodup_iff
@[simp] lemma rotate_eq_nil_iff {l : list α} {n : ℕ} : l.rotate n = [] ↔ l = [] :=
begin
induction n with n hn generalizing l,
{ simp },
{ cases l with hd tl,
{ simp },
{ simp [rotate_cons_succ, hn] } }
end
@[simp] lemma nil_eq_rotate_iff {l : list α} {n : ℕ} : [] = l.rotate n ↔ [] = l :=
by rw [eq_comm, rotate_eq_nil_iff, eq_comm]
@[simp] lemma rotate_singleton (x : α) (n : ℕ) :
[x].rotate n = [x] :=
begin
induction n with n hn,
{ simp },
{ rwa [rotate_cons_succ] }
end
@[simp] lemma rotate_eq_singleton_iff {l : list α} {n : ℕ} {x : α} : l.rotate n = [x] ↔ l = [x] :=
begin
induction n with n hn generalizing l,
{ simp },
{ cases l with hd tl,
{ simp },
{ simp [rotate_cons_succ, hn, append_eq_cons_iff, and_comm] } }
end
@[simp] lemma singleton_eq_rotate_iff {l : list α} {n : ℕ} {x : α} : [x] = l.rotate n ↔ [x] = l :=
by rw [eq_comm, rotate_eq_singleton_iff, eq_comm]
lemma zip_with_rotate_distrib {α β γ : Type*} (f : α → β → γ) (l : list α) (l' : list β) (n : ℕ)
(h : l.length = l'.length) :
(zip_with f l l').rotate n = zip_with f (l.rotate n) (l'.rotate n) :=
begin
rw [rotate_eq_drop_append_take_mod, rotate_eq_drop_append_take_mod,
rotate_eq_drop_append_take_mod, h, zip_with_append, ←zip_with_distrib_drop,
←zip_with_distrib_take, list.length_zip_with, h, min_self],
rw [length_drop, length_drop, h]
end
local attribute [simp] rotate_cons_succ
@[simp] lemma zip_with_rotate_one {β : Type*} (f : α → α → β) (x y : α) (l : list α) :
zip_with f (x :: y :: l) ((x :: y :: l).rotate 1) =
f x y :: zip_with f (y :: l) (l ++ [x]) :=
by simp
lemma nth_le_rotate_one (l : list α) (k : ℕ) (hk : k < (l.rotate 1).length) :
(l.rotate 1).nth_le k hk = l.nth_le ((k + 1) % l.length)
(mod_lt _ (length_rotate l 1 ▸ k.zero_le.trans_lt hk)) :=
begin
cases l with hd tl,
{ simp },
{ have : k ≤ tl.length,
{ refine nat.le_of_lt_succ _,
simpa using hk },
rcases this.eq_or_lt with rfl|hk',
{ simp [nth_le_append_right (le_refl _)] },
{ simpa [nth_le_append _ hk', length_cons, nat.mod_eq_of_lt (nat.succ_lt_succ hk')] } }
end
lemma nth_le_rotate (l : list α) (n k : ℕ) (hk : k < (l.rotate n).length) :
(l.rotate n).nth_le k hk = l.nth_le ((k + n) % l.length)
(mod_lt _ (length_rotate l n ▸ k.zero_le.trans_lt hk)) :=
begin
induction n with n hn generalizing l k,
{ have hk' : k < l.length := by simpa using hk,
simp [nat.mod_eq_of_lt hk'] },
{ simp [nat.succ_eq_add_one, ←rotate_rotate, nth_le_rotate_one, hn l, add_comm, add_left_comm] }
end
/-- A variant of `nth_le_rotate` useful for rewrites. -/
lemma nth_le_rotate' (l : list α) (n k : ℕ) (hk : k < l.length) :
(l.rotate n).nth_le ((l.length - n % l.length + k) % l.length)
((nat.mod_lt _ (k.zero_le.trans_lt hk)).trans_le (length_rotate _ _).ge) = l.nth_le k hk :=
begin
rw nth_le_rotate,
congr,
set m := l.length,
rw [mod_add_mod, add_assoc, add_left_comm, add_comm, add_mod, add_mod _ n],
cases (n % m).zero_le.eq_or_lt with hn hn,
{ simpa [←hn] using nat.mod_eq_of_lt hk },
{ have mpos : 0 < m := k.zero_le.trans_lt hk,
have hm : m - n % m < m := nat.sub_lt_self mpos hn,
have hn' : n % m < m := nat.mod_lt _ mpos,
simpa [mod_eq_of_lt hm, nat.sub_add_cancel hn'.le] using nat.mod_eq_of_lt hk }
end
lemma rotate_injective (n : ℕ) : function.injective (λ l : list α, l.rotate n) :=
begin
rintros l l' (h : l.rotate n = l'.rotate n),
have hle : l.length = l'.length := (l.length_rotate n).symm.trans (h.symm ▸ l'.length_rotate n),
rw [rotate_eq_drop_append_take_mod, rotate_eq_drop_append_take_mod] at h,
obtain ⟨hd, ht⟩ := append_inj h _,
{ rw [←take_append_drop _ l, ht, hd, take_append_drop] },
{ rw [length_drop, length_drop, hle] }
end
-- possibly easier to find in doc-gen, otherwise not that useful.
lemma rotate_eq_rotate {l l' : list α} {n : ℕ} :
l.rotate n = l'.rotate n ↔ l = l' :=
(rotate_injective n).eq_iff
lemma rotate_eq_iff {l l' : list α} {n : ℕ} :
l.rotate n = l' ↔ l = l'.rotate (l'.length - n % l'.length) :=
begin
rw [←@rotate_eq_rotate _ l _ n, rotate_rotate, ←rotate_mod l', add_mod],
cases l'.length.zero_le.eq_or_lt with hl hl,
{ rw [eq_nil_of_length_eq_zero hl.symm, rotate_nil, rotate_eq_nil_iff] },
{ cases (nat.zero_le (n % l'.length)).eq_or_lt with hn hn,
{ simp [←hn] },
{ rw [mod_eq_of_lt (nat.sub_lt_self hl hn), nat.sub_add_cancel, mod_self, rotate_zero],
exact (nat.mod_lt _ hl).le } }
end
lemma reverse_rotate (l : list α) (n : ℕ) :
(l.rotate n).reverse = l.reverse.rotate (l.length - (n % l.length)) :=
begin
rw [←length_reverse l, ←rotate_eq_iff],
induction n with n hn generalizing l,
{ simp },
{ cases l with hd tl,
{ simp },
{ rw [rotate_cons_succ, nat.succ_eq_add_one, ←rotate_rotate, hn],
simp } }
end
lemma rotate_reverse (l : list α) (n : ℕ) :
l.reverse.rotate n = (l.rotate (l.length - (n % l.length))).reverse :=
begin
rw [←reverse_reverse l],
simp_rw [reverse_rotate, reverse_reverse, rotate_eq_iff, rotate_rotate, length_rotate,
length_reverse],
rw [←length_reverse l],
set k := n % l.reverse.length with hk,
cases hk' : k with k',
{ simp [-length_reverse, ←rotate_rotate] },
{ cases l with x l,
{ simp },
{ have : k'.succ < (x :: l).length,
{ simp [←hk', hk, nat.mod_lt] },
rw [nat.mod_eq_of_lt, nat.sub_add_cancel, rotate_length],
{ exact nat.sub_le_self _ _ },
{ exact nat.sub_lt_self (by simp) nat.succ_pos' } } }
end
lemma map_rotate {β : Type*} (f : α → β) (l : list α) (n : ℕ) :
map f (l.rotate n) = (map f l).rotate n :=
begin
induction n with n hn IH generalizing l,
{ simp },
{ cases l with hd tl,
{ simp },
{ simp [hn] } }
end
theorem nodup.rotate_eq_self_iff {l : list α} (hl : l.nodup) {n : ℕ} :
l.rotate n = l ↔ n % l.length = 0 ∨ l = [] :=
begin
split,
{ intro h,
cases l.length.zero_le.eq_or_lt with hl' hl',
{ simp [←length_eq_zero, ←hl'] },
left,
rw nodup_iff_nth_le_inj at hl,
refine hl _ _ (mod_lt _ hl') hl' _,
rw ←nth_le_rotate' _ n,
simp_rw [h, nat.sub_add_cancel (mod_lt _ hl').le, mod_self] },
{ rintro (h|h),
{ rw [←rotate_mod, h],
exact rotate_zero l },
{ simp [h] } }
end
lemma nodup.rotate_congr {l : list α} (hl : l.nodup) (hn : l ≠ []) (i j : ℕ)
(h : l.rotate i = l.rotate j) : i % l.length = j % l.length :=
begin
have hi : i % l.length < l.length := mod_lt _ (length_pos_of_ne_nil hn),
have hj : j % l.length < l.length := mod_lt _ (length_pos_of_ne_nil hn),
refine (nodup_iff_nth_le_inj.mp hl) _ _ hi hj _,
rw [←nth_le_rotate' l i, ←nth_le_rotate' l j],
simp [nat.sub_add_cancel, hi.le, hj.le, h]
end
section is_rotated
variables (l l' : list α)
/-- `is_rotated l₁ l₂` or `l₁ ~r l₂` asserts that `l₁` and `l₂` are cyclic permutations
of each other. This is defined by claiming that `∃ n, l.rotate n = l'`. -/
def is_rotated : Prop := ∃ n, l.rotate n = l'
infixr ` ~r `:1000 := is_rotated
variables {l l'}
@[refl] lemma is_rotated.refl (l : list α) : l ~r l :=
⟨0, by simp⟩
@[symm] lemma is_rotated.symm (h : l ~r l') : l' ~r l :=
begin
obtain ⟨n, rfl⟩ := h,
cases l with hd tl,
{ simp },
{ use (hd :: tl).length * n - n,
rw [rotate_rotate, nat.add_sub_cancel', rotate_length_mul],
exact nat.le_mul_of_pos_left (by simp) }
end
lemma is_rotated_comm : l ~r l' ↔ l' ~r l :=
⟨is_rotated.symm, is_rotated.symm⟩
@[simp] protected lemma is_rotated.forall (l : list α) (n : ℕ) : l.rotate n ~r l :=
is_rotated.symm ⟨n, rfl⟩
@[trans] lemma is_rotated.trans {l'' : list α} (h : l ~r l') (h' : l' ~r l'') :
l ~r l'' :=
begin
obtain ⟨n, rfl⟩ := h,
obtain ⟨m, rfl⟩ := h',
rw rotate_rotate,
use (n + m)
end
lemma is_rotated.eqv : equivalence (@is_rotated α) :=
mk_equivalence _ is_rotated.refl (λ _ _, is_rotated.symm) (λ _ _ _, is_rotated.trans)
/-- The relation `list.is_rotated l l'` forms a `setoid` of cycles. -/
def is_rotated.setoid (α : Type*) : setoid (list α) :=
{ r := is_rotated, iseqv := is_rotated.eqv }
lemma is_rotated.perm (h : l ~r l') : l ~ l' :=
exists.elim h (λ _ hl, hl ▸ (rotate_perm _ _).symm)
lemma is_rotated.nodup_iff (h : l ~r l') : nodup l ↔ nodup l' :=
h.perm.nodup_iff
lemma is_rotated.mem_iff (h : l ~r l') {a : α} : a ∈ l ↔ a ∈ l' :=
h.perm.mem_iff
@[simp] lemma is_rotated_nil_iff : l ~r [] ↔ l = [] :=
⟨λ ⟨n, hn⟩, by simpa using hn, λ h, h ▸ by refl⟩
@[simp] lemma is_rotated_nil_iff' : [] ~r l ↔ [] = l :=
by rw [is_rotated_comm, is_rotated_nil_iff, eq_comm]
@[simp] lemma is_rotated_singleton_iff {x : α} : l ~r [x] ↔ l = [x] :=
⟨λ ⟨n, hn⟩, by simpa using hn, λ h, h ▸ by refl⟩
@[simp] lemma is_rotated_singleton_iff' {x : α} : [x] ~r l ↔ [x] = l :=
by rw [is_rotated_comm, is_rotated_singleton_iff, eq_comm]
lemma is_rotated_concat (hd : α) (tl : list α) :
(tl ++ [hd]) ~r (hd :: tl) :=
is_rotated.symm ⟨1, by simp⟩
lemma is_rotated.reverse (h : l ~r l') : l.reverse ~r l'.reverse :=
begin
obtain ⟨n, rfl⟩ := h,
exact ⟨_, (reverse_rotate _ _).symm⟩
end
lemma is_rotated_reverse_comm_iff :
l.reverse ~r l' ↔ l ~r l'.reverse :=
begin
split;
{ intro h,
simpa using h.reverse }
end
@[simp] lemma is_rotated_reverse_iff :
l.reverse ~r l'.reverse ↔ l ~r l' :=
by simp [is_rotated_reverse_comm_iff]
lemma is_rotated_iff_mod : l ~r l' ↔ ∃ n ≤ l.length, l.rotate n = l' :=
begin
refine ⟨λ h, _, λ ⟨n, _, h⟩, ⟨n, h⟩⟩,
obtain ⟨n, rfl⟩ := h,
cases l with hd tl,
{ simp },
{ refine ⟨n % (hd :: tl).length, _, rotate_mod _ _⟩,
refine (nat.mod_lt _ _).le,
simp }
end
lemma is_rotated_iff_mem_map_range : l ~r l' ↔ l' ∈ (list.range (l.length + 1)).map l.rotate :=
begin
simp_rw [mem_map, mem_range, is_rotated_iff_mod],
exact ⟨λ ⟨n, hn, h⟩, ⟨n, nat.lt_succ_of_le hn, h⟩, λ ⟨n, hn, h⟩, ⟨n, nat.le_of_lt_succ hn, h⟩⟩
end
@[congr] theorem is_rotated.map {β : Type*} {l₁ l₂ : list α} (h : l₁ ~r l₂) (f : α → β) :
map f l₁ ~r map f l₂ :=
begin
obtain ⟨n, rfl⟩ := h,
rw map_rotate,
use n
end
/-- List of all cyclic permutations of `l`.
The `cyclic_permutations` of a nonempty list `l` will always contain `list.length l` elements.
This implies that under certain conditions, there are duplicates in `list.cyclic_permutations l`.
The `n`th entry is equal to `l.rotate n`, proven in `list.nth_le_cyclic_permutations`.
The proof that every cyclic permutant of `l` is in the list is `list.mem_cyclic_permutations_iff`.
cyclic_permutations [1, 2, 3, 2, 4] =
[[1, 2, 3, 2, 4], [2, 3, 2, 4, 1], [3, 2, 4, 1, 2],
[2, 4, 1, 2, 3], [4, 1, 2, 3, 2]] -/
def cyclic_permutations : list α → list (list α)
| [] := [[]]
| l@(_ :: _) := init (zip_with (++) (tails l) (inits l))
@[simp] lemma cyclic_permutations_nil : cyclic_permutations ([] : list α) = [[]] := rfl
lemma cyclic_permutations_cons (x : α) (l : list α) :
cyclic_permutations (x :: l) = init (zip_with (++) (tails (x :: l)) (inits (x :: l))) := rfl
lemma cyclic_permutations_of_ne_nil (l : list α) (h : l ≠ []) :
cyclic_permutations l = init (zip_with (++) (tails l) (inits l)) :=
begin
obtain ⟨hd, tl, rfl⟩ := exists_cons_of_ne_nil h,
exact cyclic_permutations_cons _ _,
end
lemma length_cyclic_permutations_cons (x : α) (l : list α) :
length (cyclic_permutations (x :: l)) = length l + 1 :=
by simp [cyclic_permutations_of_ne_nil]
@[simp] lemma length_cyclic_permutations_of_ne_nil (l : list α) (h : l ≠ []) :
length (cyclic_permutations l) = length l :=
by simp [cyclic_permutations_of_ne_nil _ h]
@[simp] lemma nth_le_cyclic_permutations (l : list α) (n : ℕ)
(hn : n < length (cyclic_permutations l)) :
nth_le (cyclic_permutations l) n hn = l.rotate n :=
begin
obtain rfl | h := eq_or_ne l [],
{ simp },
{ rw length_cyclic_permutations_of_ne_nil _ h at hn,
simp [init_eq_take, cyclic_permutations_of_ne_nil _ h, nth_le_take',
rotate_eq_drop_append_take hn.le] }
end
lemma mem_cyclic_permutations_self (l : list α) :
l ∈ cyclic_permutations l :=
begin
cases l with x l,
{ simp },
{ rw mem_iff_nth_le,
refine ⟨0, by simp, _⟩,
simp }
end
lemma length_mem_cyclic_permutations (l : list α) (h : l' ∈ cyclic_permutations l) :
length l' = length l :=
begin
obtain ⟨k, hk, rfl⟩ := nth_le_of_mem h,
simp
end
@[simp] lemma mem_cyclic_permutations_iff {l l' : list α} :
l ∈ cyclic_permutations l' ↔ l ~r l' :=
begin
split,
{ intro h,
obtain ⟨k, hk, rfl⟩ := nth_le_of_mem h,
simp },
{ intro h,
obtain ⟨k, rfl⟩ := h.symm,
rw mem_iff_nth_le,
simp only [exists_prop, nth_le_cyclic_permutations],
cases l' with x l,
{ simp },
{ refine ⟨k % length (x :: l), _, rotate_mod _ _⟩,
simpa using nat.mod_lt _ (zero_lt_succ _) } }
end
@[simp] lemma cyclic_permutations_eq_nil_iff {l : list α} :
cyclic_permutations l = [[]] ↔ l = [] :=
begin
refine ⟨λ h, _, λ h, by simp [h]⟩,
rw [eq_comm, ←is_rotated_nil_iff', ←mem_cyclic_permutations_iff, h, mem_singleton]
end
@[simp] lemma cyclic_permutations_eq_singleton_iff {l : list α} {x : α} :
cyclic_permutations l = [[x]] ↔ l = [x] :=
begin
refine ⟨λ h, _, λ h, by simp [cyclic_permutations, h, init_eq_take]⟩,
rw [eq_comm, ←is_rotated_singleton_iff', ←mem_cyclic_permutations_iff, h, mem_singleton]
end
/-- If a `l : list α` is `nodup l`, then all of its cyclic permutants are distinct. -/
lemma nodup.cyclic_permutations {l : list α} (hn : nodup l) :
nodup (cyclic_permutations l) :=
begin
cases l with x l,
{ simp },
rw nodup_iff_nth_le_inj,
intros i j hi hj h,
simp only [length_cyclic_permutations_cons] at hi hj,
rw [←mod_eq_of_lt hi, ←mod_eq_of_lt hj, ←length_cons x l],
apply hn.rotate_congr,
{ simp },
{ simpa using h }
end
@[simp] lemma cyclic_permutations_rotate (l : list α) (k : ℕ) :
(l.rotate k).cyclic_permutations = l.cyclic_permutations.rotate k :=
begin
have : (l.rotate k).cyclic_permutations.length = length (l.cyclic_permutations.rotate k),
{ cases l,
{ simp },
{ rw length_cyclic_permutations_of_ne_nil;
simp } },
refine ext_le this (λ n hn hn', _),
rw [nth_le_cyclic_permutations, nth_le_rotate, nth_le_cyclic_permutations,
rotate_rotate, ←rotate_mod, add_comm],
cases l;
simp
end
lemma is_rotated.cyclic_permutations {l l' : list α} (h : l ~r l') :
l.cyclic_permutations ~r l'.cyclic_permutations :=
begin
obtain ⟨k, rfl⟩ := h,
exact ⟨k, by simp⟩
end
@[simp] lemma is_rotated_cyclic_permutations_iff {l l' : list α} :
l.cyclic_permutations ~r l'.cyclic_permutations ↔ l ~r l' :=
begin
by_cases hl : l = [],
{ simp [hl, eq_comm] },
have hl' : l.cyclic_permutations.length = l.length := length_cyclic_permutations_of_ne_nil _ hl,
refine ⟨λ h, _, is_rotated.cyclic_permutations⟩,
obtain ⟨k, hk⟩ := h,
refine ⟨k % l.length, _⟩,
have hk' : k % l.length < l.length := mod_lt _ (length_pos_of_ne_nil hl),
rw [←nth_le_cyclic_permutations _ _ (hk'.trans_le hl'.ge), ←nth_le_rotate' _ k],
simp [hk, hl', nat.sub_add_cancel hk'.le]
end
section decidable
variables [decidable_eq α]
instance is_rotated_decidable (l l' : list α) : decidable (l ~r l') :=
decidable_of_iff' _ is_rotated_iff_mem_map_range
instance {l l' : list α} : decidable (@setoid.r _ (is_rotated.setoid α) l l') :=
list.is_rotated_decidable _ _
end decidable
end is_rotated
end list
|
e569c0d542e6d2562eea2f37f4d7310257a2f8b7 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/measure_theory/covering/vitali.lean | ce810149771fb3a5ca0b2358ecdc8a808bc30477 | [
"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 | 25,650 | lean | /-
Copyright (c) 2021 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import topology.metric_space.basic
import measure_theory.constructions.borel_space
/-!
# Vitali covering theorems
The topological Vitali covering theorem, in its most classical version, states the following.
Consider a family of balls `(B (x_i, r_i))_{i ∈ I}` in a metric space, with uniformly bounded
radii. Then one can extract a disjoint subfamily indexed by `J ⊆ I`, such that any `B (x_i, r_i)`
is included in a ball `B (x_j, 5 r_j)`.
We prove this theorem in `vitali.exists_disjoint_subfamily_covering_enlargment_closed_ball`.
It is deduced from a more general version, called
`vitali.exists_disjoint_subfamily_covering_enlargment`, which applies to any family of sets
together with a size function `δ` (think "radius" or "diameter").
We deduce the measurable Vitali covering theorem. Assume one is given a family `t` of closed sets
with nonempty interior, such that each `a ∈ t` is included in a ball `B (x, r)` and covers a
definite proportion of the ball `B (x, 6 r)` for a given measure `μ` (think of the situation
where `μ` is a doubling measure and `t` is a family of balls). Consider a set `s` at which the
family is fine, i.e., every point of `s` belongs to arbitrarily small elements of `t`. Then one
can extract from `t` a disjoint subfamily that covers almost all `s`. It is proved in
`vitali.exists_disjoint_covering_ae`.
-/
variables {α : Type*}
open set metric measure_theory topological_space filter
open_locale nnreal classical ennreal topological_space
namespace vitali
/-- Vitali covering theorem: given a set `t` of subsets of a type, one may extract a disjoint
subfamily `u` such that the `τ`-enlargment of this family covers all elements of `t`, where `τ > 1`
is any fixed number.
When `t` is a family of balls, the `τ`-enlargment of `ball x r` is `ball x ((1+2τ) r)`. In general,
it is expressed in terms of a function `δ` (think "radius" or "diameter"), positive and bounded on
all elements of `t`. The condition is that every element `a` of `t` should intersect an
element `b` of `u` of size larger than that of `a` up to `τ`, i.e., `δ b ≥ δ a / τ`.
-/
theorem exists_disjoint_subfamily_covering_enlargment
(t : set (set α)) (δ : set α → ℝ) (τ : ℝ) (hτ : 1 < τ) (δnonneg : ∀ a ∈ t, 0 ≤ δ a)
(R : ℝ) (δle : ∀ a ∈ t, δ a ≤ R) (hne : ∀ a ∈ t, set.nonempty a) :
∃ u ⊆ t, u.pairwise_on disjoint ∧
∀ a ∈ t, ∃ b ∈ u, set.nonempty (a ∩ b) ∧ δ a ≤ τ * δ b :=
begin
/- The proof could be formulated as a transfinite induction. First pick an element of `t` with `δ`
as large as possible (up to a factor of `τ`). Then among the remaining elements not intersecting
the already chosen one, pick another element with large `δ`. Go on forever (transfinitely) until
there is nothing left.
Instead, we give a direct Zorn-based argument. Consider a maximal family `u` of disjoint sets
with the following property: if an element `a` of `t` intersects some element `b` of `u`, then it
intersects some `b' ∈ u` with `δ b' ≥ δ a / τ`. Such a maximal family exists by Zorn. If this
family did not intersect some element `a ∈ t`, then take an element `a' ∈ t` which does not
intersect any element of `u`, with `δ a'` almost as large as possible. One checks easily
that `u ∪ {a'}` still has this property, contradicting the maximality. Therefore, `u`
intersects all elements of `t`, and by definition it satisfies all the desired properties.
-/
let T : set (set (set α)) := {u | u ⊆ t ∧ u.pairwise_on disjoint
∧ ∀ a ∈ t, ∀ b ∈ u, set.nonempty (a ∩ b) → ∃ c ∈ u, (a ∩ c).nonempty ∧ δ a ≤ τ * δ c},
-- By Zorn, choose a maximal family in the good set `T` of disjoint families.
obtain ⟨u, uT, hu⟩ : ∃ u ∈ T, ∀ v ∈ T, u ⊆ v → v = u,
{ refine zorn.zorn_subset _ (λ U UT hU, _),
refine ⟨⋃₀ U, _, λ s hs, subset_sUnion_of_mem hs⟩,
simp only [set.sUnion_subset_iff, and_imp, exists_prop, forall_exists_index,
set.mem_set_of_eq],
refine ⟨λ u hu, (UT hu).1, _, λ a hat b u uU hbu hab, _⟩,
{ rw [pairwise_on_sUnion hU.directed_on],
assume u hu,
exact (UT hu).2.1 },
{ obtain ⟨c, cu, ac, hc⟩ : ∃ (c : set α) (H : c ∈ u), (a ∩ c).nonempty ∧ δ a ≤ τ * δ c :=
(UT uU).2.2 a hat b hbu hab,
exact ⟨c, ⟨u, uU, cu⟩, ac, hc⟩ } },
-- the only nontrivial bit is to check that every `a ∈ t` intersects an element `b ∈ u` with
-- comparatively large `δ b`. Assume this is not the case, then we will contradict the maximality.
refine ⟨u, uT.1, uT.2.1, λ a hat, _⟩,
contrapose! hu,
have a_disj : ∀ c ∈ u, disjoint a c,
{ assume c hc,
by_contra,
rw not_disjoint_iff_nonempty_inter at h,
obtain ⟨d, du, ad, hd⟩ : ∃ (d : set α) (H : d ∈ u), (a ∩ d).nonempty ∧ δ a ≤ τ * δ d :=
uT.2.2 a hat c hc h,
exact lt_irrefl _ ((hu d du ad).trans_le hd) },
-- Let `A` be all the elements of `t` which do not intersect the family `u`. It is nonempty as it
-- contains `a`. We will pick an element `a'` of `A` with `δ a'` almost as large as possible.
let A := {a' | a' ∈ t ∧ ∀ c ∈ u, disjoint a' c},
have Anonempty : A.nonempty := ⟨a, hat, a_disj⟩,
let m := Sup (δ '' A),
have bddA : bdd_above (δ '' A),
{ refine ⟨R, λ x xA, _⟩,
rcases (mem_image _ _ _).1 xA with ⟨a', ha', rfl⟩,
exact δle a' ha'.1 },
obtain ⟨a', a'A, ha'⟩ : ∃ a' ∈ A, m / τ ≤ δ a',
{ have : 0 ≤ m := (δnonneg a hat).trans (le_cSup bddA (mem_image_of_mem _ ⟨hat, a_disj⟩)),
rcases eq_or_lt_of_le this with mzero|mpos,
{ refine ⟨a, ⟨hat, a_disj⟩, _⟩,
simpa only [← mzero, zero_div] using δnonneg a hat },
{ have I : m / τ < m,
{ rw div_lt_iff (zero_lt_one.trans hτ),
conv_lhs { rw ← mul_one m },
exact (mul_lt_mul_left mpos).2 hτ },
rcases exists_lt_of_lt_cSup (nonempty_image_iff.2 Anonempty) I with ⟨x, xA, hx⟩,
rcases (mem_image _ _ _).1 xA with ⟨a', ha', rfl⟩,
exact ⟨a', ha', hx.le⟩, } },
clear hat hu a_disj a,
have a'_ne_u : a' ∉ u := λ H, (hne _ a'A.1).ne_empty (disjoint_self.1 (a'A.2 _ H)),
-- we claim that `u ∪ {a'}` still belongs to `T`, contradicting the maximality of `u`.
refine ⟨insert a' u, ⟨_, _, _⟩, subset_insert _ _, (ne_insert_of_not_mem _ a'_ne_u).symm⟩,
-- check that `u ∪ {a'}` is made of elements of `t`.
{ rw insert_subset,
exact ⟨a'A.1, uT.1⟩ },
-- check that `u ∪ {a'}` is a disjoint family. This follows from the fact that `a'` does not
-- intersect `u`.
{ rw pairwise_on_insert_of_symmetric, swap,
{ simp only [function.on_fun, symmetric, disjoint.comm, imp_self, forall_const] },
exact ⟨uT.2.1, λ b bu ba', a'A.2 b bu⟩ },
-- check that every element `c` of `t` intersecting `u ∪ {a'}` intersects an element of this
-- family with large `δ`.
{ assume c ct b ba'u hcb,
-- if `c` already intersects an element of `u`, then it intersects an element of `u` with
-- large `δ` by the assumption on `u`, and there is nothing left to do.
by_cases H : ∃ d ∈ u, set.nonempty (c ∩ d),
{ rcases H with ⟨d, du, hd⟩,
rcases uT.2.2 c ct d du hd with ⟨d', d'u, hd'⟩,
exact ⟨d', mem_insert_of_mem _ d'u, hd'⟩ },
-- otherwise, `c` belongs to `A`. The element of `u ∪ {a'}` that it intersects has to be `a'`.
-- moreover, `δ c` is smaller than the maximum `m` of `δ` over `A`, which is `≤ δ a' / τ`
-- thanks to the good choice of `a'`. This is the desired inequality.
{ push_neg at H,
simp only [← not_disjoint_iff_nonempty_inter, not_not] at H,
rcases mem_insert_iff.1 ba'u with rfl|H',
{ refine ⟨b, mem_insert _ _, hcb, _⟩,
calc δ c ≤ m : le_cSup bddA (mem_image_of_mem _ ⟨ct, H⟩)
... = τ * (m / τ) : by { field_simp [(zero_lt_one.trans hτ).ne'], ring }
... ≤ τ * δ b : mul_le_mul_of_nonneg_left ha' (zero_le_one.trans hτ.le) },
{ rw ← not_disjoint_iff_nonempty_inter at hcb,
exact (hcb (H _ H')).elim } } }
end
/-- Vitali covering theorem, closed balls version: given a family `t` of closed balls, one can
extract a disjoint subfamily `u ⊆ t` so that all balls in `t` are covered by the 5-times
dilations of balls in `u`. -/
theorem exists_disjoint_subfamily_covering_enlargment_closed_ball [metric_space α]
(t : set (set α)) (R : ℝ) (ht : ∀ s ∈ t, ∃ x r, s = closed_ball x r ∧ r ≤ R) :
∃ u ⊆ t, u.pairwise_on disjoint ∧
∀ a ∈ t, ∃ x r, closed_ball x r ∈ u ∧ a ⊆ closed_ball x (5 * r) :=
begin
rcases eq_empty_or_nonempty t with rfl|tnonempty,
{ exact ⟨∅, subset.refl _, by simp⟩ },
haveI : inhabited α,
{ choose s hst using tnonempty,
choose x r hxr using ht s hst,
exact ⟨x⟩ },
-- Exclude the trivial case where `t` is reduced to the empty set.
rcases eq_or_ne t {∅} with rfl|t_ne_empty,
{ refine ⟨{∅}, subset.refl _, _⟩,
simp only [true_and, closed_ball_eq_empty, mem_singleton_iff, and_true, empty_subset, forall_eq,
pairwise_on_singleton, exists_const],
exact ⟨-1, by simp only [right.neg_neg_iff, zero_lt_one]⟩ },
-- The real proof starts now. Since the center or the radius of a ball is not uniquely defined
-- in a general metric space, we just choose one for definiteness.
choose! x r hxr using ht,
have r_nonneg : ∀ (a : set α), a ∈ t → a.nonempty → 0 ≤ r a,
{ assume a hat a_nonempty,
rw (hxr a hat).1 at a_nonempty,
simpa only [nonempty_closed_ball] using a_nonempty },
-- The difference with the generic version is that we are not excluding empty sets in our family
-- (which would correspond to `r a < 0`). To compensate for this, we apply the generic version
-- to the subfamily `t'` made of nonempty sets, and we use `δ = r` there. This gives a disjointed
-- subfamily `u'`.
let t' := {a ∈ t | 0 ≤ r a},
obtain ⟨u', u't', u'_disj, hu'⟩ : ∃ u' ⊆ t', u'.pairwise_on disjoint ∧
∀ a ∈ t', ∃ b ∈ u', set.nonempty (a ∩ b) ∧ r a ≤ 2 * r b,
{ refine exists_disjoint_subfamily_covering_enlargment t' r 2 one_lt_two
(λ a ha, ha.2) R (λ a ha, (hxr a ha.1).2) (λ a ha, _),
rw [(hxr a ha.1).1],
simp only [ha.2, nonempty_closed_ball] },
-- this subfamily is nonempty, as we have excluded the situation `t = {∅}`.
have u'_nonempty : u'.nonempty,
{ have : ∃ a ∈ t, a ≠ ∅,
{ contrapose! t_ne_empty,
apply subset.antisymm,
{ simpa only using t_ne_empty },
{ rcases tnonempty with ⟨a, hat⟩,
have := t_ne_empty a hat,
simpa only [this, singleton_subset_iff] using hat } },
rcases this with ⟨a, hat, a_nonempty⟩,
have ranonneg : 0 ≤ r a := r_nonneg a hat (ne_empty_iff_nonempty.1 a_nonempty),
rcases hu' a ⟨hat, ranonneg⟩ with ⟨b, bu', hb⟩,
exact ⟨b, bu'⟩ },
-- check that the family `u'` gives the desired disjoint covering.
refine ⟨u', λ a ha, (u't' ha).1, u'_disj, λ a hat, _⟩,
-- it remains to check that any ball in `t` is contained in the 5-dilation of a ball
-- in `u'`. This depends on whether the ball is empty of not.
rcases eq_empty_or_nonempty a with rfl|a_nonempty,
-- if the ball is empty, use any element of `u'` (since we know that `u'` is nonempty).
{ rcases u'_nonempty with ⟨b, hb⟩,
refine ⟨x b, r b, _, empty_subset _⟩,
rwa ← (hxr b (u't' hb).1).1 },
-- if the ball is not empty, it belongs to `t'`. Then it intersects a ball `a'` in `u'` with
-- controlled radius, by definition of `u'`. It is straightforward to check that this ball
-- satisfies all the desired properties.
{ have hat' : a ∈ t' := ⟨hat, r_nonneg a hat a_nonempty⟩,
obtain ⟨a', a'u', aa', raa'⟩ :
(∃ (a' : set α) (H : a' ∈ u'), (a ∩ a').nonempty ∧ r a ≤ 2 * r a') := hu' a hat',
refine ⟨x a', r a', _, _⟩,
{ convert a'u',
exact (hxr a' (u't' a'u').1).1.symm },
{ rw (hxr a hat'.1).1 at aa' ⊢,
rw (hxr a' (u't' a'u').1).1 at aa',
have : dist (x a) (x a') ≤ r a + r a' :=
dist_le_add_of_nonempty_closed_ball_inter_closed_ball aa',
apply closed_ball_subset_closed_ball',
linarith } }
end
/-- The measurable Vitali covering theorem. Assume one is given a family `t` of closed sets with
nonempty interior, such that each `a ∈ t` is included in a ball `B (x, r)` and covers a definite
proportion of the ball `B (x, 6 r)` for a given measure `μ` (think of the situation where `μ` is
a doubling measure and `t` is a family of balls). Consider a (possible non-measurable) set `s`
at which the family is fine, i.e., every point of `s` belongs to arbitrarily small elements of `t`.
Then one can extract from `t` a disjoint subfamily that covers almost all `s`. -/
theorem exists_disjoint_covering_ae [metric_space α] [measurable_space α] [opens_measurable_space α]
[second_countable_topology α]
(μ : measure α) [is_locally_finite_measure μ] (s : set α)
(t : set (set α)) (hf : ∀ x ∈ s, ∀ (ε > (0 : ℝ)), ∃ a ∈ t, x ∈ a ∧ a ⊆ closed_ball x ε)
(ht : ∀ a ∈ t, (interior a).nonempty) (h't : ∀ a ∈ t, is_closed a)
(C : ℝ≥0) (h : ∀ a ∈ t, ∃ x ∈ a, μ (closed_ball x (3 * diam a)) ≤ C * μ a) :
∃ u ⊆ t, countable u ∧ u.pairwise_on disjoint ∧ μ (s \ ⋃ (a ∈ u), a) = 0 :=
begin
/- The idea of the proof is the following. Assume for simplicity that `μ` is finite. Applying the
abstract Vitali covering theorem with `δ = diam`, one obtains a disjoint subfamily `u`, such
that any element of `t` intersects an element of `u` with comparable diameter. Fix `ε > 0`.
Since the elements of `u` have summable measure, one can remove finitely elements `w_1, ..., w_n`.
so that the measure of the remaining elements is `< ε`. Consider now a point `z` not
in the `w_i`. There is a small ball around `z` not intersecting the `w_i` (as they are closed),
an element `a ∈ t` contained in this small ball (as the family `t` is fine at `z`) and an element
`b ∈ u` intersecting `a`, with comparable diameter (by definition of `u`). Then `z` belongs to the
enlargement of `b`. This shows that `s \ (w_1 ∪ ... ∪ w_n)` is contained in
`⋃ (b ∈ u \ {w_1, ... w_n}) (enlargement of b)`. The measure of the latter set is bounded by
`∑ (b ∈ u \ {w_1, ... w_n}) C * μ b` (by the doubling property of the measure), which is at most
`C ε`. Letting `ε` tend to `0` shows that `s` is almost everywhere covered by the family `u`.
For the real argument, the measure is only locally finite. Therefore, we implement the same
strategy, but locally restricted to balls on which the measure is finite. For this, we do not
use the whole family `t`, but a subfamily `t'` supported on small balls (which is possible since
the family is assumed to be fine at every point of `s`).
-/
rcases eq_empty_or_nonempty s with rfl|nonempty,
{ refine ⟨∅, empty_subset _, countable_empty, by simp only [pairwise_on_empty],
by simp only [measure_empty, Union_false, Union_empty, diff_self]⟩ },
haveI : inhabited α,
{ choose x hx using nonempty,
exact ⟨x⟩ },
-- choose around each `x` a small ball on which the measure is finite
have : ∀ x, ∃ r, 0 < r ∧ r ≤ 1 ∧ μ (closed_ball x (20 * r)) < ∞,
{ assume x,
obtain ⟨R, Rpos, μR⟩ : ∃ (R : ℝ) (hR : 0 < R), μ (closed_ball x R) < ∞ :=
(μ.finite_at_nhds x).exists_mem_basis nhds_basis_closed_ball,
refine ⟨min 1 (R/20), _, min_le_left _ _, _⟩,
{ simp only [true_and, lt_min_iff, zero_lt_one],
linarith },
{ apply lt_of_le_of_lt (measure_mono _) μR,
apply closed_ball_subset_closed_ball,
calc 20 * min 1 (R / 20) ≤ 20 * (R/20) :
mul_le_mul_of_nonneg_left (min_le_right _ _) (by norm_num)
... = R : by ring } },
choose r hr using this,
-- we restrict to a subfamily `t'` of `t`, made of elements small enough to ensure that
-- they only see a finite part of the measure.
let t' := {a ∈ t | ∃ x, a ⊆ closed_ball x (r x)},
-- extract a disjoint subfamily `u` of `t'` thanks to the abstract Vitali covering theorem.
obtain ⟨u, ut', u_disj, hu⟩ : ∃ u ⊆ t', u.pairwise_on disjoint ∧
∀ a ∈ t', ∃ b ∈ u, set.nonempty (a ∩ b) ∧ diam a ≤ 2 * diam b,
{ have A : ∀ (a : set α), a ∈ t' → diam a ≤ 2,
{ rintros a ⟨hat, ⟨x, hax⟩⟩,
calc diam a ≤ diam (closed_ball x (r x)) : diam_mono hax bounded_closed_ball
... ≤ 2 * r x : diam_closed_ball (hr x).1.le
... ≤ 2 * 1 : mul_le_mul_of_nonneg_left (hr x).2.1 zero_le_two
... = 2 : by norm_num },
have B : ∀ (a : set α), a ∈ t' → a.nonempty :=
λ a hat', set.nonempty.mono interior_subset (ht a hat'.1),
exact exists_disjoint_subfamily_covering_enlargment t' diam 2 one_lt_two
(λ a ha, diam_nonneg) 2 A B },
have ut : u ⊆ t := λ a hau, (ut' hau).1,
-- As the space is second countable, the family is countable since all its sets have nonempty
-- interior.
have u_count : countable u :=
countable_of_nonempty_interior_of_disjoint id (λ a ha, ht a (ut ha)) u_disj,
-- the family `u` will be the desired family
refine ⟨u, λ a hat', (ut' hat').1, u_count, u_disj, _⟩,
-- it suffices to show that it covers almost all `s` locally around each point `x`.
refine null_of_locally_null _ (λ x hx, _),
-- let `v` be the subfamily of `u` made of those sets intersecting the small ball `ball x (r x)`
let v := {a ∈ u | (a ∩ ball x (r x)).nonempty },
have vu : v ⊆ u := λ a ha, ha.1,
-- they are all contained in a fixed ball of finite measure, thanks to our choice of `t'`
obtain ⟨R, μR, hR⟩ : ∃ R, μ (closed_ball x R) < ∞ ∧
∀ a ∈ u, (a ∩ ball x (r x)).nonempty → a ⊆ closed_ball x R,
{ have : ∀ a ∈ u, ∃ y, a ⊆ closed_ball y (r y) := λ a hau, (ut' hau).2,
choose! y hy using this,
have Idist_v : ∀ a ∈ v, dist (y a) x ≤ r (y a) + r x,
{ assume a hav,
apply dist_le_add_of_nonempty_closed_ball_inter_closed_ball,
exact hav.2.mono (inter_subset_inter (hy a hav.1) ball_subset_closed_ball) },
set R0 := Sup ((λ a, r (y a)) '' v) with hR0,
have R0_bdd : bdd_above ((λ a, r (y a)) '' v),
{ refine ⟨1, λ r' hr', _⟩,
rcases (mem_image _ _ _).1 hr' with ⟨b, hb, rfl⟩,
exact (hr _).2.1 },
rcases le_total R0 (r x) with H|H,
{ refine ⟨20 * r x, (hr x).2.2, λ a au hax, _⟩,
refine (hy a au).trans _,
apply closed_ball_subset_closed_ball',
have : r (y a) ≤ R0 := le_cSup R0_bdd (mem_image_of_mem _ ⟨au, hax⟩),
linarith [(hr (y a)).1.le, (hr x).1.le, Idist_v a ⟨au, hax⟩] },
{ have R0pos : 0 < R0 := (hr x).1.trans_le H,
have vnonempty : v.nonempty,
{ by_contra,
rw [← ne_empty_iff_nonempty, not_not] at h,
simp only [h, real.Sup_empty, image_empty] at hR0,
exact lt_irrefl _ (R0pos.trans_le (le_of_eq hR0)) },
obtain ⟨a, hav, R0a⟩ : ∃ a ∈ v, R0/2 < r (y a),
{ obtain ⟨r', r'mem, hr'⟩ : ∃ r' ∈ ((λ a, r (y a)) '' v), R0 / 2 < r' :=
exists_lt_of_lt_cSup (nonempty_image_iff.2 vnonempty) (half_lt_self R0pos),
rcases (mem_image _ _ _).1 r'mem with ⟨a, hav, rfl⟩,
exact ⟨a, hav, hr'⟩ },
refine ⟨8 * R0, _, _⟩,
{ apply lt_of_le_of_lt (measure_mono _) (hr (y a)).2.2,
apply closed_ball_subset_closed_ball',
rw dist_comm,
linarith [Idist_v a hav] },
{ assume b bu hbx,
refine (hy b bu).trans _,
apply closed_ball_subset_closed_ball',
have : r (y b) ≤ R0 := le_cSup R0_bdd (mem_image_of_mem _ ⟨bu, hbx⟩),
linarith [Idist_v b ⟨bu, hbx⟩] } } },
-- we will show that, in `ball x (r x)`, almost all `s` is covered by the family `u`.
refine ⟨ball x (r x), _, le_antisymm (le_of_forall_le_of_dense (λ ε εpos, _)) bot_le⟩,
{ apply mem_nhds_within_of_mem_nhds (is_open_ball.mem_nhds _),
simp only [(hr x).left, mem_ball, dist_self] },
-- the elements of `v` are disjoint and all contained in a finite volume ball, hence the sum
-- of their measures is finite.
have I : ∑' (a : v), μ a < ∞,
{ calc ∑' (a : v), μ a = μ (⋃ (a ∈ v), a) : begin
rw measure_bUnion (u_count.mono vu) _ (λ a ha, (h't _ (vu.trans ut ha)).measurable_set),
exact u_disj.mono vu
end
... ≤ μ (closed_ball x R) : measure_mono (bUnion_subset (λ a ha, hR a (vu ha) ha.2))
... < ∞ : μR },
-- we can obtain a finite subfamily of `v`, such that the measures of the remaining elements
-- add up to an arbitrarily small number, say `ε / C`.
obtain ⟨w, hw⟩ : ∃ (w : finset ↥v), ∑' (a : {a // a ∉ w}), μ a < ε / C,
{ haveI : ne_bot (at_top : filter (finset v)) := at_top_ne_bot,
have : 0 < ε / C, by simp only [ennreal.div_pos_iff, εpos.ne', ennreal.coe_ne_top, ne.def,
not_false_iff, and_self],
exact ((tendsto_order.1 (ennreal.tendsto_tsum_compl_at_top_zero I.ne)).2 _ this).exists },
choose! y hy using h,
-- main property: the points `z` of `s` which are not covered by `u` are contained in the
-- enlargements of the elements not in `w`.
have M : (s \ ⋃ (a : set α) (H : a ∈ u), a) ∩ ball x (r x)
⊆ ⋃ (a : {a // a ∉ w}), closed_ball (y a) (3 * diam (a : set α)),
{ assume z hz,
set k := ⋃ (a : v) (ha : a ∈ w), (a : set α) with hk,
have k_closed : is_closed k :=
is_closed_bUnion w.finite_to_set (λ i hi, h't _ (ut (vu i.2))),
have z_notmem_k : z ∉ k,
{ simp only [not_exists, exists_prop, mem_Union, mem_sep_eq, forall_exists_index,
set_coe.exists, not_and, exists_and_distrib_right, subtype.coe_mk],
assume b hbv h'b h'z,
have : z ∈ (s \ ⋃ (a : set α) (H : a ∈ u), a) ∩ (⋃ (a : set α) (H : a ∈ u), a) :=
mem_inter (mem_of_mem_inter_left hz) (mem_bUnion (vu hbv) h'z),
simpa only [diff_inter_self] },
-- since the elements of `w` are closed and finitely many, one can find a small ball around `z`
-- not intersecting them
have : ball x (r x) \ k ∈ 𝓝 z,
{ apply is_open.mem_nhds (is_open_ball.sdiff k_closed) _,
exact (mem_diff _).2 ⟨mem_of_mem_inter_right hz, z_notmem_k⟩ },
obtain ⟨d, dpos, hd⟩ : ∃ (d : ℝ) (dpos : 0 < d), closed_ball z d ⊆ ball x (r x) \ k :=
nhds_basis_closed_ball.mem_iff.1 this,
-- choose an element `a` of the family `t` contained in this small ball
obtain ⟨a, hat, za, ad⟩ : ∃ a ∈ t, z ∈ a ∧ a ⊆ closed_ball z d :=
hf z ((mem_diff _).1 (mem_of_mem_inter_left hz)).1 d dpos,
have ax : a ⊆ ball x (r x) := ad.trans (hd.trans (diff_subset (ball x (r x)) k)),
-- it intersects an element `b` of `u` with comparable diameter, by definition of `u`
obtain ⟨b, bu, ab, bdiam⟩ : ∃ (b : set α) (H : b ∈ u), (a ∩ b).nonempty ∧ diam a ≤ 2 * diam b :=
hu a ⟨hat, ⟨x, ax.trans ball_subset_closed_ball⟩⟩,
have bv : b ∈ v,
{ refine ⟨bu, ab.mono _⟩,
rw inter_comm,
exact inter_subset_inter_right _ ax },
let b' : v := ⟨b, bv⟩,
-- `b` can not belong to `w`, as the elements of `w` do not intersect `closed_ball z d`,
-- contrary to `b`
have b'_notmem_w : b' ∉ w,
{ assume b'w,
have b'k : (b' : set α) ⊆ k := finset.subset_set_bUnion_of_mem b'w,
have : ((ball x (r x) \ k) ∩ k).nonempty := ab.mono (inter_subset_inter (ad.trans hd) b'k),
simpa only [diff_inter_self, not_nonempty_empty] },
let b'' : {a // a ∉ w} := ⟨b', b'_notmem_w⟩,
-- since `a` and `b` have comparable diameters, it follows that `z` belongs to the
-- enlargement of `b`
have zb : z ∈ closed_ball (y b) (3 * diam b),
{ rcases ab with ⟨e, ⟨ea, eb⟩⟩,
have A : dist z e ≤ diam a := dist_le_diam_of_mem (bounded_closed_ball.mono ad) za ea,
have B : dist e (y b) ≤ diam b,
{ rcases (ut' bu).2 with ⟨c, hc⟩,
apply dist_le_diam_of_mem (bounded_closed_ball.mono hc) eb (hy b (ut bu)).1 },
simp only [mem_closed_ball],
linarith [dist_triangle z e (y b)] },
suffices H : closed_ball (y (b'' : set α)) (3 * diam (b'' : set α))
⊆ ⋃ (a : {a // a ∉ w}), closed_ball (y (a : set α)) (3 * diam (a : set α)), from H zb,
exact subset_Union (λ (a : {a // a ∉ w}), closed_ball (y a) (3 * diam (a : set α))) b'' },
-- now that we have proved our main inclusion, we can use it to estimate the measure of the points
-- in `ball x (r x)` not covered by `u`.
haveI : encodable v := (u_count.mono vu).to_encodable,
calc μ ((s \ ⋃ (a : set α) (H : a ∈ u), a) ∩ ball x (r x))
≤ μ (⋃ (a : {a // a ∉ w}), closed_ball (y a) (3 * diam (a : set α))) : measure_mono M
... ≤ ∑' (a : {a // a ∉ w}), μ (closed_ball (y a) (3 * diam (a : set α))) : measure_Union_le _
... ≤ ∑' (a : {a // a ∉ w}), C * μ a : ennreal.tsum_le_tsum (λ a, (hy a (ut (vu a.1.2))).2)
... = C * ∑' (a : {a // a ∉ w}), μ a : ennreal.tsum_mul_left
... ≤ C * (ε / C) : ennreal.mul_le_mul le_rfl hw.le
... ≤ ε : ennreal.mul_div_le,
end
end vitali
|
14664fae4a2fe1dfea8707557d45d6f7ce58e9d5 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /hott/init/trunc.hlean | 4b5ebb4e4db1cb6a108ffc4add86f282f603982e | [
"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 | 12,710 | hlean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Floris van Doorn
Definition of is_trunc (n-truncatedness)
Ported from Coq HoTT.
-/
prelude
import .nat .logic .equiv .pathover
open eq nat sigma unit sigma.ops
--set_option class.force_new true
/- Truncation levels -/
inductive trunc_index : Type₀ :=
| minus_two : trunc_index
| succ : trunc_index → trunc_index
open trunc_index
/-
notation for trunc_index is -2, -1, 0, 1, ...
from 0 and up this comes from the way numerals are parsed in Lean.
Any structure with a 0, a 1, and a + have numerals defined in them.
-/
notation `ℕ₋₂` := trunc_index -- input using \N-2
definition has_zero_trunc_index [instance] [priority 2000] : has_zero ℕ₋₂ :=
has_zero.mk (succ (succ minus_two))
definition has_one_trunc_index [instance] [priority 2000] : has_one ℕ₋₂ :=
has_one.mk (succ (succ (succ minus_two)))
namespace trunc_index
notation `-1` := trunc_index.succ trunc_index.minus_two -- ISSUE: -1 gets printed as -2.+1?
notation `-2` := trunc_index.minus_two
postfix `.+1`:(max+1) := trunc_index.succ
postfix `.+2`:(max+1) := λn, (n .+1 .+1)
--addition, where we add two to the result
definition add_plus_two [reducible] (n m : ℕ₋₂) : ℕ₋₂ :=
trunc_index.rec_on m n (λ k l, l .+1)
infix ` +2+ `:65 := trunc_index.add_plus_two
-- addition of trunc_indices, where results smaller than -2 are changed to -2
protected definition add (n m : ℕ₋₂) : ℕ₋₂ :=
trunc_index.cases_on m
(trunc_index.cases_on n -2 (λn', (trunc_index.cases_on n' -2 id)))
(λm', trunc_index.cases_on m'
(trunc_index.cases_on n -2 id)
(add_plus_two n))
/- we give a weird name to the reflexivity step to avoid overloading le.refl
(which can be used if types.trunc is imported) -/
inductive le (a : ℕ₋₂) : ℕ₋₂ → Type :=
| tr_refl : le a a
| step : Π {b}, le a b → le a (b.+1)
end trunc_index
definition has_le_trunc_index [instance] [priority 2000] : has_le ℕ₋₂ :=
has_le.mk trunc_index.le
attribute trunc_index.add [reducible]
definition has_add_trunc_index [instance] [priority 2000] : has_add ℕ₋₂ :=
has_add.mk trunc_index.add
namespace trunc_index
definition sub_two [reducible] (n : ℕ) : ℕ₋₂ :=
nat.rec_on n -2 (λ n k, k.+1)
definition add_two [reducible] (n : ℕ₋₂) : ℕ :=
trunc_index.rec_on n nat.zero (λ n k, nat.succ k)
postfix `.-2`:(max+1) := sub_two
postfix `.-1`:(max+1) := λn, (n .-2 .+1)
definition of_nat [coercion] [reducible] (n : ℕ) : ℕ₋₂ :=
n.-2.+2
definition succ_le_succ {n m : ℕ₋₂} (H : n ≤ m) : n.+1 ≤ m.+1 :=
by induction H with m H IH; apply le.tr_refl; exact le.step IH
definition minus_two_le (n : ℕ₋₂) : -2 ≤ n :=
by induction n with n IH; apply le.tr_refl; exact le.step IH
end trunc_index open trunc_index
namespace is_trunc
export [notation] [coercion] trunc_index
/- truncated types -/
/-
Just as in Coq HoTT we define an internal version of contractibility and is_trunc, but we only
use `is_trunc` and `is_contr`
-/
structure contr_internal (A : Type) :=
(center : A)
(center_eq : Π(a : A), center = a)
definition is_trunc_internal (n : ℕ₋₂) : Type → Type :=
trunc_index.rec_on n
(λA, contr_internal A)
(λn trunc_n A, (Π(x y : A), trunc_n (x = y)))
end is_trunc open is_trunc
structure is_trunc [class] (n : ℕ₋₂) (A : Type) :=
(to_internal : is_trunc_internal n A)
open nat num trunc_index
namespace is_trunc
abbreviation is_contr := is_trunc -2
abbreviation is_prop := is_trunc -1
abbreviation is_set := is_trunc 0
variables {A B : Type}
definition is_trunc_succ_intro (A : Type) (n : ℕ₋₂) [H : ∀x y : A, is_trunc n (x = y)]
: is_trunc n.+1 A :=
is_trunc.mk (λ x y, !is_trunc.to_internal)
definition is_trunc_eq [instance] [priority 1200]
(n : ℕ₋₂) [H : is_trunc (n.+1) A] (x y : A) : is_trunc n (x = y) :=
is_trunc.mk (is_trunc.to_internal (n.+1) A x y)
/- contractibility -/
definition is_contr.mk (center : A) (center_eq : Π(a : A), center = a) : is_contr A :=
is_trunc.mk (contr_internal.mk center center_eq)
definition center (A : Type) [H : is_contr A] : A :=
contr_internal.center (is_trunc.to_internal -2 A)
definition center_eq [H : is_contr A] (a : A) : !center = a :=
contr_internal.center_eq (is_trunc.to_internal -2 A) a
definition eq_of_is_contr [H : is_contr A] (x y : A) : x = y :=
(center_eq x)⁻¹ ⬝ (center_eq y)
definition prop_eq_of_is_contr {A : Type} [H : is_contr A] {x y : A} (p q : x = y) : p = q :=
have K : ∀ (r : x = y), eq_of_is_contr x y = r, from (λ r, eq.rec_on r !con.left_inv),
(K p)⁻¹ ⬝ K q
theorem is_contr_eq {A : Type} [H : is_contr A] (x y : A) : is_contr (x = y) :=
is_contr.mk !eq_of_is_contr (λ p, !prop_eq_of_is_contr)
local attribute is_contr_eq [instance]
/- truncation is upward close -/
-- n-types are also (n+1)-types
theorem is_trunc_succ [instance] [priority 900] (A : Type) (n : ℕ₋₂)
[H : is_trunc n A] : is_trunc (n.+1) A :=
trunc_index.rec_on n
(λ A (H : is_contr A), !is_trunc_succ_intro)
(λ n IH A (H : is_trunc (n.+1) A), @is_trunc_succ_intro _ _ (λ x y, IH _ _))
A H
--in the proof the type of H is given explicitly to make it available for class inference
theorem is_trunc_of_le.{l} (A : Type.{l}) {n m : ℕ₋₂} (Hnm : n ≤ m)
[Hn : is_trunc n A] : is_trunc m A :=
begin
induction Hnm with m Hnm IH,
{ exact Hn},
{ exact _}
end
definition is_trunc_of_imp_is_trunc {n : ℕ₋₂} (H : A → is_trunc (n.+1) A)
: is_trunc (n.+1) A :=
@is_trunc_succ_intro _ _ (λx y, @is_trunc_eq _ _ (H x) x y)
definition is_trunc_of_imp_is_trunc_of_le {n : ℕ₋₂} (Hn : -1 ≤ n) (H : A → is_trunc n A)
: is_trunc n A :=
begin
cases Hn with n' Hn': apply is_trunc_of_imp_is_trunc H
end
-- these must be definitions, because we need them to compute sometimes
definition is_trunc_of_is_contr (A : Type) (n : ℕ₋₂) [H : is_contr A] : is_trunc n A :=
trunc_index.rec_on n H (λn H, _)
definition is_trunc_succ_of_is_prop (A : Type) (n : ℕ₋₂) [H : is_prop A]
: is_trunc (n.+1) A :=
is_trunc_of_le A (show -1 ≤ n.+1, from succ_le_succ (minus_two_le n))
definition is_trunc_succ_succ_of_is_set (A : Type) (n : ℕ₋₂) [H : is_set A]
: is_trunc (n.+2) A :=
is_trunc_of_le A (show 0 ≤ n.+2, from succ_le_succ (succ_le_succ (minus_two_le n)))
/- props -/
definition is_prop.elim [H : is_prop A] (x y : A) : x = y :=
!center
definition is_contr_of_inhabited_prop {A : Type} [H : is_prop A] (x : A) : is_contr A :=
is_contr.mk x (λy, !is_prop.elim)
theorem is_prop_of_imp_is_contr {A : Type} (H : A → is_contr A) : is_prop A :=
@is_trunc_succ_intro A -2
(λx y,
have H2 : is_contr A, from H x,
!is_contr_eq)
theorem is_prop.mk {A : Type} (H : ∀x y : A, x = y) : is_prop A :=
is_prop_of_imp_is_contr (λ x, is_contr.mk x (H x))
theorem is_prop_elim_self {A : Type} {H : is_prop A} (x : A) : is_prop.elim x x = idp :=
!is_prop.elim
/- sets -/
theorem is_set.mk (A : Type) (H : ∀(x y : A) (p q : x = y), p = q) : is_set A :=
@is_trunc_succ_intro _ _ (λ x y, is_prop.mk (H x y))
definition is_set.elim [H : is_set A] ⦃x y : A⦄ (p q : x = y) : p = q :=
!is_prop.elim
/- instances -/
definition is_contr_sigma_eq [instance] [priority 800] {A : Type} (a : A)
: is_contr (Σ(x : A), a = x) :=
is_contr.mk (sigma.mk a idp) (λp, sigma.rec_on p (λ b q, eq.rec_on q idp))
definition is_contr_sigma_eq' [instance] [priority 800] {A : Type} (a : A)
: is_contr (Σ(x : A), x = a) :=
is_contr.mk (sigma.mk a idp) (λp, sigma.rec_on p (λ b q, eq.rec_on q idp))
definition ap_pr1_center_eq_sigma_eq {A : Type} {a x : A} (p : a = x)
: ap pr₁ (center_eq ⟨x, p⟩) = p :=
by induction p; reflexivity
definition ap_pr1_center_eq_sigma_eq' {A : Type} {a x : A} (p : x = a)
: ap pr₁ (center_eq ⟨x, p⟩) = p⁻¹ :=
by induction p; reflexivity
definition is_contr_unit : is_contr unit :=
is_contr.mk star (λp, unit.rec_on p idp)
definition is_prop_empty : is_prop empty :=
is_prop.mk (λx, !empty.elim x)
local attribute is_contr_unit is_prop_empty [instance]
definition is_trunc_unit [instance] (n : ℕ₋₂) : is_trunc n unit :=
!is_trunc_of_is_contr
definition is_trunc_empty [instance] (n : ℕ₋₂) : is_trunc (n.+1) empty :=
!is_trunc_succ_of_is_prop
/- interaction with equivalences -/
section
open is_equiv equiv
definition is_contr_is_equiv_closed (f : A → B) [Hf : is_equiv f] [HA: is_contr A]
: (is_contr B) :=
is_contr.mk (f (center A)) (λp, eq_of_eq_inv !center_eq)
definition is_contr_equiv_closed (H : A ≃ B) [HA: is_contr A] : is_contr B :=
is_contr_is_equiv_closed (to_fun H)
definition equiv_of_is_contr_of_is_contr [HA : is_contr A] [HB : is_contr B] : A ≃ B :=
equiv.mk
(λa, center B)
(is_equiv.adjointify (λa, center B) (λb, center A) center_eq center_eq)
theorem is_trunc_is_equiv_closed (n : ℕ₋₂) (f : A → B) [H : is_equiv f]
[HA : is_trunc n A] : is_trunc n B :=
begin
revert A HA B f H, induction n with n IH: intros,
{ exact is_contr_is_equiv_closed f},
{ apply is_trunc_succ_intro, intro x y,
exact IH (f⁻¹ x = f⁻¹ y) _ (x = y) (ap f⁻¹)⁻¹ !is_equiv_inv}
end
definition is_trunc_is_equiv_closed_rev (n : ℕ₋₂) (f : A → B) [H : is_equiv f]
[HA : is_trunc n B] : is_trunc n A :=
is_trunc_is_equiv_closed n f⁻¹
definition is_trunc_equiv_closed (n : ℕ₋₂) (f : A ≃ B) [HA : is_trunc n A]
: is_trunc n B :=
is_trunc_is_equiv_closed n (to_fun f)
definition is_trunc_equiv_closed_rev (n : ℕ₋₂) (f : A ≃ B) [HA : is_trunc n B]
: is_trunc n A :=
is_trunc_is_equiv_closed n (to_inv f)
definition is_equiv_of_is_prop [constructor] [HA : is_prop A] [HB : is_prop B]
(f : A → B) (g : B → A) : is_equiv f :=
is_equiv.mk f g (λb, !is_prop.elim) (λa, !is_prop.elim) (λa, !is_set.elim)
definition is_equiv_of_is_contr [constructor] [HA : is_contr A] [HB : is_contr B]
(f : A → B) : is_equiv f :=
is_equiv.mk f (λx, !center) (λb, !is_prop.elim) (λa, !is_prop.elim) (λa, !is_set.elim)
definition equiv_of_is_prop [constructor] [HA : is_prop A] [HB : is_prop B]
(f : A → B) (g : B → A) : A ≃ B :=
equiv.mk f (is_equiv_of_is_prop f g)
definition equiv_of_iff_of_is_prop [unfold 5] [HA : is_prop A] [HB : is_prop B] (H : A ↔ B) : A ≃ B :=
equiv_of_is_prop (iff.elim_left H) (iff.elim_right H)
/- truncatedness of lift -/
definition is_trunc_lift [instance] [priority 1450] (A : Type) (n : ℕ₋₂)
[H : is_trunc n A] : is_trunc n (lift A) :=
is_trunc_equiv_closed _ !equiv_lift
end
/- interaction with the Unit type -/
open equiv
/- A contractible type is equivalent to unit. -/
variable (A)
definition equiv_unit_of_is_contr [H : is_contr A] : A ≃ unit :=
equiv.MK (λ (x : A), ⋆)
(λ (u : unit), center A)
(λ (u : unit), unit.rec_on u idp)
(λ (x : A), center_eq x)
/- interaction with pathovers -/
variable {A}
variables {C : A → Type}
{a a₂ : A} (p : a = a₂)
(c : C a) (c₂ : C a₂)
definition is_prop.elimo [H : is_prop (C a)] : c =[p] c₂ :=
pathover_of_eq_tr !is_prop.elim
definition is_trunc_pathover [instance]
(n : ℕ₋₂) [H : is_trunc (n.+1) (C a)] : is_trunc n (c =[p] c₂) :=
is_trunc_equiv_closed_rev n !pathover_equiv_eq_tr
variables {p c c₂}
theorem is_set.elimo (q q' : c =[p] c₂) [H : is_set (C a)] : q = q' :=
!is_prop.elim
-- TODO: port "Truncated morphisms"
/- truncated universe -/
end is_trunc
structure trunctype (n : ℕ₋₂) :=
(carrier : Type)
(struct : is_trunc n carrier)
notation n `-Type` := trunctype n
abbreviation Prop := -1-Type
abbreviation Set := 0-Type
attribute trunctype.carrier [coercion]
attribute trunctype.struct [instance] [priority 1400]
protected abbreviation Prop.mk := @trunctype.mk -1
protected abbreviation Set.mk := @trunctype.mk (-1.+1)
protected definition trunctype.mk' [constructor] (n : ℕ₋₂) (A : Type) [H : is_trunc n A]
: n-Type :=
trunctype.mk A H
namespace is_trunc
definition tlift.{u v} [constructor] {n : ℕ₋₂} (A : trunctype.{u} n)
: trunctype.{max u v} n :=
trunctype.mk (lift A) !is_trunc_lift
end is_trunc
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.