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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0f46c9a32cc929794f65243bb1a052f43c7c74e5 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/category_theory/monoidal/of_chosen_finite_products.lean | bf8c7e579e2a8e7750061e3173db67477efb19f2 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 15,877 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Simon Hudon
-/
import category_theory.monoidal.braided
import category_theory.limits.shapes.binary_products
import category_theory.limits.shapes.terminal
import category_theory.pempty
/-!
# The monoidal structure on a category with chosen finite products.
This is a variant of the development in `category_theory.monoidal.of_has_finite_products`,
which uses specified choices of the terminal object and binary product,
enabling the construction of a cartesian category with specific definitions of the tensor unit
and tensor product.
(Because the construction in `category_theory.monoidal.of_has_finite_products` uses `has_limit`
classes, the actual definitions there are opaque behind `classical.choice`.)
We use this in `category_theory.monoidal.types` to construct the monoidal category of types
so that the tensor product is the usual cartesian product of types.
For now we only do the construction from products, and not from coproducts,
which seems less often useful.
-/
universes v u
noncomputable theory
namespace category_theory
variables (C : Type u) [category.{v} C] {X Y : C}
namespace limits
section
variables {C}
/-- Swap the two sides of a `binary_fan`. -/
def binary_fan.swap {P Q : C} (t : binary_fan P Q) : binary_fan Q P :=
binary_fan.mk t.snd t.fst
@[simp] lemma binary_fan.swap_fst {P Q : C} (t : binary_fan P Q) : t.swap.fst = t.snd := rfl
@[simp] lemma binary_fan.swap_snd {P Q : C} (t : binary_fan P Q) : t.swap.snd = t.fst := rfl
/--
If a cone `t` over `P Q` is a limit cone, then `t.swap` is a limit cone over `Q P`.
-/
@[simps]
def is_limit.swap_binary_fan {P Q : C} {t : binary_fan P Q} (I : is_limit t) : is_limit t.swap :=
{ lift := λ s, I.lift (binary_fan.swap s),
fac' := λ s, by { rintro ⟨⟩; simp, },
uniq' := λ s m w,
begin
have h := I.uniq (binary_fan.swap s) m,
rw h,
intro j,
specialize w j.swap,
cases j; exact w,
end }
/--
Construct `has_binary_product Q P` from `has_binary_product P Q`.
This can't be an instance, as it would cause a loop in typeclass search.
-/
lemma has_binary_product.swap (P Q : C) [has_binary_product P Q] : has_binary_product Q P :=
has_limit.mk ⟨binary_fan.swap (limit.cone (pair P Q)), (limit.is_limit (pair P Q)).swap_binary_fan⟩
/--
Given a limit cone over `X` and `Y`, and another limit cone over `Y` and `X`, we can construct
an isomorphism between the cone points. Relative to some fixed choice of limits cones for every pair,
these isomorphisms constitute a braiding.
-/
def binary_fan.braiding {X Y : C}
{s : binary_fan X Y} (P : is_limit s) {t : binary_fan Y X} (Q : is_limit t) :
s.X ≅ t.X :=
is_limit.cone_point_unique_up_to_iso P Q.swap_binary_fan
/--
Given binary fans `sXY` over `X Y`, and `sYZ` over `Y Z`, and `s` over `sXY.X Z`,
if `sYZ` is a limit cone we can construct a binary fan over `X sYZ.X`.
This is an ingredient of building the associator for a cartesian category.
-/
def binary_fan.assoc {X Y Z : C}
{sXY : binary_fan X Y} {sYZ : binary_fan Y Z} (Q : is_limit sYZ) (s : binary_fan sXY.X Z) :
binary_fan X sYZ.X :=
binary_fan.mk (s.fst ≫ sXY.fst) (Q.lift (binary_fan.mk (s.fst ≫ sXY.snd) s.snd))
@[simp] lemma binary_fan.assoc_fst {X Y Z : C}
{sXY : binary_fan X Y} {sYZ : binary_fan Y Z} (Q : is_limit sYZ) (s : binary_fan sXY.X Z) :
(s.assoc Q).fst = s.fst ≫ sXY.fst := rfl
@[simp] lemma binary_fan.assoc_snd {X Y Z : C}
{sXY : binary_fan X Y} {sYZ : binary_fan Y Z} (Q : is_limit sYZ) (s : binary_fan sXY.X Z) :
(s.assoc Q).snd = Q.lift (binary_fan.mk (s.fst ≫ sXY.snd) s.snd) := rfl
/--
Given binary fans `sXY` over `X Y`, and `sYZ` over `Y Z`, and `s` over `X sYZ.X`,
if `sYZ` is a limit cone we can construct a binary fan over `sXY.X Z`.
This is an ingredient of building the associator for a cartesian category.
-/
def binary_fan.assoc_inv {X Y Z : C}
{sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (s : binary_fan X sYZ.X) :
binary_fan sXY.X Z :=
binary_fan.mk (P.lift (binary_fan.mk s.fst (s.snd ≫ sYZ.fst))) (s.snd ≫ sYZ.snd)
@[simp] lemma binary_fan.assoc_inv_fst {X Y Z : C}
{sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (s : binary_fan X sYZ.X) :
(s.assoc_inv P).fst = P.lift (binary_fan.mk s.fst (s.snd ≫ sYZ.fst)) := rfl
@[simp] lemma binary_fan.assoc_inv_snd {X Y Z : C}
{sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (s : binary_fan X sYZ.X) :
(s.assoc_inv P).snd = s.snd ≫ sYZ.snd := rfl
/--
If all the binary fans involved a limit cones, `binary_fan.assoc` produces another limit cone.
-/
@[simps]
def is_limit.assoc {X Y Z : C}
{sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (Q : is_limit sYZ)
{s : binary_fan sXY.X Z} (R : is_limit s) : is_limit (s.assoc Q) :=
{ lift := λ t, R.lift (binary_fan.assoc_inv P t),
fac' := λ t,
begin
rintro ⟨⟩; simp,
apply Q.hom_ext,
rintro ⟨⟩; simp,
end,
uniq' := λ t m w,
begin
have h := R.uniq (binary_fan.assoc_inv P t) m,
rw h,
rintro ⟨⟩; simp,
apply P.hom_ext,
rintro ⟨⟩; simp,
{ exact w walking_pair.left, },
{ specialize w walking_pair.right,
simp at w,
rw [←w], simp, },
{ specialize w walking_pair.right,
simp at w,
rw [←w], simp, },
end, }
/--
Given two pairs of limit cones corresponding to the parenthesisations of `X × Y × Z`,
we obtain an isomorphism between the cone points.
-/
@[reducible]
def binary_fan.associator {X Y Z : C}
{sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (Q : is_limit sYZ)
{s : binary_fan sXY.X Z} (R : is_limit s) {t : binary_fan X sYZ.X} (S : is_limit t) :
s.X ≅ t.X :=
is_limit.cone_point_unique_up_to_iso (is_limit.assoc P Q R) S
/--
Given a fixed family of limit data for every pair `X Y`, we obtain an associator.
-/
@[reducible]
def binary_fan.associator_of_limit_cone
(L : Π X Y : C, limit_cone (pair X Y)) (X Y Z : C) :
(L (L X Y).cone.X Z).cone.X ≅ (L X (L Y Z).cone.X).cone.X :=
binary_fan.associator
(L X Y).is_limit (L Y Z).is_limit
(L (L X Y).cone.X Z).is_limit (L X (L Y Z).cone.X).is_limit
/--
Construct a left unitor from specified limit cones.
-/
@[simps]
def binary_fan.left_unitor
{X : C} {s : cone (functor.empty C)} (P : is_limit s) {t : binary_fan s.X X} (Q : is_limit t) :
t.X ≅ X :=
{ hom := t.snd,
inv := Q.lift (binary_fan.mk (P.lift { X := X, π := { app := pempty.rec _ } }) (𝟙 X) ),
hom_inv_id' := by { apply Q.hom_ext, rintro ⟨⟩, { apply P.hom_ext, rintro ⟨⟩, }, { simp, }, }, }
/--
Construct a right unitor from specified limit cones.
-/
@[simps]
def binary_fan.right_unitor
{X : C} {s : cone (functor.empty C)} (P : is_limit s) {t : binary_fan X s.X} (Q : is_limit t) :
t.X ≅ X :=
{ hom := t.fst,
inv := Q.lift (binary_fan.mk (𝟙 X) (P.lift { X := X, π := { app := pempty.rec _ } })),
hom_inv_id' := by { apply Q.hom_ext, rintro ⟨⟩, { simp, }, { apply P.hom_ext, rintro ⟨⟩, }, }, }
end
end limits
open category_theory.limits
section
local attribute [tidy] tactic.case_bash
variables {C}
variables (𝒯 : limit_cone (functor.empty C))
variables (ℬ : Π (X Y : C), limit_cone (pair X Y))
namespace monoidal_of_chosen_finite_products
/-- Implementation of the tensor product for `monoidal_of_chosen_finite_products`. -/
@[reducible]
def tensor_obj (X Y : C) : C := (ℬ X Y).cone.X
/-- Implementation of the tensor product of morphisms for `monoidal_of_chosen_finite_products`. -/
@[reducible]
def tensor_hom {W X Y Z : C} (f : W ⟶ X) (g : Y ⟶ Z) : tensor_obj ℬ W Y ⟶ tensor_obj ℬ X Z :=
(binary_fan.is_limit.lift' (ℬ X Z).is_limit
((ℬ W Y).cone.π.app walking_pair.left ≫ f)
(((ℬ W Y).cone.π.app walking_pair.right : (ℬ W Y).cone.X ⟶ Y) ≫ g)).val
lemma tensor_id (X₁ X₂ : C) : tensor_hom ℬ (𝟙 X₁) (𝟙 X₂) = 𝟙 (tensor_obj ℬ X₁ X₂) :=
begin
apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟩;
{ dsimp [tensor_hom], simp, },
end
lemma tensor_comp {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : C}
(f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂) :
tensor_hom ℬ (f₁ ≫ g₁) (f₂ ≫ g₂) =
tensor_hom ℬ f₁ f₂ ≫ tensor_hom ℬ g₁ g₂ :=
begin
apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟩;
{ dsimp [tensor_hom], simp, },
end
lemma pentagon (W X Y Z : C) :
tensor_hom ℬ (binary_fan.associator_of_limit_cone ℬ W X Y).hom (𝟙 Z) ≫
(binary_fan.associator_of_limit_cone ℬ W (tensor_obj ℬ X Y) Z).hom ≫
tensor_hom ℬ (𝟙 W) (binary_fan.associator_of_limit_cone ℬ X Y Z).hom =
(binary_fan.associator_of_limit_cone ℬ (tensor_obj ℬ W X) Y Z).hom ≫
(binary_fan.associator_of_limit_cone ℬ W X (tensor_obj ℬ Y Z)).hom :=
begin
dsimp [tensor_hom],
apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟩,
{ simp, },
{ apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟩,
{ simp, },
apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟩,
{ simp, },
{ simp, }, }
end
lemma triangle (X Y : C) :
(binary_fan.associator_of_limit_cone ℬ X 𝒯.cone.X Y).hom ≫
tensor_hom ℬ (𝟙 X) (binary_fan.left_unitor 𝒯.is_limit (ℬ 𝒯.cone.X Y).is_limit).hom =
tensor_hom ℬ (binary_fan.right_unitor 𝒯.is_limit (ℬ X 𝒯.cone.X).is_limit).hom (𝟙 Y) :=
begin
dsimp [tensor_hom],
apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟩; simp,
end
lemma left_unitor_naturality {X₁ X₂ : C} (f : X₁ ⟶ X₂) :
tensor_hom ℬ (𝟙 𝒯.cone.X) f ≫ (binary_fan.left_unitor 𝒯.is_limit (ℬ 𝒯.cone.X X₂).is_limit).hom =
(binary_fan.left_unitor 𝒯.is_limit (ℬ 𝒯.cone.X X₁).is_limit).hom ≫ f :=
begin
dsimp [tensor_hom],
simp,
end
lemma right_unitor_naturality {X₁ X₂ : C} (f : X₁ ⟶ X₂) :
tensor_hom ℬ f (𝟙 𝒯.cone.X) ≫ (binary_fan.right_unitor 𝒯.is_limit (ℬ X₂ 𝒯.cone.X).is_limit).hom =
(binary_fan.right_unitor 𝒯.is_limit (ℬ X₁ 𝒯.cone.X).is_limit).hom ≫ f :=
begin
dsimp [tensor_hom],
simp,
end
lemma associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) :
tensor_hom ℬ (tensor_hom ℬ f₁ f₂) f₃ ≫ (binary_fan.associator_of_limit_cone ℬ Y₁ Y₂ Y₃).hom =
(binary_fan.associator_of_limit_cone ℬ X₁ X₂ X₃).hom ≫ tensor_hom ℬ f₁ (tensor_hom ℬ f₂ f₃) :=
begin
dsimp [tensor_hom],
apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟩,
{ simp, },
{ apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟩,
{ simp, },
{ simp, }, },
end
end monoidal_of_chosen_finite_products
open monoidal_of_chosen_finite_products
/-- A category with a terminal object and binary products has a natural monoidal structure. -/
def monoidal_of_chosen_finite_products :
monoidal_category C :=
{ tensor_unit := 𝒯.cone.X,
tensor_obj := λ X Y, tensor_obj ℬ X Y,
tensor_hom := λ _ _ _ _ f g, tensor_hom ℬ f g,
tensor_id' := tensor_id ℬ,
tensor_comp' := λ _ _ _ _ _ _ f₁ f₂ g₁ g₂, tensor_comp ℬ f₁ f₂ g₁ g₂,
associator := λ X Y Z, binary_fan.associator_of_limit_cone ℬ X Y Z,
left_unitor := λ X, binary_fan.left_unitor (𝒯.is_limit) (ℬ 𝒯.cone.X X).is_limit,
right_unitor := λ X, binary_fan.right_unitor (𝒯.is_limit) (ℬ X 𝒯.cone.X).is_limit,
pentagon' := pentagon ℬ,
triangle' := triangle 𝒯 ℬ,
left_unitor_naturality' := λ _ _ f, left_unitor_naturality 𝒯 ℬ f,
right_unitor_naturality' := λ _ _ f, right_unitor_naturality 𝒯 ℬ f,
associator_naturality' := λ _ _ _ _ _ _ f₁ f₂ f₃, associator_naturality ℬ f₁ f₂ f₃, }
namespace monoidal_of_chosen_finite_products
open monoidal_category
/--
A type synonym for `C` carrying a monoidal category structure corresponding to
a fixed choice of limit data for the empty functor, and for `pair X Y` for every `X Y : C`.
This is an implementation detail for `symmetric_of_chosen_finite_products`.
-/
@[derive category, nolint unused_arguments has_inhabited_instance]
def monoidal_of_chosen_finite_products_synonym
(𝒯 : limit_cone (functor.empty C)) (ℬ : Π (X Y : C), limit_cone (pair X Y)):= C
instance : monoidal_category (monoidal_of_chosen_finite_products_synonym 𝒯 ℬ) :=
monoidal_of_chosen_finite_products 𝒯 ℬ
lemma braiding_naturality {X X' Y Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y') :
(tensor_hom ℬ f g) ≫ (limits.binary_fan.braiding (ℬ Y Y').is_limit (ℬ Y' Y).is_limit).hom =
(limits.binary_fan.braiding (ℬ X X').is_limit (ℬ X' X).is_limit).hom ≫ (tensor_hom ℬ g f) :=
begin
dsimp [tensor_hom, limits.binary_fan.braiding],
apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟩;
{ dsimp [limits.is_limit.cone_point_unique_up_to_iso], simp, },
end
lemma hexagon_forward (X Y Z : C) :
(binary_fan.associator_of_limit_cone ℬ X Y Z).hom ≫
(limits.binary_fan.braiding (ℬ X (tensor_obj ℬ Y Z)).is_limit (ℬ (tensor_obj ℬ Y Z) X).is_limit).hom ≫
(binary_fan.associator_of_limit_cone ℬ Y Z X).hom =
(tensor_hom ℬ (limits.binary_fan.braiding (ℬ X Y).is_limit (ℬ Y X).is_limit).hom (𝟙 Z)) ≫
(binary_fan.associator_of_limit_cone ℬ Y X Z).hom ≫
(tensor_hom ℬ (𝟙 Y) (limits.binary_fan.braiding (ℬ X Z).is_limit (ℬ Z X).is_limit).hom) :=
begin
dsimp [tensor_hom, limits.binary_fan.braiding],
apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟩,
{ dsimp [limits.is_limit.cone_point_unique_up_to_iso], simp, },
{ apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟩;
{ dsimp [limits.is_limit.cone_point_unique_up_to_iso], simp, }, }
end
lemma hexagon_reverse (X Y Z : C) :
(binary_fan.associator_of_limit_cone ℬ X Y Z).inv ≫
(limits.binary_fan.braiding (ℬ (tensor_obj ℬ X Y) Z).is_limit (ℬ Z (tensor_obj ℬ X Y)).is_limit).hom ≫
(binary_fan.associator_of_limit_cone ℬ Z X Y).inv =
(tensor_hom ℬ (𝟙 X) (limits.binary_fan.braiding (ℬ Y Z).is_limit (ℬ Z Y).is_limit).hom) ≫
(binary_fan.associator_of_limit_cone ℬ X Z Y).inv ≫
(tensor_hom ℬ (limits.binary_fan.braiding (ℬ X Z).is_limit (ℬ Z X).is_limit).hom (𝟙 Y)) :=
begin
dsimp [tensor_hom, limits.binary_fan.braiding],
apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟩,
{ apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟩;
{ dsimp [binary_fan.associator_of_limit_cone, binary_fan.associator,
limits.is_limit.cone_point_unique_up_to_iso],
simp, }, },
{ dsimp [binary_fan.associator_of_limit_cone, binary_fan.associator,
limits.is_limit.cone_point_unique_up_to_iso],
simp, },
end
lemma symmetry (X Y : C) :
(limits.binary_fan.braiding (ℬ X Y).is_limit (ℬ Y X).is_limit).hom ≫
(limits.binary_fan.braiding (ℬ Y X).is_limit (ℬ X Y).is_limit).hom =
𝟙 (tensor_obj ℬ X Y) :=
begin
dsimp [tensor_hom, limits.binary_fan.braiding],
apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟩;
{ dsimp [limits.is_limit.cone_point_unique_up_to_iso], simp, },
end
end monoidal_of_chosen_finite_products
open monoidal_of_chosen_finite_products
/--
The monoidal structure coming from finite products is symmetric.
-/
def symmetric_of_chosen_finite_products :
symmetric_category (monoidal_of_chosen_finite_products_synonym 𝒯 ℬ) :=
{ braiding := λ X Y, limits.binary_fan.braiding (ℬ _ _).is_limit (ℬ _ _).is_limit,
braiding_naturality' := λ X X' Y Y' f g, braiding_naturality ℬ f g,
hexagon_forward' := λ X Y Z, hexagon_forward ℬ X Y Z,
hexagon_reverse' := λ X Y Z, hexagon_reverse ℬ X Y Z,
symmetry' := λ X Y, symmetry ℬ X Y, }
end
end category_theory
|
aacbd146a106249ea97e8161dc02a03492c9764d | 4376c25f060c13471bb89cdb12aeac1d53e53876 | /Lean Game/world2_multiplication.lean | 2637639815214889d7caff0029107ba5bb183268 | [
"MIT"
] | permissive | RaitoBezarius/projet-maths-lean | 8fa7df563d64c256561ab71893c523fc1424b85c | 42356e980e021a20c3468f5ca1639fec01bb934f | refs/heads/master | 1,613,002,128,339 | 1,589,289,282,000 | 1,589,289,282,000 | 244,431,534 | 0 | 1 | MIT | 1,584,312,574,000 | 1,583,169,883,000 | TeX | UTF-8 | Lean | false | false | 6,247 | lean | import solutions.world1_addition -- addition lemmas
import mynat.mul
/- Here's what you get from the import:
1) The following data:
* a function called mynat.mul, and notation a * b for this function
2) The following axioms:
* `mul_zero : ∀ a : mynat, a * 0 = 0`
* `mul_succ : ∀ a b : mynat, a * succ(b) = a * b + a`
These axiom between them tell you how to work out a * x for every x; use induction on x to
reduce to the case either `x = 0` or `x = succ b`, and then use `mul_zero` or `mul_succ` appropriately.
-/
namespace mynat
--MULTIPLICATION WORLD
--Level 1 :
lemma zero_mul (m : mynat) : 0 * m = 0 :=
begin [nat_num_game]
-- On fait une induction sur m :
induction m with d hd,
-- Le cas de base :
rw mul_zero,
refl,
-- Le cas d'induction :
rw mul_succ,
rw add_zero,
rw hd,
refl,
end
--Level 2 :
lemma mul_one (m : mynat) : m * 1 = m :=
begin [nat_num_game]
-- On fait une induction sur m :
induction m with d hd,
-- Le cas de base :
rw zero_mul,
refl,
-- Le cas d'induction :
rw one_eq_succ_zero,
rw mul_succ,
rw mul_zero,
rw zero_add,
refl,
end
--Level 3 :
lemma one_mul (m : mynat) : 1 * m = m :=
begin [nat_num_game]
-- On fait une induction sur m :
induction m with d hd,
-- Le cas de base :
rw mul_zero,
refl,
-- Le cas d'induction :
rw mul_succ,
rw hd,
rw succ_eq_add_one,
refl,
end
-- mul_assoc immediately, leads to this:
-- ⊢ a * (b * d) + a * b = a * (b * d + b)
-- so let's prove mul_add first.
--Level 4 :
lemma mul_add (a b c : mynat) : a * (b + c) = a * b + a * c :=
begin [nat_num_game]
-- On fait une induction sur b :
induction c with d hd,
-- Le cas de base :
refl,
-- Le cas d'induction :
rw mul_succ,
rw ← add_assoc,
rw ← hd,
rw add_succ,
rw mul_succ,
refl,
end
-- just ignore this
def left_distrib := mul_add -- stupid field name,
-- I just don't instinctively know what left_distrib means
--Level 5 :
lemma mul_assoc (a b c : mynat) : (a * b) * c = a * (b * c) :=
begin [nat_num_game]
-- On fait une induction sur c :
induction c with d hd,
-- Le cas de base :
repeat {rw mul_zero},
-- Le cas d'induction :
repeat {rw mul_succ},
rw mul_add,
rw hd,
refl,
end
-- goal : mul_comm.
-- mul_comm leads to ⊢ a * d + a = succ d * a
-- so perhaps we need add_mul
-- but add_mul leads to either a+b+c=a+c+b or (a+b)+(c+d)=(a+c)+(b+d)
-- (depending on whether we do induction on b or c)
-- I need this for mul_comm
--Level 6 :
lemma succ_mul (a b : mynat) : succ a * b = a * b + b :=
begin [nat_num_game]
-- Attention, ne pas oublier de taper 'espace' après les '\l' !!!
-- On fait une induction sur b :
induction b with d hd,
-- Le cas de base :
refl,
-- Le cas d'induction :
rw succ_eq_add_one d,
rw mul_add,
rw hd,
rw succ_eq_add_one,
rw mul_add,
repeat {rw mul_one},
repeat {rw ← add_assoc},
rw add_assoc,
rw add_assoc (a * d) (d) (a + 1),
rw add_comm d _,
rw add_right_comm,
rw ← add_assoc (a*d) (a+d) 1,
rw ← add_assoc (a*d) a d,
refl,
end
--Level 7 :
lemma add_mul (a b c : mynat) : (a + b) * c = a * c + b * c :=
begin [nat_num_game]
-- On fait une induction sur t :
induction c with d hd,
-- Le cas de base :
refl,
-- Le cas d'induction :
repeat {rw mul_succ},
rw hd,
rw ← add_assoc,
rw ← add_assoc (a*d +a) _ _,
rw add_assoc (a*d) a _,
rw add_comm a (b*d),
rw ← add_assoc,
refl,
end
-- ignore this
def right_distrib := add_mul -- stupid field name,
--Level 8 :
lemma mul_comm (a b : mynat) : a * b = b * a :=
begin [nat_num_game]
-- On fait une induction sur b :
induction b with d hd,
-- Le cas de base :
rw zero_mul,
rw mul_zero,
refl,
-- Le cas d'induction :
rw mul_succ,
rw succ_mul,
rw hd,
refl,
end
--Level 9 :
lemma mul_left_comm (a b c : mynat) : a * (b * c) = b * (a * c) :=
begin [nat_num_game]
-- On met tout dans le bon ordre
rw ← mul_assoc,
rw mul_comm a b,
rw mul_assoc,
refl,
end
--ADVANCED MULTIPLICATION WORLD
--Level 1 :
theorem mul_pos (a b : mynat) : a ≠ 0 → b ≠ 0 → a * b ≠ 0 :=
begin [nat_num_game]
intros ha hb hab,
apply ha,
--On divise le goal en 2 cas :
cases b with n,
--Le cas 'b = 0' :
exfalso,
apply hb,
refl,
--Le cas 'b = succ n' :
rw mul_succ at hab,
rw add_left_eq_zero hab,
refl,
end
--Level 2 :
theorem eq_zero_or_eq_zero_of_mul_eq_zero ⦃a b : mynat⦄ (h : a * b = 0) : a = 0 ∨ b = 0 :=
begin [nat_num_game]
--On fait une distintion de cas sur b :
cases b with n,
--Cas 'b = 0' :
right,
refl,
--Cas 'b = succ n' :
rw mul_succ at h, --Pas strictement nécessaire car les notations sont égales par définition.
left,
apply add_left_eq_zero h,
end
--Level 3 :
theorem mul_eq_zero_iff : ∀ (a b : mynat), a * b = 0 ↔ a = 0 ∨ b = 0 :=
begin [nat_num_game]
intros a b,
--On divise le goal en 2 implications :
split,
--Sens →
intro h,
exact eq_zero_or_eq_zero_of_mul_eq_zero h,
--Sens ←
intro h,
cases h with g h,
rw g,
rw zero_mul,
refl,
rw h,
rw mul_zero,
refl,
end
instance : comm_semiring mynat := by structure_helper
--Level 4 :
theorem mul_left_cancel ⦃a b c : mynat⦄ (ha : a ≠ 0) : a * b = a * c → b = c :=
begin [nat_num_game]
-- Attention, ne pas oublier de taper 'espace' après les '\or' et '\ne'!!!
revert b,
-- On fait une induction sur c :
induction c with n hn,
--Le cas de base :
rw mul_zero,
intros b h,
rw mul_eq_zero_iff a b at h,
--On casse le ∨ :
cases h with hha hhb,
--Si 'a = 0' :
exfalso,
apply ha,
exact hha,
--Si 'b = 0' :
exact hhb,
--Le cas d'induction :
intros b h,
--On fait une distinction de cas sur b :
cases b with c,
--Cas 'b = 0' :
rw mul_zero at h,
exfalso,
apply mul_pos a (succ n), --On a besoin de démontrer les hypothèses de mul_pos :
--Hypothèse 'a ≠ 0' :
exact ha,
--Hypothèse 'succ n ≠ 0' :
intro hnn,
exact succ_ne_zero hnn,
--Retour à la preuve par l'absurde :
symmetry,
exact h,
--Cas 'b = succ c' :
repeat {rw succ_eq_add_one},
rw add_right_cancel_iff,
apply hn,
repeat {rw mul_succ at h},
rw add_right_cancel_iff at h,
exact h,
end
end mynat
|
ee544d410e3ac2c47d16e393e5360b32f1bd9b61 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/algebra/order_functions.lean | 8874d6aceae19188aedc0515a9467889f91a9771 | [
"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 | 10,582 | 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 algebra.ordered_ring
/-!
# strictly monotone functions, max, min and abs
This file proves basic properties about strictly monotone functions,
maxima and minima on a `decidable_linear_order`, and the absolute value
function on linearly ordered add_comm_groups, semirings and rings.
## Tags
min, max, abs
-/
universes u v
variables {α : Type u} {β : Type v}
attribute [simp] max_eq_left max_eq_right min_eq_left min_eq_right
section
variables [decidable_linear_order α] [decidable_linear_order β] {f : α → β} {a b c d : α}
-- translate from lattices to linear orders (sup → max, inf → min)
@[simp] lemma le_min_iff : c ≤ min a b ↔ c ≤ a ∧ c ≤ b := le_inf_iff
@[simp] lemma max_le_iff : max a b ≤ c ↔ a ≤ c ∧ b ≤ c := sup_le_iff
lemma max_le_max : a ≤ c → b ≤ d → max a b ≤ max c d := sup_le_sup
lemma min_le_min : a ≤ c → b ≤ d → min a b ≤ min c d := inf_le_inf
lemma le_max_left_of_le : a ≤ b → a ≤ max b c := le_sup_left_of_le
lemma le_max_right_of_le : a ≤ c → a ≤ max b c := le_sup_right_of_le
lemma min_le_left_of_le : a ≤ c → min a b ≤ c := inf_le_left_of_le
lemma min_le_right_of_le : b ≤ c → min a b ≤ c := inf_le_right_of_le
lemma max_min_distrib_left : max a (min b c) = min (max a b) (max a c) := sup_inf_left
lemma max_min_distrib_right : max (min a b) c = min (max a c) (max b c) := sup_inf_right
lemma min_max_distrib_left : min a (max b c) = max (min a b) (min a c) := inf_sup_left
lemma min_max_distrib_right : min (max a b) c = max (min a c) (min b c) := inf_sup_right
lemma min_le_max : min a b ≤ max a b := le_trans (min_le_left a b) (le_max_left a b)
/-- An instance asserting that `max a a = a` -/
instance max_idem : is_idempotent α max := by apply_instance -- short-circuit type class inference
/-- An instance asserting that `min a a = a` -/
instance min_idem : is_idempotent α min := by apply_instance -- short-circuit type class inference
@[simp] lemma min_le_iff : min a b ≤ c ↔ a ≤ c ∨ b ≤ c :=
have a ≤ b → (a ≤ c ∨ b ≤ c ↔ a ≤ c),
from assume h, or_iff_left_of_imp $ le_trans h,
have b ≤ a → (a ≤ c ∨ b ≤ c ↔ b ≤ c),
from assume h, or_iff_right_of_imp $ le_trans h,
by cases le_total a b; simp *
@[simp] lemma le_max_iff : a ≤ max b c ↔ a ≤ b ∨ a ≤ c :=
have b ≤ c → (a ≤ b ∨ a ≤ c ↔ a ≤ c),
from assume h, or_iff_right_of_imp $ assume h', le_trans h' h,
have c ≤ b → (a ≤ b ∨ a ≤ c ↔ a ≤ b),
from assume h, or_iff_left_of_imp $ assume h', le_trans h' h,
by cases le_total b c; simp *
@[simp] lemma max_lt_iff : max a b < c ↔ (a < c ∧ b < c) :=
by rw [lt_iff_not_ge]; simp [(≥), le_max_iff, not_or_distrib]
@[simp] lemma lt_min_iff : a < min b c ↔ (a < b ∧ a < c) :=
by rw [lt_iff_not_ge]; simp [(≥), min_le_iff, not_or_distrib]
@[simp] lemma lt_max_iff : a < max b c ↔ a < b ∨ a < c :=
by rw [lt_iff_not_ge]; simp [(≥), max_le_iff, not_and_distrib]
@[simp] lemma min_lt_iff : min a b < c ↔ a < c ∨ b < c :=
by rw [lt_iff_not_ge]; simp [(≥), le_min_iff, not_and_distrib]
lemma max_lt_max (h₁ : a < c) (h₂ : b < d) : max a b < max c d :=
by apply max_lt; simp [lt_max_iff, h₁, h₂]
lemma min_lt_min (h₁ : a < c) (h₂ : b < d) : min a b < min c d :=
by apply lt_min; simp [min_lt_iff, h₁, h₂]
theorem min_right_comm (a b c : α) : min (min a b) c = min (min a c) b :=
right_comm min min_comm min_assoc a b c
theorem max.left_comm (a b c : α) : max a (max b c) = max b (max a c) :=
left_comm max max_comm max_assoc a b c
theorem max.right_comm (a b c : α) : max (max a b) c = max (max a c) b :=
right_comm max max_comm max_assoc a b c
lemma monotone.map_max (hf : monotone f) : f (max a b) = max (f a) (f b) :=
by cases le_total a b; simp [h, hf h]
lemma monotone.map_min (hf : monotone f) : f (min a b) = min (f a) (f b) :=
by cases le_total a b; simp [h, hf h]
theorem min_choice (a b : α) : min a b = a ∨ min a b = b :=
by by_cases h : a ≤ b; simp [min, h]
theorem max_choice (a b : α) : max a b = a ∨ max a b = b :=
by by_cases h : b ≤ a; simp [max, h]
lemma le_of_max_le_left {a b c : α} (h : max a b ≤ c) : a ≤ c :=
le_trans (le_max_left _ _) h
lemma le_of_max_le_right {a b c : α} (h : max a b ≤ c) : b ≤ c :=
le_trans (le_max_right _ _) h
end
lemma min_sub {α : Type u} [decidable_linear_ordered_add_comm_group α] (a b c : α) :
min a b - c = min (a - c) (b - c) :=
by simp only [min_add_add_right, sub_eq_add_neg]
/- Some lemmas about types that have an ordering and a binary operation, with no
rules relating them. -/
@[to_additive]
lemma fn_min_mul_fn_max [decidable_linear_order α] [comm_semigroup β] (f : α → β) (n m : α) :
f (min n m) * f (max n m) = f n * f m :=
by { cases le_total n m with h h; simp [h, mul_comm] }
@[to_additive]
lemma min_mul_max [decidable_linear_order α] [comm_semigroup α] (n m : α) :
min n m * max n m = n * m :=
fn_min_mul_fn_max id n m
section decidable_linear_ordered_add_comm_group
variables [decidable_linear_ordered_add_comm_group α] {a b c : α}
attribute [simp] abs_zero abs_neg
lemma abs_add (a b : α) : abs (a + b) ≤ abs a + abs b := abs_add_le_abs_add_abs a b
theorem abs_le : abs a ≤ b ↔ - b ≤ a ∧ a ≤ b :=
⟨assume h, ⟨neg_le_of_neg_le $ le_trans (neg_le_abs_self _) h, le_trans (le_abs_self _) h⟩,
assume ⟨h₁, h₂⟩, abs_le_of_le_of_neg_le h₂ $ neg_le_of_neg_le h₁⟩
lemma abs_lt : abs a < b ↔ - b < a ∧ a < b :=
⟨assume h, ⟨neg_lt_of_neg_lt $ lt_of_le_of_lt (neg_le_abs_self _) h, lt_of_le_of_lt (le_abs_self _) h⟩,
assume ⟨h₁, h₂⟩, abs_lt_of_lt_of_neg_lt h₂ $ neg_lt_of_neg_lt h₁⟩
lemma lt_abs : a < abs b ↔ a < b ∨ a < -b := lt_max_iff
lemma abs_sub_le_iff : abs (a - b) ≤ c ↔ a - b ≤ c ∧ b - a ≤ c :=
by rw [abs_le, neg_le_sub_iff_le_add, @sub_le_iff_le_add' _ _ b, and_comm]
lemma abs_sub_lt_iff : abs (a - b) < c ↔ a - b < c ∧ b - a < c :=
by rw [abs_lt, neg_lt_sub_iff_lt_add, @sub_lt_iff_lt_add' _ _ b, and_comm]
lemma sub_abs_le_abs_sub (a b : α) : abs a - abs b ≤ abs (a - b) := abs_sub_abs_le_abs_sub a b
lemma abs_abs_sub_le_abs_sub (a b : α) : abs (abs a - abs b) ≤ abs (a - b) :=
abs_sub_le_iff.2 ⟨sub_abs_le_abs_sub _ _, by rw abs_sub; apply sub_abs_le_abs_sub⟩
lemma abs_eq (hb : 0 ≤ b) : abs a = b ↔ a = b ∨ a = -b :=
iff.intro
begin
cases le_total a 0 with a_nonpos a_nonneg,
{ rw [abs_of_nonpos a_nonpos, neg_eq_iff_neg_eq, eq_comm], exact or.inr },
{ rw [abs_of_nonneg a_nonneg, eq_comm], exact or.inl }
end
(by intro h; cases h; subst h; try { rw abs_neg }; exact abs_of_nonneg hb)
@[simp] lemma abs_eq_zero : abs a = 0 ↔ a = 0 :=
⟨eq_zero_of_abs_eq_zero, λ e, e.symm ▸ abs_zero⟩
lemma abs_pos_iff {a : α} : 0 < abs a ↔ a ≠ 0 :=
⟨λ h, mt abs_eq_zero.2 (ne_of_gt h), abs_pos_of_ne_zero⟩
@[simp] lemma abs_nonpos_iff {a : α} : abs a ≤ 0 ↔ a = 0 :=
by rw [← not_lt, abs_pos_iff, not_not]
lemma abs_le_max_abs_abs (hab : a ≤ b) (hbc : b ≤ c) : abs b ≤ max (abs a) (abs c) :=
abs_le_of_le_of_neg_le
(by simp [le_max_iff, le_trans hbc (le_abs_self c)])
(by simp [le_max_iff, le_trans (neg_le_neg hab) (neg_le_abs_self a)])
theorem abs_le_abs {α : Type*} [decidable_linear_ordered_add_comm_group α] {a b : α}
(h₀ : a ≤ b) (h₁ : -a ≤ b) :
abs a ≤ abs b :=
calc abs a
≤ b : by { apply abs_le_of_le_of_neg_le; assumption }
... ≤ abs b : le_abs_self _
lemma min_le_add_of_nonneg_right {a b : α} (hb : 0 ≤ b) : min a b ≤ a + b :=
calc
min a b ≤ a : by apply min_le_left
... ≤ a + b : le_add_of_nonneg_right hb
lemma min_le_add_of_nonneg_left {a b : α} (ha : 0 ≤ a) : min a b ≤ a + b :=
calc
min a b ≤ b : by apply min_le_right
... ≤ a + b : le_add_of_nonneg_left ha
lemma max_le_add_of_nonneg {a b : α} (ha : 0 ≤ a) (hb : 0 ≤ b) : max a b ≤ a + b :=
max_le_iff.2 (by split; simpa)
lemma max_zero_sub_eq_self (a : α) : max a 0 - max (-a) 0 = a :=
begin
rcases le_total a 0,
{ rw [max_eq_right h, max_eq_left, zero_sub, neg_neg], { rwa [le_neg, neg_zero] } },
{ rw [max_eq_left, max_eq_right, sub_zero], { rwa [neg_le, neg_zero] }, exact h }
end
lemma abs_max_sub_max_le_abs (a b c : α) : abs (max a c - max b c) ≤ abs (a - b) :=
begin
simp_rw [abs_le, le_sub_iff_add_le, sub_le_iff_le_add, ← max_add_add_left],
split; apply max_le_max; simp only [← le_sub_iff_add_le, ← sub_le_iff_le_add, sub_self, neg_le,
neg_le_abs_self, neg_zero, abs_nonneg, le_abs_self]
end
lemma max_sub_min_eq_abs' (a b : α) : max a b - min a b = abs (a - b) :=
begin
cases le_total a b with ab ba,
{ rw [max_eq_right ab, min_eq_left ab, abs_of_nonpos, neg_sub], rwa sub_nonpos },
{ rw [max_eq_left ba, min_eq_right ba, abs_of_nonneg], exact sub_nonneg_of_le ba }
end
lemma max_sub_min_eq_abs (a b : α) : max a b - min a b = abs (b - a) :=
by { rw [abs_sub], exact max_sub_min_eq_abs' _ _ }
end decidable_linear_ordered_add_comm_group
section decidable_linear_ordered_semiring
variables [decidable_linear_ordered_semiring α] {a b c d : α}
lemma mul_max_of_nonneg (b c : α) (ha : 0 ≤ a) : a * max b c = max (a * b) (a * c) :=
(monotone_mul_left_of_nonneg ha).map_max
lemma mul_min_of_nonneg (b c : α) (ha : 0 ≤ a) : a * min b c = min (a * b) (a * c) :=
(monotone_mul_left_of_nonneg ha).map_min
lemma max_mul_of_nonneg (a b : α) (hc : 0 ≤ c) : max a b * c = max (a * c) (b * c) :=
(monotone_mul_right_of_nonneg hc).map_max
lemma min_mul_of_nonneg (a b : α) (hc : 0 ≤ c) : min a b * c = min (a * c) (b * c) :=
(monotone_mul_right_of_nonneg hc).map_min
end decidable_linear_ordered_semiring
section decidable_linear_ordered_comm_ring
variables [decidable_linear_ordered_comm_ring α] {a b c d : α}
@[simp] lemma abs_one : abs (1 : α) = 1 := abs_of_pos zero_lt_one
lemma max_mul_mul_le_max_mul_max (b c : α) (ha : 0 ≤ a) (hd: 0 ≤ d) :
max (a * b) (d * c) ≤ max a c * max d b :=
have ba : b * a ≤ max d b * max c a,
from mul_le_mul (le_max_right d b) (le_max_right c a) ha (le_trans hd (le_max_left d b)),
have cd : c * d ≤ max a c * max b d,
from mul_le_mul (le_max_right a c) (le_max_right b d) hd (le_trans ha (le_max_left a c)),
max_le
(by simpa [mul_comm, max_comm] using ba)
(by simpa [mul_comm, max_comm] using cd)
end decidable_linear_ordered_comm_ring
|
1540c7fcf22392799dea3aea6a4684de667422e5 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/clifford_algebra/conjugation.lean | f25611184e923c8be8cd59e0009825660cf25bde | [
"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 | 11,094 | 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 linear_algebra.clifford_algebra.grading
import algebra.module.opposites
/-!
# Conjugations
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the grade reversal and grade involution functions on multivectors, `reverse` and
`involute`.
Together, these operations compose to form the "Clifford conjugate", hence the name of this file.
https://en.wikipedia.org/wiki/Clifford_algebra#Antiautomorphisms
## Main definitions
* `clifford_algebra.involute`: the grade involution, negating each basis vector
* `clifford_algebra.reverse`: the grade reversion, reversing the order of a product of vectors
## Main statements
* `clifford_algebra.involute_involutive`
* `clifford_algebra.reverse_involutive`
* `clifford_algebra.reverse_involute_commute`
* `clifford_algebra.involute_mem_even_odd_iff`
* `clifford_algebra.reverse_mem_even_odd_iff`
-/
variables {R : Type*} [comm_ring R]
variables {M : Type*} [add_comm_group M] [module R M]
variables {Q : quadratic_form R M}
namespace clifford_algebra
section involute
/-- Grade involution, inverting the sign of each basis vector. -/
def involute : clifford_algebra Q →ₐ[R] clifford_algebra Q :=
clifford_algebra.lift Q ⟨-(ι Q), λ m, by simp⟩
@[simp] lemma involute_ι (m : M) : involute (ι Q m) = -ι Q m :=
lift_ι_apply _ _ m
@[simp] lemma involute_comp_involute : involute.comp involute = alg_hom.id R (clifford_algebra Q) :=
by { ext, simp }
lemma involute_involutive : function.involutive (involute : _ → clifford_algebra Q) :=
alg_hom.congr_fun involute_comp_involute
@[simp] lemma involute_involute : ∀ a : clifford_algebra Q, involute (involute a) = a :=
involute_involutive
/-- `clifford_algebra.involute` as an `alg_equiv`. -/
@[simps] def involute_equiv : clifford_algebra Q ≃ₐ[R] clifford_algebra Q :=
alg_equiv.of_alg_hom involute involute
(alg_hom.ext $ involute_involute) (alg_hom.ext $ involute_involute)
end involute
section reverse
open mul_opposite
/-- Grade reversion, inverting the multiplication order of basis vectors.
Also called *transpose* in some literature. -/
def reverse : clifford_algebra Q →ₗ[R] clifford_algebra Q :=
(op_linear_equiv R).symm.to_linear_map.comp (
clifford_algebra.lift Q ⟨(mul_opposite.op_linear_equiv R).to_linear_map.comp (ι Q),
λ m, unop_injective $ by simp⟩).to_linear_map
@[simp] lemma reverse_ι (m : M) : reverse (ι Q m) = ι Q m :=
by simp [reverse]
@[simp] lemma reverse.commutes (r : R) :
reverse (algebra_map R (clifford_algebra Q) r) = algebra_map R _ r :=
by simp [reverse]
@[simp] lemma reverse.map_one : reverse (1 : clifford_algebra Q) = 1 :=
by convert reverse.commutes (1 : R); simp
@[simp] lemma reverse.map_mul (a b : clifford_algebra Q) :
reverse (a * b) = reverse b * reverse a :=
by simp [reverse]
@[simp] lemma reverse_comp_reverse :
reverse.comp reverse = (linear_map.id : _ →ₗ[R] clifford_algebra Q) :=
begin
ext m,
simp only [linear_map.id_apply, linear_map.comp_apply],
induction m using clifford_algebra.induction,
-- simp can close these goals, but is slow
case h_grade0 : { rw [reverse.commutes, reverse.commutes] },
case h_grade1 : { rw [reverse_ι, reverse_ι] },
case h_mul : a b ha hb { rw [reverse.map_mul, reverse.map_mul, ha, hb], },
case h_add : a b ha hb { rw [reverse.map_add, reverse.map_add, ha, hb], },
end
@[simp] lemma reverse_involutive : function.involutive (reverse : _ → clifford_algebra Q) :=
linear_map.congr_fun reverse_comp_reverse
@[simp] lemma reverse_reverse : ∀ a : clifford_algebra Q, reverse (reverse a) = a :=
reverse_involutive
/-- `clifford_algebra.reverse` as a `linear_equiv`. -/
@[simps] def reverse_equiv : clifford_algebra Q ≃ₗ[R] clifford_algebra Q :=
linear_equiv.of_involutive reverse reverse_involutive
lemma reverse_comp_involute :
reverse.comp involute.to_linear_map =
(involute.to_linear_map.comp reverse : _ →ₗ[R] clifford_algebra Q) :=
begin
ext,
simp only [linear_map.comp_apply, alg_hom.to_linear_map_apply],
induction x using clifford_algebra.induction,
case h_grade0 : { simp },
case h_grade1 : { simp },
case h_mul : a b ha hb { simp only [ha, hb, reverse.map_mul, alg_hom.map_mul], },
case h_add : a b ha hb { simp only [ha, hb, reverse.map_add, alg_hom.map_add], },
end
/-- `clifford_algebra.reverse` and `clifford_algebra.inverse` commute. Note that the composition
is sometimes referred to as the "clifford conjugate". -/
lemma reverse_involute_commute : function.commute (reverse : _ → clifford_algebra Q) involute :=
linear_map.congr_fun reverse_comp_involute
lemma reverse_involute : ∀ a : clifford_algebra Q, reverse (involute a) = involute (reverse a) :=
reverse_involute_commute
end reverse
/-!
### Statements about conjugations of products of lists
-/
section list
/-- Taking the reverse of the product a list of $n$ vectors lifted via `ι` is equivalent to
taking the product of the reverse of that list. -/
lemma reverse_prod_map_ι : ∀ (l : list M), reverse (l.map $ ι Q).prod = (l.map $ ι Q).reverse.prod
| [] := by simp
| (x :: xs) := by simp [reverse_prod_map_ι xs]
/-- Taking the involute of the product a list of $n$ vectors lifted via `ι` is equivalent to
premultiplying by ${-1}^n$. -/
lemma involute_prod_map_ι : ∀ l : list M,
involute (l.map $ ι Q).prod = ((-1 : R)^l.length) • (l.map $ ι Q).prod
| [] := by simp
| (x :: xs) := by simp [pow_add, involute_prod_map_ι xs]
end list
/-!
### Statements about `submodule.map` and `submodule.comap`
-/
section submodule
variables (Q)
section involute
lemma submodule_map_involute_eq_comap (p : submodule R (clifford_algebra Q)) :
p.map (involute : clifford_algebra Q →ₐ[R] clifford_algebra Q).to_linear_map
= p.comap (involute : clifford_algebra Q →ₐ[R] clifford_algebra Q).to_linear_map :=
(submodule.map_equiv_eq_comap_symm involute_equiv.to_linear_equiv _)
@[simp] lemma ι_range_map_involute :
(ι Q).range.map (involute : clifford_algebra Q →ₐ[R] clifford_algebra Q).to_linear_map
= (ι Q).range :=
(ι_range_map_lift _ _).trans (linear_map.range_neg _)
@[simp] lemma ι_range_comap_involute :
(ι Q).range.comap (involute : clifford_algebra Q →ₐ[R] clifford_algebra Q).to_linear_map
= (ι Q).range :=
by rw [←submodule_map_involute_eq_comap, ι_range_map_involute]
@[simp] lemma even_odd_map_involute (n : zmod 2) :
(even_odd Q n).map (involute : clifford_algebra Q →ₐ[R] clifford_algebra Q).to_linear_map
= (even_odd Q n) :=
by simp_rw [even_odd, submodule.map_supr, submodule.map_pow, ι_range_map_involute]
@[simp] lemma even_odd_comap_involute (n : zmod 2) :
(even_odd Q n).comap (involute : clifford_algebra Q →ₐ[R] clifford_algebra Q).to_linear_map
= even_odd Q n :=
by rw [←submodule_map_involute_eq_comap, even_odd_map_involute]
end involute
section reverse
lemma submodule_map_reverse_eq_comap (p : submodule R (clifford_algebra Q)) :
p.map (reverse : clifford_algebra Q →ₗ[R] clifford_algebra Q)
= p.comap (reverse : clifford_algebra Q →ₗ[R] clifford_algebra Q):=
(submodule.map_equiv_eq_comap_symm (reverse_equiv : _ ≃ₗ[R] _) _)
@[simp] lemma ι_range_map_reverse :
(ι Q).range.map (reverse : clifford_algebra Q →ₗ[R] clifford_algebra Q) = (ι Q).range :=
begin
rw [reverse, submodule.map_comp, ι_range_map_lift, linear_map.range_comp, ←submodule.map_comp],
exact submodule.map_id _,
end
@[simp] lemma ι_range_comap_reverse :
(ι Q).range.comap (reverse : clifford_algebra Q →ₗ[R] clifford_algebra Q) = (ι Q).range :=
by rw [←submodule_map_reverse_eq_comap, ι_range_map_reverse]
/-- Like `submodule.map_mul`, but with the multiplication reversed. -/
lemma submodule_map_mul_reverse (p q : submodule R (clifford_algebra Q)) :
(p * q).map (reverse : clifford_algebra Q →ₗ[R] clifford_algebra Q)
= q.map (reverse : clifford_algebra Q →ₗ[R] clifford_algebra Q)
* p.map (reverse : clifford_algebra Q →ₗ[R] clifford_algebra Q) :=
by simp_rw [reverse, submodule.map_comp, linear_equiv.to_linear_map_eq_coe, submodule.map_mul,
submodule.map_unop_mul]
lemma submodule_comap_mul_reverse (p q : submodule R (clifford_algebra Q)) :
(p * q).comap (reverse : clifford_algebra Q →ₗ[R] clifford_algebra Q)
= q.comap (reverse : clifford_algebra Q →ₗ[R] clifford_algebra Q)
* p.comap (reverse : clifford_algebra Q →ₗ[R] clifford_algebra Q) :=
by simp_rw [←submodule_map_reverse_eq_comap, submodule_map_mul_reverse]
/-- Like `submodule.map_pow` -/
lemma submodule_map_pow_reverse (p : submodule R (clifford_algebra Q)) (n : ℕ) :
(p ^ n).map (reverse : clifford_algebra Q →ₗ[R] clifford_algebra Q)
= p.map (reverse : clifford_algebra Q →ₗ[R] clifford_algebra Q) ^ n :=
by simp_rw [reverse, submodule.map_comp, linear_equiv.to_linear_map_eq_coe, submodule.map_pow,
submodule.map_unop_pow]
lemma submodule_comap_pow_reverse (p : submodule R (clifford_algebra Q)) (n : ℕ) :
(p ^ n).comap (reverse : clifford_algebra Q →ₗ[R] clifford_algebra Q)
= p.comap (reverse : clifford_algebra Q →ₗ[R] clifford_algebra Q) ^ n :=
by simp_rw [←submodule_map_reverse_eq_comap, submodule_map_pow_reverse]
@[simp] lemma even_odd_map_reverse (n : zmod 2) :
(even_odd Q n).map (reverse : clifford_algebra Q →ₗ[R] clifford_algebra Q) = even_odd Q n :=
by simp_rw [even_odd, submodule.map_supr, submodule_map_pow_reverse, ι_range_map_reverse]
@[simp] lemma even_odd_comap_reverse (n : zmod 2) :
(even_odd Q n).comap (reverse : clifford_algebra Q →ₗ[R] clifford_algebra Q) = even_odd Q n :=
by rw [←submodule_map_reverse_eq_comap, even_odd_map_reverse]
end reverse
@[simp] lemma involute_mem_even_odd_iff {x : clifford_algebra Q} {n : zmod 2} :
involute x ∈ even_odd Q n ↔ x ∈ even_odd Q n :=
set_like.ext_iff.mp (even_odd_comap_involute Q n) x
@[simp] lemma reverse_mem_even_odd_iff {x : clifford_algebra Q} {n : zmod 2} :
reverse x ∈ even_odd Q n ↔ x ∈ even_odd Q n :=
set_like.ext_iff.mp (even_odd_comap_reverse Q n) x
end submodule
/-!
### Related properties of the even and odd submodules
TODO: show that these are `iff`s when `invertible (2 : R)`.
-/
lemma involute_eq_of_mem_even {x : clifford_algebra Q} (h : x ∈ even_odd Q 0) :
involute x = x :=
begin
refine even_induction Q (alg_hom.commutes _) _ _ x h,
{ rintros x y hx hy ihx ihy,
rw [map_add, ihx, ihy]},
{ intros m₁ m₂ x hx ihx,
rw [map_mul, map_mul, involute_ι, involute_ι, ihx, neg_mul_neg], },
end
lemma involute_eq_of_mem_odd {x : clifford_algebra Q} (h : x ∈ even_odd Q 1) :
involute x = -x :=
begin
refine odd_induction Q involute_ι _ _ x h,
{ rintros x y hx hy ihx ihy,
rw [map_add, ihx, ihy, neg_add] },
{ intros m₁ m₂ x hx ihx,
rw [map_mul, map_mul, involute_ι, involute_ι, ihx, neg_mul_neg, mul_neg] },
end
end clifford_algebra
|
71e2e43aba3f32a155a9704dcfc9c815c679e446 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/analysis/special_functions/gamma.lean | fd7163e6326af4916fc1154c404dd62a0a721b64 | [
"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 | 69,460 | lean | /-
Copyright (c) 2022 David Loeffler. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Loeffler
-/
import measure_theory.integral.exp_decay
import analysis.special_functions.improper_integrals
import analysis.convolution
import analysis.special_functions.trigonometric.euler_sine_prod
/-!
# The Gamma and Beta functions
This file defines the `Γ` function (of a real or complex variable `s`). We define this by Euler's
integral `Γ(s) = ∫ x in Ioi 0, exp (-x) * x ^ (s - 1)` in the range where this integral converges
(i.e., for `0 < s` in the real case, and `0 < re s` in the complex case).
We show that this integral satisfies `Γ(1) = 1` and `Γ(s + 1) = s * Γ(s)`; hence we can define
`Γ(s)` for all `s` as the unique function satisfying this recurrence and agreeing with Euler's
integral in the convergence range. (If `s = -n` for `n ∈ ℕ`, then the function is undefined, and we
set it to be `0` by convention.)
## Gamma function: main statements (complex case)
* `complex.Gamma`: the `Γ` function (of a complex variable).
* `complex.Gamma_eq_integral`: for `0 < re s`, `Γ(s)` agrees with Euler's integral.
* `complex.Gamma_add_one`: for all `s : ℂ` with `s ≠ 0`, we have `Γ (s + 1) = s Γ(s)`.
* `complex.Gamma_nat_eq_factorial`: for all `n : ℕ` we have `Γ (n + 1) = n!`.
* `complex.differentiable_at_Gamma`: `Γ` is complex-differentiable at all `s : ℂ` with
`s ∉ {-n : n ∈ ℕ}`.
* `complex.Gamma_ne_zero`: for all `s : ℂ` with `s ∉ {-n : n ∈ ℕ}` we have `Γ s ≠ 0`.
* `complex.Gamma_seq_tendsto_Gamma`: for all `s`, the limit as `n → ∞` of the sequence
`n ↦ n ^ s * n! / (s * (s + 1) * ... * (s + n))` is `Γ(s)`.
* `complex.Gamma_mul_Gamma_one_sub`: Euler's reflection formula
`Gamma s * Gamma (1 - s) = π / sin π s`.
## Gamma function: main statements (real case)
* `real.Gamma`: the `Γ` function (of a real variable).
* Real counterparts of all the properties of the complex Gamma function listed above:
`real.Gamma_eq_integral`, `real.Gamma_add_one`, `real.Gamma_nat_eq_factorial`,
`real.differentiable_at_Gamma`, `real.Gamma_ne_zero`, `real.Gamma_seq_tendsto_Gamma`,
`real.Gamma_mul_Gamma_one_sub`.
* `real.convex_on_log_Gamma` : `log ∘ Γ` is convex on `Ioi 0`.
* `real.eq_Gamma_of_log_convex` : the Bohr-Mollerup theorem, which states that the `Γ` function is
the unique log-convex, positive-valued function on `Ioi 0` satisfying the functional equation
and having `Γ 1 = 1`.
## Beta function
* `complex.beta_integral`: the Beta function `Β(u, v)`, where `u`, `v` are complex with positive
real part.
* `complex.Gamma_mul_Gamma_eq_beta_integral`: the formula
`Gamma u * Gamma v = Gamma (u + v) * beta_integral u v`.
## Tags
Gamma
-/
noncomputable theory
open filter interval_integral set real measure_theory asymptotics
open_locale nat topology ennreal big_operators complex_conjugate
namespace real
/-- Asymptotic bound for the `Γ` function integrand. -/
lemma Gamma_integrand_is_o (s : ℝ) :
(λ x:ℝ, exp (-x) * x ^ s) =o[at_top] (λ x:ℝ, exp (-(1/2) * x)) :=
begin
refine is_o_of_tendsto (λ x hx, _) _,
{ exfalso, exact (exp_pos (-(1 / 2) * x)).ne' hx },
have : (λ (x:ℝ), exp (-x) * x ^ s / exp (-(1 / 2) * x)) = (λ (x:ℝ), exp ((1 / 2) * x) / x ^ s )⁻¹,
{ ext1 x,
field_simp [exp_ne_zero, exp_neg, ← real.exp_add],
left,
ring },
rw this,
exact (tendsto_exp_mul_div_rpow_at_top s (1 / 2) one_half_pos).inv_tendsto_at_top,
end
/-- The Euler integral for the `Γ` function converges for positive real `s`. -/
lemma Gamma_integral_convergent {s : ℝ} (h : 0 < s) :
integrable_on (λ x:ℝ, exp (-x) * x ^ (s - 1)) (Ioi 0) :=
begin
rw [←Ioc_union_Ioi_eq_Ioi (@zero_le_one ℝ _ _ _ _), integrable_on_union],
split,
{ rw ←integrable_on_Icc_iff_integrable_on_Ioc,
refine integrable_on.continuous_on_mul continuous_on_id.neg.exp _ is_compact_Icc,
refine (interval_integrable_iff_integrable_Icc_of_le zero_le_one).mp _,
exact interval_integrable_rpow' (by linarith), },
{ refine integrable_of_is_O_exp_neg one_half_pos _ (Gamma_integrand_is_o _ ).is_O,
refine continuous_on_id.neg.exp.mul (continuous_on_id.rpow_const _),
intros x hx,
exact or.inl ((zero_lt_one : (0 : ℝ) < 1).trans_le hx).ne' }
end
end real
namespace complex
/- Technical note: In defining the Gamma integrand exp (-x) * x ^ (s - 1) for s complex, we have to
make a choice between ↑(real.exp (-x)), complex.exp (↑(-x)), and complex.exp (-↑x), all of which are
equal but not definitionally so. We use the first of these throughout. -/
/-- The integral defining the `Γ` function converges for complex `s` with `0 < re s`.
This is proved by reduction to the real case. -/
lemma Gamma_integral_convergent {s : ℂ} (hs : 0 < s.re) :
integrable_on (λ x, (-x).exp * x ^ (s - 1) : ℝ → ℂ) (Ioi 0) :=
begin
split,
{ refine continuous_on.ae_strongly_measurable _ measurable_set_Ioi,
apply (continuous_of_real.comp continuous_neg.exp).continuous_on.mul,
apply continuous_at.continuous_on,
intros x hx,
have : continuous_at (λ x:ℂ, x ^ (s - 1)) ↑x,
{ apply continuous_at_cpow_const, rw of_real_re, exact or.inl hx, },
exact continuous_at.comp this continuous_of_real.continuous_at },
{ rw ←has_finite_integral_norm_iff,
refine has_finite_integral.congr (real.Gamma_integral_convergent hs).2 _,
refine (ae_restrict_iff' measurable_set_Ioi).mpr (ae_of_all _ (λ x hx, _)),
dsimp only,
rw [norm_eq_abs, map_mul, abs_of_nonneg $ le_of_lt $ exp_pos $ -x,
abs_cpow_eq_rpow_re_of_pos hx _],
simp }
end
/-- Euler's integral for the `Γ` function (of a complex variable `s`), defined as
`∫ x in Ioi 0, exp (-x) * x ^ (s - 1)`.
See `complex.Gamma_integral_convergent` for a proof of the convergence of the integral for
`0 < re s`. -/
def Gamma_integral (s : ℂ) : ℂ := ∫ x in Ioi (0:ℝ), ↑(-x).exp * ↑x ^ (s - 1)
lemma Gamma_integral_conj (s : ℂ) : Gamma_integral (conj s) = conj (Gamma_integral s) :=
begin
rw [Gamma_integral, Gamma_integral, ←integral_conj],
refine set_integral_congr measurable_set_Ioi (λ x hx, _),
dsimp only,
rw [ring_hom.map_mul, conj_of_real, cpow_def_of_ne_zero (of_real_ne_zero.mpr (ne_of_gt hx)),
cpow_def_of_ne_zero (of_real_ne_zero.mpr (ne_of_gt hx)), ←exp_conj, ring_hom.map_mul,
←of_real_log (le_of_lt hx), conj_of_real, ring_hom.map_sub, ring_hom.map_one],
end
lemma Gamma_integral_of_real (s : ℝ) :
Gamma_integral ↑s = ↑(∫ x:ℝ in Ioi 0, real.exp (-x) * x ^ (s - 1)) :=
begin
rw [Gamma_integral, ←_root_.integral_of_real],
refine set_integral_congr measurable_set_Ioi _,
intros x hx, dsimp only,
rw [of_real_mul, of_real_cpow (mem_Ioi.mp hx).le],
simp,
end
lemma Gamma_integral_one : Gamma_integral 1 = 1 :=
by simpa only [←of_real_one, Gamma_integral_of_real, of_real_inj, sub_self,
rpow_zero, mul_one] using integral_exp_neg_Ioi_zero
end complex
/-! Now we establish the recurrence relation `Γ(s + 1) = s * Γ(s)` using integration by parts. -/
namespace complex
section Gamma_recurrence
/-- The indefinite version of the `Γ` function, `Γ(s, X) = ∫ x ∈ 0..X, exp(-x) x ^ (s - 1)`. -/
def partial_Gamma (s : ℂ) (X : ℝ) : ℂ := ∫ x in 0..X, (-x).exp * x ^ (s - 1)
lemma tendsto_partial_Gamma {s : ℂ} (hs: 0 < s.re) :
tendsto (λ X:ℝ, partial_Gamma s X) at_top (𝓝 $ Gamma_integral s) :=
interval_integral_tendsto_integral_Ioi 0 (Gamma_integral_convergent hs) tendsto_id
private lemma Gamma_integrand_interval_integrable (s : ℂ) {X : ℝ} (hs : 0 < s.re) (hX : 0 ≤ X):
interval_integrable (λ x, (-x).exp * x ^ (s - 1) : ℝ → ℂ) volume 0 X :=
begin
rw interval_integrable_iff_integrable_Ioc_of_le hX,
exact integrable_on.mono_set (Gamma_integral_convergent hs) Ioc_subset_Ioi_self
end
private lemma Gamma_integrand_deriv_integrable_A {s : ℂ} (hs : 0 < s.re) {X : ℝ} (hX : 0 ≤ X):
interval_integrable (λ x, -((-x).exp * x ^ s) : ℝ → ℂ) volume 0 X :=
begin
convert (Gamma_integrand_interval_integrable (s+1) _ hX).neg,
{ ext1, simp only [add_sub_cancel, pi.neg_apply] },
{ simp only [add_re, one_re], linarith,},
end
private lemma Gamma_integrand_deriv_integrable_B {s : ℂ} (hs : 0 < s.re) {Y : ℝ} (hY : 0 ≤ Y) :
interval_integrable (λ (x : ℝ), (-x).exp * (s * x ^ (s - 1)) : ℝ → ℂ) volume 0 Y :=
begin
have : (λ x, (-x).exp * (s * x ^ (s - 1)) : ℝ → ℂ) =
(λ x, s * ((-x).exp * x ^ (s - 1)) : ℝ → ℂ),
{ ext1, ring, },
rw [this, interval_integrable_iff_integrable_Ioc_of_le hY],
split,
{ refine (continuous_on_const.mul _).ae_strongly_measurable measurable_set_Ioc,
apply (continuous_of_real.comp continuous_neg.exp).continuous_on.mul,
apply continuous_at.continuous_on,
intros x hx,
refine (_ : continuous_at (λ x:ℂ, x ^ (s - 1)) _).comp continuous_of_real.continuous_at,
apply continuous_at_cpow_const, rw of_real_re, exact or.inl hx.1, },
rw ←has_finite_integral_norm_iff,
simp_rw [norm_eq_abs, map_mul],
refine (((real.Gamma_integral_convergent hs).mono_set
Ioc_subset_Ioi_self).has_finite_integral.congr _).const_mul _,
rw [eventually_eq, ae_restrict_iff'],
{ apply ae_of_all, intros x hx,
rw [abs_of_nonneg (exp_pos _).le,abs_cpow_eq_rpow_re_of_pos hx.1],
simp },
{ exact measurable_set_Ioc},
end
/-- The recurrence relation for the indefinite version of the `Γ` function. -/
lemma partial_Gamma_add_one {s : ℂ} (hs: 0 < s.re) {X : ℝ} (hX : 0 ≤ X) :
partial_Gamma (s + 1) X = s * partial_Gamma s X - (-X).exp * X ^ s :=
begin
rw [partial_Gamma, partial_Gamma, add_sub_cancel],
have F_der_I: (∀ (x:ℝ), (x ∈ Ioo 0 X) → has_deriv_at (λ x, (-x).exp * x ^ s : ℝ → ℂ)
( -((-x).exp * x ^ s) + (-x).exp * (s * x ^ (s - 1))) x),
{ intros x hx,
have d1 : has_deriv_at (λ (y: ℝ), (-y).exp) (-(-x).exp) x,
{ simpa using (has_deriv_at_neg x).exp },
have d2 : has_deriv_at (λ (y : ℝ), ↑y ^ s) (s * x ^ (s - 1)) x,
{ have t := @has_deriv_at.cpow_const _ _ _ s (has_deriv_at_id ↑x) _,
simpa only [mul_one] using t.comp_of_real,
simpa only [id.def, of_real_re, of_real_im,
ne.def, eq_self_iff_true, not_true, or_false, mul_one] using hx.1, },
simpa only [of_real_neg, neg_mul] using d1.of_real_comp.mul d2 },
have cont := (continuous_of_real.comp continuous_neg.exp).mul
(continuous_of_real_cpow_const hs),
have der_ible := (Gamma_integrand_deriv_integrable_A hs hX).add
(Gamma_integrand_deriv_integrable_B hs hX),
have int_eval := integral_eq_sub_of_has_deriv_at_of_le hX cont.continuous_on F_der_I der_ible,
-- We are basically done here but manipulating the output into the right form is fiddly.
apply_fun (λ x:ℂ, -x) at int_eval,
rw [interval_integral.integral_add (Gamma_integrand_deriv_integrable_A hs hX)
(Gamma_integrand_deriv_integrable_B hs hX), interval_integral.integral_neg, neg_add, neg_neg]
at int_eval,
rw [eq_sub_of_add_eq int_eval, sub_neg_eq_add, neg_sub, add_comm, add_sub],
simp only [sub_left_inj, add_left_inj],
have : (λ x, (-x).exp * (s * x ^ (s - 1)) : ℝ → ℂ) = (λ x, s * (-x).exp * x ^ (s - 1) : ℝ → ℂ),
{ ext1, ring,},
rw this,
have t := @integral_const_mul 0 X volume _ _ s (λ x:ℝ, (-x).exp * x ^ (s - 1)),
dsimp at t, rw [←t, of_real_zero, zero_cpow],
{ rw [mul_zero, add_zero], congr', ext1, ring },
{ contrapose! hs, rw [hs, zero_re] }
end
/-- The recurrence relation for the `Γ` integral. -/
theorem Gamma_integral_add_one {s : ℂ} (hs: 0 < s.re) :
Gamma_integral (s + 1) = s * Gamma_integral s :=
begin
suffices : tendsto (s+1).partial_Gamma at_top (𝓝 $ s * Gamma_integral s),
{ refine tendsto_nhds_unique _ this,
apply tendsto_partial_Gamma, rw [add_re, one_re], linarith, },
have : (λ X:ℝ, s * partial_Gamma s X - X ^ s * (-X).exp) =ᶠ[at_top] (s+1).partial_Gamma,
{ apply eventually_eq_of_mem (Ici_mem_at_top (0:ℝ)),
intros X hX,
rw partial_Gamma_add_one hs (mem_Ici.mp hX),
ring_nf, },
refine tendsto.congr' this _,
suffices : tendsto (λ X, -X ^ s * (-X).exp : ℝ → ℂ) at_top (𝓝 0),
{ simpa using tendsto.add (tendsto.const_mul s (tendsto_partial_Gamma hs)) this },
rw tendsto_zero_iff_norm_tendsto_zero,
have : (λ (e : ℝ), ‖-(e:ℂ) ^ s * (-e).exp‖ ) =ᶠ[at_top] (λ (e : ℝ), e ^ s.re * (-1 * e).exp ),
{ refine eventually_eq_of_mem (Ioi_mem_at_top 0) _,
intros x hx, dsimp only,
rw [norm_eq_abs, map_mul, abs.map_neg, abs_cpow_eq_rpow_re_of_pos hx,
abs_of_nonneg (exp_pos(-x)).le, neg_mul, one_mul],},
exact (tendsto_congr' this).mpr (tendsto_rpow_mul_exp_neg_mul_at_top_nhds_0 _ _ zero_lt_one),
end
end Gamma_recurrence
/-! Now we define `Γ(s)` on the whole complex plane, by recursion. -/
section Gamma_def
/-- The `n`th function in this family is `Γ(s)` if `-n < s.re`, and junk otherwise. -/
noncomputable def Gamma_aux : ℕ → (ℂ → ℂ)
| 0 := Gamma_integral
| (n+1) := λ s:ℂ, (Gamma_aux n (s+1)) / s
lemma Gamma_aux_recurrence1 (s : ℂ) (n : ℕ) (h1 : -s.re < ↑n) :
Gamma_aux n s = Gamma_aux n (s+1) / s :=
begin
induction n with n hn generalizing s,
{ simp only [nat.cast_zero, neg_lt_zero] at h1,
dsimp only [Gamma_aux], rw Gamma_integral_add_one h1,
rw [mul_comm, mul_div_cancel], contrapose! h1, rw h1,
simp },
{ dsimp only [Gamma_aux],
have hh1 : -(s+1).re < n,
{ rw [nat.succ_eq_add_one, nat.cast_add, nat.cast_one] at h1,
rw [add_re, one_re], linarith, },
rw ←(hn (s+1) hh1) }
end
lemma Gamma_aux_recurrence2 (s : ℂ) (n : ℕ) (h1 : -s.re < ↑n) :
Gamma_aux n s = Gamma_aux (n+1) s :=
begin
cases n,
{ simp only [nat.cast_zero, neg_lt_zero] at h1,
dsimp only [Gamma_aux],
rw [Gamma_integral_add_one h1, mul_div_cancel_left],
rintro rfl,
rw [zero_re] at h1,
exact h1.false },
{ dsimp only [Gamma_aux],
have : (Gamma_aux n (s + 1 + 1)) / (s+1) = Gamma_aux n (s + 1),
{ have hh1 : -(s+1).re < n,
{ rw [nat.succ_eq_add_one, nat.cast_add, nat.cast_one] at h1,
rw [add_re, one_re], linarith, },
rw Gamma_aux_recurrence1 (s+1) n hh1, },
rw this },
end
/-- The `Γ` function (of a complex variable `s`). -/
@[pp_nodot] def Gamma (s : ℂ) : ℂ := Gamma_aux ⌊1 - s.re⌋₊ s
lemma Gamma_eq_Gamma_aux (s : ℂ) (n : ℕ) (h1 : -s.re < ↑n) : Gamma s = Gamma_aux n s :=
begin
have u : ∀ (k : ℕ), Gamma_aux (⌊1 - s.re⌋₊ + k) s = Gamma s,
{ intro k, induction k with k hk,
{ simp [Gamma],},
{ rw [←hk, nat.succ_eq_add_one, ←add_assoc],
refine (Gamma_aux_recurrence2 s (⌊1 - s.re⌋₊ + k) _).symm,
rw nat.cast_add,
have i0 := nat.sub_one_lt_floor (1 - s.re),
simp only [sub_sub_cancel_left] at i0,
refine lt_add_of_lt_of_nonneg i0 _,
rw [←nat.cast_zero, nat.cast_le], exact nat.zero_le k, } },
convert (u $ n - ⌊1 - s.re⌋₊).symm, rw nat.add_sub_of_le,
by_cases (0 ≤ 1 - s.re),
{ apply nat.le_of_lt_succ,
exact_mod_cast lt_of_le_of_lt (nat.floor_le h) (by linarith : 1 - s.re < n + 1) },
{ rw nat.floor_of_nonpos, linarith, linarith },
end
/-- The recurrence relation for the `Γ` function. -/
theorem Gamma_add_one (s : ℂ) (h2 : s ≠ 0) : Gamma (s+1) = s * Gamma s :=
begin
let n := ⌊1 - s.re⌋₊,
have t1 : -s.re < n,
{ simpa only [sub_sub_cancel_left] using nat.sub_one_lt_floor (1 - s.re) },
have t2 : -(s+1).re < n,
{ rw [add_re, one_re], linarith, },
rw [Gamma_eq_Gamma_aux s n t1, Gamma_eq_Gamma_aux (s+1) n t2, Gamma_aux_recurrence1 s n t1],
field_simp, ring,
end
theorem Gamma_eq_integral {s : ℂ} (hs : 0 < s.re) : Gamma s = Gamma_integral s :=
Gamma_eq_Gamma_aux s 0 (by { norm_cast, linarith })
lemma Gamma_one : Gamma 1 = 1 :=
by { rw Gamma_eq_integral, simpa using Gamma_integral_one, simp }
theorem Gamma_nat_eq_factorial (n : ℕ) : Gamma (n+1) = n! :=
begin
induction n with n hn,
{ simpa using Gamma_one },
{ rw (Gamma_add_one n.succ $ nat.cast_ne_zero.mpr $ nat.succ_ne_zero n),
simp only [nat.cast_succ, nat.factorial_succ, nat.cast_mul], congr, exact hn },
end
/-- At `0` the Gamma function is undefined; by convention we assign it the value `0`. -/
lemma Gamma_zero : Gamma 0 = 0 :=
by simp_rw [Gamma, zero_re, sub_zero, nat.floor_one, Gamma_aux, div_zero]
/-- At `-n` for `n ∈ ℕ`, the Gamma function is undefined; by convention we assign it the value 0. -/
lemma Gamma_neg_nat_eq_zero (n : ℕ) : Gamma (-n) = 0 :=
begin
induction n with n IH,
{ rw [nat.cast_zero, neg_zero, Gamma_zero] },
{ have A : -(n.succ : ℂ) ≠ 0,
{ rw [neg_ne_zero, nat.cast_ne_zero],
apply nat.succ_ne_zero },
have : -(n:ℂ) = -↑n.succ + 1, by simp,
rw [this, Gamma_add_one _ A] at IH,
contrapose! IH,
exact mul_ne_zero A IH }
end
lemma Gamma_conj (s : ℂ) : Gamma (conj s) = conj (Gamma s) :=
begin
suffices : ∀ (n:ℕ) (s:ℂ) , Gamma_aux n (conj s) = conj (Gamma_aux n s), from this _ _,
intro n,
induction n with n IH,
{ rw Gamma_aux, exact Gamma_integral_conj, },
{ intro s,
rw Gamma_aux,
dsimp only,
rw [div_eq_mul_inv _ s, ring_hom.map_mul, conj_inv, ←div_eq_mul_inv],
suffices : conj s + 1 = conj (s + 1), by rw [this, IH],
rw [ring_hom.map_add, ring_hom.map_one] }
end
end Gamma_def
end complex
/-! Now check that the `Γ` function is differentiable, wherever this makes sense. -/
section Gamma_has_deriv
/-- Integrand for the derivative of the `Γ` function -/
def dGamma_integrand (s : ℂ) (x : ℝ) : ℂ := exp (-x) * log x * x ^ (s - 1)
/-- Integrand for the absolute value of the derivative of the `Γ` function -/
def dGamma_integrand_real (s x : ℝ) : ℝ := |exp (-x) * log x * x ^ (s - 1)|
lemma dGamma_integrand_is_o_at_top (s : ℝ) :
(λ x : ℝ, exp (-x) * log x * x ^ (s - 1)) =o[at_top] (λ x, exp (-(1/2) * x)) :=
begin
refine is_o_of_tendsto (λ x hx, _) _,
{ exfalso, exact (-(1/2) * x).exp_pos.ne' hx, },
have : eventually_eq at_top (λ (x : ℝ), exp (-x) * log x * x ^ (s - 1) / exp (-(1 / 2) * x))
(λ (x : ℝ), (λ z:ℝ, exp (1 / 2 * z) / z ^ s) x * (λ z:ℝ, z / log z) x)⁻¹,
{ refine eventually_of_mem (Ioi_mem_at_top 1) _,
intros x hx, dsimp,
replace hx := lt_trans zero_lt_one (mem_Ioi.mp hx),
rw [real.exp_neg, neg_mul, real.exp_neg, rpow_sub hx],
have : exp x = exp(x/2) * exp(x/2),
{ rw [←real.exp_add, add_halves], },
rw this, field_simp [hx.ne', exp_ne_zero (x/2)], ring, },
refine tendsto.congr' this.symm (tendsto.inv_tendsto_at_top _),
apply tendsto.at_top_mul_at_top (tendsto_exp_mul_div_rpow_at_top s (1/2) one_half_pos),
refine tendsto.congr' _ ((tendsto_exp_div_pow_at_top 1).comp tendsto_log_at_top),
apply eventually_eq_of_mem (Ioi_mem_at_top (0:ℝ)),
intros x hx, simp [exp_log hx],
end
/-- Absolute convergence of the integral which will give the derivative of the `Γ` function on
`1 < re s`. -/
lemma dGamma_integral_abs_convergent (s : ℝ) (hs : 1 < s) :
integrable_on (λ x:ℝ, ‖exp (-x) * log x * x ^ (s-1)‖) (Ioi 0) :=
begin
rw [←Ioc_union_Ioi_eq_Ioi (@zero_le_one ℝ _ _ _ _), integrable_on_union],
refine ⟨⟨_, _⟩, _⟩,
{ refine continuous_on.ae_strongly_measurable (continuous_on.mul _ _).norm measurable_set_Ioc,
{ refine (continuous_exp.comp continuous_neg).continuous_on.mul (continuous_on_log.mono _),
simp, },
{ apply continuous_on_id.rpow_const, intros x hx, right, linarith }, },
{ apply has_finite_integral_of_bounded,
swap, { exact 1 / (s - 1), },
refine (ae_restrict_iff' measurable_set_Ioc).mpr (ae_of_all _ (λ x hx, _)),
rw [norm_norm, norm_eq_abs, mul_assoc, abs_mul, ←one_mul (1 / (s - 1))],
refine mul_le_mul _ _ (abs_nonneg _) zero_le_one,
{ rw [abs_of_pos (exp_pos(-x)), exp_le_one_iff, neg_le, neg_zero], exact hx.1.le },
{ exact (abs_log_mul_self_rpow_lt x (s-1) hx.1 hx.2 (sub_pos.mpr hs)).le }, },
{ have := (dGamma_integrand_is_o_at_top s).is_O.norm_left,
refine integrable_of_is_O_exp_neg one_half_pos (continuous_on.mul _ _).norm this,
{ refine (continuous_exp.comp continuous_neg).continuous_on.mul (continuous_on_log.mono _),
simp, },
{ apply continuous_at.continuous_on (λ x hx, _),
apply continuous_at_id.rpow continuous_at_const,
dsimp, right, linarith, }, }
end
/-- A uniform bound for the `s`-derivative of the `Γ` integrand for `s` in vertical strips. -/
lemma loc_unif_bound_dGamma_integrand {t : ℂ} {s1 s2 x : ℝ} (ht1 : s1 ≤ t.re)
(ht2: t.re ≤ s2) (hx : 0 < x) :
‖dGamma_integrand t x‖ ≤ dGamma_integrand_real s1 x + dGamma_integrand_real s2 x :=
begin
rcases le_or_lt 1 x with h|h,
{ -- case 1 ≤ x
refine le_add_of_nonneg_of_le (abs_nonneg _) _,
rw [dGamma_integrand, dGamma_integrand_real, complex.norm_eq_abs, map_mul, abs_mul,
←complex.of_real_mul, complex.abs_of_real],
refine mul_le_mul_of_nonneg_left _ (abs_nonneg _),
rw complex.abs_cpow_eq_rpow_re_of_pos hx,
refine le_trans _ (le_abs_self _),
apply rpow_le_rpow_of_exponent_le h,
rw [complex.sub_re, complex.one_re], linarith, },
{ refine le_add_of_le_of_nonneg _ (abs_nonneg _),
rw [dGamma_integrand, dGamma_integrand_real, complex.norm_eq_abs, map_mul, abs_mul,
←complex.of_real_mul, complex.abs_of_real],
refine mul_le_mul_of_nonneg_left _ (abs_nonneg _),
rw complex.abs_cpow_eq_rpow_re_of_pos hx,
refine le_trans _ (le_abs_self _),
apply rpow_le_rpow_of_exponent_ge hx h.le,
rw [complex.sub_re, complex.one_re], linarith, },
end
namespace complex
/-- The derivative of the `Γ` integral, at any `s ∈ ℂ` with `1 < re s`, is given by the integral
of `exp (-x) * log x * x ^ (s - 1)` over `[0, ∞)`. -/
theorem has_deriv_at_Gamma_integral {s : ℂ} (hs : 1 < s.re) :
(integrable_on (λ x, real.exp (-x) * real.log x * x ^ (s - 1) : ℝ → ℂ) (Ioi 0) volume) ∧
(has_deriv_at Gamma_integral (∫ x:ℝ in Ioi 0, real.exp (-x) * real.log x * x ^ (s - 1)) s) :=
begin
let ε := (s.re - 1) / 2,
let μ := volume.restrict (Ioi (0:ℝ)),
let bound := (λ x:ℝ, dGamma_integrand_real (s.re - ε) x + dGamma_integrand_real (s.re + ε) x),
have cont : ∀ (t : ℂ), continuous_on (λ x, real.exp (-x) * x ^ (t - 1) : ℝ → ℂ) (Ioi 0),
{ intro t, apply (continuous_of_real.comp continuous_neg.exp).continuous_on.mul,
apply continuous_at.continuous_on, intros x hx,
refine (continuous_at_cpow_const _).comp continuous_of_real.continuous_at,
exact or.inl hx, },
have eps_pos: 0 < ε := div_pos (sub_pos.mpr hs) zero_lt_two,
have hF_meas : ∀ᶠ (t : ℂ) in 𝓝 s,
ae_strongly_measurable (λ x, real.exp(-x) * x ^ (t - 1) : ℝ → ℂ) μ,
{ apply eventually_of_forall, intro t,
exact (cont t).ae_strongly_measurable measurable_set_Ioi, },
have hF'_meas : ae_strongly_measurable (dGamma_integrand s) μ,
{ refine continuous_on.ae_strongly_measurable _ measurable_set_Ioi,
have : dGamma_integrand s = (λ x, real.exp (-x) * x ^ (s - 1) * real.log x : ℝ → ℂ),
{ ext1, simp only [dGamma_integrand], ring },
rw this,
refine continuous_on.mul (cont s) (continuous_at.continuous_on _),
exact λ x hx, continuous_of_real.continuous_at.comp (continuous_at_log (mem_Ioi.mp hx).ne'), },
have h_bound : ∀ᵐ (x : ℝ) ∂μ, ∀ (t : ℂ), t ∈ metric.ball s ε → ‖ dGamma_integrand t x ‖ ≤ bound x,
{ refine (ae_restrict_iff' measurable_set_Ioi).mpr (ae_of_all _ (λ x hx, _)),
intros t ht,
rw [metric.mem_ball, complex.dist_eq] at ht,
replace ht := lt_of_le_of_lt (complex.abs_re_le_abs $ t - s ) ht,
rw [complex.sub_re, @abs_sub_lt_iff ℝ _ t.re s.re ((s.re - 1) / 2) ] at ht,
refine loc_unif_bound_dGamma_integrand _ _ hx,
all_goals { simp only [ε], linarith } },
have bound_integrable : integrable bound μ,
{ apply integrable.add,
{ refine dGamma_integral_abs_convergent (s.re - ε) _,
field_simp, rw one_lt_div,
{ linarith }, { exact zero_lt_two }, },
{ refine dGamma_integral_abs_convergent (s.re + ε) _, linarith, }, },
have h_diff : ∀ᵐ (x : ℝ) ∂μ, ∀ (t : ℂ), t ∈ metric.ball s ε
→ has_deriv_at (λ u, real.exp (-x) * x ^ (u - 1) : ℂ → ℂ) (dGamma_integrand t x) t,
{ refine (ae_restrict_iff' measurable_set_Ioi).mpr (ae_of_all _ (λ x hx, _)),
intros t ht, rw mem_Ioi at hx,
simp only [dGamma_integrand],
rw mul_assoc,
apply has_deriv_at.const_mul,
rw [of_real_log hx.le, mul_comm],
have := ((has_deriv_at_id t).sub_const 1).const_cpow (or.inl (of_real_ne_zero.mpr hx.ne')),
rwa mul_one at this },
exact (has_deriv_at_integral_of_dominated_loc_of_deriv_le eps_pos hF_meas
(Gamma_integral_convergent (zero_lt_one.trans hs)) hF'_meas h_bound bound_integrable h_diff),
end
lemma differentiable_at_Gamma_aux (s : ℂ) (n : ℕ) (h1 : (1 - s.re) < n ) (h2 : ∀ m : ℕ, s ≠ -m) :
differentiable_at ℂ (Gamma_aux n) s :=
begin
induction n with n hn generalizing s,
{ refine (has_deriv_at_Gamma_integral _).2.differentiable_at,
rw nat.cast_zero at h1, linarith },
{ dsimp only [Gamma_aux],
specialize hn (s + 1),
have a : 1 - (s + 1).re < ↑n,
{ rw nat.cast_succ at h1, rw [complex.add_re, complex.one_re], linarith },
have b : ∀ m : ℕ, s + 1 ≠ -m,
{ intro m, have := h2 (1 + m),
contrapose! this,
rw ←eq_sub_iff_add_eq at this,
simpa using this },
refine differentiable_at.div (differentiable_at.comp _ (hn a b) _) _ _,
simp, simp, simpa using h2 0 }
end
theorem differentiable_at_Gamma (s : ℂ) (hs : ∀ m : ℕ, s ≠ -m) : differentiable_at ℂ Gamma s :=
begin
let n := ⌊1 - s.re⌋₊ + 1,
have hn : 1 - s.re < n := by exact_mod_cast nat.lt_floor_add_one (1 - s.re),
apply (differentiable_at_Gamma_aux s n hn hs).congr_of_eventually_eq,
let S := { t : ℂ | 1 - t.re < n },
have : S ∈ 𝓝 s,
{ rw mem_nhds_iff, use S,
refine ⟨subset.rfl, _, hn⟩,
have : S = re⁻¹' Ioi (1 - n : ℝ),
{ ext, rw [preimage,Ioi, mem_set_of_eq, mem_set_of_eq, mem_set_of_eq], exact sub_lt_comm },
rw this,
refine continuous.is_open_preimage continuous_re _ is_open_Ioi, },
apply eventually_eq_of_mem this,
intros t ht, rw mem_set_of_eq at ht,
apply Gamma_eq_Gamma_aux, linarith,
end
end complex
end Gamma_has_deriv
namespace real
/-- The `Γ` function (of a real variable `s`). -/
@[pp_nodot] def Gamma (s : ℝ) : ℝ := (complex.Gamma s).re
lemma Gamma_eq_integral {s : ℝ} (hs : 0 < s) : Gamma s = ∫ x in Ioi 0, exp (-x) * x ^ (s - 1) :=
begin
rw [Gamma, complex.Gamma_eq_integral (by rwa complex.of_real_re : 0 < complex.re s)],
dsimp only [complex.Gamma_integral],
simp_rw [←complex.of_real_one, ←complex.of_real_sub],
suffices : ∫ (x : ℝ) in Ioi 0, ↑(exp (-x)) * (x : ℂ) ^ ((s - 1 : ℝ) : ℂ) =
∫ (x : ℝ) in Ioi 0, ((exp (-x) * x ^ (s - 1) : ℝ) : ℂ),
{ rw [this, _root_.integral_of_real, complex.of_real_re], },
refine set_integral_congr measurable_set_Ioi (λ x hx, _),
push_cast,
rw complex.of_real_cpow (le_of_lt hx),
push_cast,
end
lemma Gamma_add_one {s : ℝ} (hs : s ≠ 0) : Gamma (s + 1) = s * Gamma s :=
begin
simp_rw Gamma,
rw [complex.of_real_add, complex.of_real_one, complex.Gamma_add_one, complex.of_real_mul_re],
rwa complex.of_real_ne_zero,
end
lemma Gamma_one : Gamma 1 = 1 :=
by rw [Gamma, complex.of_real_one, complex.Gamma_one, complex.one_re]
lemma _root_.complex.Gamma_of_real (s : ℝ) : complex.Gamma (s : ℂ) = Gamma s :=
by rw [Gamma, eq_comm, ←complex.conj_eq_iff_re, ←complex.Gamma_conj, complex.conj_of_real]
theorem Gamma_nat_eq_factorial (n : ℕ) : Gamma (n + 1) = n! :=
by rw [Gamma, complex.of_real_add, complex.of_real_nat_cast, complex.of_real_one,
complex.Gamma_nat_eq_factorial, ←complex.of_real_nat_cast, complex.of_real_re]
/-- At `0` the Gamma function is undefined; by convention we assign it the value `0`. -/
lemma Gamma_zero : Gamma 0 = 0 :=
by simpa only [←complex.of_real_zero, complex.Gamma_of_real, complex.of_real_inj]
using complex.Gamma_zero
/-- At `-n` for `n ∈ ℕ`, the Gamma function is undefined; by convention we assign it the value `0`.
-/
lemma Gamma_neg_nat_eq_zero (n : ℕ) : Gamma (-n) = 0 :=
begin
simpa only [←complex.of_real_nat_cast, ←complex.of_real_neg, complex.Gamma_of_real,
complex.of_real_eq_zero] using complex.Gamma_neg_nat_eq_zero n,
end
lemma Gamma_pos_of_pos {s : ℝ} (hs : 0 < s) : 0 < Gamma s :=
begin
rw Gamma_eq_integral hs,
have : function.support (λ (x : ℝ), exp (-x) * x ^ (s - 1)) ∩ Ioi 0 = Ioi 0,
{ rw inter_eq_right_iff_subset,
intros x hx,
rw function.mem_support,
exact mul_ne_zero (exp_pos _).ne' (rpow_pos_of_pos hx _).ne' },
rw set_integral_pos_iff_support_of_nonneg_ae,
{ rw [this, volume_Ioi, ←ennreal.of_real_zero],
exact ennreal.of_real_lt_top },
{ refine eventually_of_mem (self_mem_ae_restrict measurable_set_Ioi) _,
exact λ x hx, (mul_pos (exp_pos _) (rpow_pos_of_pos hx _)).le },
{ exact Gamma_integral_convergent hs },
end
/-- The Gamma function does not vanish on `ℝ` (except at non-positive integers, where the function
is mathematically undefined and we set it to `0` by convention). -/
lemma Gamma_ne_zero {s : ℝ} (hs : ∀ m : ℕ, s ≠ -m) : Gamma s ≠ 0 :=
begin
suffices : ∀ {n : ℕ}, (-(n:ℝ) < s) → Gamma s ≠ 0,
{ apply this,
swap, use (⌊-s⌋₊ + 1),
rw [neg_lt, nat.cast_add, nat.cast_one],
exact nat.lt_floor_add_one _ },
intro n,
induction n generalizing s,
{ intro hs,
refine (Gamma_pos_of_pos _).ne',
rwa [nat.cast_zero, neg_zero] at hs },
{ intro hs',
have : Gamma (s + 1) ≠ 0,
{ apply n_ih,
{ intro m,
specialize hs (1 + m),
contrapose! hs,
rw ←eq_sub_iff_add_eq at hs,
rw hs,
push_cast,
ring },
{ rw [nat.succ_eq_add_one, nat.cast_add, nat.cast_one, neg_add] at hs',
linarith } },
rw [Gamma_add_one, mul_ne_zero_iff] at this,
{ exact this.2 },
{ simpa using hs 0 } },
end
lemma Gamma_eq_zero_iff (s : ℝ) : Gamma s = 0 ↔ ∃ m : ℕ, s = -m :=
⟨by { contrapose!, exact Gamma_ne_zero }, by { rintro ⟨m, rfl⟩, exact Gamma_neg_nat_eq_zero m }⟩
lemma differentiable_at_Gamma {s : ℝ} (hs : ∀ m : ℕ, s ≠ -m) : differentiable_at ℝ Gamma s :=
begin
refine ((complex.differentiable_at_Gamma _ _).has_deriv_at).real_of_complex.differentiable_at,
simp_rw [←complex.of_real_nat_cast, ←complex.of_real_neg, ne.def, complex.of_real_inj],
exact hs,
end
/-- Log-convexity of the Gamma function on the positive reals (stated in multiplicative form),
proved using the Hölder inequality applied to Euler's integral. -/
lemma Gamma_mul_add_mul_le_rpow_Gamma_mul_rpow_Gamma {s t a b : ℝ}
(hs : 0 < s) (ht : 0 < t) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) :
Gamma (a * s + b * t) ≤ Gamma s ^ a * Gamma t ^ b :=
begin
-- We will apply Hölder's inequality, for the conjugate exponents `p = 1 / a`
-- and `q = 1 / b`, to the functions `f a s` and `f b t`, where `f` is as follows:
let f : ℝ → ℝ → ℝ → ℝ := λ c u x, exp (-c * x) * x ^ (c * (u - 1)),
have e : is_conjugate_exponent (1 / a) (1 / b) := real.is_conjugate_exponent_one_div ha hb hab,
have hab' : b = 1 - a := by linarith,
have hst : 0 < a * s + b * t := add_pos (mul_pos ha hs) (mul_pos hb ht),
-- some properties of f:
have posf : ∀ (c u x : ℝ), x ∈ Ioi (0:ℝ) → 0 ≤ f c u x :=
λ c u x hx, mul_nonneg (exp_pos _).le (rpow_pos_of_pos hx _).le,
have posf' : ∀ (c u : ℝ), ∀ᵐ (x : ℝ) ∂volume.restrict (Ioi 0), 0 ≤ f c u x :=
λ c u, (ae_restrict_iff' measurable_set_Ioi).mpr (ae_of_all _ (posf c u)),
have fpow : ∀ {c x : ℝ} (hc : 0 < c) (u : ℝ) (hx : 0 < x),
exp (-x) * x ^ (u - 1) = f c u x ^ (1 / c),
{ intros c x hc u hx,
dsimp only [f],
rw [mul_rpow (exp_pos _).le ((rpow_nonneg_of_nonneg hx.le) _), ←exp_mul, ←rpow_mul hx.le],
congr' 2;
{ field_simp [hc.ne'], ring } },
-- show `f c u` is in `ℒp` for `p = 1/c`:
have f_mem_Lp : ∀ {c u : ℝ} (hc : 0 < c) (hu : 0 < u),
mem_ℒp (f c u) (ennreal.of_real (1 / c)) (volume.restrict (Ioi 0)),
{ intros c u hc hu,
have A : ennreal.of_real (1 / c) ≠ 0,
by rwa [ne.def, ennreal.of_real_eq_zero, not_le, one_div_pos],
have B : ennreal.of_real (1 / c) ≠ ∞, from ennreal.of_real_ne_top,
rw [←mem_ℒp_norm_rpow_iff _ A B, ennreal.to_real_of_real (one_div_nonneg.mpr hc.le),
ennreal.div_self A B, mem_ℒp_one_iff_integrable],
{ apply integrable.congr (Gamma_integral_convergent hu),
refine eventually_eq_of_mem (self_mem_ae_restrict measurable_set_Ioi) (λ x hx, _),
dsimp only,
rw fpow hc u hx,
congr' 1,
exact (norm_of_nonneg (posf _ _ x hx)).symm },
{ refine continuous_on.ae_strongly_measurable _ measurable_set_Ioi,
refine (continuous.continuous_on _).mul (continuous_at.continuous_on (λ x hx, _)),
{ exact continuous_exp.comp (continuous_const.mul continuous_id'), },
{ exact continuous_at_rpow_const _ _ (or.inl (ne_of_lt hx).symm), } } },
-- now apply Hölder:
rw [Gamma_eq_integral hs, Gamma_eq_integral ht, Gamma_eq_integral hst],
convert measure_theory.integral_mul_le_Lp_mul_Lq_of_nonneg e (posf' a s) (posf' b t)
(f_mem_Lp ha hs) (f_mem_Lp hb ht) using 1,
{ refine set_integral_congr measurable_set_Ioi (λ x hx, _),
dsimp only [f],
have A : exp (-x) = exp (-a * x) * exp (-b * x),
{ rw [←exp_add, ←add_mul, ←neg_add, hab, neg_one_mul] },
have B : x ^ (a * s + b * t - 1) = (x ^ (a * (s - 1))) * (x ^ (b * (t - 1))),
{ rw [←rpow_add hx, hab'], congr' 1, ring },
rw [A, B],
ring },
{ rw [one_div_one_div, one_div_one_div],
congr' 2;
exact set_integral_congr measurable_set_Ioi (λ x hx, fpow (by assumption) _ hx) },
end
lemma convex_on_log_Gamma : convex_on ℝ (Ioi 0) (log ∘ Gamma) :=
begin
refine convex_on_iff_forall_pos.mpr ⟨convex_Ioi _, λ x hx y hy a b ha hb hab, _⟩,
have : b = 1 - a := by linarith, subst this,
simp_rw [function.comp_app, smul_eq_mul],
rw [←log_rpow (Gamma_pos_of_pos hy), ←log_rpow (Gamma_pos_of_pos hx),
←log_mul
((rpow_pos_of_pos (Gamma_pos_of_pos hx) _).ne') (rpow_pos_of_pos (Gamma_pos_of_pos hy) _).ne',
log_le_log
(Gamma_pos_of_pos (add_pos (mul_pos ha hx) (mul_pos hb hy)))
(mul_pos
(rpow_pos_of_pos (Gamma_pos_of_pos hx) _) (rpow_pos_of_pos (Gamma_pos_of_pos hy) _))],
exact Gamma_mul_add_mul_le_rpow_Gamma_mul_rpow_Gamma hx hy ha hb hab,
end
lemma convex_on_Gamma : convex_on ℝ (Ioi 0) Gamma :=
begin
refine ⟨convex_Ioi 0, λ x hx y hy a b ha hb hab, _⟩,
have := convex_on.comp (convex_on_exp.subset (subset_univ _) _) convex_on_log_Gamma
(λ u hu v hv huv, exp_le_exp.mpr huv),
convert this.2 hx hy ha hb hab,
{ rw [function.comp_app, exp_log (Gamma_pos_of_pos $ this.1 hx hy ha hb hab)] },
{ rw [function.comp_app, exp_log (Gamma_pos_of_pos hx)] },
{ rw [function.comp_app, exp_log (Gamma_pos_of_pos hy)] },
{ rw convex_iff_is_preconnected,
refine is_preconnected_Ioi.image _ (λ x hx, continuous_at.continuous_within_at _),
refine (differentiable_at_Gamma (λ m, _)).continuous_at.log (Gamma_pos_of_pos hx).ne',
exact (neg_lt_iff_pos_add.mpr (add_pos_of_pos_of_nonneg hx (nat.cast_nonneg m))).ne' }
end
section bohr_mollerup
/-! ## The Bohr-Mollerup theorem
In this section we prove two interrelated statements about the `Γ` function on the positive reals:
* the Euler limit formula `real.bohr_mollerup.tendsto_log_gamma_seq`, stating that for positive
real `x` the sequence `x * log n + log n! - ∑ (m : ℕ) in finset.range (n + 1), log (x + m)`
tends to `log Γ(x)` as `n → ∞`.
* the Bohr-Mollerup theorem (`real.eq_Gamma_of_log_convex`) which states that `Γ` is the unique
*log-convex*, positive-real-valued function on the positive reals satisfying
`f (x + 1) = x f x` and `f 1 = 1`.
To do this, we prove that any function satisfying the hypotheses of the Bohr--Mollerup theorem must
agree with the limit in the Euler limit formula, so there is at most one such function. Then we
show that `Γ` satisfies these conditions.
Since most of the auxiliary lemmas for the Bohr-Mollerup theorem are of no relevance outside the
context of this proof, we place them in a separate namespace `real.bohr_mollerup` to avoid clutter.
(This includes the logarithmic form of the Euler limit formula, since later we will prove a more
general form of the Euler limit formula valid for any real or complex `x`; see
`real.Gamma_seq_tendsto_Gamma` and `complex.Gamma_seq_tendsto_Gamma`.)
-/
namespace bohr_mollerup
/-- The function `n ↦ x log n + log n! - (log x + ... + log (x + n))`, which we will show tends to
`log (Gamma x)` as `n → ∞`. -/
def log_gamma_seq (x : ℝ) (n : ℕ) : ℝ :=
x * log n + log n! - ∑ (m : ℕ) in finset.range (n + 1), log (x + m)
variables {f : ℝ → ℝ} {x : ℝ} {n : ℕ}
lemma f_nat_eq (hf_feq : ∀ {y:ℝ}, 0 < y → f (y + 1) = f y + log y) (hn : n ≠ 0) :
f n = f 1 + log (n - 1)! :=
begin
refine nat.le_induction (by simp) (λ m hm IH, _) n (nat.one_le_iff_ne_zero.2 hn),
have A : 0 < (m : ℝ), from nat.cast_pos.2 hm,
simp only [hf_feq A, nat.cast_add, algebra_map.coe_one, nat.add_succ_sub_one, add_zero],
rw [IH, add_assoc, ← log_mul (nat.cast_ne_zero.mpr (nat.factorial_ne_zero _)) A.ne',
← nat.cast_mul],
conv_rhs { rw [← nat.succ_pred_eq_of_pos hm, nat.factorial_succ, mul_comm] },
congr,
exact (nat.succ_pred_eq_of_pos hm).symm
end
lemma f_add_nat_eq (hf_feq : ∀ {y:ℝ}, 0 < y → f (y + 1) = f y + log y) (hx : 0 < x) (n : ℕ) :
f (x + n) = f x + ∑ (m : ℕ) in finset.range n, log (x + m) :=
begin
induction n with n hn,
{ simp },
{ have : x + n.succ = (x + n) + 1,
{ push_cast, ring },
rw [this, hf_feq, hn],
rw [finset.range_succ, finset.sum_insert (finset.not_mem_range_self)],
abel,
linarith [(nat.cast_nonneg n : 0 ≤ (n:ℝ))] },
end
/-- Linear upper bound for `f (x + n)` on unit interval -/
lemma f_add_nat_le
(hf_conv : convex_on ℝ (Ioi 0) f) (hf_feq : ∀ {y:ℝ}, 0 < y → f (y + 1) = f y + log y)
(hn : n ≠ 0) (hx : 0 < x) (hx' : x ≤ 1) :
f (n + x) ≤ f n + x * log n :=
begin
have hn': 0 < (n:ℝ) := nat.cast_pos.mpr (nat.pos_of_ne_zero hn),
have : f n + x * log n = (1 - x) * f n + x * f (n + 1),
{ rw [hf_feq hn'], ring, },
rw [this, (by ring : (n:ℝ) + x = (1 - x) * n + x * (n + 1))],
simpa only [smul_eq_mul] using hf_conv.2 hn' (by linarith : 0 < (n + 1 : ℝ))
(by linarith : 0 ≤ 1 - x) hx.le (by linarith),
end
/-- Linear lower bound for `f (x + n)` on unit interval -/
lemma f_add_nat_ge
(hf_conv : convex_on ℝ (Ioi 0) f) (hf_feq : ∀ {y:ℝ}, 0 < y → f (y + 1) = f y + log y)
(hn : 2 ≤ n) (hx : 0 < x) :
f n + x * log (n - 1) ≤ f (n + x) :=
begin
have npos : 0 < (n:ℝ) - 1,
{ rw [←nat.cast_one, sub_pos, nat.cast_lt], linarith, },
have c := (convex_on_iff_slope_mono_adjacent.mp $ hf_conv).2
npos (by linarith : 0 < (n:ℝ) + x) (by linarith : (n:ℝ) - 1 < (n:ℝ)) (by linarith),
rw [add_sub_cancel', sub_sub_cancel, div_one] at c,
have : f (↑n - 1) = f n - log (↑n - 1),
{ nth_rewrite_rhs 0 (by ring : (n:ℝ) = (↑n - 1) + 1),
rw [hf_feq npos, add_sub_cancel] },
rwa [this, le_div_iff hx, sub_sub_cancel, le_sub_iff_add_le, mul_comm _ x, add_comm] at c,
end
lemma log_gamma_seq_add_one (x : ℝ) (n : ℕ) :
log_gamma_seq (x + 1) n = log_gamma_seq x (n + 1) + log x - (x + 1) * (log (n + 1) - log n) :=
begin
dsimp only [nat.factorial_succ, log_gamma_seq],
conv_rhs { rw [finset.sum_range_succ', nat.cast_zero, add_zero], },
rw [nat.cast_mul, log_mul], rotate,
{ rw nat.cast_ne_zero, exact nat.succ_ne_zero n },
{ rw nat.cast_ne_zero, exact nat.factorial_ne_zero n, },
have : ∑ (m : ℕ) in finset.range (n + 1), log (x + 1 + ↑m) =
∑ (k : ℕ) in finset.range (n + 1), log (x + ↑(k + 1)),
{ refine finset.sum_congr (by refl) (λ m hm, _),
congr' 1,
push_cast,
abel },
rw [←this, nat.cast_add_one n],
ring,
end
lemma le_log_gamma_seq
(hf_conv : convex_on ℝ (Ioi 0) f) (hf_feq : ∀ {y:ℝ}, 0 < y → f (y + 1) = f y + log y)
(hx : 0 < x) (hx' : x ≤ 1) (n : ℕ) :
f x ≤ f 1 + x * log (n + 1) - x * log n + log_gamma_seq x n :=
begin
rw [log_gamma_seq, ←add_sub_assoc, le_sub_iff_add_le, ←f_add_nat_eq @hf_feq hx, add_comm x],
refine (f_add_nat_le hf_conv @hf_feq (nat.add_one_ne_zero n) hx hx').trans (le_of_eq _),
rw [f_nat_eq @hf_feq (by linarith : n + 1 ≠ 0), nat.add_sub_cancel, nat.cast_add_one],
ring,
end
lemma ge_log_gamma_seq
(hf_conv : convex_on ℝ (Ioi 0) f) (hf_feq : ∀ {y:ℝ}, 0 < y → f (y + 1) = f y + log y)
(hx : 0 < x) (hn : n ≠ 0) :
f 1 + log_gamma_seq x n ≤ f x :=
begin
dsimp [log_gamma_seq],
rw [←add_sub_assoc, sub_le_iff_le_add, ←f_add_nat_eq @hf_feq hx, add_comm x _],
refine le_trans (le_of_eq _) (f_add_nat_ge hf_conv @hf_feq _ hx),
{ rw [f_nat_eq @hf_feq, nat.add_sub_cancel, nat.cast_add_one, add_sub_cancel],
{ ring },
{ exact nat.succ_ne_zero _} },
{ apply nat.succ_le_succ,
linarith [nat.pos_of_ne_zero hn] },
end
lemma tendsto_log_gamma_seq_of_le_one
(hf_conv : convex_on ℝ (Ioi 0) f) (hf_feq : ∀ {y:ℝ}, 0 < y → f (y + 1) = f y + log y)
(hx : 0 < x) (hx' : x ≤ 1) :
tendsto (log_gamma_seq x) at_top (𝓝 $ f x - f 1) :=
begin
refine tendsto_of_tendsto_of_tendsto_of_le_of_le' _ tendsto_const_nhds _ _,
show ∀ᶠ (n : ℕ) in at_top, log_gamma_seq x n ≤ f x - f 1,
{ refine eventually.mp (eventually_ne_at_top 0) (eventually_of_forall (λ n hn, _)),
exact le_sub_iff_add_le'.mpr (ge_log_gamma_seq hf_conv @hf_feq hx hn) },
show ∀ᶠ (n : ℕ) in at_top, f x - f 1 - x * (log (n + 1) - log n) ≤ log_gamma_seq x n,
{ refine eventually_of_forall (λ n, _),
rw [sub_le_iff_le_add', sub_le_iff_le_add'],
convert le_log_gamma_seq hf_conv @hf_feq hx hx' n using 1,
ring },
{ have : f x - f 1 = (f x - f 1) - x * 0 := by ring,
nth_rewrite 0 this,
exact tendsto.sub tendsto_const_nhds (tendsto_log_nat_add_one_sub_log.const_mul _), }
end
lemma tendsto_log_gamma_seq
(hf_conv : convex_on ℝ (Ioi 0) f) (hf_feq : ∀ {y:ℝ}, 0 < y → f (y + 1) = f y + log y)
(hx : 0 < x) :
tendsto (log_gamma_seq x) at_top (𝓝 $ f x - f 1) :=
begin
suffices : ∀ (m : ℕ), ↑m < x → x ≤ m + 1 →
tendsto (log_gamma_seq x) at_top (𝓝 $ f x - f 1),
{ refine this (⌈x - 1⌉₊) _ _,
{ rcases lt_or_le x 1,
{ rwa [nat.ceil_eq_zero.mpr (by linarith : x - 1 ≤ 0), nat.cast_zero] },
{ convert nat.ceil_lt_add_one (by linarith : 0 ≤ x - 1),
abel } },
{ rw ←sub_le_iff_le_add, exact nat.le_ceil _}, },
intro m,
induction m with m hm generalizing x,
{ rw [nat.cast_zero, zero_add],
exact λ _ hx', tendsto_log_gamma_seq_of_le_one hf_conv @hf_feq hx hx' },
{ intros hy hy',
rw [nat.cast_succ, ←sub_le_iff_le_add] at hy',
rw [nat.cast_succ, ←lt_sub_iff_add_lt] at hy,
specialize hm ((nat.cast_nonneg _).trans_lt hy) hy hy',
-- now massage gauss_product n (x - 1) into gauss_product (n - 1) x
have : ∀ᶠ (n:ℕ) in at_top, log_gamma_seq (x - 1) n = log_gamma_seq x (n - 1) +
x * (log (↑(n - 1) + 1) - log ↑(n - 1)) - log (x - 1),
{ refine eventually.mp (eventually_ge_at_top 1) (eventually_of_forall (λ n hn, _)),
have := log_gamma_seq_add_one (x - 1) (n - 1),
rw [sub_add_cancel, nat.sub_add_cancel hn] at this,
rw this,
ring },
replace hm := ((tendsto.congr' this hm).add
(tendsto_const_nhds : tendsto (λ _, log (x - 1)) _ _)).comp (tendsto_add_at_top_nat 1),
have :
(λ (x_1 : ℕ), (λ (n : ℕ), log_gamma_seq x (n - 1) +
x * (log (↑(n - 1) + 1) - log ↑(n - 1)) - log (x - 1)) x_1 +
(λ (b : ℕ), log (x - 1)) x_1) ∘ (λ (a : ℕ), a + 1) =
λ n, log_gamma_seq x n + x * (log (↑n + 1) - log ↑n),
{ ext1 n,
dsimp only [function.comp_app],
rw [sub_add_cancel, nat.add_sub_cancel] },
rw this at hm,
convert hm.sub (tendsto_log_nat_add_one_sub_log.const_mul x) using 2,
{ ext1 n, ring },
{ have := hf_feq ((nat.cast_nonneg m).trans_lt hy),
rw sub_add_cancel at this,
rw this,
ring } },
end
lemma tendsto_log_Gamma {x : ℝ} (hx : 0 < x) :
tendsto (log_gamma_seq x) at_top (𝓝 $ log (Gamma x)) :=
begin
have : log (Gamma x) = (log ∘ Gamma) x - (log ∘ Gamma) 1,
{ simp_rw [function.comp_app, Gamma_one, log_one, sub_zero] },
rw this,
refine bohr_mollerup.tendsto_log_gamma_seq convex_on_log_Gamma (λ y hy, _) hx,
rw [function.comp_app, Gamma_add_one hy.ne', log_mul hy.ne' (Gamma_pos_of_pos hy).ne', add_comm],
end
end bohr_mollerup -- (namespace)
/-- The **Bohr-Mollerup theorem**: the Gamma function is the *unique* log-convex, positive-valued
function on the positive reals which satisfies `f 1 = 1` and `f (x + 1) = x * f x` for all `x`. -/
lemma eq_Gamma_of_log_convex {f : ℝ → ℝ}
(hf_conv : convex_on ℝ (Ioi 0) (log ∘ f))
(hf_feq : ∀ {y:ℝ}, 0 < y → f (y + 1) = y * f y)
(hf_pos : ∀ {y:ℝ}, 0 < y → 0 < f y)
(hf_one : f 1 = 1) :
eq_on f Gamma (Ioi (0:ℝ)) :=
begin
suffices : eq_on (log ∘ f) (log ∘ Gamma) (Ioi (0:ℝ)),
from λ x hx, log_inj_on_pos (hf_pos hx) (Gamma_pos_of_pos hx) (this hx),
intros x hx,
have e1 := bohr_mollerup.tendsto_log_gamma_seq hf_conv _ hx,
{ rw [function.comp_app log f 1, hf_one, log_one, sub_zero] at e1,
exact tendsto_nhds_unique e1 (bohr_mollerup.tendsto_log_Gamma hx) },
{ intros y hy,
rw [function.comp_app, hf_feq hy, log_mul hy.ne' (hf_pos hy).ne'],
ring }
end
end bohr_mollerup -- (section)
section strict_mono
lemma Gamma_two : Gamma 2 = 1 := by simpa using Gamma_nat_eq_factorial 1
lemma Gamma_three_div_two_lt_one : Gamma (3 / 2) < 1 :=
begin
-- This can also be proved using the closed-form evaluation of `Gamma (1 / 2)` in
-- `analysis.special_functions.gaussian`, but we give a self-contained proof using log-convexity
-- to avoid unnecessary imports.
have A : (0:ℝ) < 3/2, by norm_num,
have := bohr_mollerup.f_add_nat_le convex_on_log_Gamma (λ y hy, _) two_ne_zero one_half_pos
(by norm_num : 1/2 ≤ (1:ℝ)),
swap, { rw [function.comp_app, Gamma_add_one hy.ne', log_mul hy.ne' (Gamma_pos_of_pos hy).ne',
add_comm] },
rw [function.comp_app, function.comp_app, nat.cast_two, Gamma_two, log_one, zero_add,
(by norm_num : (2:ℝ) + 1/2 = 3/2 + 1), Gamma_add_one A.ne',
log_mul A.ne' (Gamma_pos_of_pos A).ne', ←le_sub_iff_add_le',
log_le_iff_le_exp (Gamma_pos_of_pos A)] at this,
refine this.trans_lt (exp_lt_one_iff.mpr _),
rw [mul_comm, ←mul_div_assoc, div_sub' _ _ (2:ℝ) two_ne_zero],
refine div_neg_of_neg_of_pos _ two_pos,
rw [sub_neg, mul_one, ←nat.cast_two, ←log_pow, ←exp_lt_exp, nat.cast_two, exp_log two_pos,
exp_log];
norm_num,
end
lemma Gamma_strict_mono_on_Ici : strict_mono_on Gamma (Ici 2) :=
begin
convert convex_on_Gamma.strict_mono_of_lt (by norm_num : (0:ℝ) < 3/2)
(by norm_num : (3/2 : ℝ) < 2) (Gamma_two.symm ▸ Gamma_three_div_two_lt_one),
symmetry,
rw inter_eq_right_iff_subset,
exact λ x hx, two_pos.trans_le hx,
end
end strict_mono
end real
section beta_integral
/-! ## The Beta function -/
namespace complex
notation `cexp` := complex.exp
/-- The Beta function `Β (u, v)`, defined as `∫ x:ℝ in 0..1, x ^ (u - 1) * (1 - x) ^ (v - 1)`. -/
noncomputable def beta_integral (u v : ℂ) : ℂ :=
∫ (x:ℝ) in 0..1, x ^ (u - 1) * (1 - x) ^ (v - 1)
/-- Auxiliary lemma for `beta_integral_convergent`, showing convergence at the left endpoint. -/
lemma beta_integral_convergent_left {u : ℂ} (hu : 0 < re u) (v : ℂ) :
interval_integrable (λ x, x ^ (u - 1) * (1 - x) ^ (v - 1) : ℝ → ℂ) volume 0 (1 / 2) :=
begin
apply interval_integrable.mul_continuous_on,
{ refine interval_integral.interval_integrable_cpow' _,
rwa [sub_re, one_re, ←zero_sub, sub_lt_sub_iff_right] },
{ apply continuous_at.continuous_on,
intros x hx,
rw uIcc_of_le (by positivity: (0:ℝ) ≤ 1/2) at hx,
apply continuous_at.cpow,
{ exact (continuous_const.sub continuous_of_real).continuous_at },
{ exact continuous_at_const },
{ rw [sub_re, one_re, of_real_re, sub_pos],
exact or.inl (hx.2.trans_lt (by norm_num : (1/2:ℝ) < 1)) } }
end
/-- The Beta integral is convergent for all `u, v` of positive real part. -/
lemma beta_integral_convergent {u v : ℂ} (hu : 0 < re u) (hv : 0 < re v) :
interval_integrable (λ x, x ^ (u - 1) * (1 - x) ^ (v - 1) : ℝ → ℂ) volume 0 1 :=
begin
refine (beta_integral_convergent_left hu v).trans _,
rw interval_integrable.iff_comp_neg,
convert ((beta_integral_convergent_left hv u).comp_add_right 1).symm,
{ ext1 x,
conv_lhs { rw mul_comm },
congr' 2;
{ push_cast, ring } },
{ norm_num },
{ norm_num }
end
lemma beta_integral_symm (u v : ℂ) :
beta_integral v u = beta_integral u v :=
begin
rw [beta_integral, beta_integral],
have := interval_integral.integral_comp_mul_add
(λ x:ℝ, (x:ℂ) ^ (u - 1) * (1 - ↑x) ^ (v - 1)) (neg_one_lt_zero.ne) 1,
rw [inv_neg, inv_one, neg_one_smul, ←interval_integral.integral_symm] at this,
convert this,
{ ext1 x, rw mul_comm, congr;
{ push_cast, ring } },
{ ring }, { ring }
end
lemma beta_integral_eval_one_right {u : ℂ} (hu : 0 < re u) :
beta_integral u 1 = 1 / u :=
begin
simp_rw [beta_integral, sub_self, cpow_zero, mul_one],
rw integral_cpow (or.inl _),
{ rw [of_real_zero, of_real_one, one_cpow, zero_cpow,
sub_zero, sub_add_cancel],
rw sub_add_cancel,
contrapose! hu, rw [hu, zero_re] },
{ rwa [sub_re, one_re, ←sub_pos, sub_neg_eq_add, sub_add_cancel] },
end
lemma beta_integral_scaled (s t : ℂ) {a : ℝ} (ha : 0 < a) :
∫ x in 0..a, (x:ℂ) ^ (s - 1) * (a - x) ^ (t - 1) = a ^ (s + t - 1) * beta_integral s t :=
begin
have ha' : (a:ℂ) ≠ 0, from of_real_ne_zero.mpr ha.ne',
rw beta_integral,
have A : (a:ℂ) ^ (s + t - 1) = a * (a ^ (s - 1) * a ^ (t - 1)),
{ rw [(by abel : s + t - 1 = 1 + (s - 1) + (t - 1)),
cpow_add _ _ ha', cpow_add 1 _ ha', cpow_one, mul_assoc] },
rw [A, mul_assoc, ←interval_integral.integral_const_mul ((↑a) ^ _ * _),
←real_smul, ←(zero_div a), ←div_self ha.ne',
←interval_integral.integral_comp_div _ ha.ne', zero_div],
simp_rw interval_integral.integral_of_le ha.le,
refine set_integral_congr measurable_set_Ioc (λ x hx, _),
dsimp only,
rw mul_mul_mul_comm,
congr' 1,
{ rw [←mul_cpow_of_real_nonneg ha.le (div_pos hx.1 ha).le, of_real_div, mul_div_cancel' _ ha'] },
{ rw [(by push_cast : (1:ℂ) - ↑(x / a) = ↑(1 - x / a)),
←mul_cpow_of_real_nonneg ha.le (sub_nonneg.mpr $ (div_le_one ha).mpr hx.2)],
push_cast,
rw [mul_sub, mul_one, mul_div_cancel' _ ha'] }
end
/-- Relation between Beta integral and Gamma function. -/
lemma Gamma_mul_Gamma_eq_beta_integral {s t : ℂ} (hs : 0 < re s) (ht : 0 < re t) :
Gamma s * Gamma t = Gamma (s + t) * beta_integral s t :=
begin
-- Note that we haven't proved (yet) that the Gamma function has no zeroes, so we can't formulate
-- this as a formula for the Beta function.
have conv_int := integral_pos_convolution (Gamma_integral_convergent hs)
(Gamma_integral_convergent ht) (continuous_linear_map.mul ℝ ℂ),
simp_rw continuous_linear_map.mul_apply' at conv_int,
have hst : 0 < re (s + t),
{ rw add_re, exact add_pos hs ht },
rw [Gamma_eq_integral hs, Gamma_eq_integral ht, Gamma_eq_integral hst, Gamma_integral,
Gamma_integral, Gamma_integral, ←conv_int, ←integral_mul_right (beta_integral _ _)],
refine set_integral_congr measurable_set_Ioi (λ x hx, _),
dsimp only,
rw [mul_assoc, ←beta_integral_scaled s t hx, ←interval_integral.integral_const_mul],
congr' 1 with y:1,
push_cast,
suffices : cexp (-x) = cexp (-y) * cexp (-(x - y)),
{ rw this, ring },
{ rw ←complex.exp_add, congr' 1, abel },
end
/-- Recurrence formula for the Beta function. -/
lemma beta_integral_recurrence {u v : ℂ} (hu : 0 < re u) (hv : 0 < re v) :
u * beta_integral u (v + 1) = v * beta_integral (u + 1) v :=
begin
-- NB: If we knew `Gamma (u + v + 1) ≠ 0` this would be an easy consequence of
-- `Gamma_mul_Gamma_eq_beta_integral`; but we don't know that yet. We will prove it later, but
-- this lemma is needed in the proof. So we give a (somewhat laborious) direct argument.
let F : ℝ → ℂ := λ x, x ^ u * (1 - x) ^ v,
have hu' : 0 < re (u + 1), by { rw [add_re, one_re], positivity },
have hv' : 0 < re (v + 1), by { rw [add_re, one_re], positivity },
have hc : continuous_on F (Icc 0 1),
{ refine (continuous_at.continuous_on (λ x hx, _)).mul (continuous_at.continuous_on (λ x hx, _)),
{ refine (continuous_at_cpow_const_of_re_pos (or.inl _) hu).comp
continuous_of_real.continuous_at,
rw of_real_re, exact hx.1 },
{ refine (continuous_at_cpow_const_of_re_pos (or.inl _) hv).comp
(continuous_const.sub continuous_of_real).continuous_at,
rw [sub_re, one_re, of_real_re, sub_nonneg],
exact hx.2 } },
have hder : ∀ (x : ℝ), x ∈ Ioo (0:ℝ) 1 → has_deriv_at F
(u * (↑x ^ (u - 1) * (1 - ↑x) ^ v) - v * (↑x ^ u * (1 - ↑x) ^ (v - 1))) x,
{ intros x hx,
have U : has_deriv_at (λ y:ℂ, y ^ u) (u * ↑x ^ (u - 1)) ↑x,
{ have := has_deriv_at.cpow_const (has_deriv_at_id ↑x) (or.inl _),
{ rw mul_one at this, exact this },
{ rw [id.def, of_real_re], exact hx.1 } },
have V : has_deriv_at (λ y:ℂ, (1 - y) ^ v) (-v * (1 - ↑x) ^ (v - 1)) ↑x,
{ have A := has_deriv_at.cpow_const (has_deriv_at_id (1 - ↑x)) (or.inl _),
rotate, { exact v },
{ rw [id.def, sub_re, one_re, of_real_re, sub_pos], exact hx.2 },
simp_rw [id.def] at A,
have B : has_deriv_at (λ y:ℂ, 1 - y) (-1) ↑x,
{ apply has_deriv_at.const_sub, apply has_deriv_at_id },
convert has_deriv_at.comp ↑x A B using 1,
ring },
convert (U.mul V).comp_of_real,
ring },
have h_int := ((beta_integral_convergent hu hv').const_mul u).sub
((beta_integral_convergent hu' hv).const_mul v),
dsimp only at h_int,
rw [add_sub_cancel, add_sub_cancel] at h_int,
have int_ev := interval_integral.integral_eq_sub_of_has_deriv_at_of_le zero_le_one hc hder h_int,
have hF0 : F 0 = 0,
{ simp only [mul_eq_zero, of_real_zero, cpow_eq_zero_iff, eq_self_iff_true,
ne.def, true_and, sub_zero, one_cpow, one_ne_zero, or_false],
contrapose! hu, rw [hu, zero_re] },
have hF1 : F 1 = 0,
{ simp only [mul_eq_zero, of_real_one, one_cpow, one_ne_zero, sub_self,
cpow_eq_zero_iff, eq_self_iff_true, ne.def, true_and, false_or],
contrapose! hv, rw [hv, zero_re] },
rw [hF0, hF1, sub_zero, interval_integral.integral_sub,
interval_integral.integral_const_mul, interval_integral.integral_const_mul] at int_ev,
{ rw [beta_integral, beta_integral, ←sub_eq_zero],
convert int_ev;
{ ext1 x, congr, abel } },
{ apply interval_integrable.const_mul,
convert beta_integral_convergent hu hv',
ext1 x, rw add_sub_cancel },
{ apply interval_integrable.const_mul,
convert beta_integral_convergent hu' hv,
ext1 x, rw add_sub_cancel },
end
/-- Explicit formula for the Beta function when second argument is a positive integer. -/
lemma beta_integral_eval_nat_add_one_right {u : ℂ} (hu : 0 < re u) (n : ℕ) :
beta_integral u (n + 1) = n! / ∏ (j:ℕ) in finset.range (n + 1), (u + j) :=
begin
induction n with n IH generalizing u,
{ rw [nat.cast_zero, zero_add, beta_integral_eval_one_right hu,
nat.factorial_zero, nat.cast_one, zero_add, finset.prod_range_one, nat.cast_zero, add_zero] },
{ have := beta_integral_recurrence hu (_ : 0 < re n.succ),
swap, { rw [←of_real_nat_cast, of_real_re], positivity },
rw [mul_comm u _, ←eq_div_iff] at this,
swap, { contrapose! hu, rw [hu, zero_re] },
rw [this, finset.prod_range_succ', nat.cast_succ, IH],
swap, { rw [add_re, one_re], positivity },
rw [nat.factorial_succ, nat.cast_mul, nat.cast_add, nat.cast_one, nat.cast_zero, add_zero,
←mul_div_assoc, ←div_div],
congr' 3 with j:1,
push_cast, abel }
end
end complex
end beta_integral
section limit_formula
/-! ## The Euler limit formula -/
namespace complex
/-- The sequence with `n`-th term `n ^ s * n! / (s * (s + 1) * ... * (s + n))`, for complex `s`.
We will show that this tends to `Γ(s)` as `n → ∞`. -/
noncomputable def Gamma_seq (s : ℂ) (n : ℕ) :=
(n:ℂ) ^ s * n! / ∏ (j:ℕ) in finset.range (n + 1), (s + j)
lemma Gamma_seq_eq_beta_integral_of_re_pos {s : ℂ} (hs : 0 < re s) (n : ℕ) :
Gamma_seq s n = n ^ s * beta_integral s (n + 1) :=
by rw [Gamma_seq, beta_integral_eval_nat_add_one_right hs n, ←mul_div_assoc]
lemma Gamma_seq_add_one_left (s : ℂ) {n : ℕ} (hn : n ≠ 0) :
(Gamma_seq (s + 1) n) / s = n / (n + 1 + s) * Gamma_seq s n :=
begin
conv_lhs { rw [Gamma_seq, finset.prod_range_succ, div_div] },
conv_rhs { rw [Gamma_seq, finset.prod_range_succ', nat.cast_zero, add_zero, div_mul_div_comm,
←mul_assoc, ←mul_assoc, mul_comm _ (finset.prod _ _)] },
congr' 3,
{ rw [cpow_add _ _ (nat.cast_ne_zero.mpr hn), cpow_one, mul_comm] },
{ refine finset.prod_congr (by refl) (λ x hx, _),
push_cast, ring },
{ abel }
end
lemma Gamma_seq_eq_approx_Gamma_integral {s : ℂ} (hs : 0 < re s) {n : ℕ} (hn : n ≠ 0) :
Gamma_seq s n = ∫ x:ℝ in 0..n, ↑((1 - x / n) ^ n) * (x:ℂ) ^ (s - 1) :=
begin
have : ∀ (x : ℝ), x = x / n * n, by { intro x, rw div_mul_cancel, exact nat.cast_ne_zero.mpr hn },
conv in (↑_ ^ _) { congr, rw this x },
rw Gamma_seq_eq_beta_integral_of_re_pos hs,
rw [beta_integral, @interval_integral.integral_comp_div _ _ _ _ 0 n _
(λ x, ↑((1 - x) ^ n) * ↑(x * ↑n) ^ (s - 1) : ℝ → ℂ) (nat.cast_ne_zero.mpr hn),
real_smul, zero_div, div_self, add_sub_cancel, ←interval_integral.integral_const_mul,
←interval_integral.integral_const_mul],
swap, { exact nat.cast_ne_zero.mpr hn },
simp_rw interval_integral.integral_of_le zero_le_one,
refine set_integral_congr measurable_set_Ioc (λ x hx, _),
push_cast,
have hn' : (n : ℂ) ≠ 0, from nat.cast_ne_zero.mpr hn,
have A : (n : ℂ) ^ s = (n : ℂ) ^ (s - 1) * n,
{ conv_lhs { rw [(by ring : s = (s - 1) + 1), cpow_add _ _ hn'] },
simp },
have B : ((x : ℂ) * ↑n) ^ (s - 1) = (x : ℂ) ^ (s - 1) * ↑n ^ (s - 1),
{ rw [←of_real_nat_cast,
mul_cpow_of_real_nonneg hx.1.le (nat.cast_pos.mpr (nat.pos_of_ne_zero hn)).le] },
rw [A, B, cpow_nat_cast], ring,
end
/-- The main techical lemma for `Gamma_seq_tendsto_Gamma`, expressing the integral defining the
Gamma function for `0 < re s` as the limit of a sequence of integrals over finite intervals. -/
lemma approx_Gamma_integral_tendsto_Gamma_integral {s : ℂ} (hs : 0 < re s) :
tendsto (λ n:ℕ, ∫ x:ℝ in 0..n, ↑((1 - x / n) ^ n) * (x:ℂ) ^ (s - 1)) at_top (𝓝 $ Gamma s) :=
begin
rw [Gamma_eq_integral hs],
-- We apply dominated convergence to the following function, which we will show is uniformly
-- bounded above by the Gamma integrand `exp (-x) * x ^ (re s - 1)`.
let f : ℕ → ℝ → ℂ := λ n, indicator (Ioc 0 (n:ℝ))
(λ x:ℝ, ↑((1 - x / n) ^ n) * (x:ℂ) ^ (s - 1)),
-- integrability of f
have f_ible : ∀ (n:ℕ), integrable (f n) (volume.restrict (Ioi 0)),
{ intro n,
rw [integrable_indicator_iff (measurable_set_Ioc : measurable_set (Ioc (_:ℝ) _)),
integrable_on, measure.restrict_restrict_of_subset Ioc_subset_Ioi_self, ←integrable_on,
←interval_integrable_iff_integrable_Ioc_of_le (by positivity : (0:ℝ) ≤ n)],
apply interval_integrable.continuous_on_mul,
{ refine interval_integral.interval_integrable_cpow' _,
rwa [sub_re, one_re, ←zero_sub, sub_lt_sub_iff_right] },
{ apply continuous.continuous_on, continuity } },
-- pointwise limit of f
have f_tends : ∀ x:ℝ, x ∈ Ioi (0:ℝ) →
tendsto (λ n:ℕ, f n x) at_top (𝓝 $ ↑(real.exp (-x)) * (x:ℂ) ^ (s - 1)),
{ intros x hx,
apply tendsto.congr',
show ∀ᶠ n:ℕ in at_top, ↑((1 - x / n) ^ n) * (x:ℂ) ^ (s - 1) = f n x,
{ refine eventually.mp (eventually_ge_at_top ⌈x⌉₊) (eventually_of_forall (λ n hn, _)),
rw nat.ceil_le at hn,
dsimp only [f],
rw indicator_of_mem,
exact ⟨hx, hn⟩ },
{ simp_rw mul_comm _ (↑x ^ _),
refine (tendsto.comp (continuous_of_real.tendsto _) _).const_mul _,
convert tendsto_one_plus_div_pow_exp (-x),
ext1 n,
rw [neg_div, ←sub_eq_add_neg] } },
-- let `convert` identify the remaining goals
convert tendsto_integral_of_dominated_convergence _ (λ n, (f_ible n).1)
(real.Gamma_integral_convergent hs) _
((ae_restrict_iff' measurable_set_Ioi).mpr (ae_of_all _ f_tends)),
-- limit of f is the integrand we want
{ ext1 n,
rw [integral_indicator (measurable_set_Ioc : measurable_set (Ioc (_:ℝ) _)),
interval_integral.integral_of_le (by positivity: 0 ≤ (n:ℝ)),
measure.restrict_restrict_of_subset Ioc_subset_Ioi_self] },
-- f is uniformly bounded by the Gamma integrand
{ intro n,
refine (ae_restrict_iff' measurable_set_Ioi).mpr (ae_of_all _ (λ x hx, _)),
dsimp only [f],
rcases lt_or_le (n:ℝ) x with hxn | hxn,
{ rw [indicator_of_not_mem (not_mem_Ioc_of_gt hxn), norm_zero,
mul_nonneg_iff_right_nonneg_of_pos (exp_pos _)],
exact rpow_nonneg_of_nonneg (le_of_lt hx) _ },
{ rw [indicator_of_mem (mem_Ioc.mpr ⟨hx, hxn⟩), norm_mul, complex.norm_eq_abs,
complex.abs_of_nonneg
(pow_nonneg (sub_nonneg.mpr $ div_le_one_of_le hxn $ by positivity) _),
complex.norm_eq_abs, abs_cpow_eq_rpow_re_of_pos hx, sub_re, one_re,
mul_le_mul_right (rpow_pos_of_pos hx _ )],
exact one_sub_div_pow_le_exp_neg hxn } }
end
/-- Euler's limit formula for the complex Gamma function. -/
lemma Gamma_seq_tendsto_Gamma (s : ℂ) :
tendsto (Gamma_seq s) at_top (𝓝 $ Gamma s) :=
begin
suffices : ∀ m : ℕ, (-↑m < re s) → tendsto (Gamma_seq s) at_top (𝓝 $ Gamma_aux m s),
{ rw Gamma,
apply this,
rw neg_lt,
rcases lt_or_le 0 (re s) with hs | hs,
{ exact (neg_neg_of_pos hs).trans_le (nat.cast_nonneg _), },
{ refine (nat.lt_floor_add_one _).trans_le _,
rw [sub_eq_neg_add, nat.floor_add_one (neg_nonneg.mpr hs), nat.cast_add_one] } },
intro m,
induction m with m IH generalizing s,
{ -- Base case: `0 < re s`, so Gamma is given by the integral formula
intro hs,
rw [nat.cast_zero, neg_zero] at hs,
rw [←Gamma_eq_Gamma_aux],
{ refine tendsto.congr' _ (approx_Gamma_integral_tendsto_Gamma_integral hs),
refine (eventually_ne_at_top 0).mp (eventually_of_forall (λ n hn, _)),
exact (Gamma_seq_eq_approx_Gamma_integral hs hn).symm },
{ rwa [nat.cast_zero, neg_lt_zero] } },
{ -- Induction step: use recurrence formulae in `s` for Gamma and Gamma_seq
intro hs,
rw [nat.cast_succ, neg_add, ←sub_eq_add_neg, sub_lt_iff_lt_add, ←one_re, ←add_re] at hs,
rw Gamma_aux,
have := tendsto.congr' ((eventually_ne_at_top 0).mp (eventually_of_forall (λ n hn, _)))
((IH _ hs).div_const s),
swap 3, { exact Gamma_seq_add_one_left s hn }, -- doesn't work if inlined?
conv at this in (_ / _ * _) { rw mul_comm },
rwa [←mul_one (Gamma_aux m (s + 1) / s), tendsto_mul_iff_of_ne_zero _ (one_ne_zero' ℂ)] at this,
simp_rw add_assoc,
exact tendsto_coe_nat_div_add_at_top (1 + s) }
end
end complex
end limit_formula
section gamma_reflection
/-! ## The reflection formula -/
open_locale real
namespace complex
lemma Gamma_seq_mul (z : ℂ) {n : ℕ} (hn : n ≠ 0) :
Gamma_seq z n * Gamma_seq (1 - z) n =
n / (n + 1 - z) * (1 / (z * ∏ j in finset.range n, (1 - z ^ 2 / (j + 1) ^ 2))) :=
begin
-- also true for n = 0 but we don't need it
have aux : ∀ (a b c d : ℂ), a * b * (c * d) = a * c * (b * d), by { intros, ring },
rw [Gamma_seq, Gamma_seq, div_mul_div_comm, aux, ←pow_two],
have : (n : ℂ) ^ z * n ^ (1 - z) = n,
{ rw [←cpow_add _ _ (nat.cast_ne_zero.mpr hn), add_sub_cancel'_right, cpow_one] },
rw [this, finset.prod_range_succ', finset.prod_range_succ, aux, ←finset.prod_mul_distrib,
nat.cast_zero, add_zero, add_comm (1 - z) n, ←add_sub_assoc],
have : ∀ (j : ℕ), (z + ↑(j + 1)) * (1 - z + ↑j) = ↑((j + 1) ^ 2) * (1 - z ^ 2 / (↑j + 1) ^ 2),
{ intro j,
push_cast,
have : (j:ℂ) + 1 ≠ 0, by { rw [←nat.cast_succ, nat.cast_ne_zero], exact nat.succ_ne_zero j },
field_simp, ring },
simp_rw this,
rw [finset.prod_mul_distrib, ←nat.cast_prod, finset.prod_pow,
finset.prod_range_add_one_eq_factorial, nat.cast_pow,
(by {intros, ring} : ∀ (a b c d : ℂ), a * b * (c * d) = a * (d * (b * c))),
←div_div, mul_div_cancel, ←div_div, mul_comm z _, mul_one_div],
exact pow_ne_zero 2 (nat.cast_ne_zero.mpr $ nat.factorial_ne_zero n),
end
/-- Euler's reflection formula for the complex Gamma function. -/
theorem Gamma_mul_Gamma_one_sub (z : ℂ) : Gamma z * Gamma (1 - z) = π / sin (π * z) :=
begin
have pi_ne : (π : ℂ) ≠ 0, from complex.of_real_ne_zero.mpr pi_ne_zero,
by_cases hs : sin (↑π * z) = 0,
{ -- first deal with silly case z = integer
rw [hs, div_zero],
rw [←neg_eq_zero, ←complex.sin_neg, ←mul_neg, complex.sin_eq_zero_iff, mul_comm] at hs,
obtain ⟨k, hk⟩ := hs,
rw [mul_eq_mul_right_iff, eq_false_intro (of_real_ne_zero.mpr pi_pos.ne'), or_false,
neg_eq_iff_eq_neg] at hk,
rw hk,
cases k,
{ rw [int.cast_of_nat, complex.Gamma_neg_nat_eq_zero, zero_mul] },
{ rw [int.cast_neg_succ_of_nat, neg_neg, nat.cast_add, nat.cast_one, add_comm, sub_add_cancel',
complex.Gamma_neg_nat_eq_zero, mul_zero] } },
refine tendsto_nhds_unique ((Gamma_seq_tendsto_Gamma z).mul (Gamma_seq_tendsto_Gamma $ 1 - z)) _,
have : ↑π / sin (↑π * z) = 1 * (π / sin (π * z)), by rw one_mul, rw this,
refine tendsto.congr' ((eventually_ne_at_top 0).mp
(eventually_of_forall (λ n hn, (Gamma_seq_mul z hn).symm))) (tendsto.mul _ _),
{ convert tendsto_coe_nat_div_add_at_top (1 - z), ext1 n, rw add_sub_assoc },
{ have : ↑π / sin (↑π * z) = 1 / (sin (π * z) / π), by field_simp, rw this,
refine tendsto_const_nhds.div _ (div_ne_zero hs pi_ne),
rw [←tendsto_mul_iff_of_ne_zero tendsto_const_nhds pi_ne, div_mul_cancel _ pi_ne],
convert tendsto_euler_sin_prod z,
ext1 n, rw [mul_comm, ←mul_assoc] },
end
/-- The Gamma function does not vanish on `ℂ` (except at non-positive integers, where the function
is mathematically undefined and we set it to `0` by convention). -/
theorem Gamma_ne_zero {s : ℂ} (hs : ∀ m : ℕ, s ≠ -m) : Gamma s ≠ 0 :=
begin
by_cases h_im : s.im = 0,
{ have : s = ↑s.re,
{ conv_lhs { rw ←complex.re_add_im s }, rw [h_im, of_real_zero, zero_mul, add_zero] },
rw [this, Gamma_of_real, of_real_ne_zero],
refine real.Gamma_ne_zero (λ n, _),
specialize hs n,
contrapose! hs,
rwa [this, ←of_real_nat_cast, ←of_real_neg, of_real_inj] },
{ have : sin (↑π * s) ≠ 0,
{ rw complex.sin_ne_zero_iff,
intro k,
apply_fun im,
rw [of_real_mul_im, ←of_real_int_cast, ←of_real_mul, of_real_im],
exact mul_ne_zero real.pi_pos.ne' h_im },
have A := div_ne_zero (of_real_ne_zero.mpr real.pi_pos.ne') this,
rw [←complex.Gamma_mul_Gamma_one_sub s, mul_ne_zero_iff] at A,
exact A.1 }
end
lemma Gamma_eq_zero_iff (s : ℂ) : Gamma s = 0 ↔ ∃ m : ℕ, s = -m :=
begin
split,
{ contrapose!, exact Gamma_ne_zero },
{ rintro ⟨m, rfl⟩, exact Gamma_neg_nat_eq_zero m },
end
end complex
namespace real
/-- The sequence with `n`-th term `n ^ s * n! / (s * (s + 1) * ... * (s + n))`, for real `s`. We
will show that this tends to `Γ(s)` as `n → ∞`. -/
noncomputable def Gamma_seq (s : ℝ) (n : ℕ) :=
(n : ℝ) ^ s * n! / ∏ (j : ℕ) in finset.range (n + 1), (s + j)
/-- Euler's limit formula for the real Gamma function. -/
lemma Gamma_seq_tendsto_Gamma (s : ℝ) : tendsto (Gamma_seq s) at_top (𝓝 $ Gamma s) :=
begin
suffices : tendsto (coe ∘ Gamma_seq s : ℕ → ℂ) at_top (𝓝 $ complex.Gamma s),
from (complex.continuous_re.tendsto (complex.Gamma ↑s)).comp this,
convert complex.Gamma_seq_tendsto_Gamma s,
ext1 n,
dsimp only [Gamma_seq, function.comp_app, complex.Gamma_seq],
push_cast,
rw [complex.of_real_cpow n.cast_nonneg, complex.of_real_nat_cast]
end
/-- Euler's reflection formula for the real Gamma function. -/
lemma Gamma_mul_Gamma_one_sub (s : ℝ) : Gamma s * Gamma (1 - s) = π / sin (π * s) :=
begin
simp_rw [←complex.of_real_inj, complex.of_real_div, complex.of_real_sin,
complex.of_real_mul, ←complex.Gamma_of_real, complex.of_real_sub, complex.of_real_one],
exact complex.Gamma_mul_Gamma_one_sub s
end
end real
end gamma_reflection
|
ddabe901aa47e2b285287c48bdd7479d48f2dd6c | 2a70b774d16dbdf5a533432ee0ebab6838df0948 | /_target/deps/mathlib/src/group_theory/dihedral.lean | c83aa3299fc86af488f868d4dd1d3356588557c3 | [
"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 | 4,799 | lean | /-
Copyright (c) 2020 Shing Tak Lam. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Shing Tak Lam
-/
import data.zmod.basic
import group_theory.order_of_element
/-!
# Dihedral Groups
We define the dihedral groups `dihedral n`, with elements `r i` and `sr i` for `i : zmod n`.
For `n ≠ 0`, `dihedral n` represents the symmetry group of the regular `n`-gon. `r i` represents
the rotations of the `n`-gon by `2πi/n`, and `sr i` represents the reflections of the `n`-gon.
`dihedral 0` corresponds to the infinite dihedral group.
-/
/--
For `n ≠ 0`, `dihedral n` represents the symmetry group of the regular `n`-gon. `r i` represents
the rotations of the `n`-gon by `2πi/n`, and `sr i` represents the reflections of the `n`-gon.
`dihedral 0` corresponds to the infinite dihedral group.
-/
@[derive decidable_eq]
inductive dihedral (n : ℕ) : Type
| r : zmod n → dihedral
| sr : zmod n → dihedral
namespace dihedral
variables {n : ℕ}
/--
Multiplication of the dihedral group.
-/
private def mul : dihedral n → dihedral n → dihedral n
| (r i) (r j) := r (i + j)
| (r i) (sr j) := sr (j - i)
| (sr i) (r j) := sr (i + j)
| (sr i) (sr j) := r (j - i)
/--
The identity `1` is the rotation by `0`.
-/
private def one : dihedral n := r 0
instance : inhabited (dihedral n) := ⟨one⟩
/--
The inverse of a an element of the dihedral group.
-/
private def inv : dihedral n → dihedral n
| (r i) := r (-i)
| (sr i) := sr i
/--
The group structure on `dihedral n`.
-/
instance : group (dihedral n) :=
{ mul := mul,
mul_assoc :=
begin
rintros (a | a) (b | b) (c | c);
simp only [mul];
ring,
end,
one := one,
one_mul :=
begin
rintros (a | a),
exact congr_arg r (zero_add a),
exact congr_arg sr (sub_zero a),
end,
mul_one := begin
rintros (a | a),
exact congr_arg r (add_zero a),
exact congr_arg sr (add_zero a),
end,
inv := inv,
mul_left_inv := begin
rintros (a | a),
exact congr_arg r (neg_add_self a),
exact congr_arg r (sub_self a),
end }
@[simp] lemma r_mul_r (i j : zmod n) : r i * r j = r (i + j) := rfl
@[simp] lemma r_mul_sr (i j : zmod n) : r i * sr j = sr (j - i) := rfl
@[simp] lemma sr_mul_r (i j : zmod n) : sr i * r j = sr (i + j) := rfl
@[simp] lemma sr_mul_sr (i j : zmod n) : sr i * sr j = r (j - i) := rfl
lemma one_def : (1 : dihedral n) = r 0 := rfl
private def fintype_helper : (zmod n ⊕ zmod n) ≃ dihedral n :=
{ inv_fun := λ i, match i with
| (r j) := sum.inl j
| (sr j) := sum.inr j
end,
to_fun := λ i, match i with
| (sum.inl j) := r j
| (sum.inr j) := sr j
end,
left_inv := by rintro (x | x); refl,
right_inv := by rintro (x | x); refl }
/--
If `0 < n`, then `dihedral n` is a finite group.
-/
instance [fact (0 < n)] : fintype (dihedral n) := fintype.of_equiv _ fintype_helper
instance : nontrivial (dihedral n) := ⟨⟨r 0, sr 0, dec_trivial⟩⟩
/--
If `0 < n`, then `dihedral n` has `2n` elements.
-/
lemma card [fact (0 < n)] : fintype.card (dihedral n) = 2 * n :=
begin
rw ←fintype.card_eq.mpr ⟨fintype_helper⟩,
change fintype.card (zmod n ⊕ zmod n) = 2 * n,
rw [fintype.card_sum, zmod.card, two_mul]
end
@[simp] lemma r_one_pow (k : ℕ) : (r 1 : dihedral n) ^ k = r k :=
begin
induction k with k IH,
{ refl },
{ rw [pow_succ, IH, r_mul_r],
congr' 1,
norm_cast,
rw nat.one_add }
end
@[simp] lemma r_one_pow_n : (r (1 : zmod n))^n = 1 :=
begin
cases n,
{ rw pow_zero },
{ rw [r_one_pow, one_def],
congr' 1,
exact zmod.cast_self _, }
end
@[simp] lemma sr_mul_self (i : zmod n) : sr i * sr i = 1 := by rw [sr_mul_sr, sub_self, one_def]
/--
If `0 < n`, then `sr i` has order 2.
-/
@[simp] lemma order_of_sr [fact (0 < n)] (i : zmod n) : order_of (sr i) = 2 :=
begin
rw order_of_eq_prime _ _,
{ exact nat.prime_two },
rw [pow_two, sr_mul_self],
dec_trivial,
end
/--
If `0 < n`, then `r 1` has order `n`.
-/
@[simp] lemma order_of_r_one [hnpos : fact (0 < n)] : order_of (r 1 : dihedral n) = n :=
begin
cases lt_or_eq_of_le (nat.le_of_dvd hnpos (order_of_dvd_of_pow_eq_one (@r_one_pow_n n))) with h h,
{ have h1 : (r 1 : dihedral n)^(order_of (r 1)) = 1,
{ exact pow_order_of_eq_one _ },
rw r_one_pow at h1,
injection h1 with h2,
rw [←zmod.val_eq_zero, zmod.val_cast_nat, nat.mod_eq_of_lt h] at h2,
exact absurd h2.symm (ne_of_lt (order_of_pos _)) },
{ exact h }
end
/--
If `0 < n`, then `i : zmod n` has order `n / gcd n i`
-/
lemma order_of_r [fact (0 < n)] (i : zmod n) : order_of (r i) = n / nat.gcd n i.val :=
begin
conv_lhs { rw ←zmod.cast_val i },
rw [←r_one_pow, order_of_pow, order_of_r_one]
end
end dihedral
|
f05be989927057a54f51ca156ca6dae78257a269 | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /src/Lean/Meta/LevelDefEq.lean | a81431df1449e840e79d568959b46c7faa417179 | [
"Apache-2.0"
] | permissive | subfish-zhou/leanprover-zh_CN.github.io | 30b9fba9bd790720bd95764e61ae796697d2f603 | 8b2985d4a3d458ceda9361ac454c28168d920d3f | refs/heads/master | 1,689,709,967,820 | 1,632,503,056,000 | 1,632,503,056,000 | 409,962,097 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,709 | 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.Util.CollectMVars
import Lean.Util.ReplaceExpr
import Lean.Meta.Basic
import Lean.Meta.InferType
namespace Lean.Meta
structure DecLevelContext where
/--
If `true`, then `decAux? ?m` returns a fresh metavariable `?n` s.t.
`?m := ?n+1`.
-/
canAssignMVars : Bool := true
private partial def decAux? : Level → ReaderT DecLevelContext MetaM (Option Level)
| Level.zero _ => return none
| Level.param _ _ => return none
| Level.mvar mvarId _ => do
let mctx ← getMCtx
match mctx.getLevelAssignment? mvarId with
| some u => decAux? u
| none =>
if (← isReadOnlyLevelMVar mvarId) || !(← read).canAssignMVars then
return none
else
let u ← mkFreshLevelMVar
trace[Meta.isLevelDefEq.step] "decAux?, {mkLevelMVar mvarId} := {mkLevelSucc u}"
assignLevelMVar mvarId (mkLevelSucc u)
return u
| Level.succ u _ => return u
| u =>
let processMax (u v : Level) : ReaderT DecLevelContext MetaM (Option Level) := do
/- Remark: this code uses the fact that `max (u+1) (v+1) = (max u v)+1`.
`decAux? (max (u+1) (v+1)) := max (decAux? (u+1)) (decAux? (v+1))`
However, we must *not* assign metavariables in the recursive calls since
`max ?u 1` is not equivalent to `max ?v 0` where `?v` is a fresh metavariable, and `?u := ?v+1`
-/
withReader (fun _ => { canAssignMVars := false }) do
match (← decAux? u) with
| none => return none
| some u => do
match (← decAux? v) with
| none => return none
| some v => return mkLevelMax' u v
match u with
| Level.max u v _ => processMax u v
/- Remark: If `decAux? v` returns `some ...`, then `imax u v` is equivalent to `max u v`. -/
| Level.imax u v _ => processMax u v
| _ => unreachable!
def decLevel? (u : Level) : MetaM (Option Level) := do
let mctx ← getMCtx
match (← decAux? u |>.run {}) with
| some v => return some v
| none => do
modify fun s => { s with mctx := mctx }
return none
def decLevel (u : Level) : MetaM Level := do
match (← decLevel? u) with
| some u => return u
| none => throwError "invalid universe level, {u} is not greater than 0"
/- This method is useful for inferring universe level parameters for function that take arguments such as `{α : Type u}`.
Recall that `Type u` is `Sort (u+1)` in Lean. Thus, given `α`, we must infer its universe level,
and then decrement 1 to obtain `u`. -/
def getDecLevel (type : Expr) : MetaM Level := do
decLevel (← getLevel type)
/--
Return true iff `lvl` occurs in `max u_1 ... u_n` and `lvl != u_i` for all `i in [1, n]`.
That is, `lvl` is a proper level subterm of some `u_i`. -/
private def strictOccursMax (lvl : Level) : Level → Bool
| Level.max u v _ => visit u || visit v
| _ => false
where
visit : Level → Bool
| Level.max u v _ => visit u || visit v
| u => u != lvl && lvl.occurs u
/-- `mkMaxArgsDiff mvarId (max u_1 ... (mvar mvarId) ... u_n) v` => `max v u_1 ... u_n` -/
private def mkMaxArgsDiff (mvarId : MVarId) : Level → Level → Level
| Level.max u v _, acc => mkMaxArgsDiff mvarId v <| mkMaxArgsDiff mvarId u acc
| l@(Level.mvar id _), acc => if id != mvarId then mkLevelMax' acc l else acc
| l, acc => mkLevelMax' acc l
/--
Solve `?m =?= max ?m v` by creating a fresh metavariable `?n`
and assigning `?m := max ?n v` -/
private def solveSelfMax (mvarId : MVarId) (v : Level) : MetaM Unit := do
assert! v.isMax
let n ← mkFreshLevelMVar
assignLevelMVar mvarId <| mkMaxArgsDiff mvarId v n
private def postponeIsLevelDefEq (lhs : Level) (rhs : Level) : MetaM Unit := do
let ref ← getRef
let ctx ← read
trace[Meta.isLevelDefEq.stuck] "{lhs} =?= {rhs}"
modifyPostponed fun postponed => postponed.push { lhs := lhs, rhs := rhs, ref := ref, ctx? := ctx.defEqCtx? }
private def isMVarWithGreaterDepth (v : Level) (mvarId : MVarId) : MetaM Bool :=
match v with
| Level.mvar mvarId' _ => return (← getLevelMVarDepth mvarId') > (← getLevelMVarDepth mvarId)
| _ => return false
mutual
private partial def solve (u v : Level) : MetaM LBool := do
match u, v with
| Level.mvar mvarId _, _ =>
if (← isReadOnlyLevelMVar mvarId) then
return LBool.undef
else if (← getConfig).ignoreLevelMVarDepth && (← isMVarWithGreaterDepth v mvarId) then
-- If both `u` and `v` are both metavariables, but depth of v is greater, then we assign `v := u`.
-- This can only happen when `ignoreLevelDepth` is set to true.
assignLevelMVar v.mvarId! u
return LBool.true
else if !u.occurs v then
assignLevelMVar u.mvarId! v
return LBool.true
else if v.isMax && !strictOccursMax u v then
solveSelfMax u.mvarId! v
return LBool.true
else
return LBool.undef
| _, Level.mvar .. => LBool.undef -- Let `solve v u` to handle this case
| Level.zero _, Level.max v₁ v₂ _ =>
Bool.toLBool <$> (isLevelDefEqAux levelZero v₁ <&&> isLevelDefEqAux levelZero v₂)
| Level.zero _, Level.imax _ v₂ _ =>
Bool.toLBool <$> isLevelDefEqAux levelZero v₂
| Level.zero _, Level.succ .. => return LBool.false
| Level.succ u _, v =>
if v.isParam then
return LBool.false
else if u.isMVar && u.occurs v then
return LBool.undef
else
match (← Meta.decLevel? v) with
| some v => Bool.toLBool <$> isLevelDefEqAux u v
| none => return LBool.undef
| _, _ => return LBool.undef
partial def isLevelDefEqAux : Level → Level → MetaM Bool
| Level.succ lhs _, Level.succ rhs _ => isLevelDefEqAux lhs rhs
| lhs, rhs => do
if lhs.getLevelOffset == rhs.getLevelOffset then
return lhs.getOffset == rhs.getOffset
else
trace[Meta.isLevelDefEq.step] "{lhs} =?= {rhs}"
let lhs' ← instantiateLevelMVars lhs
let lhs' := lhs'.normalize
let rhs' ← instantiateLevelMVars rhs
let rhs' := rhs'.normalize
if lhs != lhs' || rhs != rhs' then
isLevelDefEqAux lhs' rhs'
else
let r ← solve lhs rhs;
if r != LBool.undef then
return r == LBool.true
else
let r ← solve rhs lhs;
if r != LBool.undef then
return r == LBool.true
else do
let mctx ← getMCtx
if !mctx.hasAssignableLevelMVar lhs && !mctx.hasAssignableLevelMVar rhs then
let ctx ← read
if ctx.config.isDefEqStuckEx && (lhs.isMVar || rhs.isMVar) then do
trace[Meta.isLevelDefEq.stuck] "{lhs} =?= {rhs}"
Meta.throwIsDefEqStuck
else
return false
else
postponeIsLevelDefEq lhs rhs
return true
end
def isListLevelDefEqAux : List Level → List Level → MetaM Bool
| [], [] => return true
| u::us, v::vs => isLevelDefEqAux u v <&&> isListLevelDefEqAux us vs
| _, _ => return false
private def getNumPostponed : MetaM Nat := do
return (← getPostponed).size
open Std (PersistentArray)
def getResetPostponed : MetaM (PersistentArray PostponedEntry) := do
let ps ← getPostponed
setPostponed {}
return ps
/-- Annotate any constant and sort in `e` that satisfies `p` with `pp.universes true` -/
private def exposeRelevantUniverses (e : Expr) (p : Level → Bool) : Expr :=
e.replace fun
| Expr.const _ us _ => if us.any p then some (e.setPPUniverses true) else none
| Expr.sort u _ => if p u then some (e.setPPUniverses true) else none
| _ => none
private def mkLeveErrorMessageCore (header : String) (entry : PostponedEntry) : MetaM MessageData := do
match entry.ctx? with
| none =>
return m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}"
| some ctx =>
withLCtx ctx.lctx ctx.localInstances do
let s := entry.lhs.collectMVars entry.rhs.collectMVars
/- `p u` is true if it contains a universe metavariable in `s` -/
let p (u : Level) := u.any fun | Level.mvar m _ => s.contains m | _ => false
let lhs := exposeRelevantUniverses (← instantiateMVars ctx.lhs) p
let rhs := exposeRelevantUniverses (← instantiateMVars ctx.rhs) p
try
addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD m!"{lhs} : {← inferType lhs}"}\nwith{indentD m!"{rhs} : {← inferType rhs}"}"
catch _ =>
addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD lhs}\nwith{indentD rhs}"
def mkLevelStuckErrorMessage (entry : PostponedEntry) : MetaM MessageData := do
mkLeveErrorMessageCore "stuck at solving universe constraint" entry
def mkLevelErrorMessage (entry : PostponedEntry) : MetaM MessageData := do
mkLeveErrorMessageCore "failed to solve universe constraint" entry
private def processPostponedStep (exceptionOnFailure : Bool) : MetaM Bool :=
traceCtx `Meta.isLevelDefEq.postponed.step do
let ps ← getResetPostponed
for p in ps do
unless (← withReader (fun ctx => { ctx with defEqCtx? := p.ctx? }) <| isLevelDefEqAux p.lhs p.rhs) do
if exceptionOnFailure then
throwError (← mkLevelErrorMessage p)
else
return false
return true
partial def processPostponed (mayPostpone : Bool := true) (exceptionOnFailure := false) : MetaM Bool := do
if (← getNumPostponed) == 0 then
return true
else
traceCtx `Meta.isLevelDefEq.postponed do
let rec loop : MetaM Bool := do
let numPostponed ← getNumPostponed
if numPostponed == 0 then
return true
else
trace[Meta.isLevelDefEq.postponed] "processing #{numPostponed} postponed is-def-eq level constraints"
if !(← processPostponedStep exceptionOnFailure) then
return false
else
let numPostponed' ← getNumPostponed
if numPostponed' == 0 then
return true
else if numPostponed' < numPostponed then
loop
else
trace[Meta.isLevelDefEq.postponed] "no progress solving pending is-def-eq level constraints"
return mayPostpone
loop
/--
`checkpointDefEq x` executes `x` and process all postponed universe level constraints produced by `x`.
We keep the modifications only if `processPostponed` return true and `x` returned `true`.
If `mayPostpone == false`, all new postponed universe level constraints must be solved before returning.
We currently try to postpone universe constraints as much as possible, even when by postponing them we
are not sure whether `x` really succeeded or not.
-/
@[specialize] def checkpointDefEq (x : MetaM Bool) (mayPostpone : Bool := true) : MetaM Bool := do
let s ← saveState
let postponed ← getResetPostponed
try
if (← x) then
if (← processPostponed mayPostpone) then
let newPostponed ← getPostponed
setPostponed (postponed ++ newPostponed)
return true
else
s.restore
return false
else
s.restore
return false
catch ex =>
s.restore
throw ex
def isLevelDefEq (u v : Level) : MetaM Bool :=
traceCtx `Meta.isLevelDefEq do
let b ← checkpointDefEq (mayPostpone := true) <| Meta.isLevelDefEqAux u v
trace[Meta.isLevelDefEq] "{u} =?= {v} ... {if b then "success" else "failure"}"
return b
def isExprDefEq (t s : Expr) : MetaM Bool :=
traceCtx `Meta.isDefEq <| withReader (fun ctx => { ctx with defEqCtx? := some { lhs := t, rhs := s, lctx := ctx.lctx, localInstances := ctx.localInstances } }) do
let b ← checkpointDefEq (mayPostpone := true) <| Meta.isExprDefEqAux t s
trace[Meta.isDefEq] "{t} =?= {s} ... {if b then "success" else "failure"}"
return b
abbrev isDefEq (t s : Expr) : MetaM Bool :=
isExprDefEq t s
def isExprDefEqGuarded (a b : Expr) : MetaM Bool := do
try isExprDefEq a b catch _ => return false
abbrev isDefEqGuarded (t s : Expr) : MetaM Bool :=
isExprDefEqGuarded t s
def isDefEqNoConstantApprox (t s : Expr) : MetaM Bool :=
approxDefEq <| isDefEq t s
builtin_initialize
registerTraceClass `Meta.isLevelDefEq
registerTraceClass `Meta.isLevelDefEq.step
registerTraceClass `Meta.isLevelDefEq.postponed
end Lean.Meta
|
04e6517ec3358cbf7a2e62f9627de2966842d853 | b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77 | /src/measure_theory/integration.lean | 6b15cffa98f9a43fa5cfeb615bcb078a7feeb7ba | [
"Apache-2.0"
] | permissive | molodiuc/mathlib | cae2ba3ef1601c1f42ca0b625c79b061b63fef5b | 98ebe5a6739fbe254f9ee9d401882d4388f91035 | refs/heads/master | 1,674,237,127,059 | 1,606,353,533,000 | 1,606,353,533,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 71,861 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Johannes Hölzl
-/
import measure_theory.measure_space
import measure_theory.borel_space
import data.indicator_function
import data.support
/-!
# Lebesgue integral for `ennreal`-valued functions
We define simple functions and show that each Borel measurable function on `ennreal` can be
approximated by a sequence of simple functions.
To prove something for an arbitrary measurable function into `ennreal`, the theorem
`measurable.ennreal_induction` shows that is it sufficient to show that the property holds for
(multiples of) characteristic functions and is closed under addition and supremum of increasing
sequences of functions.
## Notation
We introduce the following notation for the lower Lebesgue integral of a function `f : α → ennreal`.
* `∫⁻ x, f x ∂μ`: integral of a function `f : α → ennreal` with respect to a measure `μ`;
* `∫⁻ x, f x`: integral of a function `f : α → ennreal` with respect to the canonical measure
`volume` on `α`;
* `∫⁻ x in s, f x ∂μ`: integral of a function `f : α → ennreal` over a set `s` with respect
to a measure `μ`, defined as `∫⁻ x, f x ∂(μ.restrict s)`;
* `∫⁻ x in s, f x`: integral of a function `f : α → ennreal` over a set `s` with respect
to the canonical measure `volume`, defined as `∫⁻ x, f x ∂(volume.restrict s)`.
-/
noncomputable theory
open set (hiding restrict restrict_apply) filter ennreal
open_locale classical topological_space big_operators nnreal
namespace measure_theory
variables {α β γ δ : Type*}
/-- A function `f` from a measurable space to any type is called *simple*,
if every preimage `f ⁻¹' {x}` is measurable, and the range is finite. This structure bundles
a function with these properties. -/
structure {u v} simple_func (α : Type u) [measurable_space α] (β : Type v) :=
(to_fun : α → β)
(is_measurable_fiber' : ∀ x, is_measurable (to_fun ⁻¹' {x}))
(finite_range' : (set.range to_fun).finite)
local infixr ` →ₛ `:25 := simple_func
namespace simple_func
section measurable
variables [measurable_space α]
instance has_coe_to_fun : has_coe_to_fun (α →ₛ β) := ⟨_, to_fun⟩
lemma coe_injective ⦃f g : α →ₛ β⦄ (H : ⇑f = g) : f = g :=
by cases f; cases g; congr; exact H
@[ext] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g :=
coe_injective $ funext H
lemma finite_range (f : α →ₛ β) : (set.range f).finite := f.finite_range'
lemma is_measurable_fiber (f : α →ₛ β) (x : β) : is_measurable (f ⁻¹' {x}) :=
f.is_measurable_fiber' x
/-- Range of a simple function `α →ₛ β` as a `finset β`. -/
protected def range (f : α →ₛ β) : finset β := f.finite_range.to_finset
@[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ b ∈ range f :=
finite.mem_to_finset
theorem mem_range_self (f : α →ₛ β) (x : α) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩
@[simp] lemma coe_range (f : α →ₛ β) : (↑f.range : set β) = set.range f :=
f.finite_range.coe_to_finset
theorem mem_range_of_measure_ne_zero {f : α →ₛ β} {x : β} {μ : measure α} (H : μ (f ⁻¹' {x}) ≠ 0) :
x ∈ f.range :=
let ⟨a, ha⟩ := nonempty_of_measure_ne_zero H in
mem_range.2 ⟨a, ha⟩
lemma forall_range_iff {f : α →ₛ β} {p : β → Prop} :
(∀ y ∈ f.range, p y) ↔ ∀ x, p (f x) :=
by simp only [mem_range, set.forall_range_iff]
lemma exists_range_iff {f : α →ₛ β} {p : β → Prop} :
(∃ y ∈ f.range, p y) ↔ ∃ x, p (f x) :=
by simpa only [mem_range, exists_prop] using set.exists_range_iff
lemma preimage_eq_empty_iff (f : α →ₛ β) (b : β) : f ⁻¹' {b} = ∅ ↔ b ∉ f.range :=
preimage_singleton_eq_empty.trans $ not_congr mem_range.symm
/-- Constant function as a `simple_func`. -/
def const (α) {β} [measurable_space α] (b : β) : α →ₛ β :=
⟨λ a, b, λ x, is_measurable.const _, finite_range_const⟩
instance [inhabited β] : inhabited (α →ₛ β) := ⟨const _ (default _)⟩
theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl
@[simp] theorem coe_const (b : β) : ⇑(const α b) = function.const α b := rfl
@[simp] lemma range_const (α) [measurable_space α] [nonempty α] (b : β) :
(const α b).range = {b} :=
finset.coe_injective $ by simp
lemma is_measurable_cut (r : α → β → Prop) (f : α →ₛ β)
(h : ∀b, is_measurable {a | r a b}) : is_measurable {a | r a (f a)} :=
begin
have : {a | r a (f a)} = ⋃ b ∈ range f, {a | r a b} ∩ f ⁻¹' {b},
{ ext a,
suffices : r a (f a) ↔ ∃ i, r a (f i) ∧ f a = f i, by simpa,
exact ⟨λ h, ⟨a, ⟨h, rfl⟩⟩, λ ⟨a', ⟨h', e⟩⟩, e.symm ▸ h'⟩ },
rw this,
exact is_measurable.bUnion f.finite_range.countable
(λ b _, is_measurable.inter (h b) (f.is_measurable_fiber _))
end
theorem is_measurable_preimage (f : α →ₛ β) (s) : is_measurable (f ⁻¹' s) :=
is_measurable_cut (λ _ b, b ∈ s) f (λ b, is_measurable.const (b ∈ s))
/-- A simple function is measurable -/
protected theorem measurable [measurable_space β] (f : α →ₛ β) : measurable f :=
λ s _, is_measurable_preimage f s
protected lemma sum_measure_preimage_singleton (f : α →ₛ β) {μ : measure α} (s : finset β) :
∑ y in s, μ (f ⁻¹' {y}) = μ (f ⁻¹' ↑s) :=
sum_measure_preimage_singleton _ (λ _ _, f.is_measurable_fiber _)
lemma sum_range_measure_preimage_singleton (f : α →ₛ β) (μ : measure α) :
∑ y in f.range, μ (f ⁻¹' {y}) = μ univ :=
by rw [f.sum_measure_preimage_singleton, coe_range, preimage_range]
/-- If-then-else as a `simple_func`. -/
def piecewise (s : set α) (hs : is_measurable s) (f g : α →ₛ β) : α →ₛ β :=
⟨s.piecewise f g,
λ x, by letI : measurable_space β := ⊤; exact
f.measurable.piecewise hs g.measurable trivial,
(f.finite_range.union g.finite_range).subset range_ite_subset⟩
@[simp] theorem coe_piecewise {s : set α} (hs : is_measurable s) (f g : α →ₛ β) :
⇑(piecewise s hs f g) = s.piecewise f g :=
rfl
theorem piecewise_apply {s : set α} (hs : is_measurable s) (f g : α →ₛ β) (a) :
piecewise s hs f g a = if a ∈ s then f a else g a :=
rfl
@[simp] lemma piecewise_compl {s : set α} (hs : is_measurable sᶜ) (f g : α →ₛ β) :
piecewise sᶜ hs f g = piecewise s hs.of_compl g f :=
coe_injective $ by simp [hs]
@[simp] lemma piecewise_univ (f g : α →ₛ β) : piecewise univ is_measurable.univ f g = f :=
coe_injective $ by simp
@[simp] lemma piecewise_empty (f g : α →ₛ β) : piecewise ∅ is_measurable.empty f g = g :=
coe_injective $ by simp
lemma measurable_bind [measurable_space γ] (f : α →ₛ β) (g : β → α → γ)
(hg : ∀ b, measurable (g b)) : measurable (λ a, g (f a) a) :=
λ s hs, f.is_measurable_cut (λ a b, g b a ∈ s) $ λ b, hg b hs
/-- If `f : α →ₛ β` is a simple function and `g : β → α →ₛ γ` is a family of simple functions,
then `f.bind g` binds the first argument of `g` to `f`. In other words, `f.bind g a = g (f a) a`. -/
def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ :=
⟨λa, g (f a) a,
λ c, f.is_measurable_cut (λ a b, g b a = c) $ λ b, (g b).is_measurable_preimage {c},
(f.finite_range.bUnion (λ b _, (g b).finite_range)).subset $
by rintro _ ⟨a, rfl⟩; simp; exact ⟨a, a, rfl⟩⟩
@[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) :
f.bind g a = g (f a) a := rfl
/-- Given a function `g : β → γ` and a simple function `f : α →ₛ β`, `f.map g` return the simple
function `g ∘ f : α →ₛ γ` -/
def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g)
theorem map_apply (g : β → γ) (f : α →ₛ β) (a) : f.map g a = g (f a) := rfl
theorem map_map (g : β → γ) (h: γ → δ) (f : α →ₛ β) : (f.map g).map h = f.map (h ∘ g) := rfl
@[simp] theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl
@[simp] theorem range_map [decidable_eq γ] (g : β → γ) (f : α →ₛ β) :
(f.map g).range = f.range.image g :=
finset.coe_injective $ by simp [range_comp]
@[simp] theorem map_const (g : β → γ) (b : β) : (const α b).map g = const α (g b) := rfl
lemma map_preimage (f : α →ₛ β) (g : β → γ) (s : set γ) :
(f.map g) ⁻¹' s = f ⁻¹' ↑(f.range.filter (λb, g b ∈ s)) :=
by { simp only [coe_range, sep_mem_eq, set.mem_range, function.comp_app, coe_map, finset.coe_filter,
← mem_preimage, inter_comm, preimage_inter_range], apply preimage_comp }
lemma map_preimage_singleton (f : α →ₛ β) (g : β → γ) (c : γ) :
(f.map g) ⁻¹' {c} = f ⁻¹' ↑(f.range.filter (λ b, g b = c)) :=
map_preimage _ _ _
/-- Composition of a `simple_fun` and a measurable function is a `simple_func`. -/
def comp [measurable_space β] (f : β →ₛ γ) (g : α → β) (hgm : measurable g) : α →ₛ γ :=
{ to_fun := f ∘ g,
finite_range' := f.finite_range.subset $ set.range_comp_subset_range _ _,
is_measurable_fiber' := λ z, hgm (f.is_measurable_fiber z) }
@[simp] lemma coe_comp [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) :
⇑(f.comp g hgm) = f ∘ g :=
rfl
lemma range_comp_subset_range [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) :
(f.comp g hgm).range ⊆ f.range :=
finset.coe_subset.1 $ by simp only [coe_range, coe_comp, set.range_comp_subset_range]
/-- If `f` is a simple function taking values in `β → γ` and `g` is another simple function
with the same domain and codomain `β`, then `f.seq g = f a (g a)`. -/
def seq (f : α →ₛ (β → γ)) (g : α →ₛ β) : α →ₛ γ := f.bind (λf, g.map f)
@[simp] lemma seq_apply (f : α →ₛ (β → γ)) (g : α →ₛ β) (a : α) : f.seq g a = f a (g a) := rfl
/-- Combine two simple functions `f : α →ₛ β` and `g : α →ₛ β`
into `λ a, (f a, g a)`. -/
def pair (f : α →ₛ β) (g : α →ₛ γ) : α →ₛ (β × γ) := (f.map prod.mk).seq g
@[simp] lemma pair_apply (f : α →ₛ β) (g : α →ₛ γ) (a) : pair f g a = (f a, g a) := rfl
lemma pair_preimage (f : α →ₛ β) (g : α →ₛ γ) (s : set β) (t : set γ) :
(pair f g) ⁻¹' (set.prod s t) = (f ⁻¹' s) ∩ (g ⁻¹' t) := rfl
/- A special form of `pair_preimage` -/
lemma pair_preimage_singleton (f : α →ₛ β) (g : α →ₛ γ) (b : β) (c : γ) :
(pair f g) ⁻¹' {(b, c)} = (f ⁻¹' {b}) ∩ (g ⁻¹' {c}) :=
by { rw ← singleton_prod_singleton, exact pair_preimage _ _ _ _ }
theorem bind_const (f : α →ₛ β) : f.bind (const α) = f := by ext; simp
instance [has_zero β] : has_zero (α →ₛ β) := ⟨const α 0⟩
instance [has_add β] : has_add (α →ₛ β) := ⟨λf g, (f.map (+)).seq g⟩
instance [has_mul β] : has_mul (α →ₛ β) := ⟨λf g, (f.map (*)).seq g⟩
instance [has_sup β] : has_sup (α →ₛ β) := ⟨λf g, (f.map (⊔)).seq g⟩
instance [has_inf β] : has_inf (α →ₛ β) := ⟨λf g, (f.map (⊓)).seq g⟩
instance [has_le β] : has_le (α →ₛ β) := ⟨λf g, ∀a, f a ≤ g a⟩
@[simp, norm_cast] lemma coe_zero [has_zero β] : ⇑(0 : α →ₛ β) = 0 := rfl
@[simp] lemma const_zero [has_zero β] : const α (0:β) = 0 := rfl
@[simp, norm_cast] lemma coe_add [has_add β] (f g : α →ₛ β) : ⇑(f + g) = f + g := rfl
@[simp, norm_cast] lemma coe_mul [has_mul β] (f g : α →ₛ β) : ⇑(f * g) = f * g := rfl
@[simp, norm_cast] lemma coe_le [preorder β] {f g : α →ₛ β} : (f : α → β) ≤ g ↔ f ≤ g := iff.rfl
@[simp] lemma range_zero [nonempty α] [has_zero β] : (0 : α →ₛ β).range = {0} :=
finset.ext $ λ x, by simp [eq_comm]
lemma eq_zero_of_mem_range_zero [has_zero β] : ∀ {y : β}, y ∈ (0 : α →ₛ β).range → y = 0 :=
forall_range_iff.2 $ λ x, rfl
lemma sup_apply [has_sup β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl
lemma mul_apply [has_mul β] (f g : α →ₛ β) (a : α) : (f * g) a = f a * g a := rfl
lemma add_apply [has_add β] (f g : α →ₛ β) (a : α) : (f + g) a = f a + g a := rfl
lemma add_eq_map₂ [has_add β] (f g : α →ₛ β) : f + g = (pair f g).map (λp:β×β, p.1 + p.2) :=
rfl
lemma mul_eq_map₂ [has_mul β] (f g : α →ₛ β) : f * g = (pair f g).map (λp:β×β, p.1 * p.2) :=
rfl
lemma sup_eq_map₂ [has_sup β] (f g : α →ₛ β) : f ⊔ g = (pair f g).map (λp:β×β, p.1 ⊔ p.2) :=
rfl
lemma const_mul_eq_map [has_mul β] (f : α →ₛ β) (b : β) : const α b * f = f.map (λa, b * a) := rfl
instance [add_monoid β] : add_monoid (α →ₛ β) :=
function.injective.add_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add
instance add_comm_monoid [add_comm_monoid β] : add_comm_monoid (α →ₛ β) :=
function.injective.add_comm_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add
instance [has_neg β] : has_neg (α →ₛ β) := ⟨λf, f.map (has_neg.neg)⟩
@[simp, norm_cast] lemma coe_neg [has_neg β] (f : α →ₛ β) : ⇑(-f) = -f := rfl
instance [add_group β] : add_group (α →ₛ β) :=
function.injective.add_group (λ f, show α → β, from f) coe_injective coe_zero coe_add coe_neg
@[simp, norm_cast] lemma coe_sub [add_group β] (f g : α →ₛ β) : ⇑(f - g) = f - g := rfl
instance [add_comm_group β] : add_comm_group (α →ₛ β) :=
function.injective.add_comm_group (λ f, show α → β, from f) coe_injective
coe_zero coe_add coe_neg
variables {K : Type*}
instance [has_scalar K β] : has_scalar K (α →ₛ β) := ⟨λk f, f.map ((•) k)⟩
@[simp] lemma coe_smul [has_scalar K β] (c : K) (f : α →ₛ β) : ⇑(c • f) = c • f := rfl
lemma smul_apply [has_scalar K β] (k : K) (f : α →ₛ β) (a : α) : (k • f) a = k • f a := rfl
instance [semiring K] [add_comm_monoid β] [semimodule K β] : semimodule K (α →ₛ β) :=
function.injective.semimodule K ⟨λ f, show α → β, from f, coe_zero, coe_add⟩
coe_injective coe_smul
lemma smul_eq_map [has_scalar K β] (k : K) (f : α →ₛ β) : k • f = f.map ((•) k) := rfl
instance [preorder β] : preorder (α →ₛ β) :=
{ le_refl := λf a, le_refl _,
le_trans := λf g h hfg hgh a, le_trans (hfg _) (hgh a),
.. simple_func.has_le }
instance [partial_order β] : partial_order (α →ₛ β) :=
{ le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a),
.. simple_func.preorder }
instance [order_bot β] : order_bot (α →ₛ β) :=
{ bot := const α ⊥, bot_le := λf a, bot_le, .. simple_func.partial_order }
instance [order_top β] : order_top (α →ₛ β) :=
{ top := const α ⊤, le_top := λf a, le_top, .. simple_func.partial_order }
instance [semilattice_inf β] : semilattice_inf (α →ₛ β) :=
{ inf := (⊓),
inf_le_left := assume f g a, inf_le_left,
inf_le_right := assume f g a, inf_le_right,
le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a),
.. simple_func.partial_order }
instance [semilattice_sup β] : semilattice_sup (α →ₛ β) :=
{ sup := (⊔),
le_sup_left := assume f g a, le_sup_left,
le_sup_right := assume f g a, le_sup_right,
sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a),
.. simple_func.partial_order }
instance [semilattice_sup_bot β] : semilattice_sup_bot (α →ₛ β) :=
{ .. simple_func.semilattice_sup,.. simple_func.order_bot }
instance [lattice β] : lattice (α →ₛ β) :=
{ .. simple_func.semilattice_sup,.. simple_func.semilattice_inf }
instance [bounded_lattice β] : bounded_lattice (α →ₛ β) :=
{ .. simple_func.lattice, .. simple_func.order_bot, .. simple_func.order_top }
lemma finset_sup_apply [semilattice_sup_bot β] {f : γ → α →ₛ β} (s : finset γ) (a : α) :
s.sup f a = s.sup (λc, f c a) :=
begin
refine finset.induction_on s rfl _,
assume a s hs ih,
rw [finset.sup_insert, finset.sup_insert, sup_apply, ih]
end
section restrict
variables [has_zero β]
/-- Restrict a simple function `f : α →ₛ β` to a set `s`. If `s` is measurable,
then `f.restrict s a = if a ∈ s then f a else 0`, otherwise `f.restrict s = const α 0`. -/
def restrict (f : α →ₛ β) (s : set α) : α →ₛ β :=
if hs : is_measurable s then piecewise s hs f 0 else 0
theorem restrict_of_not_measurable {f : α →ₛ β} {s : set α}
(hs : ¬is_measurable s) :
restrict f s = 0 :=
dif_neg hs
@[simp] theorem coe_restrict (f : α →ₛ β) {s : set α} (hs : is_measurable s) :
⇑(restrict f s) = indicator s f :=
by { rw [restrict, dif_pos hs], refl }
@[simp] theorem restrict_univ (f : α →ₛ β) : restrict f univ = f :=
by simp [restrict]
@[simp] theorem restrict_empty (f : α →ₛ β) : restrict f ∅ = 0 :=
by simp [restrict]
theorem map_restrict_of_zero [has_zero γ] {g : β → γ} (hg : g 0 = 0) (f : α →ₛ β) (s : set α) :
(f.restrict s).map g = (f.map g).restrict s :=
ext $ λ x,
if hs : is_measurable s then by simp [hs, set.indicator_comp_of_zero hg]
else by simp [restrict_of_not_measurable hs, hg]
theorem map_coe_ennreal_restrict (f : α →ₛ nnreal) (s : set α) :
(f.restrict s).map (coe : nnreal → ennreal) = (f.map coe).restrict s :=
map_restrict_of_zero ennreal.coe_zero _ _
theorem map_coe_nnreal_restrict (f : α →ₛ nnreal) (s : set α) :
(f.restrict s).map (coe : nnreal → ℝ) = (f.map coe).restrict s :=
map_restrict_of_zero nnreal.coe_zero _ _
theorem restrict_apply (f : α →ₛ β) {s : set α} (hs : is_measurable s) (a) :
restrict f s a = if a ∈ s then f a else 0 :=
by simp only [hs, coe_restrict]
theorem restrict_preimage (f : α →ₛ β) {s : set α} (hs : is_measurable s)
{t : set β} (ht : (0:β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t :=
by simp [hs, indicator_preimage_of_not_mem _ _ ht]
theorem restrict_preimage_singleton (f : α →ₛ β) {s : set α} (hs : is_measurable s)
{r : β} (hr : r ≠ 0) : restrict f s ⁻¹' {r} = s ∩ f ⁻¹' {r} :=
f.restrict_preimage hs hr.symm
lemma mem_restrict_range {r : β} {s : set α} {f : α →ₛ β} (hs : is_measurable s) :
r ∈ (restrict f s).range ↔ (r = 0 ∧ s ≠ univ) ∨ (r ∈ f '' s) :=
by rw [← finset.mem_coe, coe_range, coe_restrict _ hs, mem_range_indicator]
lemma mem_image_of_mem_range_restrict {r : β} {s : set α} {f : α →ₛ β}
(hr : r ∈ (restrict f s).range) (h0 : r ≠ 0) :
r ∈ f '' s :=
if hs : is_measurable s then by simpa [mem_restrict_range hs, h0] using hr
else by { rw [restrict_of_not_measurable hs] at hr,
exact (h0 $ eq_zero_of_mem_range_zero hr).elim }
@[mono] lemma restrict_mono [preorder β] (s : set α) {f g : α →ₛ β} (H : f ≤ g) :
f.restrict s ≤ g.restrict s :=
if hs : is_measurable s then λ x, by simp only [coe_restrict _ hs, indicator_le_indicator (H x)]
else by simp only [restrict_of_not_measurable hs, le_refl]
end restrict
section approx
section
variables [semilattice_sup_bot β] [has_zero β]
/-- Fix a sequence `i : ℕ → β`. Given a function `α → β`, its `n`-th approximation
by simple functions is defined so that in case `β = ennreal` it sends each `a` to the supremum
of the set `{i k | k ≤ n ∧ i k ≤ f a}`, see `approx_apply` and `supr_approx_apply` for details. -/
def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β :=
(finset.range n).sup (λk, restrict (const α (i k)) {a:α | i k ≤ f a})
lemma approx_apply [topological_space β] [order_closed_topology β] [measurable_space β]
[opens_measurable_space β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : measurable f) :
(approx i f n : α →ₛ β) a = (finset.range n).sup (λk, if i k ≤ f a then i k else 0) :=
begin
dsimp only [approx],
rw [finset_sup_apply],
congr,
funext k,
rw [restrict_apply],
refl,
exact (hf is_measurable_Ici)
end
lemma monotone_approx (i : ℕ → β) (f : α → β) : monotone (approx i f) :=
assume n m h, finset.sup_mono $ finset.range_subset.2 h
lemma approx_comp [topological_space β] [order_closed_topology β] [measurable_space β]
[opens_measurable_space β] [measurable_space γ]
{i : ℕ → β} {f : γ → β} {g : α → γ} {n : ℕ} (a : α)
(hf : measurable f) (hg : measurable g) :
(approx i (f ∘ g) n : α →ₛ β) a = (approx i f n : γ →ₛ β) (g a) :=
by rw [approx_apply _ hf, approx_apply _ (hf.comp hg)]
end
lemma supr_approx_apply [topological_space β] [complete_lattice β] [order_closed_topology β]
[has_zero β] [measurable_space β] [opens_measurable_space β]
(i : ℕ → β) (f : α → β) (a : α) (hf : measurable f) (h_zero : (0 : β) = ⊥) :
(⨆n, (approx i f n : α →ₛ β) a) = (⨆k (h : i k ≤ f a), i k) :=
begin
refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _),
{ rw [approx_apply a hf, h_zero],
refine finset.sup_le (assume k hk, _),
split_ifs,
exact le_supr_of_le k (le_supr _ h),
exact bot_le },
{ refine le_supr_of_le (k+1) _,
rw [approx_apply a hf],
have : k ∈ finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _),
refine le_trans (le_of_eq _) (finset.le_sup this),
rw [if_pos hk] }
end
end approx
section eapprox
/-- A sequence of `ennreal`s such that its range is the set of non-negative rational numbers. -/
def ennreal_rat_embed (n : ℕ) : ennreal :=
ennreal.of_real ((encodable.decode ℚ n).get_or_else (0 : ℚ))
lemma ennreal_rat_embed_encode (q : ℚ) :
ennreal_rat_embed (encodable.encode q) = nnreal.of_real q :=
by rw [ennreal_rat_embed, encodable.encodek]; refl
/-- Approximate a function `α → ennreal` by a sequence of simple functions. -/
def eapprox : (α → ennreal) → ℕ → α →ₛ ennreal :=
approx ennreal_rat_embed
lemma monotone_eapprox (f : α → ennreal) : monotone (eapprox f) :=
monotone_approx _ f
lemma supr_eapprox_apply (f : α → ennreal) (hf : measurable f) (a : α) :
(⨆n, (eapprox f n : α →ₛ ennreal) a) = f a :=
begin
rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl],
refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _),
assume h,
rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨q, hq, lt_q, q_lt⟩,
have : (nnreal.of_real q : ennreal) ≤
(⨆ (k : ℕ) (h : ennreal_rat_embed k ≤ f a), ennreal_rat_embed k),
{ refine le_supr_of_le (encodable.encode q) _,
rw [ennreal_rat_embed_encode q],
refine le_supr_of_le (le_of_lt q_lt) _,
exact le_refl _ },
exact lt_irrefl _ (lt_of_le_of_lt this lt_q)
end
lemma eapprox_comp [measurable_space γ] {f : γ → ennreal} {g : α → γ} {n : ℕ}
(hf : measurable f) (hg : measurable g) :
(eapprox (f ∘ g) n : α → ennreal) = (eapprox f n : γ →ₛ ennreal) ∘ g :=
funext $ assume a, approx_comp a hf hg
end eapprox
end measurable
section measure
variables [measurable_space α] {μ : measure α}
/-- Integral of a simple function whose codomain is `ennreal`. -/
def lintegral (f : α →ₛ ennreal) (μ : measure α) : ennreal :=
∑ x in f.range, x * μ (f ⁻¹' {x})
lemma lintegral_eq_of_subset (f : α →ₛ ennreal) {s : finset ennreal}
(hs : ∀ x, f x ≠ 0 → μ (f ⁻¹' {f x}) ≠ 0 → f x ∈ s) :
f.lintegral μ = ∑ x in s, x * μ (f ⁻¹' {x}) :=
begin
refine finset.sum_bij_ne_zero (λr _ _, r) _ _ _ _,
{ simpa only [forall_range_iff, mul_ne_zero_iff, and_imp] },
{ intros, assumption },
{ intros b _ hb,
refine ⟨b, _, hb, rfl⟩,
rw [mem_range, ← preimage_singleton_nonempty],
exact nonempty_of_measure_ne_zero (mul_ne_zero_iff.1 hb).2 },
{ intros, refl }
end
/-- Calculate the integral of `(g ∘ f)`, where `g : β → ennreal` and `f : α →ₛ β`. -/
lemma map_lintegral (g : β → ennreal) (f : α →ₛ β) :
(f.map g).lintegral μ = ∑ x in f.range, g x * μ (f ⁻¹' {x}) :=
begin
simp only [lintegral, range_map],
refine finset.sum_image' _ (assume b hb, _),
rcases mem_range.1 hb with ⟨a, rfl⟩,
rw [map_preimage_singleton, ← f.sum_measure_preimage_singleton, finset.mul_sum],
refine finset.sum_congr _ _,
{ congr },
{ assume x, simp only [finset.mem_filter], rintro ⟨_, h⟩, rw h },
end
lemma add_lintegral (f g : α →ₛ ennreal) : (f + g).lintegral μ = f.lintegral μ + g.lintegral μ :=
calc (f + g).lintegral μ =
∑ x in (pair f g).range, (x.1 * μ (pair f g ⁻¹' {x}) + x.2 * μ (pair f g ⁻¹' {x})) :
by rw [add_eq_map₂, map_lintegral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _)
... = ∑ x in (pair f g).range, x.1 * μ (pair f g ⁻¹' {x}) +
∑ x in (pair f g).range, x.2 * μ (pair f g ⁻¹' {x}) : by rw [finset.sum_add_distrib]
... = ((pair f g).map prod.fst).lintegral μ + ((pair f g).map prod.snd).lintegral μ :
by rw [map_lintegral, map_lintegral]
... = lintegral f μ + lintegral g μ : rfl
lemma const_mul_lintegral (f : α →ₛ ennreal) (x : ennreal) :
(const α x * f).lintegral μ = x * f.lintegral μ :=
calc (f.map (λa, x * a)).lintegral μ = ∑ r in f.range, x * r * μ (f ⁻¹' {r}) :
map_lintegral _ _
... = ∑ r in f.range, x * (r * μ (f ⁻¹' {r})) :
finset.sum_congr rfl (assume a ha, mul_assoc _ _ _)
... = x * f.lintegral μ :
finset.mul_sum.symm
/-- Integral of a simple function `α →ₛ ennreal` as a bilinear map. -/
def lintegralₗ : (α →ₛ ennreal) →ₗ[ennreal] measure α →ₗ[ennreal] ennreal :=
{ to_fun := λ f,
{ to_fun := lintegral f,
map_add' := by simp [lintegral, mul_add, finset.sum_add_distrib],
map_smul' := λ c μ, by simp [lintegral, mul_left_comm _ c, finset.mul_sum] },
map_add' := λ f g, linear_map.ext (λ μ, add_lintegral f g),
map_smul' := λ c f, linear_map.ext (λ μ, const_mul_lintegral f c) }
@[simp] lemma zero_lintegral : (0 : α →ₛ ennreal).lintegral μ = 0 :=
linear_map.ext_iff.1 lintegralₗ.map_zero μ
lemma lintegral_add {ν} (f : α →ₛ ennreal) : f.lintegral (μ + ν) = f.lintegral μ + f.lintegral ν :=
(lintegralₗ f).map_add μ ν
lemma lintegral_smul (f : α →ₛ ennreal) (c : ennreal) :
f.lintegral (c • μ) = c • f.lintegral μ :=
(lintegralₗ f).map_smul c μ
@[simp] lemma lintegral_zero (f : α →ₛ ennreal) :
f.lintegral 0 = 0 :=
(lintegralₗ f).map_zero
lemma lintegral_sum {ι} (f : α →ₛ ennreal) (μ : ι → measure α) :
f.lintegral (measure.sum μ) = ∑' i, f.lintegral (μ i) :=
begin
simp only [lintegral, measure.sum_apply, f.is_measurable_preimage, ← finset.tsum_subtype,
← ennreal.tsum_mul_left],
apply ennreal.tsum_comm
end
lemma restrict_lintegral (f : α →ₛ ennreal) {s : set α} (hs : is_measurable s) :
(restrict f s).lintegral μ = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) :=
calc (restrict f s).lintegral μ = ∑ r in f.range, r * μ (restrict f s ⁻¹' {r}) :
lintegral_eq_of_subset _ $ λ x hx, if hxs : x ∈ s
then by simp [f.restrict_apply hs, if_pos hxs, mem_range_self]
else false.elim $ hx $ by simp [*]
... = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) :
finset.sum_congr rfl $ forall_range_iff.2 $ λ b, if hb : f b = 0 then by simp only [hb, zero_mul]
else by rw [restrict_preimage_singleton _ hs hb, inter_comm]
lemma lintegral_restrict (f : α →ₛ ennreal) (s : set α) (μ : measure α) :
f.lintegral (μ.restrict s) = ∑ y in f.range, y * μ (f ⁻¹' {y} ∩ s) :=
by simp only [lintegral, measure.restrict_apply, f.is_measurable_preimage]
lemma restrict_lintegral_eq_lintegral_restrict (f : α →ₛ ennreal) {s : set α}
(hs : is_measurable s) :
(restrict f s).lintegral μ = f.lintegral (μ.restrict s) :=
by rw [f.restrict_lintegral hs, lintegral_restrict]
lemma const_lintegral (c : ennreal) : (const α c).lintegral μ = c * μ univ :=
begin
rw [lintegral],
by_cases ha : nonempty α,
{ resetI, simp [preimage_const_of_mem] },
{ simp [μ.eq_zero_of_not_nonempty ha] }
end
lemma const_lintegral_restrict (c : ennreal) (s : set α) :
(const α c).lintegral (μ.restrict s) = c * μ s :=
by rw [const_lintegral, measure.restrict_apply is_measurable.univ, univ_inter]
lemma restrict_const_lintegral (c : ennreal) {s : set α} (hs : is_measurable s) :
((const α c).restrict s).lintegral μ = c * μ s :=
by rw [restrict_lintegral_eq_lintegral_restrict _ hs, const_lintegral_restrict]
lemma le_sup_lintegral (f g : α →ₛ ennreal) : f.lintegral μ ⊔ g.lintegral μ ≤ (f ⊔ g).lintegral μ :=
calc f.lintegral μ ⊔ g.lintegral μ =
((pair f g).map prod.fst).lintegral μ ⊔ ((pair f g).map prod.snd).lintegral μ : rfl
... ≤ ∑ x in (pair f g).range, (x.1 ⊔ x.2) * μ (pair f g ⁻¹' {x}) :
begin
rw [map_lintegral, map_lintegral],
refine sup_le _ _;
refine finset.sum_le_sum (λ a _, canonically_ordered_semiring.mul_le_mul _ (le_refl _)),
exact le_sup_left,
exact le_sup_right
end
... = (f ⊔ g).lintegral μ : by rw [sup_eq_map₂, map_lintegral]
/-- `simple_func.lintegral` is monotone both in function and in measure. -/
@[mono] lemma lintegral_mono {f g : α →ₛ ennreal} (hfg : f ≤ g) {μ ν : measure α} (hμν : μ ≤ ν) :
f.lintegral μ ≤ g.lintegral ν :=
calc f.lintegral μ ≤ f.lintegral μ ⊔ g.lintegral μ : le_sup_left
... ≤ (f ⊔ g).lintegral μ : le_sup_lintegral _ _
... = g.lintegral μ : by rw [sup_of_le_right hfg]
... ≤ g.lintegral ν : finset.sum_le_sum $ λ y hy, ennreal.mul_left_mono $
hμν _ (g.is_measurable_preimage _)
/-- `simple_func.lintegral` depends only on the measures of `f ⁻¹' {y}`. -/
lemma lintegral_eq_of_measure_preimage [measurable_space β] {f : α →ₛ ennreal} {g : β →ₛ ennreal}
{ν : measure β} (H : ∀ y, μ (f ⁻¹' {y}) = ν (g ⁻¹' {y})) :
f.lintegral μ = g.lintegral ν :=
begin
simp only [lintegral, ← H],
apply lintegral_eq_of_subset,
simp only [H],
intros,
exact mem_range_of_measure_ne_zero ‹_›
end
/-- If two simple functions are equal a.e., then their `lintegral`s are equal. -/
lemma lintegral_congr {f g : α →ₛ ennreal} (h : f =ᵐ[μ] g) :
f.lintegral μ = g.lintegral μ :=
lintegral_eq_of_measure_preimage $ λ y, measure_congr $
eventually.set_eq $ h.mono $ λ x hx, by simp [hx]
lemma lintegral_map {β} [measurable_space β] {μ' : measure β} (f : α →ₛ ennreal) (g : β →ₛ ennreal)
(m : α → β) (eq : ∀a:α, f a = g (m a)) (h : ∀s:set β, is_measurable s → μ' s = μ (m ⁻¹' s)) :
f.lintegral μ = g.lintegral μ' :=
lintegral_eq_of_measure_preimage $ λ y,
by { simp only [preimage, eq], exact (h (g ⁻¹' {y}) (g.is_measurable_preimage _)).symm }
end measure
section fin_meas_supp
variables [measurable_space α] [has_zero β] [has_zero γ] {μ : measure α}
open finset ennreal function
lemma support_eq (f : α →ₛ β) : support f = ⋃ y ∈ f.range.filter (λ y, y ≠ 0), f ⁻¹' {y} :=
set.ext $ λ x, by simp only [finset.bUnion_preimage_singleton, mem_support, set.mem_preimage,
finset.mem_coe, mem_filter, mem_range_self, true_and]
/-- A `simple_func` has finite measure support if it is equal to `0` outside of a set of finite
measure. -/
protected def fin_meas_supp (f : α →ₛ β) (μ : measure α) : Prop :=
f =ᶠ[μ.cofinite] 0
lemma fin_meas_supp_iff_support {f : α →ₛ β} {μ : measure α} :
f.fin_meas_supp μ ↔ μ (support f) < ⊤ :=
iff.rfl
lemma fin_meas_supp_iff {f : α →ₛ β} {μ : measure α} :
f.fin_meas_supp μ ↔ ∀ y ≠ 0, μ (f ⁻¹' {y}) < ⊤ :=
begin
split,
{ refine λ h y hy, lt_of_le_of_lt (measure_mono _) h,
exact λ x hx (H : f x = 0), hy $ H ▸ eq.symm hx },
{ intro H,
rw [fin_meas_supp_iff_support, support_eq],
refine lt_of_le_of_lt (measure_bUnion_finset_le _ _) (sum_lt_top _),
exact λ y hy, H y (finset.mem_filter.1 hy).2 }
end
namespace fin_meas_supp
lemma meas_preimage_singleton_ne_zero {f : α →ₛ β} (h : f.fin_meas_supp μ) {y : β} (hy : y ≠ 0) :
μ (f ⁻¹' {y}) < ⊤ :=
fin_meas_supp_iff.1 h y hy
protected lemma map {f : α →ₛ β} {g : β → γ} (hf : f.fin_meas_supp μ) (hg : g 0 = 0) :
(f.map g).fin_meas_supp μ :=
flip lt_of_le_of_lt hf (measure_mono $ support_comp_subset hg f)
lemma of_map {f : α →ₛ β} {g : β → γ} (h : (f.map g).fin_meas_supp μ) (hg : ∀b, g b = 0 → b = 0) :
f.fin_meas_supp μ :=
flip lt_of_le_of_lt h $ measure_mono $ support_subset_comp hg _
lemma map_iff {f : α →ₛ β} {g : β → γ} (hg : ∀ {b}, g b = 0 ↔ b = 0) :
(f.map g).fin_meas_supp μ ↔ f.fin_meas_supp μ :=
⟨λ h, h.of_map $ λ b, hg.1, λ h, h.map $ hg.2 rfl⟩
protected lemma pair {f : α →ₛ β} {g : α →ₛ γ} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) :
(pair f g).fin_meas_supp μ :=
calc μ (support $ pair f g) = μ (support f ∪ support g) : congr_arg μ $ support_prod_mk f g
... ≤ μ (support f) + μ (support g) : measure_union_le _ _
... < _ : add_lt_top.2 ⟨hf, hg⟩
protected lemma map₂ [has_zero δ] {μ : measure α} {f : α →ₛ β} (hf : f.fin_meas_supp μ)
{g : α →ₛ γ} (hg : g.fin_meas_supp μ) {op : β → γ → δ} (H : op 0 0 = 0) :
((pair f g).map (function.uncurry op)).fin_meas_supp μ :=
(hf.pair hg).map H
protected lemma add {β} [add_monoid β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ)
(hg : g.fin_meas_supp μ) :
(f + g).fin_meas_supp μ :=
by { rw [add_eq_map₂], exact hf.map₂ hg (zero_add 0) }
protected lemma mul {β} [monoid_with_zero β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ)
(hg : g.fin_meas_supp μ) :
(f * g).fin_meas_supp μ :=
by { rw [mul_eq_map₂], exact hf.map₂ hg (zero_mul 0) }
lemma lintegral_lt_top {f : α →ₛ ennreal} (hm : f.fin_meas_supp μ) (hf : ∀ᵐ a ∂μ, f a < ⊤) :
f.lintegral μ < ⊤ :=
begin
refine sum_lt_top (λ a ha, _),
rcases eq_or_lt_of_le (le_top : a ≤ ⊤) with rfl|ha,
{ simp only [ae_iff, lt_top_iff_ne_top, ne.def, not_not] at hf,
simp [set.preimage, hf] },
{ by_cases ha0 : a = 0,
{ subst a, rwa [zero_mul] },
{ exact mul_lt_top ha (fin_meas_supp_iff.1 hm _ ha0) } }
end
lemma of_lintegral_lt_top {f : α →ₛ ennreal} (h : f.lintegral μ < ⊤) : f.fin_meas_supp μ :=
begin
refine fin_meas_supp_iff.2 (λ b hb, _),
rw [lintegral, sum_lt_top_iff] at h,
by_cases b_mem : b ∈ f.range,
{ rw ennreal.lt_top_iff_ne_top,
have h : ¬ _ = ⊤ := ennreal.lt_top_iff_ne_top.1 (h b b_mem),
simp only [mul_eq_top, not_or_distrib, not_and_distrib] at h,
rcases h with ⟨h, h'⟩,
refine or.elim h (λh, by contradiction) (λh, h) },
{ rw ← preimage_eq_empty_iff at b_mem,
rw [b_mem, measure_empty],
exact with_top.zero_lt_top }
end
lemma iff_lintegral_lt_top {f : α →ₛ ennreal} (hf : ∀ᵐ a ∂μ, f a < ⊤) :
f.fin_meas_supp μ ↔ f.lintegral μ < ⊤ :=
⟨λ h, h.lintegral_lt_top hf, λ h, of_lintegral_lt_top h⟩
end fin_meas_supp
end fin_meas_supp
/-- To prove something for an arbitrary simple function, it suffices to show
that the property holds for (multiples of) characteristic functions and is closed under
addition (of functions with disjoint support).
It is possible to make the hypotheses in `h_sum` a bit stronger, and such conditions can be added
once we need them (for example it is only necessary to consider the case where `g` is a multiple
of a characteristic function, and that this multiple doesn't appear in the image of `f`) -/
@[elab_as_eliminator]
protected lemma induction {α γ} [measurable_space α] [add_monoid γ] {P : simple_func α γ → Prop}
(h_ind : ∀ c {s} (hs : is_measurable s),
P (simple_func.piecewise s hs (simple_func.const _ c) (simple_func.const _ 0)))
(h_sum : ∀ ⦃f g : simple_func α γ⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → P f → P g → P (f + g))
(f : simple_func α γ) : P f :=
begin
generalize' h : f.range \ {0} = s,
rw [← finset.coe_inj, finset.coe_sdiff, finset.coe_singleton, simple_func.coe_range] at h,
revert s f h, refine finset.induction _ _,
{ intros f hf, rw [finset.coe_empty, diff_eq_empty, range_subset_singleton] at hf,
convert h_ind 0 is_measurable.univ, ext x, simp [hf] },
{ intros x s hxs ih f hf,
have mx := f.is_measurable_preimage {x},
let g := simple_func.piecewise (f ⁻¹' {x}) mx 0 f,
have Pg : P g,
{ apply ih, simp only [g, simple_func.coe_piecewise, range_piecewise],
rw [image_compl_preimage, union_diff_distrib, diff_diff_comm, hf, finset.coe_insert,
insert_diff_self_of_not_mem, diff_eq_empty.mpr, set.empty_union],
{ rw [set.image_subset_iff], convert set.subset_univ _,
exact preimage_const_of_mem (mem_singleton _) },
{ rwa [finset.mem_coe] }},
convert h_sum _ Pg (h_ind x mx),
{ ext1 y, by_cases hy : y ∈ f ⁻¹' {x}; [simpa [hy], simp [hy]] },
{ rintro y -, by_cases hy : y ∈ f ⁻¹' {x}; simp [hy] } }
end
end simple_func
section lintegral
open simple_func
variables [measurable_space α] {μ : measure α}
/-- The lower Lebesgue integral of a function `f` with respect to a measure `μ`. -/
def lintegral (μ : measure α) (f : α → ennreal) : ennreal :=
⨆ (g : α →ₛ ennreal) (hf : ⇑g ≤ f), g.lintegral μ
/-! In the notation for integrals, an expression like `∫⁻ x, g ∥x∥ ∂μ` will not be parsed correctly,
and needs parentheses. We do not set the binding power of `r` to `0`, because then
`∫⁻ x, f x = 0` will be parsed incorrectly. -/
notation `∫⁻` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := lintegral μ r
notation `∫⁻` binders `, ` r:(scoped:60 f, lintegral volume f) := r
notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 :=
lintegral (measure.restrict μ s) r
notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, lintegral (measure.restrict volume s) f) := r
theorem simple_func.lintegral_eq_lintegral (f : α →ₛ ennreal) (μ : measure α) :
∫⁻ a, f a ∂ μ = f.lintegral μ :=
le_antisymm
(bsupr_le $ λ g hg, lintegral_mono hg $ le_refl _)
(le_supr_of_le f $ le_supr_of_le (le_refl _) (le_refl _))
@[mono] lemma lintegral_mono' ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) ⦃f g : α → ennreal⦄ (hfg : f ≤ g) :
∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂ν :=
supr_le_supr $ λ φ, supr_le_supr2 $ λ hφ, ⟨le_trans hφ hfg, lintegral_mono (le_refl φ) hμν⟩
lemma lintegral_mono ⦃f g : α → ennreal⦄ (hfg : f ≤ g) :
∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ :=
lintegral_mono' (le_refl μ) hfg
lemma lintegral_mono_nnreal {f g : α → nnreal} (h : f ≤ g) :
∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ :=
begin
refine lintegral_mono _,
intro a,
rw ennreal.coe_le_coe,
exact h a,
end
lemma monotone_lintegral (μ : measure α) : monotone (lintegral μ) :=
lintegral_mono
@[simp] lemma lintegral_const (c : ennreal) : ∫⁻ a, c ∂μ = c * μ univ :=
by rw [← simple_func.const_lintegral, ← simple_func.lintegral_eq_lintegral, simple_func.coe_const]
lemma set_lintegral_one (s) : ∫⁻ a in s, 1 ∂μ = μ s :=
by rw [lintegral_const, one_mul, measure.restrict_apply_univ]
/-- `∫⁻ a in s, f a ∂μ` is defined as the supremum of integrals of simple functions
`φ : α →ₛ ennreal` such that `φ ≤ f`. This lemma says that it suffices to take
functions `φ : α →ₛ ℝ≥0`. -/
lemma lintegral_eq_nnreal (f : α → ennreal) (μ : measure α) :
(∫⁻ a, f a ∂μ) = (⨆ (φ : α →ₛ ℝ≥0) (hf : ∀ x, ↑(φ x) ≤ f x),
(φ.map (coe : nnreal → ennreal)).lintegral μ) :=
begin
refine le_antisymm
(bsupr_le $ assume φ hφ, _)
(supr_le_supr2 $ λ φ, ⟨φ.map (coe : ℝ≥0 → ennreal), le_refl _⟩),
by_cases h : ∀ᵐ a ∂μ, φ a ≠ ⊤,
{ let ψ := φ.map ennreal.to_nnreal,
replace h : ψ.map (coe : ℝ≥0 → ennreal) =ᵐ[μ] φ :=
h.mono (λ a, ennreal.coe_to_nnreal),
have : ∀ x, ↑(ψ x) ≤ f x := λ x, le_trans ennreal.coe_to_nnreal_le_self (hφ x),
exact le_supr_of_le (φ.map ennreal.to_nnreal)
(le_supr_of_le this (ge_of_eq $ lintegral_congr h)) },
{ have h_meas : μ (φ ⁻¹' {⊤}) ≠ 0, from mt measure_zero_iff_ae_nmem.1 h,
refine le_trans le_top (ge_of_eq $ (supr_eq_top _).2 $ λ b hb, _),
obtain ⟨n, hn⟩ : ∃ n : ℕ, b < n * μ (φ ⁻¹' {⊤}), from exists_nat_mul_gt h_meas (ne_of_lt hb),
use (const α (n : ℝ≥0)).restrict (φ ⁻¹' {⊤}),
simp only [lt_supr_iff, exists_prop, coe_restrict, φ.is_measurable_preimage, coe_const,
ennreal.coe_indicator, map_coe_ennreal_restrict, map_const, ennreal.coe_nat,
restrict_const_lintegral],
refine ⟨indicator_le (λ x hx, le_trans _ (hφ _)), hn⟩,
simp only [mem_preimage, mem_singleton_iff] at hx,
simp only [hx, le_top] }
end
theorem supr_lintegral_le {ι : Sort*} (f : ι → α → ennreal) :
(⨆i, ∫⁻ a, f i a ∂μ) ≤ (∫⁻ a, ⨆i, f i a ∂μ) :=
begin
simp only [← supr_apply],
exact (monotone_lintegral μ).le_map_supr
end
theorem supr2_lintegral_le {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ennreal) :
(⨆i (h : ι' i), ∫⁻ a, f i h a ∂μ) ≤ (∫⁻ a, ⨆i (h : ι' i), f i h a ∂μ) :=
by { convert (monotone_lintegral μ).le_map_supr2 f, ext1 a, simp only [supr_apply] }
theorem le_infi_lintegral {ι : Sort*} (f : ι → α → ennreal) :
(∫⁻ a, ⨅i, f i a ∂μ) ≤ (⨅i, ∫⁻ a, f i a ∂μ) :=
by { simp only [← infi_apply], exact (monotone_lintegral μ).map_infi_le }
theorem le_infi2_lintegral {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ennreal) :
(∫⁻ a, ⨅ i (h : ι' i), f i h a ∂μ) ≤ (⨅ i (h : ι' i), ∫⁻ a, f i h a ∂μ) :=
by { convert (monotone_lintegral μ).map_infi2_le f, ext1 a, simp only [infi_apply] }
/-- Monotone convergence theorem -- sometimes called Beppo-Levi convergence.
See `lintegral_supr_directed` for a more general form. -/
theorem lintegral_supr
{f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : monotone f) :
(∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) :=
begin
set c : nnreal → ennreal := coe,
set F := λ a:α, ⨆n, f n a,
have hF : measurable F := measurable_supr hf,
refine le_antisymm _ (supr_lintegral_le _),
rw [lintegral_eq_nnreal],
refine supr_le (assume s, supr_le (assume hsf, _)),
refine ennreal.le_of_forall_lt_one_mul_lt (assume a ha, _),
rcases ennreal.lt_iff_exists_coe.1 ha with ⟨r, rfl, ha⟩,
have ha : r < 1 := ennreal.coe_lt_coe.1 ha,
let rs := s.map (λa, r * a),
have eq_rs : (const α r : α →ₛ ennreal) * map c s = rs.map c,
{ ext1 a, exact ennreal.coe_mul.symm },
have eq : ∀p, (rs.map c) ⁻¹' {p} = (⋃n, (rs.map c) ⁻¹' {p} ∩ {a | p ≤ f n a}),
{ assume p,
rw [← inter_Union, ← inter_univ ((map c rs) ⁻¹' {p})] {occs := occurrences.pos [1]},
refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _),
by_cases p_eq : p = 0, { simp [p_eq] },
simp at hx, subst hx,
have : r * s x ≠ 0, { rwa [(≠), ← ennreal.coe_eq_zero] },
have : s x ≠ 0, { refine mt _ this, assume h, rw [h, mul_zero] },
have : (rs.map c) x < ⨆ (n : ℕ), f n x,
{ refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x),
suffices : r * s x < 1 * s x, simpa [rs],
exact mul_lt_mul_of_pos_right ha (zero_lt_iff_ne_zero.2 this) },
rcases lt_supr_iff.1 this with ⟨i, hi⟩,
exact mem_Union.2 ⟨i, le_of_lt hi⟩ },
have mono : ∀r:ennreal, monotone (λn, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}),
{ assume r i j h,
refine inter_subset_inter (subset.refl _) _,
assume x hx, exact le_trans hx (h_mono h x) },
have h_meas : ∀n, is_measurable {a : α | ⇑(map c rs) a ≤ f n a} :=
assume n, is_measurable_le (simple_func.measurable _) (hf n),
calc (r:ennreal) * (s.map c).lintegral μ = ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r}) :
by rw [← const_mul_lintegral, eq_rs, simple_func.lintegral]
... ≤ ∑ r in (rs.map c).range, r * μ (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) :
le_of_eq (finset.sum_congr rfl $ assume x hx, by rw ← eq)
... ≤ ∑ r in (rs.map c).range, (⨆n, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) :
le_of_eq (finset.sum_congr rfl $ assume x hx,
begin
rw [measure_Union_eq_supr _ (directed_of_sup $ mono x), ennreal.mul_supr],
{ assume i,
refine ((rs.map c).is_measurable_preimage _).inter _,
exact hf i is_measurable_Ici }
end)
... ≤ ⨆n, ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) :
begin
refine le_of_eq _,
rw [ennreal.finset_sum_supr_nat],
assume p i j h,
exact canonically_ordered_semiring.mul_le_mul (le_refl _) (measure_mono $ mono p h)
end
... ≤ (⨆n:ℕ, ((rs.map c).restrict {a | (rs.map c) a ≤ f n a}).lintegral μ) :
begin
refine supr_le_supr (assume n, _),
rw [restrict_lintegral _ (h_meas n)],
{ refine le_of_eq (finset.sum_congr rfl $ assume r hr, _),
congr' 2 with a,
refine and_congr_right _,
simp {contextual := tt} }
end
... ≤ (⨆n, ∫⁻ a, f n a ∂μ) :
begin
refine supr_le_supr (assume n, _),
rw [← simple_func.lintegral_eq_lintegral],
refine lintegral_mono (assume a, _),
dsimp,
rw [restrict_apply],
split_ifs; simp, simpa using h,
exact h_meas n
end
end
lemma lintegral_eq_supr_eapprox_lintegral {f : α → ennreal} (hf : measurable f) :
(∫⁻ a, f a ∂μ) = (⨆n, (eapprox f n).lintegral μ) :=
calc (∫⁻ a, f a ∂μ) = (∫⁻ a, ⨆n, (eapprox f n : α → ennreal) a ∂μ) :
by congr; ext a; rw [supr_eapprox_apply f hf]
... = (⨆n, ∫⁻ a, (eapprox f n : α → ennreal) a ∂μ) :
begin
rw [lintegral_supr],
{ assume n, exact (eapprox f n).measurable },
{ assume i j h, exact (monotone_eapprox f h) }
end
... = (⨆n, (eapprox f n).lintegral μ) : by congr; ext n; rw [(eapprox f n).lintegral_eq_lintegral]
@[simp] lemma lintegral_add {f g : α → ennreal} (hf : measurable f) (hg : measurable g) :
(∫⁻ a, f a + g a ∂μ) = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) :=
calc (∫⁻ a, f a + g a ∂μ) =
(∫⁻ a, (⨆n, (eapprox f n : α → ennreal) a) + (⨆n, (eapprox g n : α → ennreal) a) ∂μ) :
by congr; funext a; rw [supr_eapprox_apply f hf, supr_eapprox_apply g hg]
... = (∫⁻ a, (⨆n, (eapprox f n + eapprox g n : α → ennreal) a) ∂μ) :
begin
congr, funext a,
rw [ennreal.supr_add_supr_of_monotone], { refl },
{ assume i j h, exact monotone_eapprox _ h a },
{ assume i j h, exact monotone_eapprox _ h a },
end
... = (⨆n, (eapprox f n).lintegral μ + (eapprox g n).lintegral μ) :
begin
rw [lintegral_supr],
{ congr,
funext n, rw [← simple_func.add_lintegral, ← simple_func.lintegral_eq_lintegral],
refl },
{ assume n, exact measurable.add (eapprox f n).measurable (eapprox g n).measurable },
{ assume i j h a, exact add_le_add (monotone_eapprox _ h _) (monotone_eapprox _ h _) }
end
... = (⨆n, (eapprox f n).lintegral μ) + (⨆n, (eapprox g n).lintegral μ) :
by refine (ennreal.supr_add_supr_of_monotone _ _).symm;
{ assume i j h, exact simple_func.lintegral_mono (monotone_eapprox _ h) (le_refl μ) }
... = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) :
by rw [lintegral_eq_supr_eapprox_lintegral hf, lintegral_eq_supr_eapprox_lintegral hg]
lemma lintegral_zero : (∫⁻ a:α, 0 ∂μ) = 0 := by simp
@[simp] lemma lintegral_smul_measure (c : ennreal) (f : α → ennreal) :
∫⁻ a, f a ∂ (c • μ) = c * ∫⁻ a, f a ∂μ :=
by simp only [lintegral, supr_subtype', simple_func.lintegral_smul, ennreal.mul_supr, smul_eq_mul]
@[simp] lemma lintegral_sum_measure {ι} (f : α → ennreal) (μ : ι → measure α) :
∫⁻ a, f a ∂(measure.sum μ) = ∑' i, ∫⁻ a, f a ∂(μ i) :=
begin
simp only [lintegral, supr_subtype', simple_func.lintegral_sum, ennreal.tsum_eq_supr_sum],
rw [supr_comm],
congr, funext s,
induction s using finset.induction_on with i s hi hs, { apply bot_unique, simp },
simp only [finset.sum_insert hi, ← hs],
refine (ennreal.supr_add_supr _).symm,
intros φ ψ,
exact ⟨⟨φ ⊔ ψ, λ x, sup_le (φ.2 x) (ψ.2 x)⟩,
add_le_add (simple_func.lintegral_mono le_sup_left (le_refl _))
(finset.sum_le_sum $ λ j hj, simple_func.lintegral_mono le_sup_right (le_refl _))⟩
end
@[simp] lemma lintegral_add_measure (f : α → ennreal) (μ ν : measure α) :
∫⁻ a, f a ∂ (μ + ν) = ∫⁻ a, f a ∂μ + ∫⁻ a, f a ∂ν :=
by simpa [tsum_fintype] using lintegral_sum_measure f (λ b, cond b μ ν)
@[simp] lemma lintegral_zero_measure (f : α → ennreal) : ∫⁻ a, f a ∂0 = 0 :=
bot_unique $ by simp [lintegral]
lemma lintegral_finset_sum (s : finset β) {f : β → α → ennreal} (hf : ∀b, measurable (f b)) :
(∫⁻ a, ∑ b in s, f b a ∂μ) = ∑ b in s, ∫⁻ a, f b a ∂μ :=
begin
refine finset.induction_on s _ _,
{ simp },
{ assume a s has ih,
simp only [finset.sum_insert has],
rw [lintegral_add (hf _) (s.measurable_sum hf), ih] }
end
@[simp] lemma lintegral_const_mul (r : ennreal) {f : α → ennreal} (hf : measurable f) :
(∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) :=
calc (∫⁻ a, r * f a ∂μ) = (∫⁻ a, (⨆n, (const α r * eapprox f n) a) ∂μ) :
by { congr, funext a, rw [← supr_eapprox_apply f hf, ennreal.mul_supr], refl }
... = (⨆n, r * (eapprox f n).lintegral μ) :
begin
rw [lintegral_supr],
{ congr, funext n,
rw [← simple_func.const_mul_lintegral, ← simple_func.lintegral_eq_lintegral] },
{ assume n, exact simple_func.measurable _ },
{ assume i j h a, exact canonically_ordered_semiring.mul_le_mul (le_refl _)
(monotone_eapprox _ h _) }
end
... = r * (∫⁻ a, f a ∂μ) : by rw [← ennreal.mul_supr, lintegral_eq_supr_eapprox_lintegral hf]
lemma lintegral_const_mul_le (r : ennreal) (f : α → ennreal) :
r * (∫⁻ a, f a ∂μ) ≤ (∫⁻ a, r * f a ∂μ) :=
begin
rw [lintegral, ennreal.mul_supr],
refine supr_le (λs, _),
rw [ennreal.mul_supr],
simp only [supr_le_iff, ge_iff_le],
assume hs,
rw ← simple_func.const_mul_lintegral,
refine le_supr_of_le (const α r * s) (le_supr_of_le (λx, _) (le_refl _)),
exact canonically_ordered_semiring.mul_le_mul (le_refl _) (hs x)
end
lemma lintegral_const_mul' (r : ennreal) (f : α → ennreal) (hr : r ≠ ⊤) :
(∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) :=
begin
by_cases h : r = 0,
{ simp [h] },
apply le_antisymm _ (lintegral_const_mul_le r f),
have rinv : r * r⁻¹ = 1 := ennreal.mul_inv_cancel h hr,
have rinv' : r ⁻¹ * r = 1, by { rw mul_comm, exact rinv },
have := lintegral_const_mul_le (r⁻¹) (λx, r * f x),
simp [(mul_assoc _ _ _).symm, rinv'] at this,
simpa [(mul_assoc _ _ _).symm, rinv]
using canonically_ordered_semiring.mul_le_mul (le_refl r) this
end
lemma lintegral_mul_const (r : ennreal) {f : α → ennreal} (hf : measurable f) :
∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r :=
by simp_rw [mul_comm, lintegral_const_mul r hf]
lemma lintegral_mul_const_le (r : ennreal) (f : α → ennreal) :
∫⁻ a, f a ∂μ * r ≤ ∫⁻ a, f a * r ∂μ :=
by simp_rw [mul_comm, lintegral_const_mul_le r f]
lemma lintegral_mul_const' (r : ennreal) (f : α → ennreal) (hr : r ≠ ⊤):
∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r :=
by simp_rw [mul_comm, lintegral_const_mul' r f hr]
lemma lintegral_mono_ae {f g : α → ennreal} (h : ∀ᵐ a ∂μ, f a ≤ g a) :
(∫⁻ a, f a ∂μ) ≤ (∫⁻ a, g a ∂μ) :=
begin
rcases exists_is_measurable_superset_of_measure_eq_zero h with ⟨t, hts, ht, ht0⟩,
have : ∀ᵐ x ∂μ, x ∉ t := measure_zero_iff_ae_nmem.1 ht0,
refine (supr_le $ assume s, supr_le $ assume hfs,
le_supr_of_le (s.restrict tᶜ) $ le_supr_of_le _ _),
{ assume a,
by_cases a ∈ t;
simp [h, restrict_apply, ht.compl],
exact le_trans (hfs a) (by_contradiction $ assume hnfg, h (hts hnfg)) },
{ refine le_of_eq (simple_func.lintegral_congr $ this.mono $ λ a hnt, _),
by_cases hat : a ∈ t; simp [hat, ht.compl],
exact (hnt hat).elim }
end
lemma lintegral_congr_ae {f g : α → ennreal} (h : f =ᵐ[μ] g) :
(∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) :=
le_antisymm (lintegral_mono_ae $ h.le) (lintegral_mono_ae $ h.symm.le)
lemma lintegral_congr {f g : α → ennreal} (h : ∀ a, f a = g a) :
(∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) :=
by simp only [h]
lemma set_lintegral_congr {f : α → ennreal} {s t : set α} (h : s =ᵐ[μ] t) :
∫⁻ x in s, f x ∂μ = ∫⁻ x in t, f x ∂μ :=
by rw [restrict_congr_set h]
-- TODO: Need a better way of rewriting inside of a integral
lemma lintegral_rw₁ {f f' : α → β} (h : f =ᵐ[μ] f') (g : β → ennreal) :
(∫⁻ a, g (f a) ∂μ) = (∫⁻ a, g (f' a) ∂μ) :=
lintegral_congr_ae $ h.mono $ λ a h, by rw h
-- TODO: Need a better way of rewriting inside of a integral
lemma lintegral_rw₂ {f₁ f₁' : α → β} {f₂ f₂' : α → γ} (h₁ : f₁ =ᵐ[μ] f₁')
(h₂ : f₂ =ᵐ[μ] f₂') (g : β → γ → ennreal) :
(∫⁻ a, g (f₁ a) (f₂ a) ∂μ) = (∫⁻ a, g (f₁' a) (f₂' a) ∂μ) :=
lintegral_congr_ae $ h₁.mp $ h₂.mono $ λ _ h₂ h₁, by rw [h₁, h₂]
@[simp] lemma lintegral_indicator (f : α → ennreal) {s : set α} (hs : is_measurable s) :
∫⁻ a, s.indicator f a ∂μ = ∫⁻ a in s, f a ∂μ :=
begin
simp only [lintegral, ← restrict_lintegral_eq_lintegral_restrict _ hs, supr_subtype'],
apply le_antisymm; refine supr_le_supr2 (subtype.forall.2 $ λ φ hφ, _),
{ refine ⟨⟨φ, le_trans hφ (indicator_le_self _ _)⟩, _⟩,
refine simple_func.lintegral_mono (λ x, _) (le_refl _),
by_cases hx : x ∈ s,
{ simp [hx, hs, le_refl] },
{ apply le_trans (hφ x),
simp [hx, hs, le_refl] } },
{ refine ⟨⟨φ.restrict s, λ x, _⟩, le_refl _⟩,
simp [hφ x, hs, indicator_le_indicator] }
end
/-- Chebyshev's inequality -/
lemma mul_meas_ge_le_lintegral {f : α → ennreal} (hf : measurable f) (ε : ennreal) :
ε * μ {x | ε ≤ f x} ≤ ∫⁻ a, f a ∂μ :=
begin
have : is_measurable {a : α | ε ≤ f a }, from hf is_measurable_Ici,
rw [← simple_func.restrict_const_lintegral _ this, ← simple_func.lintegral_eq_lintegral],
refine lintegral_mono (λ a, _),
simp only [restrict_apply _ this],
split_ifs; [assumption, exact zero_le _]
end
lemma meas_ge_le_lintegral_div {f : α → ennreal} (hf : measurable f) {ε : ennreal}
(hε : ε ≠ 0) (hε' : ε ≠ ⊤) :
μ {x | ε ≤ f x} ≤ (∫⁻ a, f a ∂μ) / ε :=
(ennreal.le_div_iff_mul_le (or.inl hε) (or.inl hε')).2 $
by { rw [mul_comm], exact mul_meas_ge_le_lintegral hf ε }
@[simp] lemma lintegral_eq_zero_iff {f : α → ennreal} (hf : measurable f) :
∫⁻ a, f a ∂μ = 0 ↔ (f =ᵐ[μ] 0) :=
begin
refine iff.intro (assume h, _) (assume h, _),
{ have : ∀n:ℕ, ∀ᵐ a ∂μ, f a < n⁻¹,
{ assume n,
rw [ae_iff, ← le_zero_iff_eq, ← @ennreal.zero_div n⁻¹,
ennreal.le_div_iff_mul_le, mul_comm],
simp only [not_lt],
-- TODO: why `rw ← h` fails with "not an equality or an iff"?
exacts [h ▸ mul_meas_ge_le_lintegral hf n⁻¹,
or.inl (ennreal.inv_ne_zero.2 ennreal.coe_nat_ne_top),
or.inr ennreal.zero_ne_top] },
refine (ae_all_iff.2 this).mono (λ a ha, _),
by_contradiction h,
rcases ennreal.exists_inv_nat_lt h with ⟨n, hn⟩,
exact (lt_irrefl _ $ lt_trans hn $ ha n).elim },
{ calc ∫⁻ a, f a ∂μ = ∫⁻ a, 0 ∂μ : lintegral_congr_ae h
... = 0 : lintegral_zero }
end
lemma lintegral_pos_iff_support {f : α → ennreal} (hf : measurable f) :
0 < ∫⁻ a, f a ∂μ ↔ 0 < μ (function.support f) :=
by simp [zero_lt_iff_ne_zero, hf, filter.eventually_eq, ae_iff, function.support]
/-- Weaker version of the monotone convergence theorem-/
lemma lintegral_supr_ae {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n))
(h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f n.succ a) :
(∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) :=
let ⟨s, hs⟩ := exists_is_measurable_superset_of_measure_eq_zero
(ae_iff.1 (ae_all_iff.2 h_mono)) in
let g := λ n a, if a ∈ s then 0 else f n a in
have g_eq_f : ∀ᵐ a ∂μ, ∀n, g n a = f n a,
from (measure_zero_iff_ae_nmem.1 hs.2.2).mono (assume a ha n, if_neg ha),
calc
∫⁻ a, ⨆n, f n a ∂μ = ∫⁻ a, ⨆n, g n a ∂μ :
lintegral_congr_ae $ g_eq_f.mono $ λ a ha, by simp only [ha]
... = ⨆n, (∫⁻ a, g n a ∂μ) :
lintegral_supr
(assume n, measurable_const.piecewise hs.2.1 (hf n))
(monotone_of_monotone_nat $ assume n a, classical.by_cases
(assume h : a ∈ s, by simp [g, if_pos h])
(assume h : a ∉ s,
begin
simp only [g, if_neg h], have := hs.1, rw subset_def at this, have := mt (this a) h,
simp only [not_not, mem_set_of_eq] at this, exact this n
end))
... = ⨆n, (∫⁻ a, f n a ∂μ) :
by simp only [lintegral_congr_ae (g_eq_f.mono $ λ a ha, ha _)]
lemma lintegral_sub {f g : α → ennreal} (hf : measurable f) (hg : measurable g)
(hg_fin : ∫⁻ a, g a ∂μ < ⊤) (h_le : g ≤ᵐ[μ] f) :
∫⁻ a, f a - g a ∂μ = ∫⁻ a, f a ∂μ - ∫⁻ a, g a ∂μ :=
begin
rw [← ennreal.add_left_inj hg_fin,
ennreal.sub_add_cancel_of_le (lintegral_mono_ae h_le),
← lintegral_add (hf.ennreal_sub hg) hg],
refine lintegral_congr_ae (h_le.mono $ λ x hx, _),
exact ennreal.sub_add_cancel_of_le hx
end
/-- Monotone convergence theorem for nonincreasing sequences of functions -/
lemma lintegral_infi_ae
{f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n))
(h_mono : ∀n:ℕ, f n.succ ≤ᵐ[μ] f n) (h_fin : ∫⁻ a, f 0 a ∂μ < ⊤) :
∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ :=
have fn_le_f0 : ∫⁻ a, ⨅n, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ, from
lintegral_mono (assume a, infi_le_of_le 0 (le_refl _)),
have fn_le_f0' : (⨅n, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, f 0 a ∂μ, from infi_le_of_le 0 (le_refl _),
(ennreal.sub_right_inj h_fin fn_le_f0 fn_le_f0').1 $
show ∫⁻ a, f 0 a ∂μ - ∫⁻ a, ⨅n, f n a ∂μ = ∫⁻ a, f 0 a ∂μ - (⨅n, ∫⁻ a, f n a ∂μ), from
calc
∫⁻ a, f 0 a ∂μ - (∫⁻ a, ⨅n, f n a ∂μ) = ∫⁻ a, f 0 a - ⨅n, f n a ∂μ:
(lintegral_sub (h_meas 0) (measurable_infi h_meas)
(calc
(∫⁻ a, ⨅n, f n a ∂μ) ≤ ∫⁻ a, f 0 a ∂μ : lintegral_mono (assume a, infi_le _ _)
... < ⊤ : h_fin )
(ae_of_all _ $ assume a, infi_le _ _)).symm
... = ∫⁻ a, ⨆n, f 0 a - f n a ∂μ : congr rfl (funext (assume a, ennreal.sub_infi))
... = ⨆n, ∫⁻ a, f 0 a - f n a ∂μ :
lintegral_supr_ae
(assume n, (h_meas 0).ennreal_sub (h_meas n))
(assume n, (h_mono n).mono $ assume a ha, ennreal.sub_le_sub (le_refl _) ha)
... = ⨆n, ∫⁻ a, f 0 a ∂μ - ∫⁻ a, f n a ∂μ :
have h_mono : ∀ᵐ a ∂μ, ∀n:ℕ, f n.succ a ≤ f n a := ae_all_iff.2 h_mono,
have h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f 0 a := assume n, h_mono.mono $ assume a h,
begin
induction n with n ih,
{exact le_refl _}, {exact le_trans (h n) ih}
end,
congr rfl (funext $ assume n, lintegral_sub (h_meas _) (h_meas _)
(calc
∫⁻ a, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ : lintegral_mono_ae $ h_mono n
... < ⊤ : h_fin)
(h_mono n))
... = ∫⁻ a, f 0 a ∂μ - ⨅n, ∫⁻ a, f n a ∂μ : ennreal.sub_infi.symm
/-- Monotone convergence theorem for nonincreasing sequences of functions -/
lemma lintegral_infi
{f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n))
(h_mono : ∀ ⦃m n⦄, m ≤ n → f n ≤ f m) (h_fin : ∫⁻ a, f 0 a ∂μ < ⊤) :
∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ :=
lintegral_infi_ae h_meas (λ n, ae_of_all _ $ h_mono $ le_of_lt n.lt_succ_self) h_fin
/-- Known as Fatou's lemma -/
lemma lintegral_liminf_le {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) :
∫⁻ a, liminf at_top (λ n, f n a) ∂μ ≤ liminf at_top (λ n, ∫⁻ a, f n a ∂μ) :=
calc
∫⁻ a, liminf at_top (λ n, f n a) ∂μ = ∫⁻ a, ⨆n:ℕ, ⨅i≥n, f i a ∂μ :
by simp only [liminf_eq_supr_infi_of_nat]
... = ⨆n:ℕ, ∫⁻ a, ⨅i≥n, f i a ∂μ :
lintegral_supr
(assume n, measurable_binfi _ (countable_encodable _) h_meas)
(assume n m hnm a, infi_le_infi_of_subset $ λ i hi, le_trans hnm hi)
... ≤ ⨆n:ℕ, ⨅i≥n, ∫⁻ a, f i a ∂μ :
supr_le_supr $ λ n, le_infi2_lintegral _
... = liminf at_top (λ n, ∫⁻ a, f n a ∂μ) : liminf_eq_supr_infi_of_nat.symm
lemma limsup_lintegral_le {f : ℕ → α → ennreal} {g : α → ennreal}
(hf_meas : ∀ n, measurable (f n)) (h_bound : ∀n, f n ≤ᵐ[μ] g) (h_fin : ∫⁻ a, g a ∂μ < ⊤) :
limsup at_top (λn, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, f n a) ∂μ :=
calc
limsup at_top (λn, ∫⁻ a, f n a ∂μ) = ⨅n:ℕ, ⨆i≥n, ∫⁻ a, f i a ∂μ :
limsup_eq_infi_supr_of_nat
... ≤ ⨅n:ℕ, ∫⁻ a, ⨆i≥n, f i a ∂μ :
infi_le_infi $ assume n, supr2_lintegral_le _
... = ∫⁻ a, ⨅n:ℕ, ⨆i≥n, f i a ∂μ :
begin
refine (lintegral_infi _ _ _).symm,
{ assume n, exact measurable_bsupr _ (countable_encodable _) hf_meas },
{ assume n m hnm a, exact (supr_le_supr_of_subset $ λ i hi, le_trans hnm hi) },
{ refine lt_of_le_of_lt (lintegral_mono_ae _) h_fin,
refine (ae_all_iff.2 h_bound).mono (λ n hn, _),
exact supr_le (λ i, supr_le $ λ hi, hn i) }
end
... = ∫⁻ a, limsup at_top (λn, f n a) ∂μ :
by simp only [limsup_eq_infi_supr_of_nat]
/-- Dominated convergence theorem for nonnegative functions -/
lemma tendsto_lintegral_of_dominated_convergence
{F : ℕ → α → ennreal} {f : α → ennreal} (bound : α → ennreal)
(hF_meas : ∀n, measurable (F n)) (h_bound : ∀n, F n ≤ᵐ[μ] bound)
(h_fin : ∫⁻ a, bound a ∂μ < ⊤)
(h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) :
tendsto (λn, ∫⁻ a, F n a ∂μ) at_top (𝓝 (∫⁻ a, f a ∂μ)) :=
tendsto_of_le_liminf_of_limsup_le
(calc ∫⁻ a, f a ∂μ = ∫⁻ a, liminf at_top (λ (n : ℕ), F n a) ∂μ :
lintegral_congr_ae $ h_lim.mono $ assume a h, h.liminf_eq.symm
... ≤ liminf at_top (λ n, ∫⁻ a, F n a ∂μ) : lintegral_liminf_le hF_meas)
(calc limsup at_top (λ (n : ℕ), ∫⁻ a, F n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, F n a) ∂μ :
limsup_lintegral_le hF_meas h_bound h_fin
... = ∫⁻ a, f a ∂μ : lintegral_congr_ae $ h_lim.mono $ λ a h, h.limsup_eq)
/-- Dominated convergence theorem for filters with a countable basis -/
lemma tendsto_lintegral_filter_of_dominated_convergence {ι} {l : filter ι}
{F : ι → α → ennreal} {f : α → ennreal} (bound : α → ennreal)
(hl_cb : l.is_countably_generated)
(hF_meas : ∀ᶠ n in l, measurable (F n))
(h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, F n a ≤ bound a)
(h_fin : ∫⁻ a, bound a ∂μ < ⊤)
(h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) l (𝓝 (f a))) :
tendsto (λn, ∫⁻ a, F n a ∂μ) l (𝓝 $ ∫⁻ a, f a ∂μ) :=
begin
rw hl_cb.tendsto_iff_seq_tendsto,
{ intros x xl,
have hxl, { rw tendsto_at_top' at xl, exact xl },
have h := inter_mem_sets hF_meas h_bound,
replace h := hxl _ h,
rcases h with ⟨k, h⟩,
rw ← tendsto_add_at_top_iff_nat k,
refine tendsto_lintegral_of_dominated_convergence _ _ _ _ _,
{ exact bound },
{ intro, refine (h _ _).1, exact nat.le_add_left _ _ },
{ intro, refine (h _ _).2, exact nat.le_add_left _ _ },
{ assumption },
{ refine h_lim.mono (λ a h_lim, _),
apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a),
{ assumption },
rw tendsto_add_at_top_iff_nat,
assumption } },
end
section
open encodable
/-- Monotone convergence for a suprema over a directed family and indexed by an encodable type -/
theorem lintegral_supr_directed [encodable β] {f : β → α → ennreal}
(hf : ∀b, measurable (f b)) (h_directed : directed (≤) f) :
∫⁻ a, ⨆b, f b a ∂μ = ⨆b, ∫⁻ a, f b a ∂μ :=
begin
by_cases hβ : nonempty β, swap,
{ simp [supr_of_empty hβ] },
resetI, inhabit β,
have : ∀a, (⨆ b, f b a) = (⨆ n, f (h_directed.sequence f n) a),
{ assume a,
refine le_antisymm (supr_le $ assume b, _) (supr_le $ assume n, le_supr (λn, f n a) _),
exact le_supr_of_le (encode b + 1) (h_directed.le_sequence b a) },
calc ∫⁻ a, ⨆ b, f b a ∂μ = ∫⁻ a, ⨆ n, f (h_directed.sequence f n) a ∂μ :
by simp only [this]
... = ⨆ n, ∫⁻ a, f (h_directed.sequence f n) a ∂μ :
lintegral_supr (assume n, hf _) h_directed.sequence_mono
... = ⨆ b, ∫⁻ a, f b a ∂μ :
begin
refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume b, _),
{ exact le_supr (λb, ∫⁻ a, f b a ∂μ) _ },
{ exact le_supr_of_le (encode b + 1)
(lintegral_mono $ h_directed.le_sequence b) }
end
end
end
lemma lintegral_tsum [encodable β] {f : β → α → ennreal} (hf : ∀i, measurable (f i)) :
∫⁻ a, ∑' i, f i a ∂μ = ∑' i, ∫⁻ a, f i a ∂μ :=
begin
simp only [ennreal.tsum_eq_supr_sum],
rw [lintegral_supr_directed],
{ simp [lintegral_finset_sum _ hf] },
{ assume b, exact finset.measurable_sum _ hf },
{ assume s t,
use [s ∪ t],
split,
exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_left _ _),
exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_right _ _) }
end
open measure
lemma lintegral_Union [encodable β] {s : β → set α} (hm : ∀ i, is_measurable (s i))
(hd : pairwise (disjoint on s)) (f : α → ennreal) :
∫⁻ a in ⋃ i, s i, f a ∂μ = ∑' i, ∫⁻ a in s i, f a ∂μ :=
by simp only [measure.restrict_Union hd hm, lintegral_sum_measure]
lemma lintegral_Union_le [encodable β] (s : β → set α) (f : α → ennreal) :
∫⁻ a in ⋃ i, s i, f a ∂μ ≤ ∑' i, ∫⁻ a in s i, f a ∂μ :=
begin
rw [← lintegral_sum_measure],
exact lintegral_mono' restrict_Union_le (le_refl _)
end
lemma lintegral_map [measurable_space β] {f : β → ennreal} {g : α → β}
(hf : measurable f) (hg : measurable g) : ∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ :=
begin
simp only [lintegral_eq_supr_eapprox_lintegral, hf, hf.comp hg],
{ congr, funext n, symmetry,
apply simple_func.lintegral_map,
{ assume a, exact congr_fun (simple_func.eapprox_comp hf hg) a },
{ assume s hs, exact map_apply hg hs } },
end
lemma lintegral_comp [measurable_space β] {f : β → ennreal} {g : α → β}
(hf : measurable f) (hg : measurable g) : lintegral μ (f ∘ g) = ∫⁻ a, f a ∂(map g μ) :=
(lintegral_map hf hg).symm
lemma set_lintegral_map [measurable_space β] {f : β → ennreal} {g : α → β}
{s : set β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) :
∫⁻ y in s, f y ∂(map g μ) = ∫⁻ x in g ⁻¹' s, f (g x) ∂μ :=
by rw [restrict_map hg hs, lintegral_map hf hg]
lemma lintegral_dirac (a : α) {f : α → ennreal} (hf : measurable f) :
∫⁻ a, f a ∂(dirac a) = f a :=
by simp [lintegral_congr_ae (eventually_eq_dirac hf)]
lemma ae_lt_top {f : α → ennreal} (hf : measurable f) (h2f : ∫⁻ x, f x ∂μ < ⊤) :
∀ᵐ x ∂μ, f x < ⊤ :=
begin
simp_rw [ae_iff, ennreal.not_lt_top], by_contra h, rw [← not_le] at h2f, apply h2f,
have : (f ⁻¹' {⊤}).indicator ⊤ ≤ f,
{ intro x, by_cases hx : x ∈ f ⁻¹' {⊤}; [simpa [hx], simp [hx]] },
convert lintegral_mono this,
rw [lintegral_indicator _ (hf (is_measurable_singleton ⊤))], simp [ennreal.top_mul, preimage, h]
end
/-- Given a measure `μ : measure α` and a function `f : α → ennreal`, `μ.with_density f` is the
measure such that for a measurable set `s` we have `μ.with_density f s = ∫⁻ a in s, f a ∂μ`. -/
def measure.with_density (μ : measure α) (f : α → ennreal) : measure α :=
measure.of_measurable (λs hs, ∫⁻ a in s, f a ∂μ) (by simp) (λ s hs hd, lintegral_Union hs hd _)
@[simp] lemma with_density_apply (f : α → ennreal) {s : set α} (hs : is_measurable s) :
μ.with_density f s = ∫⁻ a in s, f a ∂μ :=
measure.of_measurable_apply s hs
end lintegral
end measure_theory
open measure_theory measure_theory.simple_func
/-- To prove something for an arbitrary measurable function into `ennreal`, it suffices to show
that the property holds for (multiples of) characteristic functions and is closed under addition
and supremum of increasing sequences of functions.
It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions
can be added once we need them (for example in `h_sum` it is only necessary to consider the sum of
a simple function with a multiple of a characteristic function and that the intersection
of their images is a subset of `{0}`. -/
@[elab_as_eliminator]
theorem measurable.ennreal_induction {α} [measurable_space α] {P : (α → ennreal) → Prop}
(h_ind : ∀ (c : ennreal) ⦃s⦄, is_measurable s → P (indicator s (λ _, c)))
(h_sum : ∀ ⦃f g : α → ennreal⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → measurable f → measurable g →
P f → P g → P (f + g))
(h_supr : ∀ ⦃f : ℕ → α → ennreal⦄ (hf : ∀n, measurable (f n)) (h_mono : monotone f)
(hP : ∀ n, P (f n)), P (λ x, ⨆ n, f n x))
⦃f : α → ennreal⦄ (hf : measurable f) : P f :=
begin
convert h_supr (λ n, (eapprox f n).measurable) (monotone_eapprox f) _,
{ ext1 x, rw [supr_eapprox_apply f hf] },
{ exact λ n, simple_func.induction (λ c s hs, h_ind c hs)
(λ f g hfg hf hg, h_sum hfg f.measurable g.measurable hf hg) (eapprox f n) }
end
namespace measure_theory
/-- This is Exercise 1.2.1 from [tao2010]. It allows you to express integration of a measurable
function with respect to `(μ.with_density f)` as an integral with respect to `μ`, called the base
measure. `μ` is often the Lebesgue measure, and in this circumstance `f` is the probability density
function, and `(μ.with_density f)` represents any continuous random variable as a
probability measure, such as the uniform distribution between 0 and 1, the Gaussian distribution,
the exponential distribution, the Beta distribution, or the Cauchy distribution (see Section 2.4
of [wasserman2004]). Thus, this method shows how to one can calculate expectations, variances,
and other moments as a function of the probability density function.
-/
lemma lintegral_with_density_eq_lintegral_mul {α} [measurable_space α] (μ : measure α)
{f : α → ennreal} (h_mf : measurable f) : ∀ {g : α → ennreal}, measurable g →
∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ :=
begin
apply measurable.ennreal_induction,
{ intros c s h_ms,
simp [*, mul_comm _ c] },
{ intros g h h_univ h_mea_g h_mea_h h_ind_g h_ind_h,
simp [mul_add, *, measurable.ennreal_mul] },
{ intros g h_mea_g h_mono_g h_ind,
have : monotone (λ n a, f a * g n a) := λ m n hmn x, ennreal.mul_le_mul le_rfl (h_mono_g hmn x),
simp [lintegral_supr, ennreal.mul_supr, h_mf.ennreal_mul (h_mea_g _), *] }
end
end measure_theory
|
e42e929cdac54f4ef8930b35a14baf00341e7e1c | a88f0086fb3e2025ebb21e0ba2f2725774c6979f | /src/topology/local_homeomorph.lean | ba2ff16f71654770192a4a8620ecb142ce818d32 | [
"Apache-2.0"
] | permissive | Kha/stdlib | b5a4456c35def0ca8f1bf2d32dbeebd7639cbc4d | e44b105c72ec77120f43a7a7dd1cd49867a65a41 | refs/heads/master | 1,609,528,111,500 | 1,572,963,395,000 | 1,572,963,395,000 | 98,516,307 | 0 | 1 | null | 1,501,146,352,000 | 1,501,146,352,000 | null | UTF-8 | Lean | false | false | 22,622 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import data.equiv.local_equiv topology.continuous_on topology.homeomorph
/-!
# Local homeomorphisms
This file defines homeomorphisms between open subsets of topological spaces. An element `e` of
`local_homeomorph α β` is an extension of `local_equiv α β`, i.e., it is a pair of functions
`e.to_fun` and `e.inv_fun`, inverse of each other on the sets `e.source` and `e.target`.
Additionally, we require that these sets are open, and that the functions are continuous on them.
Equivalently, they are homeomorphisms there.
Contrary to equivs, we do not register the coercion to functions and we use explicitly to_fun and
inv_fun: coercions create unification problems for manifolds.
## Main definitions
`homeomorph.to_local_homeomorph`: associating a local homeomorphism to a homeomorphism, with
source = target = univ
`local_homeomorph.symm` : the inverse of a local homeomorphism
`local_homeomorph.trans` : the composition of two local homeomorphisms
`local_homeomorph.refl` : the identity local homeomorphism
`local_homeomorph.of_set`: the identity on a set `s`
`eq_on_source` : equivalence relation describing the "right" notion of equality for local
homeomorphisms
## Implementation notes
Most statements are copied from their local_equiv versions, although some care is required
especially when restricting to subsets, as these should be open subsets.
For design notes, see `local_equiv.lean`.
-/
open function set
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
[topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
/-- local homeomorphisms, defined on open subsets of the space -/
structure local_homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β]
extends local_equiv α β :=
(open_source : is_open source)
(open_target : is_open target)
(continuous_to_fun : continuous_on to_fun source)
(continuous_inv_fun : continuous_on inv_fun target)
/-- A homeomorphism induces a local homeomorphism on the whole space -/
def homeomorph.to_local_homeomorph (e : homeomorph α β) :
local_homeomorph α β :=
{ open_source := is_open_univ,
open_target := is_open_univ,
continuous_to_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_to_fun },
continuous_inv_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_inv_fun },
..e.to_equiv.to_local_equiv }
namespace local_homeomorph
variables (e : local_homeomorph α β) (e' : local_homeomorph β γ)
lemma eq_of_local_equiv_eq {e e' : local_homeomorph α β}
(h : e.to_local_equiv = e'.to_local_equiv) : e = e' :=
begin
cases e, cases e',
dsimp at *,
induction h,
refl
end
/-- Two local homeomorphisms are equal when they have equal to_fun, inv_fun and source. It is not
sufficient to have equal to_fun and source, as this only determines inv_fun on the target. This
would only be true for a weaker notion of equality, arguably the right one, called `eq_on_source`. -/
@[extensionality]
protected lemma ext (e' : local_homeomorph α β) (h : ∀x, e.to_fun x = e'.to_fun x)
(hinv: ∀x, e.inv_fun x = e'.inv_fun x) (hs : e.source = e'.source) : e = e' :=
eq_of_local_equiv_eq (local_equiv.ext e.to_local_equiv e'.to_local_equiv h hinv hs)
/-- The inverse of a local homeomorphism -/
protected def symm : local_homeomorph β α :=
{ open_source := e.open_target,
open_target := e.open_source,
continuous_to_fun := e.continuous_inv_fun,
continuous_inv_fun := e.continuous_to_fun,
..e.to_local_equiv.symm }
@[simp] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl
@[simp] lemma symm_to_fun : e.symm.to_fun = e.inv_fun := rfl
@[simp] lemma symm_inv_fun : e.symm.inv_fun = e.to_fun := rfl
@[simp] lemma symm_source : e.symm.source = e.target := rfl
@[simp] lemma symm_target : e.symm.target = e.source := rfl
@[simp] lemma symm_symm : e.symm.symm = e := eq_of_local_equiv_eq $ by simp
/-- Preimage of interior or interior of preimage coincide for local homeomorphisms, when restricted
to the source. -/
lemma preimage_interior (s : set β) :
e.source ∩ e.to_fun ⁻¹' (interior s) = e.source ∩ interior (e.to_fun ⁻¹' s) :=
begin
apply subset.antisymm,
{ exact e.continuous_to_fun.preimage_interior_subset_interior_preimage e.open_source },
{ calc e.source ∩ interior (e.to_fun ⁻¹' s)
= (e.source ∩ e.to_fun ⁻¹' e.target) ∩ interior (e.to_fun ⁻¹' s) : begin
congr,
apply (inter_eq_self_of_subset_left _).symm,
apply e.to_local_equiv.source_subset_preimage_target,
end
... = (e.source ∩ interior (e.to_fun ⁻¹' s)) ∩ (e.to_fun ⁻¹' e.target) :
by simp [inter_comm, inter_assoc]
... = (e.source ∩ e.to_fun ⁻¹' (e.inv_fun ⁻¹' (interior (e.to_fun ⁻¹' s)))) ∩ (e.to_fun ⁻¹' e.target) :
by rw e.to_local_equiv.source_inter_preimage_inv_preimage
... = e.source ∩ e.to_fun ⁻¹' (e.target ∩ e.inv_fun ⁻¹' (interior (e.to_fun ⁻¹' s))) :
by rw [inter_comm e.target, preimage_inter, inter_assoc]
... ⊆ e.source ∩ e.to_fun ⁻¹' (e.target ∩ interior (e.inv_fun ⁻¹' (e.to_fun ⁻¹' s))) : begin
apply inter_subset_inter (subset.refl _) (preimage_mono _),
exact e.continuous_inv_fun.preimage_interior_subset_interior_preimage e.open_target
end
... = e.source ∩ e.to_fun ⁻¹' (interior (e.target ∩ e.inv_fun ⁻¹' (e.to_fun ⁻¹' s))) :
by rw [interior_inter, interior_eq_of_open e.open_target]
... = e.source ∩ e.to_fun ⁻¹' (interior (e.target ∩ s)) :
by rw e.to_local_equiv.target_inter_inv_preimage_preimage
... = e.source ∩ e.to_fun ⁻¹' e.target ∩ e.to_fun ⁻¹' (interior s) :
by rw [interior_inter, preimage_inter, interior_eq_of_open e.open_target, inter_assoc]
... = e.source ∩ e.to_fun ⁻¹' (interior s) : begin
congr,
apply inter_eq_self_of_subset_left,
apply e.to_local_equiv.source_subset_preimage_target
end }
end
/-- Restricting a local homeomorphism `e` to `e.source ∩ s` when `s` is open. This is sometimes hard
to use because of the openness assumption, but it has the advantage that when it can
be used then its local_equiv is defeq to local_equiv.restr -/
protected def restr_open (s : set α) (hs : is_open s) :
local_homeomorph α β :=
{ open_source := is_open_inter e.open_source hs,
open_target := (continuous_on_open_iff e.open_target).1 e.continuous_inv_fun s hs,
continuous_to_fun := e.continuous_to_fun.mono (inter_subset_left _ _),
continuous_inv_fun := e.continuous_inv_fun.mono (inter_subset_left _ _),
..e.to_local_equiv.restr s}
@[simp] lemma restr_open_source (s : set α) (hs : is_open s) :
(e.restr_open s hs).source = e.source ∩ s := rfl
@[simp] lemma restr_open_to_local_equiv (s : set α) (hs : is_open s) :
(e.restr_open s hs).to_local_equiv = e.to_local_equiv.restr s := rfl
/-- Restricting a local homeomorphism `e` to `e.source ∩ interior s`. We use the interior to make
sure that the restriction is well defined whatever the set s, since local homeomorphisms are by
definition defined on open sets. In applications where `s` is open, this coincides with the
restriction of local equivalences -/
protected def restr (s : set α) : local_homeomorph α β :=
e.restr_open (interior s) is_open_interior
@[simp] lemma restr_to_fun (s : set α) : (e.restr s).to_fun = e.to_fun := rfl
@[simp] lemma restr_inv_fun (s : set α) : (e.restr s).inv_fun = e.inv_fun := rfl
@[simp] lemma restr_source (s : set α) : (e.restr s).source = e.source ∩ interior s := rfl
@[simp] lemma restr_target (s : set α) :
(e.restr s).target = e.target ∩ e.inv_fun ⁻¹' (interior s) := rfl
@[simp] lemma restr_to_local_equiv (s : set α) :
(e.restr s).to_local_equiv = (e.to_local_equiv).restr (interior s) := rfl
lemma restr_source' (s : set α) (hs : is_open s) : (e.restr s).source = e.source ∩ s :=
by rw [e.restr_source, interior_eq_of_open hs]
lemma restr_to_local_equiv' (s : set α) (hs : is_open s):
(e.restr s).to_local_equiv = e.to_local_equiv.restr s :=
by rw [e.restr_to_local_equiv, interior_eq_of_open hs]
lemma restr_eq_of_source_subset {e : local_homeomorph α β} {s : set α} (h : e.source ⊆ s) :
e.restr s = e :=
begin
apply eq_of_local_equiv_eq,
rw restr_to_local_equiv,
apply local_equiv.restr_eq_of_source_subset,
have := interior_mono h,
rwa interior_eq_of_open (e.open_source) at this
end
@[simp] lemma restr_univ {e : local_homeomorph α β} : e.restr univ = e :=
restr_eq_of_source_subset (subset_univ _)
lemma restr_source_inter (s : set α) : e.restr (e.source ∩ s) = e.restr s :=
begin
refine local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) _,
simp [interior_eq_of_open e.open_source],
rw [← inter_assoc, inter_self]
end
/-- The identity on the whole space as a local homeomorphism. -/
protected def refl (α : Type*) [topological_space α] : local_homeomorph α α :=
(homeomorph.refl α).to_local_homeomorph
@[simp] lemma refl_source : (local_homeomorph.refl α).source = univ := rfl
@[simp] lemma refl_target : (local_homeomorph.refl α).target = univ := rfl
@[simp] lemma refl_symm : (local_homeomorph.refl α).symm = local_homeomorph.refl α := rfl
@[simp] lemma refl_to_fun : (local_homeomorph.refl α).to_fun = id := rfl
@[simp] lemma refl_inv_fun : (local_homeomorph.refl α).inv_fun = id := rfl
@[simp] lemma refl_local_equiv : (local_homeomorph.refl α).to_local_equiv = local_equiv.refl α := rfl
section
variables {s : set α} (hs : is_open s)
/-- The identity local equiv on a set `s` -/
def of_set (s : set α) (hs : is_open s) : local_homeomorph α α :=
{ open_source := hs,
open_target := hs,
continuous_to_fun := continuous_id.continuous_on,
continuous_inv_fun := continuous_id.continuous_on,
..local_equiv.of_set s }
@[simp] lemma of_set_source : (of_set s hs).source = s := rfl
@[simp] lemma of_set_target : (of_set s hs).target = s := rfl
@[simp] lemma of_set_to_fun : (of_set s hs).to_fun = id := rfl
@[simp] lemma of_set_inv_fun : (of_set s hs).inv_fun = id := rfl
@[simp] lemma of_set_symm : (of_set s hs).symm = of_set s hs := rfl
@[simp] lemma of_set_to_local_equiv : (of_set s hs).to_local_equiv = local_equiv.of_set s := rfl
end
/-- Composition of two local homeomorphisms when the target of the first and the source of
the second coincide. -/
protected def trans' (h : e.target = e'.source) : local_homeomorph α γ :=
{ open_source := e.open_source,
open_target := e'.open_target,
continuous_to_fun := begin
apply continuous_on.comp e'.continuous_to_fun e.continuous_to_fun,
rw [e.to_local_equiv.image_source_eq_target, h]
end,
continuous_inv_fun := begin
apply continuous_on.comp e.continuous_inv_fun e'.continuous_inv_fun,
rw [e'.to_local_equiv.inv_image_target_eq_source, h],
end,
..local_equiv.trans' e.to_local_equiv e'.to_local_equiv h }
/-- Composing two local homeomorphisms, by restricting to the maximal domain where their
composition is well defined. -/
protected def trans : local_homeomorph α γ :=
local_homeomorph.trans' (e.symm.restr_open e'.source e'.open_source).symm
(e'.restr_open e.target e.open_target) (by simp [inter_comm])
@[simp] lemma trans_to_local_equiv :
(e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv := rfl
@[simp] lemma trans_to_fun : (e.trans e').to_fun = e'.to_fun ∘ e.to_fun := rfl
@[simp] lemma trans_inv_fun : (e.trans e').inv_fun = e.inv_fun ∘ e'.inv_fun := rfl
lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm :=
by cases e; cases e'; refl
/- This could be considered as a simp lemma, but there are many situations where it makes something
simple into something more complicated. -/
lemma trans_source : (e.trans e').source = e.source ∩ e.to_fun ⁻¹' e'.source :=
local_equiv.trans_source e.to_local_equiv e'.to_local_equiv
lemma trans_source' : (e.trans e').source = e.source ∩ e.to_fun ⁻¹' (e.target ∩ e'.source) :=
local_equiv.trans_source' e.to_local_equiv e'.to_local_equiv
lemma trans_source'' : (e.trans e').source = e.inv_fun '' (e.target ∩ e'.source) :=
local_equiv.trans_source'' e.to_local_equiv e'.to_local_equiv
lemma image_trans_source : e.to_fun '' (e.trans e').source = e.target ∩ e'.source :=
local_equiv.image_trans_source e.to_local_equiv e'.to_local_equiv
lemma trans_target : (e.trans e').target = e'.target ∩ e'.inv_fun ⁻¹' e.target := rfl
lemma trans_target' : (e.trans e').target = e'.target ∩ e'.inv_fun ⁻¹' (e'.source ∩ e.target) :=
trans_source' e'.symm e.symm
lemma trans_target'' : (e.trans e').target = e'.to_fun '' (e'.source ∩ e.target) :=
trans_source'' e'.symm e.symm
lemma inv_image_trans_target : e'.inv_fun '' (e.trans e').target = e'.source ∩ e.target :=
image_trans_source e'.symm e.symm
lemma trans_assoc (e'' : local_homeomorph γ δ) :
(e.trans e').trans e'' = e.trans (e'.trans e'') :=
eq_of_local_equiv_eq $ local_equiv.trans_assoc e.to_local_equiv e'.to_local_equiv e''.to_local_equiv
@[simp] lemma trans_refl : e.trans (local_homeomorph.refl β) = e :=
eq_of_local_equiv_eq $ local_equiv.trans_refl e.to_local_equiv
@[simp] lemma refl_trans : (local_homeomorph.refl α).trans e = e :=
eq_of_local_equiv_eq $ local_equiv.refl_trans e.to_local_equiv
lemma trans_of_set {s : set β} (hs : is_open s) :
e.trans (of_set s hs) = e.restr (e.to_fun ⁻¹' s) :=
local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $
by simp [local_equiv.trans_source, (e.preimage_interior _).symm, interior_eq_of_open hs]
lemma trans_of_set' {s : set β} (hs : is_open s) :
e.trans (of_set s hs) = e.restr (e.source ∩ e.to_fun ⁻¹' s) :=
by rw [trans_of_set, restr_source_inter]
lemma of_set_trans {s : set α} (hs : is_open s) :
(of_set s hs).trans e = e.restr s :=
local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $
by simp [local_equiv.trans_source, interior_eq_of_open hs, inter_comm]
lemma of_set_trans' {s : set α} (hs : is_open s) :
(of_set s hs).trans e = e.restr (e.source ∩ s) :=
by rw [of_set_trans, restr_source_inter]
lemma restr_trans (s : set α) :
(e.restr s).trans e' = (e.trans e').restr s :=
eq_of_local_equiv_eq $ local_equiv.restr_trans e.to_local_equiv e'.to_local_equiv (interior s)
/-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. They
should really be considered the same local equiv. -/
def eq_on_source (e e' : local_homeomorph α β) : Prop :=
e.source = e'.source ∧ (∀x ∈ e.source, e.to_fun x = e'.to_fun x)
lemma eq_on_source_iff (e e' : local_homeomorph α β) :
eq_on_source e e' ↔ local_equiv.eq_on_source e.to_local_equiv e'.to_local_equiv :=
by refl
/-- `eq_on_source` is an equivalence relation -/
instance : setoid (local_homeomorph α β) :=
{ r := eq_on_source,
iseqv := ⟨
λe, (@local_equiv.eq_on_source_setoid α β).iseqv.1 e.to_local_equiv,
λe e' h, (@local_equiv.eq_on_source_setoid α β).iseqv.2.1 ((eq_on_source_iff e e').1 h),
λe e' e'' h h', (@local_equiv.eq_on_source_setoid α β).iseqv.2.2
((eq_on_source_iff e e').1 h) ((eq_on_source_iff e' e'').1 h')⟩ }
lemma eq_on_source_refl : e ≈ e := setoid.refl _
/-- If two local homeomorphisms are equivalent, so are their inverses -/
lemma eq_on_source_symm {e e' : local_homeomorph α β} (h : e ≈ e') : e.symm ≈ e'.symm :=
local_equiv.eq_on_source_symm h
/-- Two equivalent local homeomorphisms have the same source -/
lemma source_eq_of_eq_on_source {e e' : local_homeomorph α β} (h : e ≈ e') : e.source = e'.source :=
h.1
/-- Two equivalent local homeomorphisms have the same target -/
lemma target_eq_of_eq_on_source {e e' : local_homeomorph α β} (h : e ≈ e') : e.target = e'.target :=
(eq_on_source_symm h).1
/-- Two equivalent local homeomorphisms have coinciding `to_fun` on the source -/
lemma apply_eq_of_eq_on_source {e e' : local_homeomorph α β} (h : e ≈ e') {x : α} (hx : x ∈ e.source) :
e.to_fun x = e'.to_fun x :=
h.2 x hx
/-- Two equivalent local homeomorphisms have coinciding `inv_fun` on the target -/
lemma inv_apply_eq_of_eq_on_source {e e' : local_homeomorph α β} (h : e ≈ e') {x : β} (hx : x ∈ e.target) :
e.inv_fun x = e'.inv_fun x :=
(eq_on_source_symm h).2 x hx
/-- Composition of local homeomorphisms respects equivalence -/
lemma eq_on_source_trans {e e' : local_homeomorph α β} {f f' : local_homeomorph β γ}
(he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' :=
begin
change local_equiv.eq_on_source (e.trans f).to_local_equiv (e'.trans f').to_local_equiv,
simp only [trans_to_local_equiv],
apply local_equiv.eq_on_source_trans,
exact he,
exact hf
end
/-- Restriction of local homeomorphisms respects equivalence -/
lemma eq_on_source_restr {e e' : local_homeomorph α β} (he : e ≈ e') (s : set α) :
e.restr s ≈ e'.restr s :=
local_equiv.eq_on_source_restr he _
/-- Composition of a local homeomorphism and its inverse is equivalent to the restriction of the
identity to the source -/
lemma trans_self_symm :
e.trans e.symm ≈ local_homeomorph.of_set e.source e.open_source :=
local_equiv.trans_self_symm _
lemma trans_symm_self :
e.symm.trans e ≈ local_homeomorph.of_set e.target e.open_target :=
e.symm.trans_self_symm
lemma eq_of_eq_on_source_univ {e e' : local_homeomorph α β} (h : e ≈ e')
(s : e.source = univ) (t : e.target = univ) : e = e' :=
eq_of_local_equiv_eq $ local_equiv.eq_of_eq_on_source_univ _ _ h s t
section prod
/-- The product of two local homeomorphisms, as a local homeomorphism on the product space. -/
def prod (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : local_homeomorph (α × γ) (β × δ) :=
{ open_source := is_open_prod e.open_source e'.open_source,
open_target := is_open_prod e.open_target e'.open_target,
continuous_to_fun := continuous_on.prod
(continuous_on.comp e.continuous_to_fun continuous_fst.continuous_on (fst_image_prod_subset _ _))
(continuous_on.comp e'.continuous_to_fun continuous_snd.continuous_on (snd_image_prod_subset _ _)),
continuous_inv_fun := continuous_on.prod
(continuous_on.comp e.continuous_inv_fun continuous_fst.continuous_on (fst_image_prod_subset _ _))
(continuous_on.comp e'.continuous_inv_fun continuous_snd.continuous_on (snd_image_prod_subset _ _)),
..e.to_local_equiv.prod e'.to_local_equiv }
@[simp] lemma prod_to_local_equiv (e : local_homeomorph α β) (e' : local_homeomorph γ δ) :
(e.prod e').to_local_equiv = e.to_local_equiv.prod e'.to_local_equiv := rfl
@[simp] lemma prod_source (e : local_homeomorph α β) (e' : local_homeomorph γ δ) :
(e.prod e').source = set.prod e.source e'.source := rfl
@[simp] lemma prod_target (e : local_homeomorph α β) (e' : local_homeomorph γ δ) :
(e.prod e').target = set.prod e.target e'.target := rfl
@[simp] lemma prod_to_fun (e : local_homeomorph α β) (e' : local_homeomorph γ δ) :
(e.prod e').to_fun = (λp, (e.to_fun p.1, e'.to_fun p.2)) := rfl
@[simp] lemma prod_inv_fun (e : local_homeomorph α β) (e' : local_homeomorph γ δ) :
(e.prod e').inv_fun = (λp, (e.inv_fun p.1, e'.inv_fun p.2)) := rfl
end prod
section continuous_on
/-- A function is continuous on a set if and only if its composition with a local homeomorphism
on the right is continuous on the corresponding set. -/
lemma continuous_on_iff_continuous_on_comp_right {f : β → γ} {s : set β} (h : s ⊆ e.target) :
continuous_on f s ↔ continuous_on (f ∘ e.to_fun) (e.source ∩ e.to_fun ⁻¹' s) :=
begin
split,
{ assume f_cont,
apply continuous_on.comp f_cont,
apply e.continuous_to_fun.mono (inter_subset_left _ _),
have : e.to_fun '' (e.to_fun ⁻¹' s) ⊆ s :=
image_preimage_subset _ _,
exact subset.trans (image_subset _ (inter_subset_right _ _)) this },
{ assume fe_cont,
have A : e.inv_fun '' s ⊆ e.source ∩ e.to_fun ⁻¹' s,
{ rw [image_subset_iff, preimage_inter],
assume x hx,
simp [h hx, hx, e.map_target] },
have : continuous_on e.inv_fun s := e.continuous_inv_fun.mono h,
have : continuous_on ((f ∘ e.to_fun) ∘ e.inv_fun) s := continuous_on.comp fe_cont this A,
refine continuous_on.congr_mono this (λx hx, _) (subset.refl _),
simp [h hx, hx] }
end
/-- A function is continuous on a set if and only if its composition with a local homeomorphism
on the left is continuous on the corresponding set. -/
lemma continuous_on_iff_continuous_on_comp_left {f : γ → α} {s : set γ} (h : f '' s ⊆ e.source) :
continuous_on f s ↔ continuous_on (e.to_fun ∘ f) s :=
begin
split,
{ assume f_cont,
exact continuous_on.comp e.continuous_to_fun f_cont h },
{ assume fe_cont,
have : e.to_fun ∘ f '' s ⊆ e.target, from calc
e.to_fun ∘ f '' s = e.to_fun '' (f '' s) : by rw image_comp
... ⊆ e.to_fun '' (e.source) : image_subset _ h
... = e.target : e.to_local_equiv.image_source_eq_target,
have : continuous_on (e.inv_fun ∘ e.to_fun ∘ f) s :=
continuous_on.comp e.continuous_inv_fun fe_cont this,
refine continuous_on.congr_mono this (λx hx, _) (subset.refl _),
have : f x ∈ e.source := h (mem_image_of_mem _ hx),
simp [this] }
end
end continuous_on
end local_homeomorph
namespace homeomorph
variables (e : homeomorph α β) (e' : homeomorph β γ)
/- Register as simp lemmas that the fields of a local homeomorphism built from a homeomorphism
correspond to the fields of the original homeomorphism. -/
@[simp] lemma to_local_homeomorph_source : e.to_local_homeomorph.source = univ := rfl
@[simp] lemma to_local_homeomorph_target : e.to_local_homeomorph.target = univ := rfl
@[simp] lemma to_local_homeomorph_to_fun : e.to_local_homeomorph.to_fun = e.to_fun := rfl
@[simp] lemma to_local_homeomorph_inv_fun : e.to_local_homeomorph.inv_fun = e.inv_fun := rfl
@[simp] lemma refl_to_local_homeomorph :
(homeomorph.refl α).to_local_homeomorph = local_homeomorph.refl α := rfl
@[simp] lemma symm_to_local_homeomorph : e.symm.to_local_homeomorph = e.to_local_homeomorph.symm := rfl
@[simp] lemma trans_to_local_homeomorph :
(e.trans e').to_local_homeomorph = e.to_local_homeomorph.trans e'.to_local_homeomorph :=
local_homeomorph.eq_of_local_equiv_eq $ equiv.trans_to_local_equiv _ _
end homeomorph
|
1dd676d0b58d3ca445947fbf6bdef09f941e80f6 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/int/cast/lemmas.lean | 88b021a9cab0c8c6d47d0b165907a8a9503548dd | [
"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 | 11,266 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.int.order.basic
import data.nat.cast.basic
/-!
# Cast of integers (additional theorems)
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file proves additional properties about the *canonical* homomorphism from
the integers into an additive group with a one (`int.cast`),
particularly results involving algebraic homomorphisms or the order structure on `ℤ`
which were not available in the import dependencies of `data.int.cast.basic`.
## Main declarations
* `cast_add_hom`: `cast` bundled as an `add_monoid_hom`.
* `cast_ring_hom`: `cast` bundled as a `ring_hom`.
-/
open nat
variables {F ι α β : Type*}
namespace int
/-- Coercion `ℕ → ℤ` as a `ring_hom`. -/
def of_nat_hom : ℕ →+* ℤ := ⟨coe, rfl, int.of_nat_mul, rfl, int.of_nat_add⟩
@[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := nat.cast_pos
lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n)
lemma to_nat_lt {a : ℤ} {b : ℕ} (hb : b ≠ 0) : a.to_nat < b ↔ a < b :=
by { rw [←to_nat_lt_to_nat, to_nat_coe_nat], exact coe_nat_pos.2 hb.bot_lt }
lemma nat_mod_lt {a : ℤ} {b : ℕ} (hb : b ≠ 0) : a.nat_mod b < b :=
(to_nat_lt hb).2 $ mod_lt_of_pos _ $ coe_nat_pos.2 hb.bot_lt
section cast
@[simp, norm_cast] theorem cast_mul [non_assoc_ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n :=
λ m, int.induction_on' m 0 (by simp) (λ k _ ih n, by simp [add_mul, ih])
(λ k _ ih n, by simp [sub_mul, ih])
@[simp, norm_cast] theorem cast_ite [add_group_with_one α] (P : Prop) [decidable P] (m n : ℤ) :
((ite P m n : ℤ) : α) = ite P m n :=
apply_ite _ _ _ _
/-- `coe : ℤ → α` as an `add_monoid_hom`. -/
def cast_add_hom (α : Type*) [add_group_with_one α] : ℤ →+ α := ⟨coe, cast_zero, cast_add⟩
@[simp] lemma coe_cast_add_hom [add_group_with_one α] : ⇑(cast_add_hom α) = coe := rfl
/-- `coe : ℤ → α` as a `ring_hom`. -/
def cast_ring_hom (α : Type*) [non_assoc_ring α] : ℤ →+* α :=
⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩
@[simp] lemma coe_cast_ring_hom [non_assoc_ring α] : ⇑(cast_ring_hom α) = coe := rfl
lemma cast_commute [non_assoc_ring α] : ∀ (m : ℤ) (x : α), commute ↑m x
| (n : ℕ) x := by simpa using n.cast_commute x
| -[1+ n] x := by simpa only [cast_neg_succ_of_nat, commute.neg_left_iff, commute.neg_right_iff]
using (n + 1).cast_commute (-x)
lemma cast_comm [non_assoc_ring α] (m : ℤ) (x : α) : (m : α) * x = x * m :=
(cast_commute m x).eq
lemma commute_cast [non_assoc_ring α] (x : α) (m : ℤ) : commute x m :=
(m.cast_commute x).symm
theorem cast_mono [ordered_ring α] : monotone (coe : ℤ → α) :=
begin
intros m n h,
rw ← sub_nonneg at h,
lift n - m to ℕ using h with k,
rw [← sub_nonneg, ← cast_sub, ← h_1, cast_coe_nat],
exact k.cast_nonneg
end
@[simp] theorem cast_nonneg [ordered_ring α] [nontrivial α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n
| (n : ℕ) := by simp
| -[1+ n] := have -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one,
by simpa [(neg_succ_lt_zero n).not_le, ← sub_eq_add_neg, le_neg] using this.not_le
@[simp, norm_cast] theorem cast_le [ordered_ring α] [nontrivial α] {m n : ℤ} :
(m : α) ≤ n ↔ m ≤ n :=
by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg]
theorem cast_strict_mono [ordered_ring α] [nontrivial α] : strict_mono (coe : ℤ → α) :=
strict_mono_of_le_iff_le $ λ m n, cast_le.symm
@[simp, norm_cast] theorem cast_lt [ordered_ring α] [nontrivial α] {m n : ℤ} :
(m : α) < n ↔ m < n :=
cast_strict_mono.lt_iff_lt
@[simp] theorem cast_nonpos [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 :=
by rw [← cast_zero, cast_le]
@[simp] theorem cast_pos [ordered_ring α] [nontrivial α] {n : ℤ} : (0 : α) < n ↔ 0 < n :=
by rw [← cast_zero, cast_lt]
@[simp] theorem cast_lt_zero [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) < 0 ↔ n < 0 :=
by rw [← cast_zero, cast_lt]
section linear_ordered_ring
variables [linear_ordered_ring α] {a b : ℤ} (n : ℤ)
@[simp, norm_cast] theorem cast_min : (↑(min a b) : α) = min a b :=
monotone.map_min cast_mono
@[simp, norm_cast] theorem cast_max : (↑(max a b) : α) = max a b :=
monotone.map_max cast_mono
@[simp, norm_cast] theorem cast_abs : ((|a| : ℤ) : α) = |a| :=
by simp [abs_eq_max_neg]
lemma cast_one_le_of_pos (h : 0 < a) : (1 : α) ≤ a :=
by exact_mod_cast int.add_one_le_of_lt h
lemma cast_le_neg_one_of_neg (h : a < 0) : (a : α) ≤ -1 :=
begin
rw [← int.cast_one, ← int.cast_neg, cast_le],
exact int.le_sub_one_of_lt h,
end
variables (α) {n}
lemma cast_le_neg_one_or_one_le_cast_of_ne_zero (hn : n ≠ 0) : (n : α) ≤ -1 ∨ 1 ≤ (n : α) :=
hn.lt_or_lt.imp cast_le_neg_one_of_neg cast_one_le_of_pos
variables {α} (n)
lemma nneg_mul_add_sq_of_abs_le_one {x : α} (hx : |x| ≤ 1) :
(0 : α) ≤ n * x + n * n :=
begin
have hnx : 0 < n → 0 ≤ x + n := λ hn, by
{ convert add_le_add (neg_le_of_abs_le hx) (cast_one_le_of_pos hn),
rw add_left_neg, },
have hnx' : n < 0 → x + n ≤ 0 := λ hn, by
{ convert add_le_add (le_of_abs_le hx) (cast_le_neg_one_of_neg hn),
rw add_right_neg, },
rw [← mul_add, mul_nonneg_iff],
rcases lt_trichotomy n 0 with h | rfl | h,
{ exact or.inr ⟨by exact_mod_cast h.le, hnx' h⟩, },
{ simp [le_total 0 x], },
{ exact or.inl ⟨by exact_mod_cast h.le, hnx h⟩, },
end
lemma cast_nat_abs : (n.nat_abs : α) = |n| :=
begin
cases n,
{ simp, },
{ simp only [int.nat_abs, int.cast_neg_succ_of_nat, abs_neg, ← nat.cast_succ, nat.abs_cast], },
end
end linear_ordered_ring
lemma coe_int_dvd [comm_ring α] (m n : ℤ) (h : m ∣ n) :
(m : α) ∣ (n : α) :=
ring_hom.map_dvd (int.cast_ring_hom α) h
end cast
end int
open int
namespace add_monoid_hom
variables {A : Type*}
/-- Two additive monoid homomorphisms `f`, `g` from `ℤ` to an additive monoid are equal
if `f 1 = g 1`. -/
@[ext] theorem ext_int [add_monoid A] {f g : ℤ →+ A} (h1 : f 1 = g 1) : f = g :=
have f.comp (int.of_nat_hom : ℕ →+ ℤ) = g.comp (int.of_nat_hom : ℕ →+ ℤ) := ext_nat' _ _ h1,
have ∀ n : ℕ, f n = g n := ext_iff.1 this,
ext $ λ n, int.cases_on n this $ λ n, eq_on_neg _ _ (this $ n + 1)
variables [add_group_with_one A]
theorem eq_int_cast_hom (f : ℤ →+ A) (h1 : f 1 = 1) : f = int.cast_add_hom A :=
ext_int $ by simp [h1]
end add_monoid_hom
lemma eq_int_cast' [add_group_with_one α] [add_monoid_hom_class F ℤ α] (f : F) (h₁ : f 1 = 1) :
∀ n : ℤ, f n = n :=
add_monoid_hom.ext_iff.1 $ (f : ℤ →+ α).eq_int_cast_hom h₁
@[simp] lemma int.cast_add_hom_int : int.cast_add_hom ℤ = add_monoid_hom.id ℤ :=
((add_monoid_hom.id ℤ).eq_int_cast_hom rfl).symm
namespace monoid_hom
variables {M : Type*} [monoid M]
open multiplicative
@[ext] theorem ext_mint {f g : multiplicative ℤ →* M} (h1 : f (of_add 1) = g (of_add 1)) : f = g :=
monoid_hom.ext $ add_monoid_hom.ext_iff.mp $
@add_monoid_hom.ext_int _ _ f.to_additive g.to_additive h1
/-- If two `monoid_hom`s agree on `-1` and the naturals then they are equal. -/
@[ext] theorem ext_int {f g : ℤ →* M}
(h_neg_one : f (-1) = g (-1))
(h_nat : f.comp int.of_nat_hom.to_monoid_hom = g.comp int.of_nat_hom.to_monoid_hom) :
f = g :=
begin
ext (x | x),
{ exact (monoid_hom.congr_fun h_nat x : _), },
{ rw [int.neg_succ_of_nat_eq, ← neg_one_mul, f.map_mul, g.map_mul],
congr' 1,
exact_mod_cast (monoid_hom.congr_fun h_nat (x + 1) : _), }
end
end monoid_hom
namespace monoid_with_zero_hom
variables {M : Type*} [monoid_with_zero M]
/-- If two `monoid_with_zero_hom`s agree on `-1` and the naturals then they are equal. -/
@[ext] lemma ext_int {f g : ℤ →*₀ M} (h_neg_one : f (-1) = g (-1))
(h_nat : f.comp int.of_nat_hom.to_monoid_with_zero_hom =
g.comp int.of_nat_hom.to_monoid_with_zero_hom) :
f = g :=
to_monoid_hom_injective $ monoid_hom.ext_int h_neg_one $ monoid_hom.ext (congr_fun h_nat : _)
end monoid_with_zero_hom
/-- If two `monoid_with_zero_hom`s agree on `-1` and the _positive_ naturals then they are equal. -/
lemma ext_int' [monoid_with_zero α] [monoid_with_zero_hom_class F ℤ α] {f g : F}
(h_neg_one : f (-1) = g (-1)) (h_pos : ∀ n : ℕ, 0 < n → f n = g n) : f = g :=
fun_like.ext _ _ $ λ n, by { have := fun_like.congr_fun (@monoid_with_zero_hom.ext_int _ _
(f : ℤ →*₀ α) (g : ℤ →*₀ α) h_neg_one $ monoid_with_zero_hom.ext_nat h_pos) n, exact this }
section non_assoc_ring
variables [non_assoc_ring α] [non_assoc_ring β]
@[simp] lemma eq_int_cast [ring_hom_class F ℤ α] (f : F) (n : ℤ) : f n = n :=
eq_int_cast' f (map_one _) n
@[simp] lemma map_int_cast [ring_hom_class F α β] (f : F) (n : ℤ) : f n = n :=
eq_int_cast ((f : α →+* β).comp (int.cast_ring_hom α)) n
namespace ring_hom
lemma eq_int_cast' (f : ℤ →+* α) : f = int.cast_ring_hom α := ring_hom.ext $ eq_int_cast f
lemma ext_int {R : Type*} [non_assoc_semiring R] (f g : ℤ →+* R) : f = g :=
coe_add_monoid_hom_injective $ add_monoid_hom.ext_int $ f.map_one.trans g.map_one.symm
instance int.subsingleton_ring_hom {R : Type*} [non_assoc_semiring R] : subsingleton (ℤ →+* R) :=
⟨ring_hom.ext_int⟩
end ring_hom
end non_assoc_ring
@[simp, norm_cast] lemma int.cast_id (n : ℤ) : ↑n = n := (eq_int_cast (ring_hom.id ℤ) _).symm
@[simp] lemma int.cast_ring_hom_int : int.cast_ring_hom ℤ = ring_hom.id ℤ :=
(ring_hom.id ℤ).eq_int_cast'.symm
namespace pi
variables {π : ι → Type*} [Π i, has_int_cast (π i)]
instance : has_int_cast (Π i, π i) :=
by refine_struct { .. }; tactic.pi_instance_derive_field
lemma int_apply (n : ℤ) (i : ι) : (n : Π i, π i) i = n := rfl
@[simp] lemma coe_int (n : ℤ) : (n : Π i, π i) = λ _, n := rfl
end pi
lemma sum.elim_int_cast_int_cast {α β γ : Type*} [has_int_cast γ] (n : ℤ) :
sum.elim (n : α → γ) (n : β → γ) = n :=
@sum.elim_lam_const_lam_const α β γ n
namespace pi
variables {π : ι → Type*} [Π i, add_group_with_one (π i)]
instance : add_group_with_one (Π i, π i) :=
by refine_struct { .. }; tactic.pi_instance_derive_field
end pi
/-! ### Order dual -/
open order_dual
instance [h : has_int_cast α] : has_int_cast αᵒᵈ := h
instance [h : add_group_with_one α] : add_group_with_one αᵒᵈ := h
instance [h : add_comm_group_with_one α] : add_comm_group_with_one αᵒᵈ := h
@[simp] lemma to_dual_int_cast [has_int_cast α] (n : ℤ) : to_dual (n : α) = n := rfl
@[simp] lemma of_dual_int_cast [has_int_cast α] (n : ℤ) : (of_dual n : α) = n := rfl
/-! ### Lexicographic order -/
instance [h : has_int_cast α] : has_int_cast (lex α) := h
instance [h : add_group_with_one α] : add_group_with_one (lex α) := h
instance [h : add_comm_group_with_one α] : add_comm_group_with_one (lex α) := h
@[simp] lemma to_lex_int_cast [has_int_cast α] (n : ℤ) : to_lex (n : α) = n := rfl
@[simp] lemma of_lex_int_cast [has_int_cast α] (n : ℤ) : (of_lex n : α) = n := rfl
|
28964eb0d756481c456f4fc46d9b3612e94adf90 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/data/nat/bitwise.lean | 597fe0fdcbe6dff43bd3bff3cc87064e6b7dc79d | [
"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,720 | 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 tactic.linarith
/-!
# Bitwise operations on natural numbers
In the first half of this file, we provide theorems for reasoning about natural numbers from their
bitwise properties. In the second half of this file, we show properties of the bitwise operations
`lor`, `land` and `lxor`, which are defined in core.
## Main results
* `eq_of_test_bit_eq`: two natural numbers are equal if they have equal bits at every position.
* `exists_most_significant_bit`: if `n ≠ 0`, then there is some position `i` that contains the most
significant `1`-bit of `n`.
* `lt_of_test_bit`: if `n` and `m` are numbers and `i` is a position such that the `i`-th bit of
of `n` is zero, the `i`-th bit of `m` is one, and all more significant bits are equal, then
`n < m`.
## Future work
There is another way to express bitwise properties of natural number: `digits 2`. The two ways
should be connected.
## Keywords
bitwise, and, or, xor
-/
namespace nat
@[simp] lemma bit_ff : bit ff = bit0 := rfl
@[simp] lemma bit_tt : bit tt = bit1 := rfl
lemma zero_of_test_bit_eq_ff {n : ℕ} (h : ∀ i, test_bit n i = ff) : n = 0 :=
begin
induction n using nat.binary_rec with b n hn,
{ refl },
{ have : b = ff := by simpa using h 0,
rw [this, bit_ff, bit0_val, hn (λ i, by rw [←h (i + 1), test_bit_succ]), mul_zero] }
end
@[simp] lemma zero_test_bit (i : ℕ) : test_bit 0 i = ff :=
by simp [test_bit]
/-- Bitwise extensionality: Two numbers agree if they agree at every bit position. -/
lemma eq_of_test_bit_eq {n m : ℕ} (h : ∀ i, test_bit n i = test_bit m i) : n = m :=
begin
induction n using nat.binary_rec with b n hn generalizing m,
{ simp only [zero_test_bit] at h,
exact (zero_of_test_bit_eq_ff (λ i, (h i).symm)).symm },
induction m using nat.binary_rec with b' m hm,
{ simp only [zero_test_bit] at h,
exact zero_of_test_bit_eq_ff h },
suffices h' : n = m,
{ rw [h', show b = b', by simpa using h 0] },
exact hn (λ i, by convert h (i + 1) using 1; rw test_bit_succ)
end
lemma exists_most_significant_bit {n : ℕ} (h : n ≠ 0) :
∃ i, test_bit n i = tt ∧ ∀ j, i < j → test_bit n j = ff :=
begin
induction n using nat.binary_rec with b n hn,
{ exact false.elim (h rfl) },
by_cases h' : n = 0,
{ subst h',
rw (show b = tt, by { revert h, cases b; simp }),
refine ⟨0, ⟨by rw [test_bit_zero], λ j hj, _⟩⟩,
obtain ⟨j', rfl⟩ := exists_eq_succ_of_ne_zero (ne_of_gt hj),
rw [test_bit_succ, zero_test_bit] },
{ obtain ⟨k, ⟨hk, hk'⟩⟩ := hn h',
refine ⟨k + 1, ⟨by rw [test_bit_succ, hk], λ j hj, _⟩⟩,
obtain ⟨j', rfl⟩ := exists_eq_succ_of_ne_zero (show j ≠ 0, by linarith),
exact (test_bit_succ _ _ _).trans (hk' _ (lt_of_succ_lt_succ hj)) }
end
lemma lt_of_test_bit {n m : ℕ} (i : ℕ) (hn : test_bit n i = ff) (hm : test_bit m i = tt)
(hnm : ∀ j, i < j → test_bit n j = test_bit m j) : n < m :=
begin
induction n using nat.binary_rec with b n hn' generalizing i m,
{ contrapose! hm,
rw le_zero_iff at hm,
simp [hm] },
induction m using nat.binary_rec with b' m hm' generalizing i,
{ exact false.elim (bool.ff_ne_tt ((zero_test_bit i).symm.trans hm)) },
by_cases hi : i = 0,
{ subst hi,
simp only [test_bit_zero] at hn hm,
have : n = m,
{ exact eq_of_test_bit_eq (λ i, by convert hnm (i + 1) dec_trivial using 1; rw test_bit_succ) },
rw [hn, hm, this, bit_ff, bit_tt, bit0_val, bit1_val],
exact lt_add_one _ },
{ obtain ⟨i', rfl⟩ := exists_eq_succ_of_ne_zero hi,
simp only [test_bit_succ] at hn hm,
have := hn' _ hn hm (λ j hj, by convert hnm j.succ (succ_lt_succ hj) using 1; rw test_bit_succ),
cases b; cases b';
simp only [bit_ff, bit_tt, bit0_val n, bit1_val n, bit0_val m, bit1_val m];
linarith }
end
/-- If `f` is a commutative operation on bools such that `f ff ff = ff`, then `bitwise f` is also
commutative. -/
lemma bitwise_comm {f : bool → bool → bool} (hf : ∀ b b', f b b' = f b' b)
(hf' : f ff ff = ff) (n m : ℕ) : bitwise f n m = bitwise f m n :=
suffices bitwise f = function.swap (bitwise f), by conv_lhs { rw this },
calc bitwise f = bitwise (function.swap f) : congr_arg _ $ funext $ λ _, funext $ hf _
... = function.swap (bitwise f) : bitwise_swap hf'
lemma lor_comm (n m : ℕ) : lor n m = lor m n := bitwise_comm bool.bor_comm rfl n m
lemma land_comm (n m : ℕ) : land n m = land m n := bitwise_comm bool.band_comm rfl n m
lemma lxor_comm (n m : ℕ) : lxor n m = lxor m n := bitwise_comm bool.bxor_comm rfl n m
@[simp] lemma zero_lxor (n : ℕ) : lxor 0 n = n := rfl
@[simp] lemma lxor_zero (n : ℕ) : lxor n 0 = n := lxor_comm 0 n ▸ rfl
@[simp] lemma zero_land (n : ℕ) : land 0 n = 0 := rfl
@[simp] lemma land_zero (n : ℕ) : land n 0 = 0 := land_comm 0 n ▸ rfl
@[simp] lemma zero_lor (n : ℕ) : lor 0 n = n := rfl
@[simp] lemma lor_zero (n : ℕ) : lor n 0 = n := lor_comm 0 n ▸ rfl
/-- Proving associativity of bitwise operations in general essentially boils down to a huge case
distinction, so it is shorter to use this tactic instead of proving it in the general case. -/
meta def bitwise_assoc_tac : tactic unit :=
`[induction n using nat.binary_rec with b n hn generalizing m k,
{ simp },
induction m using nat.binary_rec with b' m hm,
{ simp },
induction k using nat.binary_rec with b'' k hk;
simp [hn]]
lemma lxor_assoc (n m k : ℕ) : lxor (lxor n m) k = lxor n (lxor m k) := by bitwise_assoc_tac
lemma land_assoc (n m k : ℕ) : land (land n m) k = land n (land m k) := by bitwise_assoc_tac
lemma lor_assoc (n m k : ℕ) : lor (lor n m) k = lor n (lor m k) := by bitwise_assoc_tac
@[simp] lemma lxor_self (n : ℕ) : lxor n n = 0 :=
zero_of_test_bit_eq_ff $ λ i, by simp
lemma lxor_right_inj {n m m' : ℕ} (h : lxor n m = lxor n m') : m = m' :=
calc m = lxor n (lxor n m') : by simp [←lxor_assoc, ←h]
... = m' : by simp [←lxor_assoc]
lemma lxor_left_inj {n n' m : ℕ} (h : lxor n m = lxor n' m) : n = n' :=
by { rw [lxor_comm n m, lxor_comm n' m] at h, exact lxor_right_inj h }
lemma lxor_eq_zero {n m : ℕ} : lxor n m = 0 ↔ n = m :=
⟨by { rw ←lxor_self m, exact lxor_left_inj }, by { rintro rfl, exact lxor_self _ }⟩
lemma lxor_trichotomy {a b c : ℕ} (h : lxor a (lxor b c) ≠ 0) :
lxor b c < a ∨ lxor a c < b ∨ lxor a b < c :=
begin
set v := lxor a (lxor b c) with hv,
-- The xor of any two of `a`, `b`, `c` is the xor of `v` and the third.
have hab : lxor a b = lxor c v,
{ rw hv, conv_rhs { rw lxor_comm, simp [lxor_assoc] } },
have hac : lxor a c = lxor b v,
{ rw hv,
conv_rhs { congr, skip, rw lxor_comm },
rw [←lxor_assoc, ←lxor_assoc, lxor_self, zero_lxor, lxor_comm] },
have hbc : lxor b c = lxor a v,
{ simp [hv, ←lxor_assoc] },
-- If `i` is the position of the most significant bit of `v`, then at least one of `a`, `b`, `c`
-- has a one bit at position `i`.
obtain ⟨i, ⟨hi, hi'⟩⟩ := exists_most_significant_bit h,
have : test_bit a i = tt ∨ test_bit b i = tt ∨ test_bit c i = tt,
{ contrapose! hi,
simp only [eq_ff_eq_not_eq_tt, ne, test_bit_lxor] at ⊢ hi,
rw [hi.1, hi.2.1, hi.2.2, bxor_ff, bxor_ff] },
-- If, say, `a` has a one bit at position `i`, then `a xor v` has a zero bit at position `i`, but
-- the same bits as `a` in positions greater than `j`, so `a xor v < a`.
rcases this with h|h|h;
[{ left, rw hbc }, { right, left, rw hac }, { right, right, rw hab }];
exact lt_of_test_bit i (by simp [h, hi]) h (λ j hj, by simp [hi' _ hj])
end
end nat
|
17685d1a3048945ba4ddc80d2357dc2ad74762c4 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/topology/sheaves/presheaf_of_functions.lean | c78f236fce4c4ceeee2706e6de07c46fa0182d2f | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 3,665 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import topology.sheaves.presheaf
import topology.category.TopCommRing
import category_theory.yoneda
import ring_theory.subring
import topology.algebra.continuous_functions
universes v u
open category_theory
open topological_space
open opposite
namespace Top
variables (X : Top.{v})
/-- The presheaf of continuous functions on `X` with values in fixed target topological space `T`. -/
def presheaf_to_Top (T : Top.{v}) : X.presheaf (Type v) :=
(opens.to_Top X).op ⋙ (yoneda.obj T)
/-- The (bundled) commutative ring of continuous functions from a topological space
to a topological commutative ring, with pointwise multiplication. -/
-- TODO upgrade the result to TopCommRing?
def continuous_functions (X : Top.{v}ᵒᵖ) (R : TopCommRing.{v}) : CommRing.{v} :=
{ α := unop X ⟶ (forget₂ TopCommRing Top).obj R,
str := _root_.continuous_comm_ring }
namespace continuous_functions
@[simp] lemma one (X : Top.{v}ᵒᵖ) (R : TopCommRing.{v}) (x) :
(monoid.one : continuous_functions X R).val x = 1 := rfl
@[simp] lemma zero (X : Top.{v}ᵒᵖ) (R : TopCommRing.{v}) (x) :
(comm_ring.zero : continuous_functions X R).val x = 0 := rfl
@[simp] lemma add (X : Top.{v}ᵒᵖ) (R : TopCommRing.{v}) (f g : continuous_functions X R) (x) :
(comm_ring.add f g).val x = f.1 x + g.1 x := rfl
@[simp] lemma mul (X : Top.{v}ᵒᵖ) (R : TopCommRing.{v}) (f g : continuous_functions X R) (x) :
(ring.mul f g).val x = f.1 x * g.1 x := rfl
/-- Pulling back functions into a topological ring along a continuous map is a ring homomorphism. -/
def pullback {X Y : Topᵒᵖ} (f : X ⟶ Y) (R : TopCommRing) :
continuous_functions X R ⟶ continuous_functions Y R :=
{ to_fun := λ g, f.unop ≫ g,
map_one' := rfl,
map_zero' := rfl,
map_add' := by tidy,
map_mul' := by tidy }
local attribute [ext] subtype.eq
/-- A homomorphism of topological rings can be postcomposed with functions from a source space `X`;
this is a ring homomorphism (with respect to the pointwise ring operations on functions). -/
def map (X : Topᵒᵖ) {R S : TopCommRing} (φ : R ⟶ S) :
continuous_functions X R ⟶ continuous_functions X S :=
{ to_fun := λ g, g ≫ ((forget₂ TopCommRing Top).map φ),
map_one' := by ext; exact φ.1.map_one,
map_zero' := by ext; exact φ.1.map_zero,
map_add' := by intros; ext; apply φ.1.map_add,
map_mul' := by intros; ext; apply φ.1.map_mul }
end continuous_functions
/-- An upgraded version of the Yoneda embedding, observing that the continuous maps
from `X : Top` to `R : TopCommRing` form a commutative ring, functorial in both `X` and `R`. -/
def CommRing_yoneda : TopCommRing.{u} ⥤ (Top.{u}ᵒᵖ ⥤ CommRing.{u}) :=
{ obj := λ R,
{ obj := λ X, continuous_functions X R,
map := λ X Y f, continuous_functions.pullback f R },
map := λ R S φ,
{ app := λ X, continuous_functions.map X φ } }
/-- The presheaf (of commutative rings), consisting of functions on an open set `U ⊆ X` with
values in some topological commutative ring `T`. -/
def presheaf_to_TopCommRing (T : TopCommRing.{v}) :
X.presheaf CommRing.{v} :=
(opens.to_Top X).op ⋙ (CommRing_yoneda.obj T)
/-- The presheaf (of commutative rings) of real valued functions. -/
noncomputable def presheaf_ℝ (Y : Top) : Y.presheaf CommRing :=
presheaf_to_TopCommRing Y (TopCommRing.of ℝ)
/-- The presheaf (of commutative rings) of complex valued functions. -/
noncomputable def presheaf_ℂ (Y : Top) : Y.presheaf CommRing :=
presheaf_to_TopCommRing Y (TopCommRing.of ℂ)
end Top
|
96972a4d603ade598b40038ac84f6d007b973938 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Lean/Compiler/IR/Borrow.lean | c2e5ed5b143a6f62bd79343b58c80ac0967c1c7e | [
"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 | 11,041 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Data.Nat
import Init.Lean.Compiler.ExportAttr
import Init.Lean.Compiler.IR.CompilerM
import Init.Lean.Compiler.IR.NormIds
namespace Lean
namespace IR
namespace Borrow
namespace OwnedSet
abbrev Key := FunId × Index
def beq : Key → Key → Bool
| (f₁, x₁), (f₂, x₂) => f₁ == f₂ && x₁ == x₂
instance : HasBeq Key := ⟨beq⟩
def getHash : Key → USize
| (f, x) => mixHash (hash f) (hash x)
instance : Hashable Key := ⟨getHash⟩
end OwnedSet
abbrev OwnedSet := HashMap OwnedSet.Key Unit
def OwnedSet.insert (s : OwnedSet) (k : OwnedSet.Key) : OwnedSet := s.insert k ()
def OwnedSet.contains (s : OwnedSet) (k : OwnedSet.Key) : Bool := s.contains k
/- We perform borrow inference in a block of mutually recursive functions.
Join points are viewed as local functions, and are identified using
their local id + the name of the surrounding function.
We keep a mapping from function and joint points to parameters (`Array Param`).
Recall that `Param` contains the field `borrow`. -/
namespace ParamMap
inductive Key
| decl (name : FunId)
| jp (name : FunId) (jpid : JoinPointId)
def beq : Key → Key → Bool
| Key.decl n₁, Key.decl n₂ => n₁ == n₂
| Key.jp n₁ id₁, Key.jp n₂ id₂ => n₁ == n₂ && id₁ == id₂
| _, _ => false
instance : HasBeq Key := ⟨beq⟩
def getHash : Key → USize
| Key.decl n => hash n
| Key.jp n id => mixHash (hash n) (hash id)
instance : Hashable Key := ⟨getHash⟩
end ParamMap
abbrev ParamMap := HashMap ParamMap.Key (Array Param)
def ParamMap.fmt (map : ParamMap) : Format :=
let fmts := map.fold (fun fmt k ps =>
let k := match k with
| ParamMap.Key.decl n => format n
| ParamMap.Key.jp n id => format n ++ ":" ++ format id;
fmt ++ Format.line ++ k ++ " -> " ++ formatParams ps)
Format.nil;
"{" ++ (Format.nest 1 fmts) ++ "}"
instance : HasFormat ParamMap := ⟨ParamMap.fmt⟩
instance : HasToString ParamMap := ⟨fun m => Format.pretty (format m)⟩
namespace InitParamMap
/- Mark parameters that take a reference as borrow -/
def initBorrow (ps : Array Param) : Array Param :=
ps.map $ fun p => { borrow := p.ty.isObj, .. p }
/- We do perform borrow inference for constants marked as `export`.
Reason: we current write wrappers in C++ for using exported functions.
These wrappers use smart pointers such as `object_ref`.
When writing a new wrapper we need to know whether an argument is a borrow
inference or not.
We can revise this decision when we implement code for generating
the wrappers automatically. -/
def initBorrowIfNotExported (exported : Bool) (ps : Array Param) : Array Param :=
if exported then ps else initBorrow ps
partial def visitFnBody (fnid : FunId) : FnBody → StateM ParamMap Unit
| FnBody.jdecl j xs v b => do
modify $ fun m => m.insert (ParamMap.Key.jp fnid j) (initBorrow xs);
visitFnBody v;
visitFnBody b
| FnBody.case _ _ _ alts => alts.forM $ fun alt => visitFnBody alt.body
| e =>
unless (e.isTerminal) $ do
let (instr, b) := e.split;
visitFnBody b
def visitDecls (env : Environment) (decls : Array Decl) : StateM ParamMap Unit :=
decls.forM $ fun decl => match decl with
| Decl.fdecl f xs _ b => do
let exported := isExport env f;
modify $ fun m => m.insert (ParamMap.Key.decl f) (initBorrowIfNotExported exported xs);
visitFnBody f b
| _ => pure ()
end InitParamMap
def mkInitParamMap (env : Environment) (decls : Array Decl) : ParamMap :=
(InitParamMap.visitDecls env decls *> get).run' {}
/- Apply the inferred borrow annotations stored at `ParamMap` to a block of mutually
recursive functions. -/
namespace ApplyParamMap
partial def visitFnBody (fn : FunId) (paramMap : ParamMap) : FnBody → FnBody
| FnBody.jdecl j xs v b =>
let v := visitFnBody v;
let b := visitFnBody b;
match paramMap.find? (ParamMap.Key.jp fn j) with
| some ys => FnBody.jdecl j ys v b
| none => unreachable!
| FnBody.case tid x xType alts =>
FnBody.case tid x xType $ alts.map $ fun alt => alt.modifyBody visitFnBody
| e =>
if e.isTerminal then e
else
let (instr, b) := e.split;
let b := visitFnBody b;
instr.setBody b
def visitDecls (decls : Array Decl) (paramMap : ParamMap) : Array Decl :=
decls.map $ fun decl => match decl with
| Decl.fdecl f xs ty b =>
let b := visitFnBody f paramMap b;
match paramMap.find? (ParamMap.Key.decl f) with
| some xs => Decl.fdecl f xs ty b
| none => unreachable!
| other => other
end ApplyParamMap
def applyParamMap (decls : Array Decl) (map : ParamMap) : Array Decl :=
-- dbgTrace ("applyParamMap " ++ toString map) $ fun _ =>
ApplyParamMap.visitDecls decls map
structure BorrowInfCtx :=
(env : Environment)
(currFn : FunId := arbitrary _) -- Function being analyzed.
(paramSet : IndexSet := {}) -- Set of all function parameters in scope. This is used to implement the heuristic at `ownArgsUsingParams`
structure BorrowInfState :=
/- Set of variables that must be `owned`. -/
(owned : OwnedSet := {})
(modified : Bool := false)
(paramMap : ParamMap)
abbrev M := ReaderT BorrowInfCtx (StateM BorrowInfState)
def getCurrFn : M FunId := do
ctx ← read;
pure ctx.currFn
def markModified : M Unit :=
modify $ fun s => { modified := true, .. s }
def ownVar (x : VarId) : M Unit := do
-- dbgTrace ("ownVar " ++ toString x) $ fun _ =>
currFn ← getCurrFn;
modify $ fun s =>
if s.owned.contains (currFn, x.idx) then s
else { owned := s.owned.insert (currFn, x.idx), modified := true, .. s }
def ownArg (x : Arg) : M Unit :=
match x with
| Arg.var x => ownVar x
| _ => pure ()
def ownArgs (xs : Array Arg) : M Unit :=
xs.forM ownArg
def isOwned (x : VarId) : M Bool := do
currFn ← getCurrFn;
s ← get;
pure $ s.owned.contains (currFn, x.idx)
/- Updates `map[k]` using the current set of `owned` variables. -/
def updateParamMap (k : ParamMap.Key) : M Unit := do
currFn ← getCurrFn;
s ← get;
match s.paramMap.find? k with
| some ps => do
ps ← ps.mapM $ fun (p : Param) =>
if !p.borrow then pure p
else condM (isOwned p.x)
(do markModified; pure { borrow := false, .. p })
(pure p);
modify $ fun s => { paramMap := s.paramMap.insert k ps, .. s }
| none => pure ()
def getParamInfo (k : ParamMap.Key) : M (Array Param) := do
s ← get;
match s.paramMap.find? k with
| some ps => pure ps
| none =>
match k with
| ParamMap.Key.decl fn => do
ctx ← read;
match findEnvDecl ctx.env fn with
| some decl => pure decl.params
| none => unreachable!
| _ => unreachable!
/- For each ps[i], if ps[i] is owned, then mark xs[i] as owned. -/
def ownArgsUsingParams (xs : Array Arg) (ps : Array Param) : M Unit :=
xs.size.forM $ fun i => do
let x := xs.get! i;
let p := ps.get! i;
unless p.borrow $ ownArg x
/- For each xs[i], if xs[i] is owned, then mark ps[i] as owned.
We use this action to preserve tail calls. That is, if we have
a tail call `f xs`, if the i-th parameter is borrowed, but `xs[i]` is owned
we would have to insert a `dec xs[i]` after `f xs` and consequently
"break" the tail call. -/
def ownParamsUsingArgs (xs : Array Arg) (ps : Array Param) : M Unit :=
xs.size.forM $ fun i => do
let x := xs.get! i;
let p := ps.get! i;
match x with
| Arg.var x => whenM (isOwned x) $ ownVar p.x
| _ => pure ()
/- Mark `xs[i]` as owned if it is one of the parameters `ps`.
We use this action to mark function parameters that are being "packed" inside constructors.
This is a heuristic, and is not related with the effectiveness of the reset/reuse optimization.
It is useful for code such as
```
def f (x y : obj) :=
let z := ctor_1 x y;
ret z
``` -/
def ownArgsIfParam (xs : Array Arg) : M Unit := do
ctx ← read;
xs.forM $ fun x =>
match x with
| Arg.var x => when (ctx.paramSet.contains x.idx) $ ownVar x
| _ => pure ()
def collectExpr (z : VarId) : Expr → M Unit
| Expr.reset _ x => ownVar z *> ownVar x
| Expr.reuse x _ _ ys => ownVar z *> ownVar x *> ownArgsIfParam ys
| Expr.ctor _ xs => ownVar z *> ownArgsIfParam xs
| Expr.proj _ x => do
whenM (isOwned x) $ ownVar z;
whenM (isOwned z) $ ownVar x
| Expr.fap g xs => do ps ← getParamInfo (ParamMap.Key.decl g);
-- dbgTrace ("collectExpr: " ++ toString g ++ " " ++ toString (formatParams ps)) $ fun _ =>
ownVar z *> ownArgsUsingParams xs ps
| Expr.ap x ys => ownVar z *> ownVar x *> ownArgs ys
| Expr.pap _ xs => ownVar z *> ownArgs xs
| other => pure ()
def preserveTailCall (x : VarId) (v : Expr) (b : FnBody) : M Unit := do
ctx ← read;
match v, b with
| (Expr.fap g ys), (FnBody.ret (Arg.var z)) =>
when (ctx.currFn == g && x == z) $ do
-- dbgTrace ("preserveTailCall " ++ toString b) $ fun _ => do
ps ← getParamInfo (ParamMap.Key.decl g);
ownParamsUsingArgs ys ps
| _, _ => pure ()
def updateParamSet (ctx : BorrowInfCtx) (ps : Array Param) : BorrowInfCtx :=
{ paramSet := ps.foldl (fun s p => s.insert p.x.idx) ctx.paramSet, .. ctx }
partial def collectFnBody : FnBody → M Unit
| FnBody.jdecl j ys v b => do
adaptReader (fun ctx => updateParamSet ctx ys) (collectFnBody v);
ctx ← read;
updateParamMap (ParamMap.Key.jp ctx.currFn j);
collectFnBody b
| FnBody.vdecl x _ v b => collectFnBody b *> collectExpr x v *> preserveTailCall x v b
| FnBody.jmp j ys => do
ctx ← read;
ps ← getParamInfo (ParamMap.Key.jp ctx.currFn j);
ownArgsUsingParams ys ps; -- for making sure the join point can reuse
ownParamsUsingArgs ys ps -- for making sure the tail call is preserved
| FnBody.case _ _ _ alts => alts.forM $ fun alt => collectFnBody alt.body
| e => unless (e.isTerminal) $ collectFnBody e.body
partial def collectDecl : Decl → M Unit
| Decl.fdecl f ys _ b =>
adaptReader (fun ctx => let ctx := updateParamSet ctx ys; { currFn := f, .. ctx }) $ do
collectFnBody b;
updateParamMap (ParamMap.Key.decl f)
| _ => pure ()
@[specialize] partial def whileModifingAux (x : M Unit) : Unit → M Unit
| _ => do
modify $ fun s => { modified := false, .. s };
-- s ← get;
-- dbgTrace (toString s.map) $ fun _ => do
x;
s ← get;
if s.modified then whileModifingAux ()
else pure ()
/- Keep executing `x` until it reaches a fixpoint -/
@[inline] def whileModifing (x : M Unit) : M Unit :=
whileModifingAux x ()
def collectDecls (decls : Array Decl) : M ParamMap := do
whileModifing (decls.forM collectDecl);
s ← get;
pure s.paramMap
def infer (env : Environment) (decls : Array Decl) : ParamMap :=
(collectDecls decls { env := env }).run' { paramMap := mkInitParamMap env decls }
end Borrow
def inferBorrow (decls : Array Decl) : CompilerM (Array Decl) := do
env ← getEnv;
let paramMap := Borrow.infer env decls;
pure (Borrow.applyParamMap decls paramMap)
end IR
end Lean
|
95897d9efe50afb08999fbd314b0bdc4c3e7de92 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/logic/is_empty.lean | 2c4bbfd668e2e60d4560379efb304c2577009b7b | [
"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 | 6,024 | lean | /-
Copyright (c) 2021 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import logic.function.basic
import tactic.protected
/-!
# Types that are empty
In this file we define a typeclass `is_empty`, which expresses that a type has no elements.
## Main declaration
* `is_empty`: a typeclass that expresses that a type is empty.
-/
variables {α β γ : Sort*}
/-- `is_empty α` expresses that `α` is empty. -/
@[protect_proj]
class is_empty (α : Sort*) : Prop :=
(false : α → false)
instance : is_empty empty := ⟨empty.elim⟩
instance : is_empty pempty := ⟨pempty.elim⟩
instance : is_empty false := ⟨id⟩
instance : is_empty (fin 0) := ⟨λ n, nat.not_lt_zero n.1 n.2⟩
protected lemma function.is_empty [is_empty β] (f : α → β) : is_empty α :=
⟨λ x, is_empty.false (f x)⟩
instance {p : α → Sort*} [h : nonempty α] [∀ x, is_empty (p x)] : is_empty (Π x, p x) :=
h.elim $ λ x, function.is_empty $ function.eval x
instance pprod.is_empty_left [is_empty α] : is_empty (pprod α β) :=
function.is_empty pprod.fst
instance pprod.is_empty_right [is_empty β] : is_empty (pprod α β) :=
function.is_empty pprod.snd
instance prod.is_empty_left {α β} [is_empty α] : is_empty (α × β) :=
function.is_empty prod.fst
instance prod.is_empty_right {α β} [is_empty β] : is_empty (α × β) :=
function.is_empty prod.snd
instance [is_empty α] [is_empty β] : is_empty (psum α β) :=
⟨λ x, psum.rec is_empty.false is_empty.false x⟩
instance {α β} [is_empty α] [is_empty β] : is_empty (α ⊕ β) :=
⟨λ x, sum.rec is_empty.false is_empty.false x⟩
/-- subtypes of an empty type are empty -/
instance [is_empty α] (p : α → Prop) : is_empty (subtype p) :=
⟨λ x, is_empty.false x.1⟩
/-- subtypes by an all-false predicate are false. -/
lemma subtype.is_empty_of_false {p : α → Prop} (hp : ∀ a, ¬(p a)) : is_empty (subtype p) :=
⟨λ x, hp _ x.2⟩
/-- subtypes by false are false. -/
instance subtype.is_empty_false : is_empty {a : α // false} :=
subtype.is_empty_of_false (λ a, id)
instance sigma.is_empty_left {α} [is_empty α] {E : α → Type*} : is_empty (sigma E) :=
function.is_empty sigma.fst
/- Test that `pi.is_empty` finds this instance. -/
example [h : nonempty α] [is_empty β] : is_empty (α → β) := by apply_instance
/-- Eliminate out of a type that `is_empty` (without using projection notation). -/
@[elab_as_eliminator]
def is_empty_elim [is_empty α] {p : α → Sort*} (a : α) : p a :=
(is_empty.false a).elim
lemma is_empty_iff : is_empty α ↔ α → false :=
⟨@is_empty.false α, is_empty.mk⟩
namespace is_empty
open function
/-- Eliminate out of a type that `is_empty` (using projection notation). -/
protected def elim (h : is_empty α) {p : α → Sort*} (a : α) : p a :=
is_empty_elim a
/-- Non-dependent version of `is_empty.elim`. Helpful if the elaborator cannot elaborate `h.elim a`
correctly. -/
protected def elim' {β : Sort*} (h : is_empty α) (a : α) : β :=
h.elim a
protected lemma prop_iff {p : Prop} : is_empty p ↔ ¬ p :=
is_empty_iff
variables [is_empty α]
@[simp] lemma forall_iff {p : α → Prop} : (∀ a, p a) ↔ true :=
iff_true_intro is_empty_elim
@[simp] lemma exists_iff {p : α → Prop} : (∃ a, p a) ↔ false :=
iff_false_intro $ λ ⟨x, hx⟩, is_empty.false x
@[priority 100] -- see Note [lower instance priority]
instance : subsingleton α := ⟨is_empty_elim⟩
end is_empty
@[simp] lemma not_nonempty_iff : ¬ nonempty α ↔ is_empty α :=
⟨λ h, ⟨λ x, h ⟨x⟩⟩, λ h1 h2, h2.elim h1.elim⟩
@[simp] lemma not_is_empty_iff : ¬ is_empty α ↔ nonempty α :=
not_iff_comm.mp not_nonempty_iff
@[simp] lemma is_empty_Prop {p : Prop} : is_empty p ↔ ¬p :=
by simp only [← not_nonempty_iff, nonempty_Prop]
@[simp] lemma is_empty_pi {π : α → Sort*} : is_empty (Π a, π a) ↔ ∃ a, is_empty (π a) :=
by simp only [← not_nonempty_iff, classical.nonempty_pi, not_forall]
@[simp] lemma is_empty_sigma {α} {E : α → Type*} :
is_empty (sigma E) ↔ ∀ a, is_empty (E a) :=
by simp only [← not_nonempty_iff, nonempty_sigma, not_exists]
@[simp] lemma is_empty_psigma {α} {E : α → Sort*} :
is_empty (psigma E) ↔ ∀ a, is_empty (E a) :=
by simp only [← not_nonempty_iff, nonempty_psigma, not_exists]
@[simp] lemma is_empty_subtype (p : α → Prop) : is_empty (subtype p) ↔ ∀ x, ¬p x :=
by simp only [← not_nonempty_iff, nonempty_subtype, not_exists]
@[simp] lemma is_empty_prod {α β : Type*} : is_empty (α × β) ↔ is_empty α ∨ is_empty β :=
by simp only [← not_nonempty_iff, nonempty_prod, not_and_distrib]
@[simp] lemma is_empty_pprod : is_empty (pprod α β) ↔ is_empty α ∨ is_empty β :=
by simp only [← not_nonempty_iff, nonempty_pprod, not_and_distrib]
@[simp] lemma is_empty_sum {α β} : is_empty (α ⊕ β) ↔ is_empty α ∧ is_empty β :=
by simp only [← not_nonempty_iff, nonempty_sum, not_or_distrib]
@[simp] lemma is_empty_psum {α β} : is_empty (psum α β) ↔ is_empty α ∧ is_empty β :=
by simp only [← not_nonempty_iff, nonempty_psum, not_or_distrib]
@[simp] lemma is_empty_ulift {α} : is_empty (ulift α) ↔ is_empty α :=
by simp only [← not_nonempty_iff, nonempty_ulift]
@[simp] lemma is_empty_plift {α} : is_empty (plift α) ↔ is_empty α :=
by simp only [← not_nonempty_iff, nonempty_plift]
lemma well_founded_of_empty {α} [is_empty α] (r : α → α → Prop) : well_founded r :=
⟨is_empty_elim⟩
variables (α)
lemma is_empty_or_nonempty : is_empty α ∨ nonempty α :=
(em $ is_empty α).elim or.inl $ or.inr ∘ not_is_empty_iff.mp
@[simp] lemma not_is_empty_of_nonempty [h : nonempty α] : ¬ is_empty α :=
not_is_empty_iff.mpr h
variable {α}
lemma function.extend_of_empty [is_empty α] (f : α → β) (g : α → γ) (h : β → γ) :
function.extend f g h = h :=
funext $ λ x, function.extend_apply' _ _ _ $ λ ⟨a, h⟩, is_empty_elim a
|
01881904878554fbc5217853a6389dd7557d4e28 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/algebra/ordered_field.lean | 61c5e9938a4aade11b426fa0579a9111b84ba479 | [
"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 | 8,999 | 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 algebra.ordered_ring algebra.field
section linear_ordered_field
variables {α : Type*} [linear_ordered_field α] {a b c d : α}
def div_pos := @div_pos_of_pos_of_pos
lemma inv_pos {a : α} : 0 < a → 0 < a⁻¹ :=
by rw [inv_eq_one_div]; exact div_pos zero_lt_one
lemma inv_lt_zero {a : α} : a < 0 → a⁻¹ < 0 :=
by rw [inv_eq_one_div]; exact div_neg_of_pos_of_neg zero_lt_one
lemma one_le_div_iff_le (hb : 0 < b) : 1 ≤ a / b ↔ b ≤ a :=
⟨le_of_one_le_div a hb, one_le_div_of_le a hb⟩
lemma one_lt_div_iff_lt (hb : 0 < b) : 1 < a / b ↔ b < a :=
⟨lt_of_one_lt_div a hb, one_lt_div_of_lt a hb⟩
lemma div_le_one_iff_le (hb : 0 < b) : a / b ≤ 1 ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 (one_lt_div_iff_lt hb)
lemma div_lt_one_iff_lt (hb : 0 < b) : a / b < 1 ↔ a < b :=
lt_iff_lt_of_le_iff_le (one_le_div_iff_le hb)
lemma le_div_iff (hc : 0 < c) : a ≤ b / c ↔ a * c ≤ b :=
⟨mul_le_of_le_div hc, le_div_of_mul_le hc⟩
lemma le_div_iff' (hc : 0 < c) : a ≤ b / c ↔ c * a ≤ b :=
by rw [mul_comm, le_div_iff hc]
lemma div_le_iff (hb : 0 < b) : a / b ≤ c ↔ a ≤ c * b :=
⟨le_mul_of_div_le hb, by rw [mul_comm]; exact div_le_of_le_mul hb⟩
lemma div_le_iff' (hb : 0 < b) : a / b ≤ c ↔ a ≤ b * c :=
by rw [mul_comm, div_le_iff hb]
lemma lt_div_iff (hc : 0 < c) : a < b / c ↔ a * c < b :=
⟨mul_lt_of_lt_div hc, lt_div_of_mul_lt hc⟩
lemma lt_div_iff' (hc : 0 < c) : a < b / c ↔ c * a < b :=
by rw [mul_comm, lt_div_iff hc]
lemma div_le_iff_of_neg (hc : c < 0) : b / c ≤ a ↔ a * c ≤ b :=
⟨mul_le_of_div_le_of_neg hc, div_le_of_mul_le_of_neg hc⟩
lemma div_lt_iff (hc : 0 < c) : b / c < a ↔ b < a * c :=
lt_iff_lt_of_le_iff_le (le_div_iff hc)
lemma div_lt_iff' (hc : 0 < c) : b / c < a ↔ b < c * a :=
by rw [mul_comm, div_lt_iff hc]
lemma div_lt_iff_of_neg (hc : c < 0) : b / c < a ↔ a * c < b :=
⟨mul_lt_of_gt_div_of_neg hc, div_lt_of_mul_gt_of_neg hc⟩
lemma inv_le_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a :=
by rw [inv_eq_one_div, div_le_iff ha,
← div_eq_inv_mul, one_le_div_iff_le hb]
lemma inv_le (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a :=
by rw [← inv_le_inv hb (inv_pos ha), division_ring.inv_inv (ne_of_gt ha)]
lemma le_inv (ha : 0 < a) (hb : 0 < b) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ :=
by rw [← inv_le_inv (inv_pos hb) ha, division_ring.inv_inv (ne_of_gt hb)]
lemma one_div_le_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ 1 / b ↔ b ≤ a :=
by simpa [one_div_eq_inv] using inv_le_inv ha hb
lemma inv_lt_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b⁻¹ ↔ b < a :=
lt_iff_lt_of_le_iff_le (inv_le_inv hb ha)
lemma inv_lt (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b ↔ b⁻¹ < a :=
lt_iff_lt_of_le_iff_le (le_inv hb ha)
lemma lt_inv (ha : 0 < a) (hb : 0 < b) : a < b⁻¹ ↔ b < a⁻¹ :=
lt_iff_lt_of_le_iff_le (inv_le hb ha)
lemma one_div_lt_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a < 1 / b ↔ b < a :=
lt_iff_lt_of_le_iff_le (one_div_le_one_div hb ha)
def div_nonneg := @div_nonneg_of_nonneg_of_pos
lemma div_lt_div_right (hc : 0 < c) : a / c < b / c ↔ a < b :=
⟨lt_imp_lt_of_le_imp_le (λ h, div_le_div_of_le_of_pos h hc),
λ h, div_lt_div_of_lt_of_pos h hc⟩
lemma div_le_div_right (hc : 0 < c) : a / c ≤ b / c ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 (div_lt_div_right hc)
lemma div_lt_div_right_of_neg (hc : c < 0) : a / c < b / c ↔ b < a :=
⟨lt_imp_lt_of_le_imp_le (λ h, div_le_div_of_le_of_neg h hc),
λ h, div_lt_div_of_lt_of_neg h hc⟩
lemma div_le_div_right_of_neg (hc : c < 0) : a / c ≤ b / c ↔ b ≤ a :=
le_iff_le_iff_lt_iff_lt.2 (div_lt_div_right_of_neg hc)
lemma div_lt_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b < a / c ↔ c < b :=
(mul_lt_mul_left ha).trans (inv_lt_inv hb hc)
lemma div_le_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b ≤ a / c ↔ c ≤ b :=
le_iff_le_iff_lt_iff_lt.2 (div_lt_div_left ha hc hb)
lemma div_lt_div_iff (b0 : 0 < b) (d0 : 0 < d) :
a / b < c / d ↔ a * d < c * b :=
by rw [lt_div_iff d0, div_mul_eq_mul_div, div_lt_iff b0]
lemma div_lt_div (hac : a < c) (hbd : d ≤ b) (c0 : 0 ≤ c) (d0 : 0 < d) :
a / b < c / d :=
(div_lt_div_iff (lt_of_lt_of_le d0 hbd) d0).2 (mul_lt_mul hac hbd d0 c0)
lemma div_lt_div' (hac : a ≤ c) (hbd : d < b) (c0 : 0 < c) (d0 : 0 < d) :
a / b < c / d :=
(div_lt_div_iff (lt_trans d0 hbd) d0).2 (mul_lt_mul' hac hbd (le_of_lt d0) c0)
lemma half_pos {a : α} (h : 0 < a) : 0 < a / 2 := div_pos h two_pos
lemma one_half_pos : (0:α) < 1 / 2 := half_pos zero_lt_one
def half_lt_self := @div_two_lt_of_pos
lemma one_half_lt_one : (1 / 2 : α) < 1 := half_lt_self zero_lt_one
lemma ivl_translate : (λx, x + c) '' {r:α | a ≤ r ∧ r ≤ b } = {r:α | a + c ≤ r ∧ r ≤ b + c} :=
calc (λx, x + c) '' {r | a ≤ r ∧ r ≤ b } = (λx, x - c) ⁻¹' {r | a ≤ r ∧ r ≤ b } :
congr_fun (set.image_eq_preimage_of_inverse
(assume a, add_sub_cancel a c) (assume b, sub_add_cancel b c)) _
... = {r | a + c ≤ r ∧ r ≤ b + c} :
set.ext $ by simp [-sub_eq_add_neg, le_sub_iff_add_le, sub_le_iff_le_add]
lemma ivl_stretch (hc : 0 < c) : (λx, x * c) '' {r | a ≤ r ∧ r ≤ b } = {r | a * c ≤ r ∧ r ≤ b * c} :=
calc (λx, x * c) '' {r | a ≤ r ∧ r ≤ b } = (λx, x / c) ⁻¹' {r | a ≤ r ∧ r ≤ b } :
congr_fun (set.image_eq_preimage_of_inverse
(assume a, mul_div_cancel _ $ ne_of_gt hc) (assume b, div_mul_cancel _ $ ne_of_gt hc)) _
... = {r | a * c ≤ r ∧ r ≤ b * c} :
set.ext $ by simp [le_div_iff, div_le_iff, hc]
instance linear_ordered_field.to_densely_ordered : densely_ordered α :=
{ dense := assume a₁ a₂ h, ⟨(a₁ + a₂) / 2,
calc a₁ = (a₁ + a₁) / 2 : (add_self_div_two a₁).symm
... < (a₁ + a₂) / 2 : div_lt_div_of_lt_of_pos (add_lt_add_left h _) two_pos,
calc (a₁ + a₂) / 2 < (a₂ + a₂) / 2 : div_lt_div_of_lt_of_pos (add_lt_add_right h _) two_pos
... = a₂ : add_self_div_two a₂⟩ }
instance linear_ordered_field.to_no_top_order : no_top_order α :=
{ no_top := assume a, ⟨a + 1, lt_add_of_le_of_pos (le_refl a) zero_lt_one ⟩ }
instance linear_ordered_field.to_no_bot_order : no_bot_order α :=
{ no_bot := assume a, ⟨a + -1,
add_lt_of_le_of_neg (le_refl _) (neg_lt_of_neg_lt $ by simp [zero_lt_one]) ⟩ }
lemma inv_lt_one {a : α} (ha : 1 < a) : a⁻¹ < 1 :=
by rw [inv_eq_one_div]; exact div_lt_of_mul_lt_of_pos (lt_trans zero_lt_one ha) (by simp *)
lemma one_lt_inv (h₁ : 0 < a) (h₂ : a < 1) : 1 < a⁻¹ :=
by rw [inv_eq_one_div, lt_div_iff h₁]; simp [h₂]
lemma inv_le_one {a : α} (ha : 1 ≤ a) : a⁻¹ ≤ 1 :=
by rw [inv_eq_one_div]; exact div_le_of_le_mul (lt_of_lt_of_le zero_lt_one ha) (by simp *)
lemma one_le_inv {x : α} (hx0 : 0 < x) (hx : x ≤ 1) : 1 ≤ x⁻¹ :=
le_of_mul_le_mul_left (by simpa [mul_inv_cancel (ne.symm (ne_of_lt hx0))]) hx0
lemma mul_self_inj_of_nonneg {a b : α} (a0 : 0 ≤ a) (b0 : 0 ≤ b) : a * a = b * b ↔ a = b :=
(mul_self_eq_mul_self_iff a b).trans $ or_iff_left_of_imp $
λ h, by subst a; rw [le_antisymm (neg_nonneg.1 a0) b0, neg_zero]
lemma div_le_div_of_le_left {a b c : α} (ha : 0 ≤ a) (hc : 0 < c) (h : c ≤ b) :
a / b ≤ a / c :=
by haveI := classical.dec_eq α; exact
if ha0 : a = 0 then by simp [ha0]
else (div_le_div_left (lt_of_le_of_ne ha (ne.symm ha0)) (lt_of_lt_of_le hc h) hc).2 h
end linear_ordered_field
namespace nat
variables {α : Type*} [linear_ordered_field α]
lemma inv_pos_of_nat {n : ℕ} : 0 < ((n : α) + 1)⁻¹ :=
inv_pos $ add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one
lemma one_div_pos_of_nat {n : ℕ} : 0 < 1 / ((n : α) + 1) :=
by { rw one_div_eq_inv, exact inv_pos_of_nat }
end nat
section
variables {α : Type*} [discrete_linear_ordered_field α] (a b c : α)
lemma inv_pos' {a : α} : 0 < a⁻¹ ↔ 0 < a :=
⟨by rw [inv_eq_one_div]; exact pos_of_one_div_pos, inv_pos⟩
lemma inv_neg' {a : α} : a⁻¹ < 0 ↔ a < 0 :=
⟨by rw [inv_eq_one_div]; exact neg_of_one_div_neg, inv_lt_zero⟩
lemma inv_nonneg {a : α} : 0 ≤ a⁻¹ ↔ 0 ≤ a :=
le_iff_le_iff_lt_iff_lt.2 inv_neg'
lemma inv_nonpos {a : α} : a⁻¹ ≤ 0 ↔ a ≤ 0 :=
le_iff_le_iff_lt_iff_lt.2 inv_pos'
lemma abs_inv : abs a⁻¹ = (abs a)⁻¹ :=
have h : abs (1 / a) = 1 / abs a,
begin rw [abs_div, abs_of_nonneg], exact zero_le_one end,
by simp [*] at *
lemma inv_neg : (-a)⁻¹ = -(a⁻¹) :=
if h : a = 0
then by simp [h, inv_zero]
else by rwa [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div]
lemma inv_le_inv_of_le {a b : α} (hb : 0 < b) (h : b ≤ a) : a⁻¹ ≤ b⁻¹ :=
begin
rw [inv_eq_one_div, inv_eq_one_div],
exact one_div_le_one_div_of_le hb h
end
lemma div_nonneg' {a b : α} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a / b :=
(lt_or_eq_of_le hb).elim (div_nonneg ha) (λ h, by simp [h.symm])
end
|
1495526d291abb09c50adb073c18436732230b1d | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/slice_auto.lean | ede7af17392303adc69462e2d8afdc6734282c4b | [] | 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,340 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.category.default
import Mathlib.PostPort
namespace Mathlib
-- TODO someone might like to generalise this tactic to work with other associative structures.
namespace tactic
end tactic
namespace conv
namespace interactive
/--
`slice` is a conv tactic; if the current focus is a composition of several morphisms,
`slice a b` reassociates as needed, and zooms in on the `a`-th through `b`-th morphisms.
Thus if the current focus is `(a ≫ b) ≫ ((c ≫ d) ≫ e)`, then `slice 2 3` zooms to `b ≫ c`.
-/
end interactive
end conv
namespace tactic
namespace interactive
/--
`slice_lhs a b { tac }` zooms to the left hand side, uses associativity for categorical
composition as needed, zooms in on the `a`-th through `b`-th morphisms, and invokes `tac`.
-/
/--
`slice_rhs a b { tac }` zooms to the right hand side, uses associativity for categorical
composition as needed, zooms in on the `a`-th through `b`-th morphisms, and invokes `tac`.
-/
end interactive
end tactic
/--
`slice_lhs a b { tac }` zooms to the left hand side, uses associativity for categorical
end Mathlib |
c44f433363fef3fe2f5ab0250547c340357ea875 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/lean/run/matchEqs.lean | f51dfa040315c47e8504876bc4844704b19cbb35 | [
"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 | 610 | lean | import Lean
syntax (name := test) "test%" ident : command
open Lean.Elab
open Lean.Elab.Command
@[commandElab test] def elabTest : CommandElab := fun stx => do
let id ← resolveGlobalConstNoOverloadWithInfo stx[1]
liftTermElabM do
IO.println (repr (← Lean.Meta.Match.getEquationsFor id))
return ()
def f (x : List Nat) : Nat :=
match x with
| [] => 1
| [a] => 2
| _ => 3
test% f.match_1
#check @f.match_1
#check @f.match_1.splitter
theorem ex (x : List Nat) : f x > 0 := by
simp [f]
split <;> decide
test% Std.RBNode.balance1.match_1
#check @Std.RBNode.balance1.match_1.splitter
|
e227a671ca85250dc13cc201a37888ff335ffa33 | 592ee40978ac7604005a4e0d35bbc4b467389241 | /Library/generated/mathscheme-lean/LeftSpindle_ShelfSig.lean | d77107112cb1e69001b0303412e3ac38ce8c0393 | [] | 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 | 9,536 | 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 LeftSpindle_ShelfSig
structure LeftSpindle_ShelfSig (A : Type) : Type :=
(linv : (A → (A → A)))
(leftDistributive : (∀ {x y z : A} , (linv x (linv y z)) = (linv (linv x y) (linv x z))))
(idempotent_linv : (∀ {x : A} , (linv x x) = x))
(rinv : (A → (A → A)))
open LeftSpindle_ShelfSig
structure Sig (AS : Type) : Type :=
(linvS : (AS → (AS → AS)))
(rinvS : (AS → (AS → AS)))
structure Product (A : Type) : Type :=
(linvP : ((Prod A A) → ((Prod A A) → (Prod A A))))
(rinvP : ((Prod A A) → ((Prod A A) → (Prod A A))))
(leftDistributiveP : (∀ {xP yP zP : (Prod A A)} , (linvP xP (linvP yP zP)) = (linvP (linvP xP yP) (linvP xP zP))))
(idempotent_linvP : (∀ {xP : (Prod A A)} , (linvP xP xP) = xP))
structure Hom {A1 : Type} {A2 : Type} (Le1 : (LeftSpindle_ShelfSig A1)) (Le2 : (LeftSpindle_ShelfSig A2)) : Type :=
(hom : (A1 → A2))
(pres_linv : (∀ {x1 x2 : A1} , (hom ((linv Le1) x1 x2)) = ((linv Le2) (hom x1) (hom x2))))
(pres_rinv : (∀ {x1 x2 : A1} , (hom ((rinv Le1) x1 x2)) = ((rinv Le2) (hom x1) (hom x2))))
structure RelInterp {A1 : Type} {A2 : Type} (Le1 : (LeftSpindle_ShelfSig A1)) (Le2 : (LeftSpindle_ShelfSig A2)) : Type 1 :=
(interp : (A1 → (A2 → Type)))
(interp_linv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((linv Le1) x1 x2) ((linv Le2) y1 y2))))))
(interp_rinv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((rinv Le1) x1 x2) ((rinv Le2) y1 y2))))))
inductive LeftSpindle_ShelfSigTerm : Type
| linvL : (LeftSpindle_ShelfSigTerm → (LeftSpindle_ShelfSigTerm → LeftSpindle_ShelfSigTerm))
| rinvL : (LeftSpindle_ShelfSigTerm → (LeftSpindle_ShelfSigTerm → LeftSpindle_ShelfSigTerm))
open LeftSpindle_ShelfSigTerm
inductive ClLeftSpindle_ShelfSigTerm (A : Type) : Type
| sing : (A → ClLeftSpindle_ShelfSigTerm)
| linvCl : (ClLeftSpindle_ShelfSigTerm → (ClLeftSpindle_ShelfSigTerm → ClLeftSpindle_ShelfSigTerm))
| rinvCl : (ClLeftSpindle_ShelfSigTerm → (ClLeftSpindle_ShelfSigTerm → ClLeftSpindle_ShelfSigTerm))
open ClLeftSpindle_ShelfSigTerm
inductive OpLeftSpindle_ShelfSigTerm (n : ℕ) : Type
| v : ((fin n) → OpLeftSpindle_ShelfSigTerm)
| linvOL : (OpLeftSpindle_ShelfSigTerm → (OpLeftSpindle_ShelfSigTerm → OpLeftSpindle_ShelfSigTerm))
| rinvOL : (OpLeftSpindle_ShelfSigTerm → (OpLeftSpindle_ShelfSigTerm → OpLeftSpindle_ShelfSigTerm))
open OpLeftSpindle_ShelfSigTerm
inductive OpLeftSpindle_ShelfSigTerm2 (n : ℕ) (A : Type) : Type
| v2 : ((fin n) → OpLeftSpindle_ShelfSigTerm2)
| sing2 : (A → OpLeftSpindle_ShelfSigTerm2)
| linvOL2 : (OpLeftSpindle_ShelfSigTerm2 → (OpLeftSpindle_ShelfSigTerm2 → OpLeftSpindle_ShelfSigTerm2))
| rinvOL2 : (OpLeftSpindle_ShelfSigTerm2 → (OpLeftSpindle_ShelfSigTerm2 → OpLeftSpindle_ShelfSigTerm2))
open OpLeftSpindle_ShelfSigTerm2
def simplifyCl {A : Type} : ((ClLeftSpindle_ShelfSigTerm A) → (ClLeftSpindle_ShelfSigTerm A))
| (linvCl x1 x2) := (linvCl (simplifyCl x1) (simplifyCl x2))
| (rinvCl x1 x2) := (rinvCl (simplifyCl x1) (simplifyCl x2))
| (sing x1) := (sing x1)
def simplifyOpB {n : ℕ} : ((OpLeftSpindle_ShelfSigTerm n) → (OpLeftSpindle_ShelfSigTerm n))
| (linvOL x1 x2) := (linvOL (simplifyOpB x1) (simplifyOpB x2))
| (rinvOL x1 x2) := (rinvOL (simplifyOpB x1) (simplifyOpB x2))
| (v x1) := (v x1)
def simplifyOp {n : ℕ} {A : Type} : ((OpLeftSpindle_ShelfSigTerm2 n A) → (OpLeftSpindle_ShelfSigTerm2 n A))
| (linvOL2 x1 x2) := (linvOL2 (simplifyOp x1) (simplifyOp x2))
| (rinvOL2 x1 x2) := (rinvOL2 (simplifyOp x1) (simplifyOp x2))
| (v2 x1) := (v2 x1)
| (sing2 x1) := (sing2 x1)
def evalB {A : Type} : ((LeftSpindle_ShelfSig A) → (LeftSpindle_ShelfSigTerm → A))
| Le (linvL x1 x2) := ((linv Le) (evalB Le x1) (evalB Le x2))
| Le (rinvL x1 x2) := ((rinv Le) (evalB Le x1) (evalB Le x2))
def evalCl {A : Type} : ((LeftSpindle_ShelfSig A) → ((ClLeftSpindle_ShelfSigTerm A) → A))
| Le (sing x1) := x1
| Le (linvCl x1 x2) := ((linv Le) (evalCl Le x1) (evalCl Le x2))
| Le (rinvCl x1 x2) := ((rinv Le) (evalCl Le x1) (evalCl Le x2))
def evalOpB {A : Type} {n : ℕ} : ((LeftSpindle_ShelfSig A) → ((vector A n) → ((OpLeftSpindle_ShelfSigTerm n) → A)))
| Le vars (v x1) := (nth vars x1)
| Le vars (linvOL x1 x2) := ((linv Le) (evalOpB Le vars x1) (evalOpB Le vars x2))
| Le vars (rinvOL x1 x2) := ((rinv Le) (evalOpB Le vars x1) (evalOpB Le vars x2))
def evalOp {A : Type} {n : ℕ} : ((LeftSpindle_ShelfSig A) → ((vector A n) → ((OpLeftSpindle_ShelfSigTerm2 n A) → A)))
| Le vars (v2 x1) := (nth vars x1)
| Le vars (sing2 x1) := x1
| Le vars (linvOL2 x1 x2) := ((linv Le) (evalOp Le vars x1) (evalOp Le vars x2))
| Le vars (rinvOL2 x1 x2) := ((rinv Le) (evalOp Le vars x1) (evalOp Le vars x2))
def inductionB {P : (LeftSpindle_ShelfSigTerm → Type)} : ((∀ (x1 x2 : LeftSpindle_ShelfSigTerm) , ((P x1) → ((P x2) → (P (linvL x1 x2))))) → ((∀ (x1 x2 : LeftSpindle_ShelfSigTerm) , ((P x1) → ((P x2) → (P (rinvL x1 x2))))) → (∀ (x : LeftSpindle_ShelfSigTerm) , (P x))))
| plinvl prinvl (linvL x1 x2) := (plinvl _ _ (inductionB plinvl prinvl x1) (inductionB plinvl prinvl x2))
| plinvl prinvl (rinvL x1 x2) := (prinvl _ _ (inductionB plinvl prinvl x1) (inductionB plinvl prinvl x2))
def inductionCl {A : Type} {P : ((ClLeftSpindle_ShelfSigTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClLeftSpindle_ShelfSigTerm A)) , ((P x1) → ((P x2) → (P (linvCl x1 x2))))) → ((∀ (x1 x2 : (ClLeftSpindle_ShelfSigTerm A)) , ((P x1) → ((P x2) → (P (rinvCl x1 x2))))) → (∀ (x : (ClLeftSpindle_ShelfSigTerm A)) , (P x)))))
| psing plinvcl prinvcl (sing x1) := (psing x1)
| psing plinvcl prinvcl (linvCl x1 x2) := (plinvcl _ _ (inductionCl psing plinvcl prinvcl x1) (inductionCl psing plinvcl prinvcl x2))
| psing plinvcl prinvcl (rinvCl x1 x2) := (prinvcl _ _ (inductionCl psing plinvcl prinvcl x1) (inductionCl psing plinvcl prinvcl x2))
def inductionOpB {n : ℕ} {P : ((OpLeftSpindle_ShelfSigTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpLeftSpindle_ShelfSigTerm n)) , ((P x1) → ((P x2) → (P (linvOL x1 x2))))) → ((∀ (x1 x2 : (OpLeftSpindle_ShelfSigTerm n)) , ((P x1) → ((P x2) → (P (rinvOL x1 x2))))) → (∀ (x : (OpLeftSpindle_ShelfSigTerm n)) , (P x)))))
| pv plinvol prinvol (v x1) := (pv x1)
| pv plinvol prinvol (linvOL x1 x2) := (plinvol _ _ (inductionOpB pv plinvol prinvol x1) (inductionOpB pv plinvol prinvol x2))
| pv plinvol prinvol (rinvOL x1 x2) := (prinvol _ _ (inductionOpB pv plinvol prinvol x1) (inductionOpB pv plinvol prinvol x2))
def inductionOp {n : ℕ} {A : Type} {P : ((OpLeftSpindle_ShelfSigTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpLeftSpindle_ShelfSigTerm2 n A)) , ((P x1) → ((P x2) → (P (linvOL2 x1 x2))))) → ((∀ (x1 x2 : (OpLeftSpindle_ShelfSigTerm2 n A)) , ((P x1) → ((P x2) → (P (rinvOL2 x1 x2))))) → (∀ (x : (OpLeftSpindle_ShelfSigTerm2 n A)) , (P x))))))
| pv2 psing2 plinvol2 prinvol2 (v2 x1) := (pv2 x1)
| pv2 psing2 plinvol2 prinvol2 (sing2 x1) := (psing2 x1)
| pv2 psing2 plinvol2 prinvol2 (linvOL2 x1 x2) := (plinvol2 _ _ (inductionOp pv2 psing2 plinvol2 prinvol2 x1) (inductionOp pv2 psing2 plinvol2 prinvol2 x2))
| pv2 psing2 plinvol2 prinvol2 (rinvOL2 x1 x2) := (prinvol2 _ _ (inductionOp pv2 psing2 plinvol2 prinvol2 x1) (inductionOp pv2 psing2 plinvol2 prinvol2 x2))
def stageB : (LeftSpindle_ShelfSigTerm → (Staged LeftSpindle_ShelfSigTerm))
| (linvL x1 x2) := (stage2 linvL (codeLift2 linvL) (stageB x1) (stageB x2))
| (rinvL x1 x2) := (stage2 rinvL (codeLift2 rinvL) (stageB x1) (stageB x2))
def stageCl {A : Type} : ((ClLeftSpindle_ShelfSigTerm A) → (Staged (ClLeftSpindle_ShelfSigTerm A)))
| (sing x1) := (Now (sing x1))
| (linvCl x1 x2) := (stage2 linvCl (codeLift2 linvCl) (stageCl x1) (stageCl x2))
| (rinvCl x1 x2) := (stage2 rinvCl (codeLift2 rinvCl) (stageCl x1) (stageCl x2))
def stageOpB {n : ℕ} : ((OpLeftSpindle_ShelfSigTerm n) → (Staged (OpLeftSpindle_ShelfSigTerm n)))
| (v x1) := (const (code (v x1)))
| (linvOL x1 x2) := (stage2 linvOL (codeLift2 linvOL) (stageOpB x1) (stageOpB x2))
| (rinvOL x1 x2) := (stage2 rinvOL (codeLift2 rinvOL) (stageOpB x1) (stageOpB x2))
def stageOp {n : ℕ} {A : Type} : ((OpLeftSpindle_ShelfSigTerm2 n A) → (Staged (OpLeftSpindle_ShelfSigTerm2 n A)))
| (sing2 x1) := (Now (sing2 x1))
| (v2 x1) := (const (code (v2 x1)))
| (linvOL2 x1 x2) := (stage2 linvOL2 (codeLift2 linvOL2) (stageOp x1) (stageOp x2))
| (rinvOL2 x1 x2) := (stage2 rinvOL2 (codeLift2 rinvOL2) (stageOp x1) (stageOp x2))
structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type :=
(linvT : ((Repr A) → ((Repr A) → (Repr A))))
(rinvT : ((Repr A) → ((Repr A) → (Repr A))))
end LeftSpindle_ShelfSig |
0408f4863894843c2d465533ac7518d41eb32ff0 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/normed/group/quotient.lean | 836809a7fec30d951d96f1a3056dc227056d594c | [
"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 | 27,533 | lean | /-
Copyright (c) 2021 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Riccardo Brasca
-/
import analysis.normed.group.hom
/-!
# Quotients of seminormed groups
For any `seminormed_add_comm_group M` and any `S : add_subgroup M`, we provide a
`seminormed_add_comm_group`, the group quotient `M ⧸ S`.
If `S` is closed, we provide `normed_add_comm_group (M ⧸ S)` (regardless of whether `M` itself is
separated). The two main properties of these structures are the underlying topology is the quotient
topology and the projection is a normed group homomorphism which is norm non-increasing
(better, it has operator norm exactly one unless `S` is dense in `M`). The corresponding
universal property is that every normed group hom defined on `M` which vanishes on `S` descends
to a normed group hom defined on `M ⧸ S`.
This file also introduces a predicate `is_quotient` characterizing normed group homs that
are isomorphic to the canonical projection onto a normed group quotient.
In addition, this file also provides normed structures for quotients of modules by submodules, and
of (commutative) rings by ideals. The `seminormed_add_comm_group` and `normed_add_comm_group`
instances described above are transferred directly, but we also define instances of `normed_space`,
`semi_normed_comm_ring`, `normed_comm_ring` and `normed_algebra` under appropriate type class
assumptions on the original space. Moreover, while `quotient_add_group.complete_space` works
out-of-the-box for quotients of `normed_add_comm_group`s by `add_subgroup`s, we need to transfer
this instance in `submodule.quotient.complete_space` so that it applies to these other quotients.
## Main definitions
We use `M` and `N` to denote seminormed groups and `S : add_subgroup M`.
All the following definitions are in the `add_subgroup` namespace. Hence we can access
`add_subgroup.normed_mk S` as `S.normed_mk`.
* `seminormed_add_comm_group_quotient` : The seminormed group structure on the quotient by
an additive subgroup. This is an instance so there is no need to explictly use it.
* `normed_add_comm_group_quotient` : The normed group structure on the quotient by
a closed additive subgroup. This is an instance so there is no need to explictly use it.
* `normed_mk S` : the normed group hom from `M` to `M ⧸ S`.
* `lift S f hf`: implements the universal property of `M ⧸ S`. Here
`(f : normed_add_group_hom M N)`, `(hf : ∀ s ∈ S, f s = 0)` and
`lift S f hf : normed_add_group_hom (M ⧸ S) N`.
* `is_quotient`: given `f : normed_add_group_hom M N`, `is_quotient f` means `N` is isomorphic
to a quotient of `M` by a subgroup, with projection `f`. Technically it asserts `f` is
surjective and the norm of `f x` is the infimum of the norms of `x + m` for `m` in `f.ker`.
## Main results
* `norm_normed_mk` : the operator norm of the projection is `1` if the subspace is not dense.
* `is_quotient.norm_lift`: Provided `f : normed_hom M N` satisfies `is_quotient f`, for every
`n : N` and positive `ε`, there exists `m` such that `f m = n ∧ ‖m‖ < ‖n‖ + ε`.
## Implementation details
For any `seminormed_add_comm_group M` and any `S : add_subgroup M` we define a norm on `M ⧸ S` by
`‖x‖ = Inf (norm '' {m | mk' S m = x})`. This formula is really an implementation detail, it
shouldn't be needed outside of this file setting up the theory.
Since `M ⧸ S` is automatically a topological space (as any quotient of a topological space),
one needs to be careful while defining the `seminormed_add_comm_group` instance to avoid having two
different topologies on this quotient. This is not purely a technological issue.
Mathematically there is something to prove. The main point is proved in the auxiliary lemma
`quotient_nhd_basis` that has no use beyond this verification and states that zero in the quotient
admits as basis of neighborhoods in the quotient topology the sets `{x | ‖x‖ < ε}` for positive `ε`.
Once this mathematical point it settled, we have two topologies that are propositionaly equal. This
is not good enough for the type class system. As usual we ensure *definitional* equality
using forgetful inheritance, see Note [forgetful inheritance]. A (semi)-normed group structure
includes a uniform space structure which includes a topological space structure, together
with propositional fields asserting compatibility conditions.
The usual way to define a `seminormed_add_comm_group` is to let Lean build a uniform space structure
using the provided norm, and then trivially build a proof that the norm and uniform structure are
compatible. Here the uniform structure is provided using `topological_add_group.to_uniform_space`
which uses the topological structure and the group structure to build the uniform structure. This
uniform structure induces the correct topological structure by construction, but the fact that it
is compatible with the norm is not obvious; this is where the mathematical content explained in
the previous paragraph kicks in.
-/
noncomputable theory
open quotient_add_group metric set
open_locale topological_space nnreal
variables {M N : Type*} [seminormed_add_comm_group M] [seminormed_add_comm_group N]
/-- The definition of the norm on the quotient by an additive subgroup. -/
noncomputable
instance norm_on_quotient (S : add_subgroup M) : has_norm (M ⧸ S) :=
{ norm := λ x, Inf (norm '' {m | mk' S m = x}) }
lemma add_subgroup.quotient_norm_eq {S : add_subgroup M} (x : M ⧸ S) :
‖x‖ = Inf (norm '' {m : M | (m : M ⧸ S) = x}) :=
rfl
lemma image_norm_nonempty {S : add_subgroup M} :
∀ x : M ⧸ S, (norm '' {m | mk' S m = x}).nonempty :=
begin
rintro ⟨m⟩,
rw set.nonempty_image_iff,
use m,
change mk' S m = _,
refl
end
lemma bdd_below_image_norm (s : set M) : bdd_below (norm '' s) :=
begin
use 0,
rintro _ ⟨x, hx, rfl⟩,
apply norm_nonneg
end
/-- The norm on the quotient satisfies `‖-x‖ = ‖x‖`. -/
lemma quotient_norm_neg {S : add_subgroup M} (x : M ⧸ S) : ‖-x‖ = ‖x‖ :=
begin
suffices : norm '' {m | mk' S m = x} = norm '' {m | mk' S m = -x},
by simp only [this, norm],
ext r,
split,
{ rintros ⟨m, rfl : mk' S m = x, rfl⟩,
rw ← norm_neg,
exact ⟨-m, by simp only [(mk' S).map_neg, set.mem_set_of_eq], rfl⟩ },
{ rintros ⟨m, hm : mk' S m = -x, rfl⟩,
exact ⟨-m, by simpa [eq_comm] using eq_neg_iff_eq_neg.mp ((mk'_apply _ _).symm.trans hm)⟩ }
end
lemma quotient_norm_sub_rev {S : add_subgroup M} (x y : M ⧸ S) : ‖x - y‖ = ‖y - x‖ :=
by rw [show x - y = -(y - x), by abel, quotient_norm_neg]
/-- The norm of the projection is smaller or equal to the norm of the original element. -/
lemma quotient_norm_mk_le (S : add_subgroup M) (m : M) :
‖mk' S m‖ ≤ ‖m‖ :=
begin
apply cInf_le,
use 0,
{ rintros _ ⟨n, h, rfl⟩,
apply norm_nonneg },
{ apply set.mem_image_of_mem,
rw set.mem_set_of_eq }
end
/-- The norm of the projection is smaller or equal to the norm of the original element. -/
lemma quotient_norm_mk_le' (S : add_subgroup M) (m : M) :
‖(m : M ⧸ S)‖ ≤ ‖m‖ := quotient_norm_mk_le S m
/-- The norm of the image under the natural morphism to the quotient. -/
lemma quotient_norm_mk_eq (S : add_subgroup M) (m : M) :
‖mk' S m‖ = Inf ((λ x, ‖m + x‖) '' S) :=
begin
change Inf _ = _,
congr' 1,
ext r,
simp_rw [coe_mk', eq_iff_sub_mem],
split,
{ rintros ⟨y, h, rfl⟩,
use [y - m, h],
simp },
{ rintros ⟨y, h, rfl⟩,
use m + y,
simpa using h },
end
/-- The quotient norm is nonnegative. -/
lemma quotient_norm_nonneg (S : add_subgroup M) : ∀ x : M ⧸ S, 0 ≤ ‖x‖ :=
begin
rintros ⟨m⟩,
change 0 ≤ ‖mk' S m‖,
apply le_cInf (image_norm_nonempty _),
rintros _ ⟨n, h, rfl⟩,
apply norm_nonneg
end
/-- The quotient norm is nonnegative. -/
lemma norm_mk_nonneg (S : add_subgroup M) (m : M) : 0 ≤ ‖mk' S m‖ :=
quotient_norm_nonneg S _
/-- The norm of the image of `m : M` in the quotient by `S` is zero if and only if `m` belongs
to the closure of `S`. -/
lemma quotient_norm_eq_zero_iff (S : add_subgroup M) (m : M) :
‖mk' S m‖ = 0 ↔ m ∈ closure (S : set M) :=
begin
have : 0 ≤ ‖mk' S m‖ := norm_mk_nonneg S m,
rw [← this.le_iff_eq, quotient_norm_mk_eq, real.Inf_le_iff],
simp_rw [zero_add],
{ calc (∀ ε > (0 : ℝ), ∃ r ∈ (λ x, ‖m + x‖) '' (S : set M), r < ε) ↔
(∀ ε > 0, (∃ x ∈ S, ‖m + x‖ < ε)) : by simp [set.bex_image_iff]
... ↔ ∀ ε > 0, (∃ x ∈ S, ‖m + -x‖ < ε) : _
... ↔ ∀ ε > 0, (∃ x ∈ S, x ∈ metric.ball m ε) : by simp [dist_eq_norm, ← sub_eq_add_neg,
norm_sub_rev]
... ↔ m ∈ closure ↑S : by simp [metric.mem_closure_iff, dist_comm],
refine forall₂_congr (λ ε ε_pos, _),
rw [← S.exists_neg_mem_iff_exists_mem],
simp },
{ use 0,
rintro _ ⟨x, x_in, rfl⟩,
apply norm_nonneg },
rw set.nonempty_image_iff,
use [0, S.zero_mem]
end
/-- For any `x : M ⧸ S` and any `0 < ε`, there is `m : M` such that `mk' S m = x`
and `‖m‖ < ‖x‖ + ε`. -/
lemma norm_mk_lt {S : add_subgroup M} (x : M ⧸ S) {ε : ℝ} (hε : 0 < ε) :
∃ (m : M), mk' S m = x ∧ ‖m‖ < ‖x‖ + ε :=
begin
obtain ⟨_, ⟨m : M, H : mk' S m = x, rfl⟩, hnorm : ‖m‖ < ‖x‖ + ε⟩ :=
real.lt_Inf_add_pos (image_norm_nonempty x) hε,
subst H,
exact ⟨m, rfl, hnorm⟩,
end
/-- For any `m : M` and any `0 < ε`, there is `s ∈ S` such that `‖m + s‖ < ‖mk' S m‖ + ε`. -/
lemma norm_mk_lt' (S : add_subgroup M) (m : M) {ε : ℝ} (hε : 0 < ε) :
∃ s ∈ S, ‖m + s‖ < ‖mk' S m‖ + ε :=
begin
obtain ⟨n : M, hn : mk' S n = mk' S m, hn' : ‖n‖ < ‖mk' S m‖ + ε⟩ :=
norm_mk_lt (quotient_add_group.mk' S m) hε,
erw [eq_comm, quotient_add_group.eq] at hn,
use [- m + n, hn],
rwa [add_neg_cancel_left]
end
/-- The quotient norm satisfies the triangle inequality. -/
lemma quotient_norm_add_le (S : add_subgroup M) (x y : M ⧸ S) : ‖x + y‖ ≤ ‖x‖ + ‖y‖ :=
begin
refine le_of_forall_pos_le_add (λ ε hε, _),
replace hε := half_pos hε,
obtain ⟨m, rfl, hm : ‖m‖ < ‖mk' S m‖ + ε / 2⟩ := norm_mk_lt x hε,
obtain ⟨n, rfl, hn : ‖n‖ < ‖mk' S n‖ + ε / 2⟩ := norm_mk_lt y hε,
calc ‖mk' S m + mk' S n‖ = ‖mk' S (m + n)‖ : by rw (mk' S).map_add
... ≤ ‖m + n‖ : quotient_norm_mk_le S (m + n)
... ≤ ‖m‖ + ‖n‖ : norm_add_le _ _
... ≤ ‖mk' S m‖ + ‖mk' S n‖ + ε : by linarith
end
/-- The quotient norm of `0` is `0`. -/
lemma norm_mk_zero (S : add_subgroup M) : ‖(0 : M ⧸ S)‖ = 0 :=
begin
erw quotient_norm_eq_zero_iff,
exact subset_closure S.zero_mem
end
/-- If `(m : M)` has norm equal to `0` in `M ⧸ S` for a closed subgroup `S` of `M`, then
`m ∈ S`. -/
lemma norm_zero_eq_zero (S : add_subgroup M) (hS : is_closed (S : set M)) (m : M)
(h : ‖mk' S m‖ = 0) : m ∈ S :=
by rwa [quotient_norm_eq_zero_iff, hS.closure_eq] at h
lemma quotient_nhd_basis (S : add_subgroup M) :
(𝓝 (0 : M ⧸ S)).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {x | ‖x‖ < ε}) :=
⟨begin
intros U,
split,
{ intros U_in,
rw ← (mk' S).map_zero at U_in,
have := preimage_nhds_coinduced U_in,
rcases metric.mem_nhds_iff.mp this with ⟨ε, ε_pos, H⟩,
use [ε/2, half_pos ε_pos],
intros x x_in,
dsimp at x_in,
rcases norm_mk_lt x (half_pos ε_pos) with ⟨y, rfl, ry⟩,
apply H,
rw ball_zero_eq,
dsimp,
linarith },
{ rintros ⟨ε, ε_pos, h⟩,
have : (mk' S) '' (ball (0 : M) ε) ⊆ {x | ‖x‖ < ε},
{ rintros _ ⟨x, x_in, rfl⟩,
rw mem_ball_zero_iff at x_in,
exact lt_of_le_of_lt (quotient_norm_mk_le S x) x_in },
apply filter.mem_of_superset _ (set.subset.trans this h),
clear h U this,
apply is_open.mem_nhds,
{ change is_open ((mk' S) ⁻¹' _),
erw quotient_add_group.preimage_image_coe,
apply is_open_Union,
rintros ⟨s, s_in⟩,
exact (continuous_add_right s).is_open_preimage _ is_open_ball },
{ exact ⟨(0 : M), mem_ball_self ε_pos, (mk' S).map_zero⟩ } },
end⟩
/-- The seminormed group structure on the quotient by an additive subgroup. -/
noncomputable
instance add_subgroup.seminormed_add_comm_group_quotient (S : add_subgroup M) :
seminormed_add_comm_group (M ⧸ S) :=
{ dist := λ x y, ‖x - y‖,
dist_self := λ x, by simp only [norm_mk_zero, sub_self],
dist_comm := quotient_norm_sub_rev,
dist_triangle := λ x y z,
begin
unfold dist,
have : x - z = (x - y) + (y - z) := by abel,
rw this,
exact quotient_norm_add_le S (x - y) (y - z)
end,
dist_eq := λ x y, rfl,
to_uniform_space := topological_add_group.to_uniform_space (M ⧸ S),
uniformity_dist :=
begin
rw uniformity_eq_comap_nhds_zero',
have := (quotient_nhd_basis S).comap (λ (p : (M ⧸ S) × M ⧸ S), p.2 - p.1),
apply this.eq_of_same_basis,
have : ∀ ε : ℝ, (λ (p : (M ⧸ S) × M ⧸ S), p.snd - p.fst) ⁻¹' {x | ‖x‖ < ε} =
{p : (M ⧸ S) × M ⧸ S | ‖p.fst - p.snd‖ < ε},
{ intro ε,
ext x,
dsimp,
rw quotient_norm_sub_rev },
rw funext this,
refine filter.has_basis_binfi_principal _ set.nonempty_Ioi,
rintros ε (ε_pos : 0 < ε) η (η_pos : 0 < η),
refine ⟨min ε η, lt_min ε_pos η_pos, _, _⟩,
{ suffices : ∀ (a b : M ⧸ S), ‖a - b‖ < ε → ‖a - b‖ < η → ‖a - b‖ < ε, by simpa,
exact λ a b h h', h },
{ simp }
end }
-- This is a sanity check left here on purpose to ensure that potential refactors won't destroy
-- this important property.
example (S : add_subgroup M) : (quotient.topological_space : topological_space $ M ⧸ S) =
S.seminormed_add_comm_group_quotient.to_uniform_space.to_topological_space :=
rfl
/-- The quotient in the category of normed groups. -/
noncomputable
instance add_subgroup.normed_add_comm_group_quotient (S : add_subgroup M) [is_closed (S : set M)] :
normed_add_comm_group (M ⧸ S) :=
{ eq_of_dist_eq_zero :=
begin
rintros ⟨m⟩ ⟨m'⟩ (h : ‖mk' S m - mk' S m'‖ = 0),
erw [← (mk' S).map_sub, quotient_norm_eq_zero_iff, ‹is_closed _›.closure_eq,
← quotient_add_group.eq_iff_sub_mem] at h,
exact h
end,
.. add_subgroup.seminormed_add_comm_group_quotient S }
-- This is a sanity check left here on purpose to ensure that potential refactors won't destroy
-- this important property.
example (S : add_subgroup M) [is_closed (S : set M)] :
S.seminormed_add_comm_group_quotient = normed_add_comm_group.to_seminormed_add_comm_group := rfl
namespace add_subgroup
open normed_add_group_hom
/-- The morphism from a seminormed group to the quotient by a subgroup. -/
noncomputable
def normed_mk (S : add_subgroup M) : normed_add_group_hom M (M ⧸ S) :=
{ bound' := ⟨1, λ m, by simpa [one_mul] using quotient_norm_mk_le _ m⟩,
.. quotient_add_group.mk' S }
/-- `S.normed_mk` agrees with `quotient_add_group.mk' S`. -/
@[simp]
lemma normed_mk.apply (S : add_subgroup M) (m : M) : normed_mk S m = quotient_add_group.mk' S m :=
rfl
/-- `S.normed_mk` is surjective. -/
lemma surjective_normed_mk (S : add_subgroup M) : function.surjective (normed_mk S) :=
surjective_quot_mk _
/-- The kernel of `S.normed_mk` is `S`. -/
lemma ker_normed_mk (S : add_subgroup M) : S.normed_mk.ker = S :=
quotient_add_group.ker_mk _
/-- The operator norm of the projection is at most `1`. -/
lemma norm_normed_mk_le (S : add_subgroup M) : ‖S.normed_mk‖ ≤ 1 :=
normed_add_group_hom.op_norm_le_bound _ zero_le_one (λ m, by simp [quotient_norm_mk_le'])
/-- The operator norm of the projection is `1` if the subspace is not dense. -/
lemma norm_normed_mk (S : add_subgroup M) (h : (S.topological_closure : set M) ≠ univ) :
‖S.normed_mk‖ = 1 :=
begin
obtain ⟨x, hx⟩ := set.nonempty_compl.2 h,
let y := S.normed_mk x,
have hy : ‖y‖ ≠ 0,
{ intro h0,
exact set.not_mem_of_mem_compl hx ((quotient_norm_eq_zero_iff S x).1 h0) },
refine le_antisymm (norm_normed_mk_le S) (le_of_forall_pos_le_add (λ ε hε, _)),
suffices : 1 ≤ ‖S.normed_mk‖ + min ε ((1 : ℝ)/2),
{ exact le_add_of_le_add_left this (min_le_left ε ((1 : ℝ)/2)) },
have hδ := sub_pos.mpr (lt_of_le_of_lt (min_le_right ε ((1 : ℝ)/2)) one_half_lt_one),
have hδpos : 0 < min ε ((1 : ℝ)/2) := lt_min hε one_half_pos,
have hδnorm := mul_pos (div_pos hδpos hδ) (lt_of_le_of_ne (norm_nonneg y) hy.symm),
obtain ⟨m, hm, hlt⟩ := norm_mk_lt y hδnorm,
have hrw : ‖y‖ + min ε (1 / 2) / (1 - min ε (1 / 2)) * ‖y‖ =
‖y‖ * (1 + min ε (1 / 2) / (1 - min ε (1 / 2))) := by ring,
rw [hrw] at hlt,
have hm0 : ‖m‖ ≠ 0,
{ intro h0,
have hnorm := quotient_norm_mk_le S m,
rw [h0, hm] at hnorm,
replace hnorm := le_antisymm hnorm (norm_nonneg _),
simpa [hnorm] using hy },
replace hlt := (div_lt_div_right (lt_of_le_of_ne (norm_nonneg m) hm0.symm)).2 hlt,
simp only [hm0, div_self, ne.def, not_false_iff] at hlt,
have hrw₁ : ‖y‖ * (1 + min ε (1 / 2) / (1 - min ε (1 / 2))) / ‖m‖ =
(‖y‖ / ‖m‖) * (1 + min ε (1 / 2) / (1 - min ε (1 / 2))) := by ring,
rw [hrw₁] at hlt,
replace hlt := (inv_pos_lt_iff_one_lt_mul (lt_trans (div_pos hδpos hδ) (lt_one_add _))).2 hlt,
suffices : ‖S.normed_mk‖ ≥ 1 - min ε (1 / 2),
{ exact sub_le_iff_le_add.mp this },
calc ‖S.normed_mk‖ ≥ ‖(S.normed_mk) m‖ / ‖m‖ : ratio_le_op_norm S.normed_mk m
... = ‖y‖ / ‖m‖ : by rw [normed_mk.apply, hm]
... ≥ (1 + min ε (1 / 2) / (1 - min ε (1 / 2)))⁻¹ : le_of_lt hlt
... = 1 - min ε (1 / 2) : by field_simp [(ne_of_lt hδ).symm]
end
/-- The operator norm of the projection is `0` if the subspace is dense. -/
lemma norm_trivial_quotient_mk (S : add_subgroup M)
(h : (S.topological_closure : set M) = set.univ) : ‖S.normed_mk‖ = 0 :=
begin
refine le_antisymm (op_norm_le_bound _ le_rfl (λ x, _)) (norm_nonneg _),
have hker : x ∈ (S.normed_mk).ker.topological_closure,
{ rw [S.ker_normed_mk],
exact set.mem_of_eq_of_mem h trivial },
rw [ker_normed_mk] at hker,
simp only [(quotient_norm_eq_zero_iff S x).mpr hker, normed_mk.apply, zero_mul],
end
end add_subgroup
namespace normed_add_group_hom
/-- `is_quotient f`, for `f : M ⟶ N` means that `N` is isomorphic to the quotient of `M`
by the kernel of `f`. -/
structure is_quotient (f : normed_add_group_hom M N) : Prop :=
(surjective : function.surjective f)
(norm : ∀ x, ‖f x‖ = Inf ((λ m, ‖x + m‖) '' f.ker))
/-- Given `f : normed_add_group_hom M N` such that `f s = 0` for all `s ∈ S`, where,
`S : add_subgroup M` is closed, the induced morphism `normed_add_group_hom (M ⧸ S) N`. -/
noncomputable
def lift {N : Type*} [seminormed_add_comm_group N] (S : add_subgroup M)
(f : normed_add_group_hom M N) (hf : ∀ s ∈ S, f s = 0) :
normed_add_group_hom (M ⧸ S) N :=
{ bound' :=
begin
obtain ⟨c : ℝ, hcpos : (0 : ℝ) < c, hc : ∀ x, ‖f x‖ ≤ c * ‖x‖⟩ := f.bound,
refine ⟨c, λ mbar, le_of_forall_pos_le_add (λ ε hε, _)⟩,
obtain ⟨m : M, rfl : mk' S m = mbar, hmnorm : ‖m‖ < ‖mk' S m‖ + ε/c⟩ :=
norm_mk_lt mbar (div_pos hε hcpos),
calc ‖f m‖ ≤ c * ‖m‖ : hc m
... ≤ c*(‖mk' S m‖ + ε/c) : ((mul_lt_mul_left hcpos).mpr hmnorm).le
... = c * ‖mk' S m‖ + ε : by rw [mul_add, mul_div_cancel' _ hcpos.ne.symm]
end,
.. quotient_add_group.lift S f.to_add_monoid_hom hf }
lemma lift_mk {N : Type*} [seminormed_add_comm_group N] (S : add_subgroup M)
(f : normed_add_group_hom M N) (hf : ∀ s ∈ S, f s = 0) (m : M) :
lift S f hf (S.normed_mk m) = f m := rfl
lemma lift_unique {N : Type*} [seminormed_add_comm_group N] (S : add_subgroup M)
(f : normed_add_group_hom M N) (hf : ∀ s ∈ S, f s = 0)
(g : normed_add_group_hom (M ⧸ S) N) :
g.comp (S.normed_mk) = f → g = lift S f hf :=
begin
intro h,
ext,
rcases add_subgroup.surjective_normed_mk _ x with ⟨x,rfl⟩,
change (g.comp (S.normed_mk) x) = _,
simpa only [h]
end
/-- `S.normed_mk` satisfies `is_quotient`. -/
lemma is_quotient_quotient (S : add_subgroup M) : is_quotient (S.normed_mk) :=
⟨S.surjective_normed_mk, λ m, by simpa [S.ker_normed_mk] using quotient_norm_mk_eq _ m⟩
lemma is_quotient.norm_lift {f : normed_add_group_hom M N} (hquot : is_quotient f) {ε : ℝ}
(hε : 0 < ε) (n : N) : ∃ (m : M), f m = n ∧ ‖m‖ < ‖n‖ + ε :=
begin
obtain ⟨m, rfl⟩ := hquot.surjective n,
have nonemp : ((λ m', ‖m + m'‖) '' f.ker).nonempty,
{ rw set.nonempty_image_iff,
exact ⟨0, f.ker.zero_mem⟩ },
rcases real.lt_Inf_add_pos nonemp hε with
⟨_, ⟨⟨x, hx, rfl⟩, H : ‖m + x‖ < Inf ((λ (m' : M), ‖m + m'‖) '' f.ker) + ε⟩⟩,
exact ⟨m+x, by rw [map_add,(normed_add_group_hom.mem_ker f x).mp hx, add_zero],
by rwa hquot.norm⟩,
end
lemma is_quotient.norm_le {f : normed_add_group_hom M N} (hquot : is_quotient f) (m : M) :
‖f m‖ ≤ ‖m‖ :=
begin
rw hquot.norm,
apply cInf_le,
{ use 0,
rintros _ ⟨m', hm', rfl⟩,
apply norm_nonneg },
{ exact ⟨0, f.ker.zero_mem, by simp⟩ }
end
lemma lift_norm_le {N : Type*} [seminormed_add_comm_group N] (S : add_subgroup M)
(f : normed_add_group_hom M N) (hf : ∀ s ∈ S, f s = 0)
{c : ℝ≥0} (fb : ‖f‖ ≤ c) :
‖lift S f hf‖ ≤ c :=
begin
apply op_norm_le_bound _ c.coe_nonneg,
intros x,
by_cases hc : c = 0,
{ simp only [hc, nnreal.coe_zero, zero_mul] at fb ⊢,
obtain ⟨x, rfl⟩ := surjective_quot_mk _ x,
show ‖f x‖ ≤ 0,
calc ‖f x‖ ≤ 0 * ‖x‖ : f.le_of_op_norm_le fb x
... = 0 : zero_mul _ },
{ replace hc : 0 < c := pos_iff_ne_zero.mpr hc,
apply le_of_forall_pos_le_add,
intros ε hε,
have aux : 0 < (ε / c) := div_pos hε hc,
obtain ⟨x, rfl, Hx⟩ : ∃ x', S.normed_mk x' = x ∧ ‖x'‖ < ‖x‖ + (ε / c) :=
(is_quotient_quotient _).norm_lift aux _,
rw lift_mk,
calc ‖f x‖ ≤ c * ‖x‖ : f.le_of_op_norm_le fb x
... ≤ c * (‖S.normed_mk x‖ + ε / c) : (mul_le_mul_left _).mpr Hx.le
... = c * _ + ε : _,
{ exact_mod_cast hc },
{ rw [mul_add, mul_div_cancel'], exact_mod_cast hc.ne' } },
end
lemma lift_norm_noninc {N : Type*} [seminormed_add_comm_group N] (S : add_subgroup M)
(f : normed_add_group_hom M N) (hf : ∀ s ∈ S, f s = 0)
(fb : f.norm_noninc) :
(lift S f hf).norm_noninc :=
λ x,
begin
have fb' : ‖f‖ ≤ (1 : ℝ≥0) := norm_noninc.norm_noninc_iff_norm_le_one.mp fb,
simpa using le_of_op_norm_le _ (f.lift_norm_le _ _ fb') _,
end
end normed_add_group_hom
/-!
### Submodules and ideals
In what follows, the norm structures created above for quotients of (semi)`normed_add_comm_group`s
by `add_subgroup`s are transferred via definitional equality to quotients of modules by submodules,
and of rings by ideals, thereby preserving the definitional equality for the topological group and
uniform structures worked for above. Completeness is also transferred via this definitional
equality.
In addition, instances are constructed for `normed_space`, `semi_normed_comm_ring`,
`normed_comm_ring` and `normed_algebra` under the appropriate hypotheses. Currently, we do not
have quotients of rings by two-sided ideals, hence the commutativity hypotheses are required.
-/
section submodule
variables {R : Type*} [ring R] [module R M] (S : submodule R M)
instance submodule.quotient.seminormed_add_comm_group :
seminormed_add_comm_group (M ⧸ S) :=
add_subgroup.seminormed_add_comm_group_quotient S.to_add_subgroup
instance submodule.quotient.normed_add_comm_group [hS : is_closed (S : set M)] :
normed_add_comm_group (M ⧸ S) :=
@add_subgroup.normed_add_comm_group_quotient _ _ S.to_add_subgroup hS
instance submodule.quotient.complete_space [complete_space M] : complete_space (M ⧸ S) :=
quotient_add_group.complete_space M S.to_add_subgroup
/-- For any `x : M ⧸ S` and any `0 < ε`, there is `m : M` such that `submodule.quotient.mk m = x`
and `‖m‖ < ‖x‖ + ε`. -/
lemma submodule.quotient.norm_mk_lt {S : submodule R M} (x : M ⧸ S) {ε : ℝ} (hε : 0 < ε) :
∃ m : M, submodule.quotient.mk m = x ∧ ‖m‖ < ‖x‖ + ε :=
norm_mk_lt x hε
lemma submodule.quotient.norm_mk_le (m : M) :
‖(submodule.quotient.mk m : M ⧸ S)‖ ≤ ‖m‖ :=
quotient_norm_mk_le S.to_add_subgroup m
instance submodule.quotient.normed_space (𝕜 : Type*) [normed_field 𝕜] [normed_space 𝕜 M]
[has_smul 𝕜 R] [is_scalar_tower 𝕜 R M] : normed_space 𝕜 (M ⧸ S) :=
{ norm_smul_le := λ k x, le_of_forall_pos_le_add $ λ ε hε,
begin
have := (nhds_basis_ball.tendsto_iff nhds_basis_ball).mp
((@real.uniform_continuous_const_mul (‖k‖)).continuous.tendsto (‖x‖)) ε hε,
simp only [mem_ball, exists_prop, dist, abs_sub_lt_iff] at this,
rcases this with ⟨δ, hδ, h⟩,
obtain ⟨a, rfl, ha⟩ := submodule.quotient.norm_mk_lt x hδ,
specialize h (‖a‖) (⟨by linarith, by linarith [submodule.quotient.norm_mk_le S a]⟩),
calc _ ≤ ‖k‖ * ‖a‖ : (quotient_norm_mk_le S.to_add_subgroup (k • a)).trans_eq (norm_smul k a)
... ≤ _ : (sub_lt_iff_lt_add'.mp h.1).le
end,
.. submodule.quotient.module' S, }
end submodule
section ideal
variables {R : Type*} [semi_normed_comm_ring R] (I : ideal R)
lemma ideal.quotient.norm_mk_lt {I : ideal R} (x : R ⧸ I) {ε : ℝ} (hε : 0 < ε) :
∃ r : R, ideal.quotient.mk I r = x ∧ ‖r‖ < ‖x‖ + ε :=
norm_mk_lt x hε
lemma ideal.quotient.norm_mk_le (r : R) :
‖ideal.quotient.mk I r‖ ≤ ‖r‖ :=
quotient_norm_mk_le I.to_add_subgroup r
instance ideal.quotient.semi_normed_comm_ring : semi_normed_comm_ring (R ⧸ I) :=
{ mul_comm := mul_comm,
norm_mul := λ x y, le_of_forall_pos_le_add $ λ ε hε,
begin
have := ((nhds_basis_ball.prod_nhds nhds_basis_ball).tendsto_iff nhds_basis_ball).mp
(real.continuous_mul.tendsto (‖x‖, ‖y‖)) ε hε,
simp only [set.mem_prod, mem_ball, and_imp, prod.forall, exists_prop, prod.exists] at this,
rcases this with ⟨ε₁, ε₂, ⟨h₁, h₂⟩, h⟩,
obtain ⟨⟨a, rfl, ha⟩, ⟨b, rfl, hb⟩⟩ :=
⟨ideal.quotient.norm_mk_lt x h₁, ideal.quotient.norm_mk_lt y h₂⟩,
simp only [dist, abs_sub_lt_iff] at h,
specialize h (‖a‖) (‖b‖) (⟨by linarith, by linarith [ideal.quotient.norm_mk_le I a]⟩)
(⟨by linarith, by linarith [ideal.quotient.norm_mk_le I b]⟩),
calc _ ≤ ‖a‖ * ‖b‖ : (ideal.quotient.norm_mk_le I (a * b)).trans (norm_mul_le a b)
... ≤ _ : (sub_lt_iff_lt_add'.mp h.1).le
end,
.. submodule.quotient.seminormed_add_comm_group I }
instance ideal.quotient.normed_comm_ring [is_closed (I : set R)] :
normed_comm_ring (R ⧸ I) :=
{ .. ideal.quotient.semi_normed_comm_ring I,
.. submodule.quotient.normed_add_comm_group I }
variables (𝕜 : Type*) [normed_field 𝕜]
instance ideal.quotient.normed_algebra [normed_algebra 𝕜 R] :
normed_algebra 𝕜 (R ⧸ I) :=
{ .. submodule.quotient.normed_space I 𝕜,
.. ideal.quotient.algebra 𝕜 }
end ideal
|
4a3f706fff72567f79cfbdf05c46d184e821d747 | 4727251e0cd73359b15b664c3170e5d754078599 | /test/transport/basic.lean | 6124edaea64dcb672cb355ad19a7cf439c9f2440 | [
"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 | 2,565 | lean | import tactic.transport
import order.bounded_order
import algebra.lie.basic
-- We verify that `transport` can move a `semiring` across an equivalence.
-- Note that we've never even mentioned the idea of addition or multiplication to `transport`.
def semiring.map {α : Type} [semiring α] {β : Type} (e : α ≃ β) : semiring β :=
by transport using e
-- Indeed, it can equally well move a `semilattice_sup`.
def sup.map {α : Type} [semilattice_sup α] {β : Type} (e : α ≃ β) : semilattice_sup β :=
by transport using e
-- Verify definitional equality of the new structure data.
example {α : Type} [semilattice_sup α] {β : Type} (e : α ≃ β) (x y : β) :
begin
haveI := sup.map e,
exact (x ≤ y) = (e.symm x ≤ e.symm y),
end :=
rfl
-- Below we verify in more detail that the transported structure for `semiring`
-- is definitionally what you would hope for.
inductive mynat : Type
| zero : mynat
| succ : mynat → mynat
def mynat_equiv : ℕ ≃ mynat :=
{ to_fun := λ n, nat.rec_on n mynat.zero (λ n, mynat.succ),
inv_fun := λ n, mynat.rec_on n nat.zero (λ n, nat.succ),
left_inv := λ n, begin induction n, refl, exact congr_arg nat.succ n_ih, end,
right_inv := λ n, begin induction n, refl, exact congr_arg mynat.succ n_ih, end }
@[simp] lemma mynat_equiv_apply_zero : mynat_equiv 0 = mynat.zero := rfl
@[simp] lemma mynat_equiv_apply_succ (n : ℕ) :
mynat_equiv (n + 1) = mynat.succ (mynat_equiv n) := rfl
@[simp] lemma mynat_equiv_symm_apply_zero : mynat_equiv.symm mynat.zero = 0:= rfl
@[simp] lemma mynat_equiv_symm_apply_succ (n : mynat) :
mynat_equiv.symm (mynat.succ n) = (mynat_equiv.symm n) + 1 := rfl
instance semiring_mynat : semiring mynat :=
semiring.map mynat_equiv
lemma mynat_add_def (a b : mynat) : a + b = mynat_equiv (mynat_equiv.symm a + mynat_equiv.symm b) :=
rfl
-- Verify that we can do computations with the transported structure.
example :
(mynat.succ (mynat.succ mynat.zero)) + (mynat.succ mynat.zero) =
(mynat.succ (mynat.succ (mynat.succ mynat.zero))) :=
rfl
lemma mynat_zero_def : (0 : mynat) = mynat_equiv 0 :=
rfl
lemma mynat_one_def : (1 : mynat) = mynat_equiv 1 :=
rfl
lemma mynat_mul_def (a b : mynat) : a * b = mynat_equiv (mynat_equiv.symm a * mynat_equiv.symm b) :=
rfl
example : (3 : mynat) + (7 : mynat) = (10 : mynat) :=
rfl
example : (2 : mynat) * (2 : mynat) = (4 : mynat) :=
rfl
example : (3 : mynat) + (7 : mynat) * (2 : mynat) = (17 : mynat) :=
rfl
example : (2 : ℕ) • (3 : mynat) = (6 : mynat) :=
rfl
example : (3 : mynat) ^ 2 = (9 : mynat) :=
rfl
|
db633fde01aba5e1d0e8b89fc65efc605baaa2d8 | e21db629d2e37a833531fdcb0b37ce4d71825408 | /src/mcl/defs.lean | 63433d7055a559ddaef21c9d39c3419f20d5c3da | [] | no_license | fischerman/GPU-transformation-verifier | 614a28cb4606a05a0eb27e8d4eab999f4f5ea60c | 75a5016f05382738ff93ce5859c4cfa47ccb63c1 | refs/heads/master | 1,586,985,789,300 | 1,579,290,514,000 | 1,579,290,514,000 | 165,031,073 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,127 | lean |
import parlang.defs
import data.rat
open parlang
notation `v[` v:(foldr `, ` (h t, vector.cons h t) vector.nil `]`) := v
namespace mcl
variables {n : ℕ}
inductive type
| int
| float
| bool
open type
instance : has_sizeof type :=
⟨λt, match t with
| type.int := 1
| type.float := 1
| type.bool := 2
end⟩
structure array :=
(dim : ℕ)
(type : type)
-- (sizes : vector ℕ dim)
inductive scope
| tlocal
| shared
structure variable_def :=
(type : array)
(scope : scope)
@[reducible]
def signature_core := string → variable_def
@[reducible]
def type_map : type → Type
| int := ℕ
| float := rat
| bool := _root_.bool
instance (t) : inhabited (type_map t) := ⟨
match t with
| type.int := 0
| type.float := 0
| type.bool := ff
end
⟩
#eval default (type_map int)
@[reducible]
def type_of : variable_def → type := λ v, v.type.type
def signature := { sig : signature_core //
type_of (sig "tid") = type.int ∧
(sig "tid").type.dim = 1 ∧
(sig "tid").scope = scope.tlocal }
-- todo: make sig parameter (instead of variable). That way I don't have to mention signature anywhere (see section 6.2)
variables {sig : signature}
@[reducible]
def lean_type_of : variable_def → Type := λ v, type_map (type_of v)
@[reducible]
def signature.type_of (n : string) (sig :signature) := type_of (sig.val n)
@[reducible]
def signature.lean_type_of (n : string) (sig : signature) := lean_type_of (sig.val n)
@[reducible]
def is_tlocal (v : variable_def) := v.scope = scope.tlocal
@[reducible]
def is_shared (v : variable_def) := v.scope = scope.shared
-- @[reducible]
-- def create_signature : list (string × variable_def) → signature
-- | [] n := { scope := scope.tlocal, type := ⟨1, int⟩} -- by default all variables are tlocal int's
-- | ((m, v) :: xs) n := if m = n then v else create_signature xs n
-- We use vectors for idx. If we compare two variable accesses to the same array: when using vectors we only have to reason about equality of elements, otherwise we have to reason about length as well
@[reducible]
def mcl_address (sig : signature) := (Σ n: string, vector ℕ (sig.val n).type.dim)
/-- Type map for shared memory -/
@[reducible]
def parlang_mcl_shared (sig : signature) := (λ i : mcl_address sig, sig.lean_type_of i.1)
/-- Type map for thread local memory -/
@[reducible]
def parlang_mcl_tlocal (sig : signature) := (λ i : mcl_address sig, sig.lean_type_of i.1)
@[reducible]
def parlang_mcl_kernel (sig : signature) := kernel (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)
lemma address_eq {sig : mcl.signature} {a b : mcl.mcl_address sig} (h : a.1 = b.1) (g: a.2 = begin rw h, exact b.2, end) : a = b := begin
cases a,
cases b,
simp at h,
subst h,
simp,
simp[eq.mpr.intro] at g,
exact g,
end
/-- all addresses of array *var* -/
def array_address_range {sig : signature} (var : string) : set (mcl_address sig) := {i | i.1 = var}
-- expression is an inductive family over types
-- type is called an index
inductive expression (sig : signature) : type → Type
| tlocal_var {t} {dim : ℕ} (n : string) (idx : fin dim → (expression int)) (h₁ : type_of (sig.val n) = t) (h₂ : (sig.val n).type.dim = dim) (h₃ : is_tlocal (sig.val n)) : expression t
| shared_var {t} {dim : ℕ} (n : string) (idx : fin dim → (expression int)) (h₁ : type_of (sig.val n) = t) (h₂ : (sig.val n).type.dim = dim) (h₃ : is_shared (sig.val n)) : expression t
| add {t} : expression t → expression t → expression t
| mult {t} : expression t → expression t → expression t
| literal_int {} {t} (n : ℕ) (h : t = type.int) : expression t
| lt {t} (h : t = type.bool) : expression int → expression int → expression t
open expression
instance (t : type) : has_add (expression sig t) := ⟨expression.add⟩
instance (t : type) : has_mul (expression sig t) := ⟨expression.mult⟩
instance : has_zero (expression sig int) := ⟨expression.literal_int 0 rfl⟩
instance : has_one (expression sig int) := ⟨expression.literal_int 1 rfl⟩
infix < := expression.lt (show type.bool = type.bool, by refl)
notation `v(` n `)`:= expression.tlocal_var n (by refl)
notation `i(` n `)`:= expression.literal_int n (by refl)
def type_map_add : Π{t : type}, type_map t → type_map t → type_map t
| int a b := a + b
| float a b := a + b
| bool a b := a && b
def type_map_mult : Π{t : type}, type_map t → type_map t → type_map t
| int a b := a * b
| float a b := a * b
| bool a b := a || b
-- we have C on idx
-- use recursor directly
#print expression.rec_on
#print expression.brec_on
#print nat.rec_on
#check ((λ n, nat.rec_on n _ _) : ℕ → ℕ)
-- pattern matching does not work due to problems with the parser
-- implicit argument C of recursor is filled in by the special elaborator "eliminator"
-- arguments sig t and expr must be named, otherwise the eliminator elaborator fails
def expression_size {sig : signature} {t : type} (expr : expression sig t) : ℕ := expression.rec_on expr
-- tlocal
(λ t dim n idx h₁ h₂ h₃ ih, 1 + (vector.of_fn ih).to_list.sum)
-- shared
(λ t dim n idx h₁ h₂ h₃ ih, 1 + (vector.of_fn ih).to_list.sum)
-- add
(λ t a b ih_a ih_b, (1 : ℕ) + (ih_a : ℕ) + (ih_b : ℕ))
-- mult
(λ t a b ih_a ih_b, (1 : ℕ) + (ih_a : ℕ) + (ih_b : ℕ))
-- literal_int
(λ t n h, (n : ℕ))
-- lt
(λ t h a b ih_a ih_b, ih_a + ih_b + 1)
-- def s₁ : signature
-- | _ := { scope := scope.shared, type := ⟨1, type.int⟩ }
-- -- appearently not true
-- def test : (7 : expression s₁ int) = (literal_int 7 (by refl)) := begin
-- sorry, -- not by refl
-- end
-- def idx₁ : fin 1 → expression s₁ int
-- | _ := 7
-- #eval expression_size (tlocal_var "n" idx₁ sorry sorry sorry : expression s₁ int)
-- #eval expression_size (expression.add (literal_int 123 (by refl)) (literal_int 123 (by refl)) : expression s₁ int)
#print expression_size
@[simp]
lemma abc (t) (expr : expression sig t) : 0 < expression_size expr := sorry
#print psigma.has_well_founded
#print psigma.lex
#print has_well_founded_of_has_sizeof
#print expression.sizeof
-- should we make this an inductive predicate
-- it would have implications on parlang
def eval {sig : signature} (m : memory $ parlang_mcl_tlocal sig) {t : type} (expr : expression sig t) : type_map t := expression.rec_on expr
-- tlocal
(λ t dim n idx h₁ h₂ h₃ ih, by rw ← h₁; rw ← h₂ at ih; exact m.get ⟨n, vector.of_fn ih⟩)
-- shared
-- requires that the shared variable has been loaded into tstate under the same name
(λ t dim n idx h₁ h₂ h₃ ih, by rw ← h₁; rw ← h₂ at ih; exact m.get ⟨n, vector.of_fn ih⟩)
-- add
(λ t a b ih_a ih_b, type_map_add ih_a ih_b)
-- mult
(λ t a b ih_a ih_b, type_map_mult ih_a ih_b)
-- literal_int
(λ t n h, (by rw [h]; exact n))
-- lt
(λ t h a b ih_a ih_b, (by rw h; exact (ih_a < ih_b)))
/-- h₂ corresponds to h₂ of expr and mclk -/
def mcl_addr_from_var {sig : signature} {n dim} (h₂ : (sig.val n).type.dim = dim) (idx : vector (expression sig type.int) dim) (m : memory $ parlang_mcl_tlocal sig) : mcl_address sig :=
⟨n, by rw ← h₂ at idx; exact idx.map (eval m)⟩
def load_shared_vars_for_expr {sig : signature} {t : type} (expr : expression sig t) : list (parlang_mcl_kernel sig) := expression.rec_on expr
-- tlocal
(λ t dim n idx h₁ h₂ h₃ ih, (vector.of_fn ih).to_list.foldl list.append [])
-- shared
-- loads the shared variable in the tlocal memory under the same name
(λ t dim n idx h₁ h₂ h₃ ih, (vector.of_fn ih).to_list.foldl list.append [] ++ [kernel.load (λ m, ⟨mcl_addr_from_var h₂ (vector.of_fn idx) m, λ v, m.update (mcl_addr_from_var h₂ (vector.of_fn idx) m) v⟩)])
-- add
(λ t a b ih_a ih_b, ih_a ++ ih_b)
-- mult
(λ t a b ih_a ih_b, ih_a ++ ih_b)
-- literal_int
(λ t n h, [])
-- lt
(λ t h a b ih_a ih_b, ih_a ++ ih_b)
def prepend_load_expr {sig : signature} {t : type} (expr : expression sig t) (k : parlang_mcl_kernel sig) :=
(load_shared_vars_for_expr expr).foldr kernel.seq k
--list_to_kernel_seq (load_shared_vars_for_expr expr ++ [k])
def append_load_expr {sig : signature} {t : type} (expr : expression sig t) (k : parlang_mcl_kernel sig) :=
(load_shared_vars_for_expr expr).foldl kernel.seq k
--list_to_kernel_seq ([k] ++ load_shared_vars_for_expr expr)
example (k) : prepend_load_expr (7 : expression sig int) k = k := by refl
example (k) (n idx h₁ h₂ h₃) : prepend_load_expr (@shared_var sig _ 1 n idx h₁ h₂ h₃ : expression sig int) k = k := begin
rw prepend_load_expr,
rw load_shared_vars_for_expr,
repeat { rw list.foldr },
sorry
end
example (k) : append_load_expr (7 : expression sig int) k = k := by refl
example (k) (n idx h₁ h₂ h₃) : append_load_expr (@shared_var sig _ 1 n idx h₁ h₂ h₃ : expression sig int) k = k := begin
rw append_load_expr,
rw load_shared_vars_for_expr,
repeat { rw list.foldl },
sorry
end
-- TODO prove lemma
-- eval expression (specifically the loads only influence the expression)
-- prove more lemmas to make sure loads are placed correctly
-- do I need a small step seantic for this?
def expr_reads (n : string) {t : type} (expr : expression sig t) : _root_.bool := expression.rec_on expr
-- tlocal
(λ t dim m idx h₁ h₂ h₃ ih, (m = n) || (vector.of_fn ih).to_list.any id)
-- shared
(λ t dim m idx h₁ h₂ h₃ ih, (m = n) || (vector.of_fn ih).to_list.any id)
-- add
(λ t a b ih_a ih_b, ih_a || ih_b)
-- mult
(λ t a b ih_a ih_b, ih_a || ih_b)
-- literal_int
(λ t n h, ff)
-- lt
(λ t h a b ih_a ih_b, ih_a || ih_b)
meta def eqt : tactic unit := do
t ← tactic.target,
match t with
| `(eq.mpr %%x %%p = eq.mpr %%y %%z) := do
s ← tactic.infer_type x,
tactic.trace s,
s ← tactic.infer_type y,
tactic.trace s
| _ := tactic.fail ()
end
lemma eval_update_ignore {sig : signature} {t t₂ : type} {n} {idx₂ : vector ℕ ((sig.val n).type).dim} {v} {expr : expression sig t} {s : memory $ parlang_mcl_tlocal sig} (h : expr_reads n expr = ff) :
eval (s.update ⟨n, idx₂⟩ v) expr = eval s expr := begin
induction expr,
{
simp [eval],
simp [eval] at expr_ih,
eqt,
sorry,
},
repeat { sorry },
end
-- can we make use of functor abstraction
lemma eval_update_ignore' {sig : signature} {t t₂ : type} {dim n} {idx₂ : vector ℕ ((sig.val n).type).dim} {v} {idx : vector (expression sig t) dim} {s : memory $ parlang_mcl_tlocal sig} (h : (idx.to_list.all $ bnot ∘ expr_reads n) = tt) :
vector.map (eval (s.update ⟨n, idx₂⟩ v)) idx = vector.map (eval s) idx := begin
admit
end
-- TODO variable assign constructors should include shared and local proof
-- expression sig (type_of (sig n)) is not definitionally equal if sig is not computable
inductive mclk (sig : signature)
| tlocal_assign {t : type} {dim : ℕ} (n : string) (idx : vector (expression sig int) dim) (h₁ : type_of (sig.val n) = t) (h₂ : (sig.val n).type.dim = idx.length) : (expression sig t) → mclk
| shared_assign {t : type} {dim : ℕ} (n) (idx : vector (expression sig int) dim) (h₁ : type_of (sig.val n) = t) (h₂ : (sig.val n).type.dim = idx.length) : (expression sig t) → mclk
| seq : mclk → mclk → mclk
| for (n : string) (h : sig.type_of n = int) (h₂ : (sig.val n).type.dim = 1) :
expression sig int → expression sig bool → mclk → mclk → mclk
| ite : expression sig bool → mclk → mclk → mclk
| skip {} : mclk
| sync {} : mclk
infixr ` ;; `:90 := mclk.seq
open mclk
def mclk_reads (n : string) : mclk sig → _root_.bool
| (tlocal_assign _ idx _ _ expr) := expr_reads n expr || (idx.to_list.any (λ e, expr_reads n e))
| (shared_assign _ idx _ _ expr) := expr_reads n expr || (idx.to_list.any (λ e, expr_reads n e))
| (seq k₁ k₂) := mclk_reads k₁ || mclk_reads k₂
| (for _ _ _ init c inc body) := expr_reads n init || expr_reads n c || mclk_reads inc || mclk_reads body
| (ite c th el) := expr_reads n c || mclk_reads th || mclk_reads el
| skip := false
| sync := false
--lemma mclk_expr_reads (k) : mclk_reads n k → ∃ expr, (expr_reads n expr ∧ subexpr expr k)
/-- A variation of *memory.update*, that is optimized for the arguments of MCL -/
def memory.update_assign {sig : signature} {t : type} {dim : ℕ} (n : string) (idx : vector (expression sig int) dim) (h₁ : type_of (sig.val n) = t) (h₂ : (sig.val n).type.dim = idx.length)
(expr : expression sig t)
(m : memory $ parlang_mcl_tlocal sig) : memory $ parlang_mcl_tlocal sig := m.update (mcl_addr_from_var h₂ idx m) (by rw ← h₁ at expr; exact (eval m expr))
def mclk_to_kernel {sig : signature} : mclk sig → parlang_mcl_kernel sig
| (seq k₁ k₂) := kernel.seq (mclk_to_kernel k₁) (mclk_to_kernel k₂)
| skip := kernel.compute id
| sync := kernel.sync
| (tlocal_assign n idx h₁ h₂ expr) := idx.to_list.foldr (λexpr' k, prepend_load_expr expr' k) $ prepend_load_expr expr (kernel.compute $ memory.update_assign n idx h₁ h₂ expr)
| (shared_assign n idx h₁ h₂ expr) := idx.to_list.foldr (λexpr' k, prepend_load_expr expr' k) $ prepend_load_expr expr (kernel.compute $ memory.update_assign n idx h₁ h₂ expr) ;; kernel.store (λ m, ⟨mcl_addr_from_var h₂ idx m, m.get $ mcl_addr_from_var h₂ idx m⟩)
| (ite c th el) := prepend_load_expr c (kernel.ite (λm, eval m c) (mclk_to_kernel th) (mclk_to_kernel el))
| (for n h h₂ expr c k_inc k_body) := prepend_load_expr expr (kernel.compute $ memory.update_assign n v[0] h h₂ expr) ;;
prepend_load_expr c (
kernel.loop (λ s, eval s c) (mclk_to_kernel k_body ;; append_load_expr c (mclk_to_kernel k_inc))
)
-- if a kernel does not contain a shared referencce it must not contain any loads
/- example (k : mclk sig) (h : ∀ n, is_shared (sig.val n) → ¬mclk_reads n k) : ∀ sk, subkernel sk (mclk_to_kernel k) → ¬∃ f, sk = (kernel.load f) := begin
intros sk hsk hl,
cases hl with f hl,
subst hl,
induction k,
{
rw mclk_to_kernel at hsk,
sorry,
}, {
rw mclk_to_kernel at hsk,
sorry,
}, {
rw mclk_to_kernel at hsk,
rw subkernel at hsk,
cases hsk,
{
sorry, -- trivial but cumbersome
}, {
cases hsk,
{
sorry,
}, {
cases hsk,
{
apply k_ih_a,
{
intros n hg hr,
apply h n hg,
unfold mclk_reads,
sorry,
}, {
assumption,
}
}, {
apply k_ih_a_1,
{
intros n hg hr,
apply h n hg,
sorry,
}, {
assumption,
}
}
}
}
}, {
sorry,
}, {
unfold mclk_to_kernel at hsk,
rw subkernel at hsk,
contradiction,
}
end -/
inductive mclp (sig : signature)
| intro (f : memory (parlang_mcl_shared sig) → ℕ) (k : mclk sig) : mclp
def mclp_to_program {sig : signature} : mclp sig → parlang.program (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)
| (mclp.intro f k) := parlang.program.intro f (mclk_to_kernel k)
def empty_state {sig : signature} : (memory $ parlang_mcl_tlocal sig) := λ var, default (type_map (type_of (sig.val var.1)))
-- we need an assumption on the signature, i.e. tid must be int
def mcl_init {sig : signature} : ℕ → (memory $ parlang_mcl_tlocal sig) := λ n : ℕ, empty_state.update ⟨"tid", begin rw sig.property.right.left, exact v[0] end⟩ (begin unfold parlang_mcl_tlocal signature.lean_type_of lean_type_of, rw sig.property.left, exact n end)
end mcl |
52e37d1e1438f0dbb30ae3aa61f95fdd4b531cc1 | 07c76fbd96ea1786cc6392fa834be62643cea420 | /hott/homotopy/circle.hlean | 4b903409d05db56fe021118997aba5365a1eb940 | [
"Apache-2.0"
] | permissive | fpvandoorn/lean2 | 5a430a153b570bf70dc8526d06f18fc000a60ad9 | 0889cf65b7b3cebfb8831b8731d89c2453dd1e9f | refs/heads/master | 1,592,036,508,364 | 1,545,093,958,000 | 1,545,093,958,000 | 75,436,854 | 0 | 0 | null | 1,480,718,780,000 | 1,480,718,780,000 | null | UTF-8 | Lean | false | false | 14,186 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
Declaration of the circle
-/
import .sphere
import types.int.hott
import algebra.homotopy_group .connectedness
open eq susp bool is_equiv equiv is_trunc is_conn pi algebra pointed
definition circle : Type₀ := sphere 1
namespace circle
notation `S¹` := circle
definition base1 : S¹ := !north
definition base2 : S¹ := !south
definition seg1 : base1 = base2 := merid ff
definition seg2 : base1 = base2 := merid tt
definition base : S¹ := base1
definition loop : base = base := seg2 ⬝ seg1⁻¹
definition rec2 {P : S¹ → Type} (Pb1 : P base1) (Pb2 : P base2)
(Ps1 : Pb1 =[seg1] Pb2) (Ps2 : Pb1 =[seg2] Pb2) (x : S¹) : P x :=
begin
induction x with b,
{ exact Pb1 },
{ exact Pb2 },
{ esimp at *, induction b with y,
{ exact Ps1 },
{ exact Ps2 }},
end
definition rec2_on [reducible] {P : S¹ → Type} (x : S¹) (Pb1 : P base1) (Pb2 : P base2)
(Ps1 : Pb1 =[seg1] Pb2) (Ps2 : Pb1 =[seg2] Pb2) : P x :=
circle.rec2 Pb1 Pb2 Ps1 Ps2 x
theorem rec2_seg1 {P : S¹ → Type} (Pb1 : P base1) (Pb2 : P base2)
(Ps1 : Pb1 =[seg1] Pb2) (Ps2 : Pb1 =[seg2] Pb2)
: apd (rec2 Pb1 Pb2 Ps1 Ps2) seg1 = Ps1 :=
!rec_merid
theorem rec2_seg2 {P : S¹ → Type} (Pb1 : P base1) (Pb2 : P base2)
(Ps1 : Pb1 =[seg1] Pb2) (Ps2 : Pb1 =[seg2] Pb2)
: apd (rec2 Pb1 Pb2 Ps1 Ps2) seg2 = Ps2 :=
!rec_merid
definition elim2 {P : Type} (Pb1 Pb2 : P) (Ps1 Ps2 : Pb1 = Pb2) (x : S¹) : P :=
rec2 Pb1 Pb2 (pathover_of_eq _ Ps1) (pathover_of_eq _ Ps2) x
definition elim2_on [reducible] {P : Type} (x : S¹) (Pb1 Pb2 : P)
(Ps1 : Pb1 = Pb2) (Ps2 : Pb1 = Pb2) : P :=
elim2 Pb1 Pb2 Ps1 Ps2 x
theorem elim2_seg1 {P : Type} (Pb1 Pb2 : P) (Ps1 : Pb1 = Pb2) (Ps2 : Pb1 = Pb2)
: ap (elim2 Pb1 Pb2 Ps1 Ps2) seg1 = Ps1 :=
begin
apply inj_inv !(pathover_constant seg1),
rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑elim2,rec2_seg1],
end
theorem elim2_seg2 {P : Type} (Pb1 Pb2 : P) (Ps1 : Pb1 = Pb2) (Ps2 : Pb1 = Pb2)
: ap (elim2 Pb1 Pb2 Ps1 Ps2) seg2 = Ps2 :=
begin
apply inj_inv !(pathover_constant seg2),
rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑elim2,rec2_seg2],
end
definition elim2_type (Pb1 Pb2 : Type) (Ps1 Ps2 : Pb1 ≃ Pb2) (x : S¹) : Type :=
elim2 Pb1 Pb2 (ua Ps1) (ua Ps2) x
definition elim2_type_on [reducible] (x : S¹) (Pb1 Pb2 : Type) (Ps1 Ps2 : Pb1 ≃ Pb2)
: Type :=
elim2_type Pb1 Pb2 Ps1 Ps2 x
theorem elim2_type_seg1 (Pb1 Pb2 : Type) (Ps1 Ps2 : Pb1 ≃ Pb2)
: transport (elim2_type Pb1 Pb2 Ps1 Ps2) seg1 = Ps1 :=
by rewrite [tr_eq_cast_ap_fn,↑elim2_type,elim2_seg1];apply cast_ua_fn
theorem elim2_type_seg2 (Pb1 Pb2 : Type) (Ps1 Ps2 : Pb1 ≃ Pb2)
: transport (elim2_type Pb1 Pb2 Ps1 Ps2) seg2 = Ps2 :=
by rewrite [tr_eq_cast_ap_fn,↑elim2_type,elim2_seg2];apply cast_ua_fn
protected definition rec {P : S¹ → Type} (Pbase : P base) (Ploop : Pbase =[loop] Pbase)
(x : S¹) : P x :=
begin
fapply (rec2_on x),
{ exact Pbase},
{ exact (transport P seg1 Pbase)},
{ apply pathover_tr},
{ apply pathover_tr_of_pathover, exact Ploop}
end
protected definition rec_on [reducible] {P : S¹ → Type} (x : S¹) (Pbase : P base)
(Ploop : Pbase =[loop] Pbase) : P x :=
circle.rec Pbase Ploop x
theorem rec_loop_helper {A : Type} (P : A → Type)
{x y z : A} {p : x = y} {p' : z = y} {u : P x} {v : P z} (q : u =[p ⬝ p'⁻¹] v) :
pathover_tr_of_pathover q ⬝o !pathover_tr⁻¹ᵒ = q :=
by cases p'; cases q; exact idp
theorem rec_loop {P : S¹ → Type} (Pbase : P base) (Ploop : Pbase =[loop] Pbase) :
apd (circle.rec Pbase Ploop) loop = Ploop :=
begin
rewrite [↑loop,apd_con,↑circle.rec,↑circle.rec2_on,↑base,rec2_seg2,apd_inv,rec2_seg1],
apply rec_loop_helper
end
protected definition elim {P : Type} (Pbase : P) (Ploop : Pbase = Pbase)
(x : S¹) : P :=
circle.rec Pbase (pathover_of_eq _ Ploop) x
protected definition elim_on [reducible] {P : Type} (x : S¹) (Pbase : P)
(Ploop : Pbase = Pbase) : P :=
circle.elim Pbase Ploop x
theorem elim_loop {P : Type} (Pbase : P) (Ploop : Pbase = Pbase) :
ap (circle.elim Pbase Ploop) loop = Ploop :=
begin
apply inj_inv !(pathover_constant loop),
rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑circle.elim,rec_loop],
end
theorem elim_seg1 {P : Type} (Pbase : P) (Ploop : Pbase = Pbase)
: ap (circle.elim Pbase Ploop) seg1 = (tr_constant seg1 Pbase)⁻¹ :=
begin
apply inj_inv !(pathover_constant seg1),
rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑circle.elim,↑circle.rec],
rewrite [↑circle.rec2_on,rec2_seg1], apply inverse,
apply pathover_of_eq_tr_constant_inv
end
theorem elim_seg2 {P : Type} (Pbase : P) (Ploop : Pbase = Pbase)
: ap (circle.elim Pbase Ploop) seg2 = Ploop ⬝ (tr_constant seg1 Pbase)⁻¹ :=
begin
apply inj_inv !(pathover_constant seg2),
rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑circle.elim,↑circle.rec],
rewrite [↑circle.rec2_on,rec2_seg2],
assert l : Π(A B : Type)(a a₂ a₂' : A)(b b' : B)(p : a = a₂)(p' : a₂' = a₂)
(q : b = b'),
pathover_tr_of_pathover (pathover_of_eq _ q)
= pathover_of_eq _ (q ⬝ (tr_constant p' b')⁻¹)
:> b =[p] p' ▸ b',
{ intros, cases q, cases p', cases p, reflexivity },
apply l
end
protected definition elim_type (Pbase : Type) (Ploop : Pbase ≃ Pbase)
(x : S¹) : Type :=
circle.elim Pbase (ua Ploop) x
protected definition elim_type_on [reducible] (x : S¹) (Pbase : Type)
(Ploop : Pbase ≃ Pbase) : Type :=
circle.elim_type Pbase Ploop x
theorem elim_type_loop_fn (Pbase : Type) (Ploop : Pbase ≃ Pbase) :
transport (circle.elim_type Pbase Ploop) loop = Ploop :=
by rewrite [tr_eq_cast_ap_fn,↑circle.elim_type,elim_loop];apply cast_ua_fn
theorem elim_type_loop (Pbase : Type) (Ploop : Pbase ≃ Pbase) (x : Pbase) :
transport (circle.elim_type Pbase Ploop) loop x = Ploop x :=
apd10 (elim_type_loop_fn Pbase Ploop) x
definition elim_type_loop_pathover (Pbase : Type) (Ploop : Pbase ≃ Pbase) (x : Pbase) :
x =[loop; circle.elim_type Pbase Ploop] Ploop x :=
pathover_of_tr_eq (elim_type_loop Pbase Ploop x)
theorem elim_type_loop_inv_fn (Pbase : Type) (Ploop : Pbase ≃ Pbase) :
transport (circle.elim_type Pbase Ploop) loop⁻¹ = to_inv Ploop :=
by rewrite [tr_inv_fn]; apply inv_eq_inv; apply elim_type_loop_fn
theorem elim_type_loop_inv (Pbase : Type) (Ploop : Pbase ≃ Pbase) (x : Pbase) :
transport (circle.elim_type Pbase Ploop) loop⁻¹ x = to_inv Ploop x :=
apd10 (elim_type_loop_inv_fn Pbase Ploop) x
end circle
attribute circle.base1 circle.base2 circle.base [constructor]
attribute circle.rec2 circle.elim2 [unfold 6] [recursor 6]
attribute circle.elim2_type [unfold 5]
attribute circle.rec2_on circle.elim2_on [unfold 2]
attribute circle.elim2_type [unfold 1]
attribute circle.rec circle.elim [unfold 4] [recursor 4]
attribute circle.elim_type [unfold 3]
attribute circle.rec_on circle.elim_on [unfold 2]
attribute circle.elim_type_on [unfold 1]
namespace circle
open sigma
/- universal property of the circle -/
definition circle_pi_equiv [constructor] (P : S¹ → Type)
: (Π(x : S¹), P x) ≃ Σ(p : P base), p =[loop] p :=
begin
fapply equiv.MK,
{ intro f, exact ⟨f base, apd f loop⟩},
{ intro v x, induction v with p q, induction x,
{ exact p},
{ exact q}},
{ intro v, induction v with p q, fapply sigma_eq,
{ reflexivity},
{ esimp, apply pathover_idp_of_eq, apply rec_loop}},
{ intro f, apply eq_of_homotopy, intro x, induction x,
{ reflexivity},
{ apply eq_pathover_dep, apply hdeg_squareover, esimp, apply rec_loop}}
end
definition circle_arrow_equiv [constructor] (P : Type)
: (S¹ → P) ≃ Σ(p : P), p = p :=
begin
fapply equiv.MK,
{ intro f, exact ⟨f base, ap f loop⟩},
{ intro v x, induction v with p q, induction x,
{ exact p},
{ exact q}},
{ intro v, induction v with p q, fapply sigma_eq,
{ reflexivity},
{ esimp, apply pathover_idp_of_eq, apply elim_loop}},
{ intro f, apply eq_of_homotopy, intro x, induction x,
{ reflexivity},
{ apply eq_pathover, apply hdeg_square, esimp, apply elim_loop}}
end
definition pointed_circle [instance] [constructor] : pointed S¹ :=
pointed.mk base
definition pcircle [constructor] : Type* := pointed.mk' S¹
notation `S¹*` := pcircle
definition loop_neq_idp : loop ≠ idp :=
assume H : loop = idp,
have H2 : Π{A : Type₁} {a : A} {p : a = a}, p = idp,
from λA a p, calc
p = ap (circle.elim a p) loop : elim_loop
... = ap (circle.elim a p) (refl base) : by rewrite H,
eq_bnot_ne_idp H2
definition circle_turn [reducible] (x : S¹) : x = x :=
begin
induction x,
{ exact loop },
{ apply eq_pathover, apply square_of_eq, rewrite ap_id }
end
definition turn_neq_idp : circle_turn ≠ (λx, idp) :=
assume H : circle_turn = λx, idp,
have H2 : loop = idp, from apd10 H base,
absurd H2 loop_neq_idp
open int
protected definition code [unfold 1] (x : S¹) : Type₀ :=
circle.elim_type_on x ℤ equiv_succ
definition transport_code_loop (a : ℤ) : transport circle.code loop a = succ a :=
!elim_type_loop
definition transport_code_loop_inv (a : ℤ) : transport circle.code loop⁻¹ a = pred a :=
!elim_type_loop_inv
protected definition encode [unfold 2] {x : S¹} (p : base = x) : circle.code x :=
transport circle.code p (0 : ℤ)
protected definition decode [unfold 1] {x : S¹} : circle.code x → base = x :=
begin
induction x,
{ exact power loop},
{ apply arrow_pathover_left, intro b, apply eq_pathover_constant_left_id_right,
apply square_of_eq, rewrite [idp_con, power_con,transport_code_loop]}
end
definition circle_eq_equiv [constructor] (x : S¹) : (base = x) ≃ circle.code x :=
begin
fapply equiv.MK,
{ exact circle.encode},
{ exact circle.decode},
{ exact abstract [irreducible] begin
induction x,
{ intro a, esimp, apply rec_nat_on a,
{ exact idp},
{ intros n p, rewrite [↑circle.encode, -power_con, con_tr, transport_code_loop],
exact ap succ p},
{ intros n p, rewrite [↑circle.encode, nat_succ_eq_int_succ, neg_succ, -power_con_inv,
@con_tr _ circle.code, transport_code_loop_inv, ↑[circle.encode] at p, p, -neg_succ] }},
{ apply pathover_of_tr_eq, apply eq_of_homotopy, intro a, apply @is_set.elim,
esimp, exact _} end end},
{ intro p, cases p, exact idp},
end
definition base_eq_base_equiv [constructor] : base = base ≃ ℤ :=
circle_eq_equiv base
definition decode_add (a b : ℤ) : circle.decode (a +[ℤ] b) = circle.decode a ⬝ circle.decode b :=
!power_con_power⁻¹
definition encode_con (p q : base = base)
: circle.encode (p ⬝ q) = circle.encode p +[ℤ] circle.encode q :=
preserve_binary_of_inv_preserve base_eq_base_equiv concat (@add ℤ _) decode_add p q
--the carrier of π₁(S¹) is the set-truncation of base = base.
open algebra trunc group
definition fg_carrier_equiv_int : π[1](S¹*) ≃ ℤ :=
trunc_equiv_trunc 0 base_eq_base_equiv ⬝e @(trunc_equiv 0 ℤ) proof _ qed
definition con_comm_base (p q : base = base) : p ⬝ q = q ⬝ p :=
inj base_eq_base_equiv (by esimp;rewrite [+encode_con,add.comm])
definition fundamental_group_of_circle : π₁(S¹*) ≃g gℤ :=
begin
apply (isomorphism_of_equiv fg_carrier_equiv_int),
intros g h,
induction g with g', induction h with h',
apply encode_con,
end
open nat
definition homotopy_group_of_circle (n : ℕ) : πg[n+2] S¹* ≃g G0 :=
begin
refine @trivial_homotopy_add_of_is_set_loopn 1 n S¹* _,
exact is_trunc_equiv_closed_rev _ base_eq_base_equiv _
end
definition eq_equiv_Z (x : S¹) : x = x ≃ ℤ :=
begin
induction x,
{ apply base_eq_base_equiv},
{ apply equiv_pathover2, intro p p' q, apply pathover_of_eq,
note H := eq_of_square (square_of_pathover q),
rewrite con_comm_base at H,
note H' := cancel_left _ H,
induction H', reflexivity}
end
proposition is_trunc_circle [instance] : is_trunc 1 S¹ :=
begin
apply is_trunc_succ_of_is_trunc_loop,
{ apply trunc_index.minus_one_le_succ },
{ intro x, exact is_trunc_equiv_closed_rev 0 !eq_equiv_Z _ }
end
proposition is_conn_circle [instance] : is_conn 0 S¹ :=
sphere.is_conn_sphere 1
definition is_conn_pcircle [instance] : is_conn 0 S¹* := !is_conn_circle
definition is_trunc_pcircle [instance] : is_trunc 1 S¹* := !is_trunc_circle
definition circle_mul [reducible] (x y : S¹) : S¹ :=
circle.elim y (circle_turn y) x
definition circle_mul_base (x : S¹) : circle_mul x base = x :=
begin
induction x,
{ reflexivity },
{ apply eq_pathover_id_right, apply hdeg_square, apply elim_loop }
end
definition circle_base_mul [reducible] (x : S¹) : circle_mul base x = x :=
idp
/-
Suppose for `f, g : A -> B` we prove a homotopy `H : f ~ g` by induction on the element in `A`.
And suppose `p : a = a'` is a path constructor in `A`.
Then `natural_square_tr H p` has type `square (H a) (H a') (ap f p) (ap g p)` and is equal
to the square which defined H on the path constructor
-/
definition natural_square_elim_loop {A : Type} {f g : S¹ → A} (p : f base = g base)
(q : square p p (ap f loop) (ap g loop))
: natural_square (circle.rec p (eq_pathover q)) loop = q :=
begin
refine ap square_of_pathover !rec_loop ⬝ _,
exact to_right_inv !eq_pathover_equiv_square q
end
definition circle_elim_constant [unfold 5] {A : Type} {a : A} {p : a = a} (r : p = idp) (x : S¹) :
circle.elim a p x = a :=
begin
induction x,
{ reflexivity },
{ apply eq_pathover_constant_right, apply hdeg_square, exact !elim_loop ⬝ r }
end
end circle
|
bc640ade5f2c228e805dd4f62352be3cb873f993 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/omega/prove_unsats.lean | c9cf94d89b524de7143289aa37dbdd5692192b99 | [] | 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 | 648 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.omega.find_ees
import Mathlib.tactic.omega.find_scalars
import Mathlib.tactic.omega.lin_comb
import Mathlib.PostPort
namespace Mathlib
/-
A tactic which constructs exprs to discharge
goals of the form `clauses.unsat cs`.
-/
namespace omega
/-- Return expr of proof that given int is negative -/
theorem forall_mem_repeat_zero_eq_zero (m : ℕ) (x : ℤ) (H : x ∈ list.repeat 0 m) : x = 0 :=
list.eq_of_mem_repeat
|
854a497002cfbf7b22a85d7191f67882c97ce396 | 3dc4623269159d02a444fe898d33e8c7e7e9461b | /.github/workflows/geo/test.lean | 4d1e63dcdc73146091594764fa7661a05cf4342b | [] | no_license | Or7ando/lean | cc003e6c41048eae7c34aa6bada51c9e9add9e66 | d41169cf4e416a0d42092fb6bdc14131cee9dd15 | refs/heads/master | 1,650,600,589,722 | 1,587,262,906,000 | 1,587,262,906,000 | 255,387,160 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 26 | lean | import algebra.archimedean |
359e55d070714eb0c075249adddc3dc9d308c4b0 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /doc/examples/NFM2022/nfm14.lean | 79569fddf6600eac57cf800d291a4bd53a602f1e | [
"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 | 592 | lean | /- Tactics -/
example : p → q → p ∧ q ∧ p := by
intro hp hq
apply And.intro
exact hp
apply And.intro
exact hq
exact hp
example : p → q → p ∧ q ∧ p := by
intro hp hq; apply And.intro hp; exact And.intro hq hp
/- Structuring proofs -/
example : p → q → p ∧ q ∧ p := by
intro hp hq
apply And.intro
case left => exact hp
case right =>
apply And.intro
case left => exact hq
case right => exact hp
example : p → q → p ∧ q ∧ p := by
intro hp hq
apply And.intro
. exact hp
. apply And.intro
. exact hq
. exact hp
|
fa175ecaef67d1f4c4a41a7c4ae6af5a100bd20b | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/analysis/special_functions/exp_log.lean | ec0a2410d4b57df40516179f0f5d99e60b2975de | [
"Apache-2.0"
] | permissive | anthony2698/mathlib | 03cd69fe5c280b0916f6df2d07c614c8e1efe890 | 407615e05814e98b24b2ff322b14e8e3eb5e5d67 | refs/heads/master | 1,678,792,774,873 | 1,614,371,563,000 | 1,614,371,563,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 34,494 | 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 data.complex.exponential
import analysis.calculus.inverse
import measure_theory.borel_space
import analysis.complex.real_deriv
/-!
# 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
lemma measurable_re : measurable re := continuous_re.measurable
lemma measurable_im : measurable im := continuous_im.measurable
lemma measurable_of_real : measurable (coe : ℝ → ℂ) := continuous_of_real.measurable
/-- 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]
lemma continuous_exp : continuous exp :=
differentiable_exp.continuous
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
lemma measurable_exp : measurable exp := continuous_exp.measurable
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 measurable.cexp {α : Type*} [measurable_space α] {f : α → ℂ} (hf : measurable f) :
measurable (λ x, complex.exp (f x)) :=
complex.measurable_exp.comp hf
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]
lemma continuous_exp : continuous exp :=
differentiable_exp.continuous
lemma measurable_exp : measurable exp := continuous_exp.measurable
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 measurable.exp {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) :
measurable (λ x, real.exp (f x)) :=
real.measurable_exp.comp hf
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
/-- 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
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 $ mem_nhds_sets 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 measurable_log : measurable log :=
measurable_of_measurable_on_compl_singleton 0 $ continuous.measurable $
continuous_on_iff_continuous_restrict.1 continuous_on_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 $
mem_nhds_sets 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 measurable.log {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) :
measurable (λ x, log (f x)) :=
measurable_log.comp hf
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 ≤ (nat_ceil x) ^ n : pow_le_pow_of_le_left hx₀.le (le_nat_ceil _) _
... ≤ exp (nat_ceil 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.inv_tendsto_at_top (tendsto_mul_exp_add_div_pow_at_top b' c' n h hn),
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
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_series_def, geom_sum (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
|
f23543eea7fd7df0b126d20e44fc7c0457cd1f56 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /library/system/io.lean | a549789d956462d85a741780dc74d6d3257a8929 | [
"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 | 7,187 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Luke Nelson, Jared Roesch and Leonardo de Moura
-/
import data.buffer
inductive io.error
| other : string → io.error
| sys : nat → io.error
structure io.terminal (m : Type → Type → Type) :=
(put_str : string → m io.error unit)
(get_line : m io.error string)
(cmdline_args : list string)
inductive io.mode
| read | write | read_write | append
structure io.file_system (handle : Type) (m : Type → Type → Type) :=
/- Remark: in Haskell, they also provide (Maybe TextEncoding) and NewlineMode -/
(mk_file_handle : string → io.mode → bool → m io.error handle)
(is_eof : handle → m io.error bool)
(flush : handle → m io.error unit)
(close : handle → m io.error unit)
(read : handle → nat → m io.error char_buffer)
(write : handle → char_buffer → m io.error unit)
(get_line : handle → m io.error char_buffer)
(stdin : m io.error handle)
(stdout : m io.error handle)
(stderr : m io.error handle)
structure io.environment (m : Type → Type → Type) :=
(get_env : string → m io.error (option string))
-- we don't provide set_env as it is (thread-)unsafe (at least with glibc)
inductive io.process.stdio
| piped
| inherit
| null
structure io.process.spawn_args :=
/- Command name. -/
(cmd : string)
/- Arguments for the process -/
(args : list string := [])
/- Configuration for the process' stdin handle. -/
(stdin := stdio.inherit)
/- Configuration for the process' stdout handle. -/
(stdout := stdio.inherit)
/- Configuration for the process' stderr handle. -/
(stderr := stdio.inherit)
/- Working directory for the process. -/
(cwd : option string := none)
/- Environment variables for the process. -/
(env : list (string × option string) := [])
structure io.process (handle : Type) (m : Type → Type → Type) :=
(child : Type) (stdin : child → handle) (stdout : child → handle) (stderr : child → handle)
(spawn : io.process.spawn_args → m io.error child)
(wait : child → m io.error nat)
class io.interface :=
(m : Type → Type → Type)
(monad : Π e, monad (m e))
(catch : Π e₁ e₂ α, m e₁ α → (e₁ → m e₂ α) → m e₂ α)
(fail : Π e α, e → m e α)
(iterate : Π e α, α → (α → m e (option α)) → m e α)
-- Primitive Types
(handle : Type)
-- Interface Extensions
(term : io.terminal m)
(fs : io.file_system handle m)
(process : io.process handle m)
(env : io.environment m)
variable [ioi : io.interface]
include ioi
def io_core (e : Type) (α : Type) :=
io.interface.m e α
@[reducible] def io (α : Type) :=
io_core io.error α
instance io_core_is_monad (e : Type) : monad (io_core e) :=
io.interface.monad e
protected def io.fail {α : Type} (s : string) : io α :=
io.interface.fail io.error α (io.error.other s)
instance : monad_fail io :=
{ io_core_is_monad io.error with
fail := @io.fail _ }
namespace io
def iterate {e α} (a : α) (f : α → io_core e (option α)) : io_core e α :=
interface.iterate e α a f
def forever {e} (a : io_core e unit) : io_core e unit :=
iterate () $ λ _, a >> return (some ())
def catch {e₁ e₂ α} (a : io_core e₁ α) (b : e₁ → io_core e₂ α) : io_core e₂ α :=
interface.catch e₁ e₂ α a b
def finally {α e} (a : io_core e α) (cleanup : io_core e unit) : io_core e α := do
res ← catch (sum.inr <$> a) (return ∘ sum.inl),
cleanup,
match res with
| sum.inr res := return res
| sum.inl error := io.interface.fail _ _ error
end
instance : alternative io :=
{ interface.monad _ with
orelse := λ _ a b, catch a (λ _, b),
failure := λ _, io.fail "failure" }
def put_str : string → io unit :=
interface.term.put_str
def put_str_ln (s : string) : io unit :=
put_str s >> put_str "\n"
def get_line : io string :=
interface.term.get_line
def cmdline_args : io (list string) :=
return interface.term.cmdline_args
def print {α} [has_to_string α] (s : α) : io unit :=
put_str ∘ to_string $ s
def print_ln {α} [has_to_string α] (s : α) : io unit :=
print s >> put_str "\n"
def handle : Type :=
interface.handle
def mk_file_handle (s : string) (m : mode) (bin : bool := ff) : io handle :=
interface.fs.mk_file_handle s m bin
def stdin : io handle :=
interface.fs.stdin
def stderr : io handle :=
interface.fs.stderr
def stdout : io handle :=
interface.fs.stdout
namespace env
def get (env_var : string) : io (option string) :=
interface.env.get_env env_var
end env
namespace fs
def is_eof : handle → io bool :=
interface.fs.is_eof
def flush : handle → io unit :=
interface.fs.flush
def close : handle → io unit :=
interface.fs.close
def read : handle → nat → io char_buffer :=
interface.fs.read
def write : handle → char_buffer → io unit :=
interface.fs.write
def get_char (h : handle) : io char :=
do b ← read h 1,
if h : b.size = 1 then return $ b.read ⟨0, h.symm ▸ zero_lt_one⟩
else io.fail "get_char failed"
def get_line : handle → io char_buffer :=
interface.fs.get_line
def put_char (h : handle) (c : char) : io unit :=
write h (mk_buffer.push_back c)
def put_str (h : handle) (s : string) : io unit :=
write h (mk_buffer.append_string s)
def put_str_ln (h : handle) (s : string) : io unit :=
put_str h s >> put_str h "\n"
def read_to_end (h : handle) : io char_buffer :=
iterate mk_buffer $ λ r,
do done ← is_eof h,
if done
then return none
else do
c ← read h 1024,
return $ some (r ++ c)
def read_file (s : string) (bin := ff) : io char_buffer :=
do h ← mk_file_handle s io.mode.read bin,
read_to_end h
end fs
namespace proc
def child : Type := interface.process.child
def child.stdin : child → handle := interface.process.stdin
def child.stdout : child → handle := interface.process.stdout
def child.stderr : child → handle := interface.process.stderr
def spawn (p : io.process.spawn_args) : io child := interface.process.spawn p
def wait (c : child) : io nat := interface.process.wait c
end proc
end io
meta constant format.print_using : format → options → io unit
meta definition format.print (fmt : format) : io unit :=
format.print_using fmt options.mk
meta definition pp_using {α : Type} [has_to_format α] (a : α) (o : options) : io unit :=
format.print_using (to_fmt a) o
meta definition pp {α : Type} [has_to_format α] (a : α) : io unit :=
format.print (to_fmt a)
/-- Run the external process specified by `args`.
The process will run to completion with its output captured by a pipe, and
read into `string` which is then returned.
-/
def io.cmd (args : io.process.spawn_args) : io string :=
do child ← io.proc.spawn { args with stdout := io.process.stdio.piped },
buf ← io.fs.read_to_end child.stdout,
exitv ← io.proc.wait child,
when (exitv ≠ 0) $ io.fail $ "process exited with status " ++ repr exitv,
return buf.to_string
omit ioi
/-- Lift a monadic `io` action into the `tactic` monad. -/
meta constant tactic.run_io {α : Type} : (Π ioi : io.interface, @io ioi α) → tactic α
|
08c88d905b662c4790d17b0807861d53d404fa12 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Control/Conditional.lean | db00e32cddc1e1b052d72d8dbd4f8919f1da0460 | [
"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 | 1,066 | 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.Control.Monad
import Init.Data.Option.Basic
universes u v
class HasToBool (α : Type u) :=
(toBool : α → Bool)
export HasToBool (toBool)
instance : HasToBool Bool := ⟨id⟩
instance {α} : HasToBool (Option α) := ⟨Option.toBool⟩
@[macroInline] def bool {β : Type u} {α : Type v} [HasToBool β] (f t : α) (b : β) : α :=
match toBool b with
| true => t
| false => f
@[macroInline] def orM {m : Type u → Type v} {β : Type u} [Monad m] [HasToBool β] (x y : m β) : m β := do
b ← x;
match toBool b with
| true => pure b
| false => y
@[macroInline] def andM {m : Type u → Type v} {β : Type u} [Monad m] [HasToBool β] (x y : m β) : m β := do
b ← x;
match toBool b with
| true => y
| false => pure b
infixl ` <||> `:30 := orM
infixl ` <&&> `:35 := andM
@[macroInline] def notM {m : Type → Type v} [Applicative m] (x : m Bool) : m Bool :=
not <$> x
|
009599c39841f8dccdd461dd31c6211d925893e0 | 1a61aba1b67cddccce19532a9596efe44be4285f | /hott/hit/pushout.hlean | ce380b9f37196a24c93670139a328770eb0dfc50 | [
"Apache-2.0"
] | permissive | eigengrau/lean | 07986a0f2548688c13ba36231f6cdbee82abf4c6 | f8a773be1112015e2d232661ce616d23f12874d0 | refs/heads/master | 1,610,939,198,566 | 1,441,352,386,000 | 1,441,352,494,000 | 41,903,576 | 0 | 0 | null | 1,441,352,210,000 | 1,441,352,210,000 | null | UTF-8 | Lean | false | false | 3,246 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
Declaration of the pushout
-/
import .quotient
open quotient eq sum equiv equiv.ops
namespace pushout
section
parameters {TL BL TR : Type} (f : TL → BL) (g : TL → TR)
local abbreviation A := BL + TR
inductive pushout_rel : A → A → Type :=
| Rmk : Π(x : TL), pushout_rel (inl (f x)) (inr (g x))
open pushout_rel
local abbreviation R := pushout_rel
definition pushout : Type := quotient R -- TODO: define this in root namespace
definition inl (x : BL) : pushout :=
class_of R (inl x)
definition inr (x : TR) : pushout :=
class_of R (inr x)
definition glue (x : TL) : inl (f x) = inr (g x) :=
eq_of_rel pushout_rel (Rmk f g x)
protected definition rec {P : pushout → Type} (Pinl : Π(x : BL), P (inl x))
(Pinr : Π(x : TR), P (inr x)) (Pglue : Π(x : TL), Pinl (f x) =[glue x] Pinr (g x))
(y : pushout) : P y :=
begin
induction y,
{ cases a,
apply Pinl,
apply Pinr},
{ cases H, apply Pglue}
end
protected definition rec_on [reducible] {P : pushout → Type} (y : pushout)
(Pinl : Π(x : BL), P (inl x)) (Pinr : Π(x : TR), P (inr x))
(Pglue : Π(x : TL), Pinl (f x) =[glue x] Pinr (g x)) : P y :=
rec Pinl Pinr Pglue y
theorem rec_glue {P : pushout → Type} (Pinl : Π(x : BL), P (inl x))
(Pinr : Π(x : TR), P (inr x)) (Pglue : Π(x : TL), Pinl (f x) =[glue x] Pinr (g x))
(x : TL) : apdo (rec Pinl Pinr Pglue) (glue x) = Pglue x :=
!rec_eq_of_rel
protected definition elim {P : Type} (Pinl : BL → P) (Pinr : TR → P)
(Pglue : Π(x : TL), Pinl (f x) = Pinr (g x)) (y : pushout) : P :=
rec Pinl Pinr (λx, pathover_of_eq (Pglue x)) y
protected definition elim_on [reducible] {P : Type} (y : pushout) (Pinl : BL → P)
(Pinr : TR → P) (Pglue : Π(x : TL), Pinl (f x) = Pinr (g x)) : P :=
elim Pinl Pinr Pglue y
theorem elim_glue {P : Type} (Pinl : BL → P) (Pinr : TR → P)
(Pglue : Π(x : TL), Pinl (f x) = Pinr (g x)) (x : TL)
: ap (elim Pinl Pinr Pglue) (glue x) = Pglue x :=
begin
apply eq_of_fn_eq_fn_inv !(pathover_constant (glue x)),
rewrite [▸*,-apdo_eq_pathover_of_eq_ap,↑pushout.elim,rec_glue],
end
protected definition elim_type (Pinl : BL → Type) (Pinr : TR → Type)
(Pglue : Π(x : TL), Pinl (f x) ≃ Pinr (g x)) (y : pushout) : Type :=
elim Pinl Pinr (λx, ua (Pglue x)) y
protected definition elim_type_on [reducible] (y : pushout) (Pinl : BL → Type)
(Pinr : TR → Type) (Pglue : Π(x : TL), Pinl (f x) ≃ Pinr (g x)) : Type :=
elim_type Pinl Pinr Pglue y
theorem elim_type_glue (Pinl : BL → Type) (Pinr : TR → Type)
(Pglue : Π(x : TL), Pinl (f x) ≃ Pinr (g x)) (x : TL)
: transport (elim_type Pinl Pinr Pglue) (glue x) = Pglue x :=
by rewrite [tr_eq_cast_ap_fn,↑elim_type,elim_glue];apply cast_ua_fn
end
end pushout
attribute pushout.inl pushout.inr [constructor]
attribute pushout.rec pushout.elim [unfold 10] [recursor 10]
attribute pushout.elim_type [unfold 9]
attribute pushout.rec_on pushout.elim_on [unfold 7]
attribute pushout.elim_type_on [unfold 6]
|
12bbe7f89fb17e50b80340c61d85091631a4c8de | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/nat/choose/cast.lean | d89a3b10422c133282f4d25ab15f707365d27b94 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 1,600 | lean | /-
Copyright (c) 2021 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.nat.choose.basic
import data.nat.factorial.cast
/-!
# Cast of binomial coefficients
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file allows calculating the binomial coefficient `a.choose b` as an element of a division ring
of characteristic `0`.
-/
open_locale nat
variables (K : Type*) [division_ring K] [char_zero K]
namespace nat
lemma cast_choose {a b : ℕ} (h : a ≤ b) :
(b.choose a : K) = b! / (a! * (b - a)!) :=
begin
have : ∀ {n : ℕ}, (n! : K) ≠ 0 := λ n, nat.cast_ne_zero.2 (factorial_ne_zero _),
rw eq_div_iff_mul_eq (mul_ne_zero this this),
rw_mod_cast [← mul_assoc, choose_mul_factorial_mul_factorial h],
end
lemma cast_add_choose {a b : ℕ} :
((a + b).choose a : K) = (a + b)! / (a! * b!) :=
by rw [cast_choose K (le_add_right le_rfl), add_tsub_cancel_left]
lemma cast_choose_eq_pochhammer_div (a b : ℕ) :
(a.choose b : K) = (pochhammer K b).eval (a - (b - 1) : ℕ) / b! :=
by rw [eq_div_iff_mul_eq (nat.cast_ne_zero.2 b.factorial_ne_zero : (b! : K) ≠ 0),
←nat.cast_mul, mul_comm, ←nat.desc_factorial_eq_factorial_mul_choose, ←cast_desc_factorial]
lemma cast_choose_two (a : ℕ) :
(a.choose 2 : K) = a * (a - 1) / 2 :=
by rw [←cast_desc_factorial_two, desc_factorial_eq_factorial_mul_choose, factorial_two, mul_comm,
cast_mul, cast_two, eq_div_iff_mul_eq (two_ne_zero : (2 : K) ≠ 0)]
end nat
|
3a247933966a43741e92cf84250f17afd67413bb | 4fa118f6209450d4e8d058790e2967337811b2b5 | /src/for_mathlib/equiv.lean | e2fc194e18191078570a95ecb5da194edc3b5dff | [
"Apache-2.0"
] | permissive | leanprover-community/lean-perfectoid-spaces | 16ab697a220ed3669bf76311daa8c466382207f7 | 95a6520ce578b30a80b4c36e36ab2d559a842690 | refs/heads/master | 1,639,557,829,139 | 1,638,797,866,000 | 1,638,797,866,000 | 135,769,296 | 96 | 10 | Apache-2.0 | 1,638,797,866,000 | 1,527,892,754,000 | Lean | UTF-8 | Lean | false | false | 4,391 | lean | import data.equiv.basic algebra.group
import order.basic logic.basic -- needed for order stuff
import for_mathlib.with_zero
import data.equiv.algebra
def equiv.with_zero_equiv {α β : Type*} (h : α ≃ β) : (with_zero α) ≃ (with_zero β) :=
{ to_fun := with_zero.map h,
inv_fun := with_zero.map h.symm,
left_inv := λ x, begin cases x, refl, show some _ = some _, congr, exact h.left_inv x end,
right_inv := λ x, begin cases x, refl, show some _ = some _, congr, exact h.right_inv x end,
}
variables {α : Type*} {β : Type*} {γ : Type*}
namespace mul_equiv
variables [monoid α] [monoid β] [monoid γ]
def to_with_zero_mul_equiv (h : α ≃* β) : (with_zero α) ≃* (with_zero β) :=
{ map_mul' := λ x y,
begin cases x; cases y; try { refl},
show some _ = some _, congr, exact @is_mul_hom.map_mul _ _ _ _ h _ x y
end,
..h.to_equiv.with_zero_equiv }
end mul_equiv
-- from here on -- should this go in data.equiv.order?
structure le_equiv (α β : Type*) [has_le α] [has_le β] extends α ≃ β :=
(le_map : ∀ ⦃x y⦄, x ≤ y ↔ to_fun x ≤ to_fun y)
infix ` ≃≤ `:50 := le_equiv
namespace le_equiv
variables (X : Type*) [has_le X] (Y : Type*) [has_le Y] (Z : Type*) [has_le Z]
variables {X} {Y} {Z}
@[refl] def refl (X : Type*) [has_le X] : X ≃≤ X :=
{ le_map := λ _ _, iff.rfl,
..equiv.refl _}
@[symm] def symm (h : X ≃≤ Y) : Y ≃≤ X :=
{ le_map := λ x₁ x₂, begin
convert (@le_equiv.le_map _ _ _ _ h (h.to_equiv.symm x₁) (h.to_equiv.symm x₂)).symm,
exact (h.right_inv x₁).symm, exact (h.right_inv x₂).symm end,
..h.to_equiv.symm
}
@[trans] def trans (h1 : X ≃≤ Y) (h2 : Y ≃≤ Z) : X ≃≤ Z :=
{ le_map := λ x₁ x₂, iff.trans (@le_equiv.le_map _ _ _ _ h1 x₁ x₂)
(@le_equiv.le_map _ _ _ _ h2 (h1.to_fun x₁) (h1.to_fun x₂)),
..equiv.trans h1.to_equiv h2.to_equiv
}
end le_equiv
def preorder_equiv (α β : Type*) [preorder α] [preorder β] := le_equiv α β
structure lt_equiv (α β : Type*) [has_lt α] [has_lt β] extends α ≃ β :=
(lt_map : ∀ ⦃x y⦄, x < y ↔ to_fun x < to_fun y)
infix ` ≃< `:50 := lt_equiv
-- iff for ordering -- is this in mathlib?
def linear_order_le_iff_of_monotone_injective {α : Type*} {β : Type*}
[linear_order α] [linear_order β] {f : α → β}
(hf : function.injective f)
(h2 : ∀ x y, x ≤ y → f x ≤ f y)
: ∀ x y, x ≤ y ↔ f x ≤ f y :=
λ x y, ⟨h2 x y, λ h3, le_of_not_lt $ λ h4, not_lt_of_le h3 $ lt_of_le_of_ne
(h2 y x $ le_of_lt h4) $ λ h5, ne_of_lt h4 $ hf h5⟩
namespace preorder_equiv
variables [preorder α] [preorder β] [preorder γ]
@[refl] def refl (α : Type*) [preorder α] : α ≃≤ α :=
{ le_map := λ _ _, iff.rfl,
..equiv.refl _}
@[symm] def symm (h : α ≃≤ β) : β ≃≤ α :=
{ le_map := λ x y, begin
convert (@le_equiv.le_map _ _ _ _ h (h.to_equiv.symm x) (h.to_equiv.symm y)).symm,
{ exact (h.right_inv x).symm},
{ exact (h.right_inv y).symm},
end
..h.to_equiv.symm}
@[trans] def trans (h1 : α ≃≤ β) (h2 : β ≃≤ γ) : (α ≃≤ γ) :=
{ le_map := λ x y,
iff.trans (@le_equiv.le_map _ _ _ _ h1 x y)
(@le_equiv.le_map _ _ _ _ h2 (h1.to_equiv x) (h1.to_equiv y)),
..equiv.trans h1.to_equiv h2.to_equiv }
end preorder_equiv
def equiv.lt_map_of_le_map {α : Type*} {β : Type*} [preorder α] [preorder β]
(he : α ≃ β) (hle : ∀ x y, x ≤ y ↔ he x ≤ he y) : (∀ x y, x < y ↔ he x < he y) :=
λ x y, by rw [lt_iff_le_not_le, hle x y, hle y x, lt_iff_le_not_le]
def equiv.le_map_iff_lt_map {α : Type*} {β : Type*} [partial_order α] [partial_order β]
(he : α ≃ β) : (∀ x y, x ≤ y ↔ he x ≤ he y) ↔ (∀ x y, x < y ↔ he x < he y) :=
⟨equiv.lt_map_of_le_map he, λ hlt x y, by rw [le_iff_eq_or_lt, le_iff_eq_or_lt];
exact or_congr (by simp) (hlt x y)⟩
def preorder_equiv.to_lt_equiv {α : Type*} {β : Type*} [preorder α] [preorder β]
(he : α ≃≤ β) : α ≃< β := {lt_map := he.to_equiv.lt_map_of_le_map he.le_map
..he.to_equiv}
def preorder_equiv.to_with_zero_preorder_equiv {α : Type*} {β : Type*} [preorder α] [preorder β]
(he : α ≃≤ β) : (with_zero α) ≃≤ (with_zero β) :=
{ le_map := with_zero.map_le he.le_map
..he.to_equiv.with_zero_equiv}
-- equiv of top spaces is already done -- it's called homeomorph in topology/constructions.lean
|
3ffaebf58ae30317ac1e1e73c219d10ae4a5ee7b | 78269ad0b3c342b20786f60690708b6e328132b0 | /src/library_dev/data/nat/gcd.lean | f9483292d73ade38409f7cee0a1119b3219339f5 | [] | 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 | 12,310 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
Definitions and properties of gcd, lcm, and coprime.
-/
import .dvd
open well_founded decidable prod
namespace nat
/- gcd -/
def gcd.F : Π (y : ℕ), (Π (y' : ℕ), y' < y → nat → nat) → nat → nat
| 0 f x := x
| (succ y) f x := f (x % succ y) (mod_lt _ $ succ_pos _) (succ y)
def gcd (x y : nat) := fix lt_wf gcd.F y x
@[simp] theorem gcd_zero_right (x : nat) : gcd x 0 = x := congr_fun (fix_eq lt_wf gcd.F 0) x
@[simp] theorem gcd_succ (x y : nat) : gcd x (succ y) = gcd (succ y) (x % succ y) :=
congr_fun (fix_eq lt_wf gcd.F (succ y)) x
theorem gcd_one_right (n : ℕ) : gcd n 1 = 1 :=
eq.trans (gcd_succ n 0) (by rw [mod_one, gcd_zero_right])
theorem gcd_def (x : ℕ) : Π (y : ℕ), gcd x y = if y = 0 then x else gcd y (x % y)
| 0 := gcd_zero_right _
| (succ y) := (gcd_succ x y).trans (if_neg (succ_ne_zero y)).symm
theorem gcd_self : Π (n : ℕ), gcd n n = n
| 0 := gcd_zero_right _
| (succ n₁) := (gcd_succ (succ n₁) n₁).trans (by rw [mod_self, gcd_zero_right])
theorem gcd_zero_left : Π (n : ℕ), gcd 0 n = n
| 0 := gcd_zero_right _
| (succ n₁) := (gcd_succ 0 n₁).trans (by rw [zero_mod, gcd_zero_right])
theorem gcd_rec (m : ℕ) : Π (n : ℕ), gcd m n = gcd n (m % n)
| 0 := by rw [mod_zero, gcd_zero_left, gcd_zero_right]
| (succ n₁) := gcd_succ _ _
@[elab_as_eliminator]
theorem gcd.induction {P : ℕ → ℕ → Prop}
(m n : ℕ)
(H0 : ∀m, P m 0)
(H1 : ∀m n, 0 < n → P n (m % n) → P m n) :
P m n :=
@induction _ _ lt_wf (λn, ∀m, P m n) n (λk IH,
by {induction k with k ih, exact H0,
exact λm, H1 _ _ (succ_pos _) (IH _ (mod_lt _ (succ_pos _)) _)}) m
theorem gcd_dvd (m n : ℕ) : (gcd m n ∣ m) ∧ (gcd m n ∣ n) :=
gcd.induction m n
(λm, by rw gcd_zero_right; exact ⟨dvd_refl m, dvd_zero m⟩)
(λm n npos, by rw -gcd_rec; exact λ ⟨IH₁, IH₂⟩, ⟨(dvd_mod_iff IH₁).1 IH₂, IH₁⟩)
theorem gcd_dvd_left (m n : ℕ) : gcd m n ∣ m := (gcd_dvd m n).left
theorem gcd_dvd_right (m n : ℕ) : gcd m n ∣ n := (gcd_dvd m n).right
theorem dvd_gcd {m n k : ℕ} : k ∣ m → k ∣ n → k ∣ gcd m n :=
gcd.induction m n (λm km _, by rw gcd_zero_right; exact km)
(λm n npos IH H1 H2, by rw gcd_rec; exact IH H2 ((dvd_mod_iff H2).2 H1))
theorem gcd_comm (m n : ℕ) : gcd m n = gcd n m :=
dvd.antisymm
(dvd_gcd (gcd_dvd_right m n) (gcd_dvd_left m n))
(dvd_gcd (gcd_dvd_right n m) (gcd_dvd_left n m))
theorem gcd_assoc (m n k : ℕ) : gcd (gcd m n) k = gcd m (gcd n k) :=
dvd.antisymm
(dvd_gcd
(dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_left m n))
(dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k)))
(dvd_gcd
(dvd_gcd (gcd_dvd_left m (gcd n k)) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_left n k)))
(dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_right n k)))
theorem gcd_one_left (m : ℕ) : gcd 1 m = 1 :=
eq.trans (gcd_comm 1 m) $ gcd_one_right m
theorem gcd_mul_left (m n k : ℕ) : gcd (m * n) (m * k) = m * gcd n k :=
gcd.induction n k
(λn, by repeat {rw mul_zero <|> rw gcd_zero_right})
(λn k H IH, by rwa [-mul_mod_mul_left, -gcd_rec, -gcd_rec] at IH)
theorem gcd_mul_right (m n k : ℕ) : gcd (m * n) (k * n) = gcd m k * n :=
by rw [mul_comm m n, mul_comm k n, mul_comm (gcd m k) n, gcd_mul_left]
theorem gcd_pos_of_pos_left {m : ℕ} (n : ℕ) (mpos : m > 0) : gcd m n > 0 :=
pos_of_dvd_of_pos (gcd_dvd_left m n) mpos
theorem gcd_pos_of_pos_right (m : ℕ) {n : ℕ} (npos : n > 0) : gcd m n > 0 :=
pos_of_dvd_of_pos (gcd_dvd_right m n) npos
theorem eq_zero_of_gcd_eq_zero_left {m n : ℕ} (H : gcd m n = 0) : m = 0 :=
or.elim (eq_zero_or_pos m) id
(assume H1 : m > 0, absurd (eq.symm H) (ne_of_lt (gcd_pos_of_pos_left _ H1)))
theorem eq_zero_of_gcd_eq_zero_right {m n : ℕ} (H : gcd m n = 0) : n = 0 :=
by rw gcd_comm at H; exact eq_zero_of_gcd_eq_zero_left H
theorem gcd_div {m n k : ℕ} (H1 : k ∣ m) (H2 : k ∣ n) :
gcd (m / k) (n / k) = gcd m n / k :=
or.elim (eq_zero_or_pos k)
(λk0, by rw [k0, nat.div_zero, nat.div_zero, nat.div_zero, gcd_zero_right])
(λH3, nat.eq_of_mul_eq_mul_right H3 $ by rw [
nat.div_mul_cancel (dvd_gcd H1 H2), -gcd_mul_right,
nat.div_mul_cancel H1, nat.div_mul_cancel H2])
theorem gcd_dvd_gcd_of_dvd_left {m k : ℕ} (n : ℕ) (H : m ∣ k) : gcd m n ∣ gcd k n :=
dvd_gcd (dvd.trans (gcd_dvd_left m n) H) (gcd_dvd_right m n)
theorem gcd_dvd_gcd_of_dvd_right {m k : ℕ} (n : ℕ) (H : m ∣ k) : gcd n m ∣ gcd n k :=
dvd_gcd (gcd_dvd_left n m) (dvd.trans (gcd_dvd_right n m) H)
theorem gcd_dvd_gcd_mul_left (m n k : ℕ) : gcd m n ∣ gcd (k * m) n :=
gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _)
theorem gcd_dvd_gcd_mul_right (m n k : ℕ) : gcd m n ∣ gcd (m * k) n :=
gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _)
theorem gcd_dvd_gcd_mul_left_right (m n k : ℕ) : gcd m n ∣ gcd m (k * n) :=
gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _)
theorem gcd_dvd_gcd_mul_right_right (m n k : ℕ) : gcd m n ∣ gcd m (n * k) :=
gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _)
/- lcm -/
def lcm (m n : ℕ) : ℕ := m * n / (gcd m n)
theorem lcm_comm (m n : ℕ) : lcm m n = lcm n m :=
by delta lcm; rw [mul_comm, gcd_comm]
theorem lcm_zero_left (m : ℕ) : lcm 0 m = 0 :=
by delta lcm; rw [zero_mul, nat.zero_div]
theorem lcm_zero_right (m : ℕ) : lcm m 0 = 0 := lcm_comm 0 m ▸ lcm_zero_left m
theorem lcm_one_left (m : ℕ) : lcm 1 m = m :=
by delta lcm; rw [one_mul, gcd_one_left, nat.div_one]
theorem lcm_one_right (m : ℕ) : lcm m 1 = m := lcm_comm 1 m ▸ lcm_one_left m
theorem lcm_self (m : ℕ) : lcm m m = m :=
or.elim (eq_zero_or_pos m)
(λh, by rw [h, lcm_zero_left])
(λh, by delta lcm; rw [gcd_self, nat.mul_div_cancel _ h])
theorem dvd_lcm_left (m n : ℕ) : m ∣ lcm m n :=
dvd.intro (n / gcd m n) (nat.mul_div_assoc _ $ gcd_dvd_right m n).symm
theorem dvd_lcm_right (m n : ℕ) : n ∣ lcm m n :=
lcm_comm n m ▸ dvd_lcm_left n m
theorem gcd_mul_lcm (m n : ℕ) : gcd m n * lcm m n = m * n :=
by delta lcm; rw [nat.mul_div_cancel' (dvd.trans (gcd_dvd_left m n) (dvd_mul_right m n))]
theorem lcm_dvd {m n k : ℕ} (H1 : m ∣ k) (H2 : n ∣ k) : lcm m n ∣ k :=
or.elim (eq_zero_or_pos k)
(λh, by rw h; exact dvd_zero _)
(λkpos, dvd_of_mul_dvd_mul_left (gcd_pos_of_pos_left n (pos_of_dvd_of_pos H1 kpos)) $
by rw [gcd_mul_lcm, -gcd_mul_right, mul_comm n k];
exact dvd_gcd (mul_dvd_mul_left _ H2) (mul_dvd_mul_right H1 _))
theorem lcm.assoc (m n k : ℕ) : lcm (lcm m n) k = lcm m (lcm n k) :=
dvd.antisymm
(lcm_dvd
(lcm_dvd (dvd_lcm_left m (lcm n k)) (dvd.trans (dvd_lcm_left n k) (dvd_lcm_right m (lcm n k))))
(dvd.trans (dvd_lcm_right n k) (dvd_lcm_right m (lcm n k))))
(lcm_dvd
(dvd.trans (dvd_lcm_left m n) (dvd_lcm_left (lcm m n) k))
(lcm_dvd (dvd.trans (dvd_lcm_right m n) (dvd_lcm_left (lcm m n) k)) (dvd_lcm_right (lcm m n) k)))
/- coprime -/
@[reducible] def coprime (m n : ℕ) : Prop := gcd m n = 1
lemma gcd_eq_one_of_coprime {m n : ℕ} : coprime m n → gcd m n = 1 :=
λ h, h
theorem coprime_swap {m n : ℕ} (H : coprime n m) : coprime m n :=
eq.trans (gcd_comm m n) H
theorem coprime_of_dvd {m n : ℕ} (H : ∀ k > 1, k ∣ m → ¬ k ∣ n) : coprime m n :=
or.elim (eq_zero_or_pos (gcd m n))
(λg0, by rw [eq_zero_of_gcd_eq_zero_left g0, eq_zero_of_gcd_eq_zero_right g0] at H; exact false.elim
(H 2 dec_trivial (dvd_zero _) (dvd_zero _)))
(λ(g1 : 1 ≤ _), eq.symm $ (lt_or_eq_of_le g1).resolve_left $ λg2,
H _ g2 (gcd_dvd_left _ _) (gcd_dvd_right _ _))
theorem coprime_of_dvd' {m n : ℕ} (H : ∀ k, k ∣ m → k ∣ n → k ∣ 1) : coprime m n :=
coprime_of_dvd $ λk kl km kn, not_le_of_gt kl $ le_of_dvd zero_lt_one (H k km kn)
theorem dvd_of_coprime_of_dvd_mul_right {m n k : ℕ} (H1 : coprime k n) (H2 : k ∣ m * n) : k ∣ m :=
let t := dvd_gcd (dvd_mul_left k m) H2 in
by rwa [gcd_mul_left, gcd_eq_one_of_coprime H1, mul_one] at t
theorem dvd_of_coprime_of_dvd_mul_left {m n k : ℕ} (H1 : coprime k m) (H2 : k ∣ m * n) : k ∣ n :=
by rw mul_comm at H2; exact dvd_of_coprime_of_dvd_mul_right H1 H2
theorem gcd_mul_left_cancel_of_coprime {k : ℕ} (m : ℕ) {n : ℕ} (H : coprime k n) :
gcd (k * m) n = gcd m n :=
have H1 : gcd (gcd (k * m) n) k = 1,
by rw [gcd_assoc, gcd_eq_one_of_coprime (coprime_swap H), gcd_one_right],
dvd.antisymm
(dvd_gcd (dvd_of_coprime_of_dvd_mul_left H1 (gcd_dvd_left _ _)) (gcd_dvd_right _ _))
(gcd_dvd_gcd_mul_left _ _ _)
theorem gcd_mul_right_cancel_of_coprime (m : ℕ) {k n : ℕ} (H : coprime k n) :
gcd (m * k) n = gcd m n :=
by rw [mul_comm m k, gcd_mul_left_cancel_of_coprime m H]
theorem gcd_mul_left_cancel_of_coprime_right {k m : ℕ} (n : ℕ) (H : coprime k m) :
gcd m (k * n) = gcd m n :=
by rw [gcd_comm m n, gcd_comm m (k * n), gcd_mul_left_cancel_of_coprime n H]
theorem gcd_mul_right_cancel_of_coprime_right {k m : ℕ} (n : ℕ) (H : coprime k m) :
gcd m (n * k) = gcd m n :=
by rw [mul_comm n k, gcd_mul_left_cancel_of_coprime_right n H]
theorem coprime_div_gcd_div_gcd {m n : ℕ} (H : gcd m n > 0) :
coprime (m / gcd m n) (n / gcd m n) :=
by delta coprime; rw [gcd_div (gcd_dvd_left m n) (gcd_dvd_right m n), nat.div_self H]
theorem not_coprime_of_dvd_of_dvd {m n d : ℕ} (dgt1 : d > 1) (Hm : d ∣ m) (Hn : d ∣ n) :
¬ coprime m n :=
λ (co : gcd m n = 1),
not_lt_of_ge (le_of_dvd zero_lt_one $ by rw -co; exact dvd_gcd Hm Hn) dgt1
theorem exists_coprime {m n : ℕ} (H : gcd m n > 0) :
exists m' n', coprime m' n' ∧ m = m' * gcd m n ∧ n = n' * gcd m n :=
⟨_, _, coprime_div_gcd_div_gcd H,
(nat.div_mul_cancel (gcd_dvd_left m n)).symm,
(nat.div_mul_cancel (gcd_dvd_right m n)).symm⟩
theorem coprime_mul {m n k : ℕ} (H1 : coprime m k) (H2 : coprime n k) : coprime (m * n) k :=
eq.trans (gcd_mul_left_cancel_of_coprime n H1) H2
theorem coprime_mul_right {k m n : ℕ} (H1 : coprime k m) (H2 : coprime k n) : coprime k (m * n) :=
coprime_swap (coprime_mul (coprime_swap H1) (coprime_swap H2))
theorem coprime_of_coprime_dvd_left {m k n : ℕ} (H1 : m ∣ k) (H2 : coprime k n) : coprime m n :=
eq_one_of_dvd_one (by delta coprime at H2; rw -H2; exact gcd_dvd_gcd_of_dvd_left _ H1)
theorem coprime_of_coprime_dvd_right {m k n : ℕ} (H1 : n ∣ m) (H2 : coprime k m) : coprime k n :=
coprime_swap $ coprime_of_coprime_dvd_left H1 $ coprime_swap H2
theorem coprime_of_coprime_mul_left {k m n : ℕ} (H : coprime (k * m) n) : coprime m n :=
coprime_of_coprime_dvd_left (dvd_mul_left _ _) H
theorem coprime_of_coprime_mul_right {k m n : ℕ} (H : coprime (m * k) n) : coprime m n :=
coprime_of_coprime_dvd_left (dvd_mul_right _ _) H
theorem coprime_of_coprime_mul_left_right {k m n : ℕ} (H : coprime m (k * n)) : coprime m n :=
coprime_of_coprime_dvd_right (dvd_mul_left _ _) H
theorem coprime_of_coprime_mul_right_right {k m n : ℕ} (H : coprime m (n * k)) : coprime m n :=
coprime_of_coprime_dvd_right (dvd_mul_right _ _) H
theorem comprime_one_left : ∀ n, coprime 1 n := gcd_one_left
theorem comprime_one_right : ∀ n, coprime n 1 := gcd_one_right
theorem coprime_pow_left {m k : ℕ} (n : ℕ) (H1 : coprime m k) : coprime (m ^ n) k :=
nat.rec_on n (comprime_one_left _) (λn IH, coprime_mul IH H1)
theorem coprime_pow_right {m k : ℕ} (n : ℕ) (H1 : coprime k m) : coprime k (m ^ n) :=
coprime_swap $ coprime_pow_left n $ coprime_swap H1
theorem coprime_pow {k l : ℕ} (m n : ℕ) (H1 : coprime k l) : coprime (k ^ m) (l ^ n) :=
coprime_pow_right _ $ coprime_pow_left _ H1
theorem exists_eq_prod_and_dvd_and_dvd {m n k : nat} (H : k ∣ m * n) :
∃ m' n', k = m' * n' ∧ m' ∣ m ∧ n' ∣ n :=
or.elim (eq_zero_or_pos (gcd k m))
(λg0, ⟨0, n,
by rw [zero_mul, eq_zero_of_gcd_eq_zero_left g0],
by rw [eq_zero_of_gcd_eq_zero_right g0]; apply dvd_zero, dvd_refl _⟩)
(λgpos, let hd := (nat.mul_div_cancel' (gcd_dvd_left k m)).symm in
⟨_, _, hd, gcd_dvd_right _ _,
dvd_of_mul_dvd_mul_left gpos $ by rw [-hd, -gcd_mul_right]; exact
dvd_gcd (dvd_mul_right _ _) H⟩)
end nat
|
6adb81e6c0178489d00a25da6cc513407a840e42 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/topology/category/Top/basic.lean | 5e29277543f5353eb95e99558eed99319334a348 | [
"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 | 3,474 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Scott Morrison, Mario Carneiro
-/
import category_theory.concrete_category.bundled_hom
import topology.continuous_function.basic
/-!
# Category instance for topological spaces
We introduce the bundled category `Top` of topological spaces together with the functors `discrete`
and `trivial` from the category of types to `Top` which equip a type with the corresponding
discrete, resp. trivial, topology. For a proof that these functors are left, resp. right adjoint
to the forgetful functor, see `topology.category.Top.adjunctions`.
-/
open category_theory
open topological_space
universe u
/-- The category of topological spaces and continuous maps. -/
def Top : Type (u+1) := bundled topological_space
namespace Top
instance bundled_hom : bundled_hom @continuous_map :=
⟨@continuous_map.to_fun, @continuous_map.id, @continuous_map.comp, @continuous_map.coe_inj⟩
attribute [derive [large_category, concrete_category]] Top
instance : has_coe_to_sort Top Type* := bundled.has_coe_to_sort
instance topological_space_unbundled (x : Top) : topological_space x := x.str
@[simp] lemma id_app (X : Top.{u}) (x : X) :
(𝟙 X : X → X) x = x := rfl
@[simp] lemma comp_app {X Y Z : Top.{u}} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) :
(f ≫ g : X → Z) x = g (f x) := rfl
/-- Construct a bundled `Top` from the underlying type and the typeclass. -/
def of (X : Type u) [topological_space X] : Top := ⟨X⟩
instance (X : Top) : topological_space X := X.str
@[simp] lemma coe_of (X : Type u) [topological_space X] : (of X : Type u) = X := rfl
instance : inhabited Top := ⟨Top.of empty⟩
/-- The discrete topology on any type. -/
def discrete : Type u ⥤ Top.{u} :=
{ obj := λ X, ⟨X, ⊥⟩,
map := λ X Y f, { to_fun := f, continuous_to_fun := continuous_bot } }
/-- The trivial topology on any type. -/
def trivial : Type u ⥤ Top.{u} :=
{ obj := λ X, ⟨X, ⊤⟩,
map := λ X Y f, { to_fun := f, continuous_to_fun := continuous_top } }
/-- Any homeomorphisms induces an isomorphism in `Top`. -/
@[simps] def iso_of_homeo {X Y : Top.{u}} (f : X ≃ₜ Y) : X ≅ Y :=
{ hom := ⟨f⟩,
inv := ⟨f.symm⟩ }
/-- Any isomorphism in `Top` induces a homeomorphism. -/
@[simps] def homeo_of_iso {X Y : Top.{u}} (f : X ≅ Y) : X ≃ₜ Y :=
{ to_fun := f.hom,
inv_fun := f.inv,
left_inv := λ x, by simp,
right_inv := λ x, by simp,
continuous_to_fun := f.hom.continuous,
continuous_inv_fun := f.inv.continuous }
@[simp] lemma of_iso_of_homeo {X Y : Top.{u}} (f : X ≃ₜ Y) : homeo_of_iso (iso_of_homeo f) = f :=
by { ext, refl }
@[simp] lemma of_homeo_of_iso {X Y : Top.{u}} (f : X ≅ Y) : iso_of_homeo (homeo_of_iso f) = f :=
by { ext, refl }
@[simp]
lemma open_embedding_iff_comp_is_iso {X Y Z : Top} (f : X ⟶ Y) (g : Y ⟶ Z) [is_iso g] :
open_embedding (f ≫ g) ↔ open_embedding f :=
open_embedding_iff_open_embedding_compose f (Top.homeo_of_iso (as_iso g)).open_embedding
@[simp]
lemma open_embedding_iff_is_iso_comp {X Y Z : Top} (f : X ⟶ Y) (g : Y ⟶ Z) [is_iso f] :
open_embedding (f ≫ g) ↔ open_embedding g :=
begin
split,
{ intro h,
convert h.comp (Top.homeo_of_iso (as_iso f).symm).open_embedding,
exact congr_arg _ (is_iso.inv_hom_id_assoc f g).symm },
{ exact λ h, h.comp (Top.homeo_of_iso (as_iso f)).open_embedding }
end
end Top
|
08349deacd7238fd2693824da5983cecff533c3d | 437dc96105f48409c3981d46fb48e57c9ac3a3e4 | /src/measure_theory/integration.lean | 54b9b8c42ff47b9d2ac4cea97639862190f705d3 | [
"Apache-2.0"
] | permissive | dan-c-k/mathlib | 08efec79bd7481ee6da9cc44c24a653bff4fbe0d | 96efc220f6225bc7a5ed8349900391a33a38cc56 | refs/heads/master | 1,658,082,847,093 | 1,589,013,201,000 | 1,589,013,201,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 57,184 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Johannes Hölzl
Lebesgue integral on `ennreal`.
We define simple functions and show that each Borel measurable function on `ennreal` can be
approximated by a sequence of simple functions.
-/
import measure_theory.measure_space
import measure_theory.borel_space
noncomputable theory
open set (hiding restrict restrict_apply) filter
open_locale classical topological_space
namespace measure_theory
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
/-- A function `f` from a measurable space to any type is called *simple*,
if every preimage `f ⁻¹' {x}` is measurable, and the range is finite. This structure bundles
a function with these properties. -/
structure {u v} simple_func (α : Type u) [measurable_space α] (β : Type v) :=
(to_fun : α → β)
(measurable_sn : ∀ x, is_measurable (to_fun ⁻¹' {x}))
(finite : (set.range to_fun).finite)
local infixr ` →ₛ `:25 := simple_func
namespace simple_func
section measurable
variables [measurable_space α]
instance has_coe_to_fun : has_coe_to_fun (α →ₛ β) := ⟨_, to_fun⟩
@[ext] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g :=
by cases f; cases g; congr; exact funext H
/-- Range of a simple function `α →ₛ β` as a `finset β`. -/
protected def range (f : α →ₛ β) : finset β := f.finite.to_finset
@[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ ∃ a, f a = b :=
finite.mem_to_finset
lemma preimage_eq_empty_iff (f : α →ₛ β) (b : β) : f ⁻¹' {b} = ∅ ↔ b ∉ f.range :=
iff.intro
(by simp [set.eq_empty_iff_forall_not_mem, mem_range])
(by simp [set.eq_empty_iff_forall_not_mem, mem_range])
/-- Constant function as a `simple_func`. -/
def const (α) {β} [measurable_space α] (b : β) : α →ₛ β :=
⟨λ a, b, λ x, is_measurable.const _,
finite_subset (set.finite_singleton b) $ by rintro _ ⟨a, rfl⟩; simp⟩
instance [inhabited β] : inhabited (α →ₛ β) := ⟨const _ (default _)⟩
@[simp] theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl
lemma range_const (α) [measurable_space α] [nonempty α] (b : β) :
(const α b).range = {b} :=
begin
ext b',
simp [mem_range],
tauto
end
lemma is_measurable_cut (p : α → β → Prop) (f : α →ₛ β)
(h : ∀b, is_measurable {a | p a b}) : is_measurable {a | p a (f a)} :=
begin
rw (_ : {a | p a (f a)} = ⋃ b ∈ set.range f, {a | p a b} ∩ f ⁻¹' {b}),
{ exact is_measurable.bUnion f.finite.countable
(λ b _, is_measurable.inter (h b) (f.measurable_sn _)) },
ext a, simp,
exact ⟨λ h, ⟨a, ⟨h, rfl⟩⟩, λ ⟨a', ⟨h', e⟩⟩, e.symm ▸ h'⟩
end
theorem preimage_measurable (f : α →ₛ β) (s) : is_measurable (f ⁻¹' s) :=
is_measurable_cut (λ _ b, b ∈ s) f (λ b, by simp [is_measurable.const])
/-- A simple function is measurable -/
theorem measurable [measurable_space β] (f : α →ₛ β) : measurable f :=
λ s _, preimage_measurable f s
def ite {s : set α} (hs : is_measurable s) (f g : α →ₛ β) : α →ₛ β :=
⟨λ a, if a ∈ s then f a else g a,
λ x, by letI : measurable_space β := ⊤; exact
measurable.if hs f.measurable g.measurable _ trivial,
finite_subset (finite_union f.finite g.finite) begin
rintro _ ⟨a, rfl⟩,
by_cases a ∈ s; simp [h],
exacts [or.inl ⟨_, rfl⟩, or.inr ⟨_, rfl⟩]
end⟩
@[simp] theorem ite_apply {s : set α} (hs : is_measurable s)
(f g : α →ₛ β) (a) : ite hs f g a = if a ∈ s then f a else g a := rfl
/-- If `f : α →ₛ β` is a simple function and `g : β → α →ₛ γ` is a family of simple functions,
then `f.bind g` binds the first argument of `g` to `f`. In other words, `f.bind g a = g (f a) a`. -/
def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ :=
⟨λa, g (f a) a,
λ c, is_measurable_cut (λa b, g b a ∈ ({c} : set γ)) f (λ b, (g b).measurable_sn c),
finite_subset (finite_bUnion f.finite (λ b, (g b).finite)) $
by rintro _ ⟨a, rfl⟩; simp; exact ⟨a, a, rfl⟩⟩
@[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) :
f.bind g a = g (f a) a := rfl
/-- Restrict a simple function `f : α →ₛ β` to a set `s`. If `s` is measurable,
then `f.restrict s a = if a ∈ s then f a else 0`, otherwise `f.restrict s = const α 0`. -/
def restrict [has_zero β] (f : α →ₛ β) (s : set α) : α →ₛ β :=
if hs : is_measurable s then ite hs f (const α 0) else const α 0
@[simp] theorem restrict_apply [has_zero β]
(f : α →ₛ β) {s : set α} (hs : is_measurable s) (a) :
restrict f s a = if a ∈ s then f a else 0 :=
by unfold_coes; simp [restrict, hs]; apply ite_apply hs
theorem restrict_preimage [has_zero β]
(f : α →ₛ β) {s : set α} (hs : is_measurable s)
{t : set β} (ht : (0:β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t :=
by ext a; dsimp [preimage]; rw [restrict_apply]; by_cases a ∈ s; simp [h, hs, ht]
/-- Given a function `g : β → γ` and a simple function `f : α →ₛ β`, `f.map g` return the simple
function `g ∘ f : α →ₛ γ` -/
def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g)
@[simp] theorem map_apply (g : β → γ) (f : α →ₛ β) (a) : f.map g a = g (f a) := rfl
theorem map_map (g : β → γ) (h: γ → δ) (f : α →ₛ β) : (f.map g).map h = f.map (h ∘ g) := rfl
theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl
@[simp] theorem range_map [decidable_eq γ] (g : β → γ) (f : α →ₛ β) :
(f.map g).range = f.range.image g :=
begin
ext c,
simp only [mem_range, exists_prop, mem_range, finset.mem_image, map_apply],
split,
{ rintros ⟨a, rfl⟩, exact ⟨f a, ⟨_, rfl⟩, rfl⟩ },
{ rintros ⟨_, ⟨a, rfl⟩, rfl⟩, exact ⟨_, rfl⟩ }
end
lemma map_preimage (f : α →ₛ β) (g : β → γ) (s : set γ) :
(f.map g) ⁻¹' s = (⋃b∈f.range.filter (λb, g b ∈ s), f ⁻¹' {b}) :=
begin
/- True because `f` only takes finitely many values. -/
ext a',
simp only [mem_Union, set.mem_preimage, exists_prop, set.mem_preimage, map_apply,
finset.mem_filter, mem_range, mem_singleton_iff, exists_eq_right'],
split,
{ assume eq, exact ⟨⟨_, rfl⟩, eq⟩ },
{ rintros ⟨_, eq⟩, exact eq }
end
lemma map_preimage_singleton (f : α →ₛ β) (g : β → γ) (c : γ) :
(f.map g) ⁻¹' {c} = (⋃b∈f.range.filter (λb, g b = c), f ⁻¹' {b}) :=
begin
rw map_preimage,
have : (λb, g b = c) = λb, g b ∈ _root_.singleton c,
funext, rw [eq_iff_iff, mem_singleton_iff],
rw this
end
/-- If `f` is a simple function taking values in `β → γ` and `g` is another simple function
with the same domain and codomain `β`, then `f.seq g = f a (g a)`. -/
def seq (f : α →ₛ (β → γ)) (g : α →ₛ β) : α →ₛ γ := f.bind (λf, g.map f)
@[simp] lemma seq_apply (f : α →ₛ (β → γ)) (g : α →ₛ β) (a : α) : f.seq g a = f a (g a) := rfl
/-- Combine two simple functions `f : α →ₛ β` and `g : α →ₛ β`
into `λ a, (f a, g a)`. -/
def pair (f : α →ₛ β) (g : α →ₛ γ) : α →ₛ (β × γ) := (f.map prod.mk).seq g
@[simp] lemma pair_apply (f : α →ₛ β) (g : α →ₛ γ) (a) : pair f g a = (f a, g a) := rfl
lemma pair_preimage (f : α →ₛ β) (g : α →ₛ γ) (s : set β) (t : set γ) :
(pair f g) ⁻¹' (set.prod s t) = (f ⁻¹' s) ∩ (g ⁻¹' t) := rfl
/- A special form of `pair_preimage` -/
lemma pair_preimage_singleton (f : α →ₛ β) (g : α →ₛ γ) (b : β) (c : γ) :
(pair f g) ⁻¹' {(b, c)} = (f ⁻¹' {b}) ∩ (g ⁻¹' {c}) :=
by { rw ← prod_singleton_singleton, exact pair_preimage _ _ _ _ }
theorem bind_const (f : α →ₛ β) : f.bind (const α) = f := by ext; simp
instance [has_zero β] : has_zero (α →ₛ β) := ⟨const α 0⟩
instance [has_add β] : has_add (α →ₛ β) := ⟨λf g, (f.map (+)).seq g⟩
instance [has_mul β] : has_mul (α →ₛ β) := ⟨λf g, (f.map (*)).seq g⟩
instance [has_sup β] : has_sup (α →ₛ β) := ⟨λf g, (f.map (⊔)).seq g⟩
instance [has_inf β] : has_inf (α →ₛ β) := ⟨λf g, (f.map (⊓)).seq g⟩
instance [has_le β] : has_le (α →ₛ β) := ⟨λf g, ∀a, f a ≤ g a⟩
@[simp] lemma sup_apply [has_sup β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl
@[simp] lemma mul_apply [has_mul β] (f g : α →ₛ β) (a : α) : (f * g) a = f a * g a := rfl
lemma add_apply [has_add β] (f g : α →ₛ β) (a : α) : (f + g) a = f a + g a := rfl
lemma add_eq_map₂ [has_add β] (f g : α →ₛ β) : f + g = (pair f g).map (λp:β×β, p.1 + p.2) :=
rfl
lemma sup_eq_map₂ [has_sup β] (f g : α →ₛ β) : f ⊔ g = (pair f g).map (λp:β×β, p.1 ⊔ p.2) :=
rfl
lemma const_mul_eq_map [has_mul β] (f : α →ₛ β) (b : β) : const α b * f = f.map (λa, b * a) := rfl
instance [add_monoid β] : add_monoid (α →ₛ β) :=
{ add := (+), zero := 0,
add_assoc := assume f g h, ext (assume a, add_assoc _ _ _),
zero_add := assume f, ext (assume a, zero_add _),
add_zero := assume f, ext (assume a, add_zero _) }
instance add_comm_monoid [add_comm_monoid β] : add_comm_monoid (α →ₛ β) :=
{ add_comm := λ f g, ext (λa, add_comm _ _),
.. simple_func.add_monoid }
instance [has_neg β] : has_neg (α →ₛ β) := ⟨λf, f.map (has_neg.neg)⟩
instance [add_group β] : add_group (α →ₛ β) :=
{ neg := has_neg.neg,
add_left_neg := λf, ext (λa, add_left_neg _),
.. simple_func.add_monoid }
instance [add_comm_group β] : add_comm_group (α →ₛ β) :=
{ add_comm := λ f g, ext (λa, add_comm _ _) ,
.. simple_func.add_group }
variables {K : Type*}
instance [has_scalar K β] : has_scalar K (α →ₛ β) := ⟨λk f, f.map (λb, k • b)⟩
instance [semiring K] [add_comm_monoid β] [semimodule K β] : semimodule K (α →ₛ β) :=
{ one_smul := λ f, ext (λa, one_smul _ _),
mul_smul := λ x y f, ext (λa, mul_smul _ _ _),
smul_add := λ r f g, ext (λa, smul_add _ _ _),
smul_zero := λ r, ext (λa, smul_zero _),
add_smul := λ r s f, ext (λa, add_smul _ _ _),
zero_smul := λ f, ext (λa, zero_smul _ _) }
instance [ring K] [add_comm_group β] [module K β] : module K (α →ₛ β) :=
{ .. simple_func.semimodule }
instance [field K] [add_comm_group β] [module K β] : vector_space K (α →ₛ β) :=
{ .. simple_func.module }
lemma smul_apply [has_scalar K β] (k : K) (f : α →ₛ β) (a : α) : (k • f) a = k • f a := rfl
lemma smul_eq_map [has_scalar K β] (k : K) (f : α →ₛ β) : k • f = f.map (λb, k • b) := rfl
instance [preorder β] : preorder (α →ₛ β) :=
{ le_refl := λf a, le_refl _,
le_trans := λf g h hfg hgh a, le_trans (hfg _) (hgh a),
.. simple_func.has_le }
instance [partial_order β] : partial_order (α →ₛ β) :=
{ le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a),
.. simple_func.preorder }
instance [order_bot β] : order_bot (α →ₛ β) :=
{ bot := const α ⊥, bot_le := λf a, bot_le, .. simple_func.partial_order }
instance [order_top β] : order_top (α →ₛ β) :=
{ top := const α⊤, le_top := λf a, le_top, .. simple_func.partial_order }
instance [semilattice_inf β] : semilattice_inf (α →ₛ β) :=
{ inf := (⊓),
inf_le_left := assume f g a, inf_le_left,
inf_le_right := assume f g a, inf_le_right,
le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a),
.. simple_func.partial_order }
instance [semilattice_sup β] : semilattice_sup (α →ₛ β) :=
{ sup := (⊔),
le_sup_left := assume f g a, le_sup_left,
le_sup_right := assume f g a, le_sup_right,
sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a),
.. simple_func.partial_order }
instance [semilattice_sup_bot β] : semilattice_sup_bot (α →ₛ β) :=
{ .. simple_func.semilattice_sup,.. simple_func.order_bot }
instance [lattice β] : lattice (α →ₛ β) :=
{ .. simple_func.semilattice_sup,.. simple_func.semilattice_inf }
instance [bounded_lattice β] : bounded_lattice (α →ₛ β) :=
{ .. simple_func.lattice, .. simple_func.order_bot, .. simple_func.order_top }
lemma finset_sup_apply [semilattice_sup_bot β] {f : γ → α →ₛ β} (s : finset γ) (a : α) :
s.sup f a = s.sup (λc, f c a) :=
begin
refine finset.induction_on s rfl _,
assume a s hs ih,
rw [finset.sup_insert, finset.sup_insert, sup_apply, ih]
end
section approx
section
variables [semilattice_sup_bot β] [has_zero β]
/-- Fix a sequence `i : ℕ → β`. Given a function `α → β`, its `n`-th approximation
by simple functions is defined so that in case `β = ennreal` it sends each `a` to the supremum
of the set `{i k | k ≤ n ∧ i k ≤ f a}`, see `approx_apply` and `supr_approx_apply` for details. -/
def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β :=
(finset.range n).sup (λk, restrict (const α (i k)) {a:α | i k ≤ f a})
lemma approx_apply [topological_space β] [order_closed_topology β] [measurable_space β]
[opens_measurable_space β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : _root_.measurable f) :
(approx i f n : α →ₛ β) a = (finset.range n).sup (λk, if i k ≤ f a then i k else 0) :=
begin
dsimp only [approx],
rw [finset_sup_apply],
congr,
funext k,
rw [restrict_apply],
refl,
exact (hf.preimage is_measurable_Ici)
end
lemma monotone_approx (i : ℕ → β) (f : α → β) : monotone (approx i f) :=
assume n m h, finset.sup_mono $ finset.range_subset.2 h
lemma approx_comp [topological_space β] [order_closed_topology β] [measurable_space β]
[opens_measurable_space β] [measurable_space γ]
{i : ℕ → β} {f : γ → β} {g : α → γ} {n : ℕ} (a : α)
(hf : _root_.measurable f) (hg : _root_.measurable g) :
(approx i (f ∘ g) n : α →ₛ β) a = (approx i f n : γ →ₛ β) (g a) :=
by rw [approx_apply _ hf, approx_apply _ (hf.comp hg)]
end
lemma supr_approx_apply [topological_space β] [complete_lattice β] [order_closed_topology β] [has_zero β]
[measurable_space β] [opens_measurable_space β]
(i : ℕ → β) (f : α → β) (a : α) (hf : _root_.measurable f) (h_zero : (0 : β) = ⊥) :
(⨆n, (approx i f n : α →ₛ β) a) = (⨆k (h : i k ≤ f a), i k) :=
begin
refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _),
{ rw [approx_apply a hf, h_zero],
refine finset.sup_le (assume k hk, _),
split_ifs,
exact le_supr_of_le k (le_supr _ h),
exact bot_le },
{ refine le_supr_of_le (k+1) _,
rw [approx_apply a hf],
have : k ∈ finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _),
refine le_trans (le_of_eq _) (finset.le_sup this),
rw [if_pos hk] }
end
end approx
section eapprox
/-- A sequence of `ennreal`s such that its range is the set of non-negative rational numbers. -/
def ennreal_rat_embed (n : ℕ) : ennreal :=
nnreal.of_real ((encodable.decode ℚ n).get_or_else (0 : ℚ))
lemma ennreal_rat_embed_encode (q : ℚ) :
ennreal_rat_embed (encodable.encode q) = nnreal.of_real q :=
by rw [ennreal_rat_embed, encodable.encodek]; refl
/-- Approximate a function `α → ennreal` by a sequence of simple functions. -/
def eapprox : (α → ennreal) → ℕ → α →ₛ ennreal :=
approx ennreal_rat_embed
lemma monotone_eapprox (f : α → ennreal) : monotone (eapprox f) :=
monotone_approx _ f
lemma supr_eapprox_apply (f : α → ennreal) (hf : _root_.measurable f) (a : α) :
(⨆n, (eapprox f n : α →ₛ ennreal) a) = f a :=
begin
rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl],
refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _),
assume h,
rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨q, hq, lt_q, q_lt⟩,
have : (nnreal.of_real q : ennreal) ≤
(⨆ (k : ℕ) (h : ennreal_rat_embed k ≤ f a), ennreal_rat_embed k),
{ refine le_supr_of_le (encodable.encode q) _,
rw [ennreal_rat_embed_encode q],
refine le_supr_of_le (le_of_lt q_lt) _,
exact le_refl _ },
exact lt_irrefl _ (lt_of_le_of_lt this lt_q)
end
lemma eapprox_comp [measurable_space γ] {f : γ → ennreal} {g : α → γ} {n : ℕ}
(hf : _root_.measurable f) (hg : _root_.measurable g) :
(eapprox (f ∘ g) n : α → ennreal) = (eapprox f n : γ →ₛ ennreal) ∘ g :=
funext $ assume a, approx_comp a hf hg
end eapprox
end measurable
section measure
variables [measure_space α]
lemma volume_bUnion_preimage (s : finset β) (f : α →ₛ β) :
volume (⋃b ∈ s, f ⁻¹' {b}) = s.sum (λb, volume (f ⁻¹' {b})) :=
begin
/- Taking advantage of the fact that `f ⁻¹' {b}` are disjoint for `b ∈ s`. -/
rw [volume_bUnion_finset],
{ simp only [pairwise_on, (on), finset.mem_coe, ne.def],
rintros _ _ _ _ ne _ ⟨h₁, h₂⟩,
simp only [mem_singleton_iff, mem_preimage] at h₁ h₂,
rw [← h₁, h₂] at ne,
exact ne rfl },
exact assume a ha, preimage_measurable _ _
end
/-- Integral of a simple function whose codomain is `ennreal`. -/
def integral (f : α →ₛ ennreal) : ennreal :=
f.range.sum (λ x, x * volume (f ⁻¹' {x}))
/-- Calculate the integral of `(g ∘ f)`, where `g : β → ennreal` and `f : α →ₛ β`. -/
lemma map_integral (g : β → ennreal) (f : α →ₛ β) :
(f.map g).integral = f.range.sum (λ x, g x * volume (f ⁻¹' {x})) :=
begin
simp only [integral, range_map],
refine finset.sum_image' _ (assume b hb, _),
rcases mem_range.1 hb with ⟨a, rfl⟩,
rw [map_preimage_singleton, volume_bUnion_preimage, finset.mul_sum],
refine finset.sum_congr _ _,
{ congr },
{ assume x, simp only [finset.mem_filter], rintro ⟨_, h⟩, rw h }
end
lemma zero_integral : (0 : α →ₛ ennreal).integral = 0 :=
begin
refine (finset.sum_eq_zero_iff_of_nonneg $ assume _ _, zero_le _).2 _,
assume r hr, rcases mem_range.1 hr with ⟨a, rfl⟩,
exact zero_mul _
end
lemma add_integral (f g : α →ₛ ennreal) : (f + g).integral = f.integral + g.integral :=
calc (f + g).integral =
(pair f g).range.sum (λx, x.1 * volume (pair f g ⁻¹' {x}) + x.2 * volume (pair f g ⁻¹' {x})) :
by rw [add_eq_map₂, map_integral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _)
... = (pair f g).range.sum (λx, x.1 * volume (pair f g ⁻¹' {x})) +
(pair f g).range.sum (λx, x.2 * volume (pair f g ⁻¹' {x})) : by rw [finset.sum_add_distrib]
... = ((pair f g).map prod.fst).integral + ((pair f g).map prod.snd).integral :
by rw [map_integral, map_integral]
... = integral f + integral g : rfl
lemma const_mul_integral (f : α →ₛ ennreal) (x : ennreal) :
(const α x * f).integral = x * f.integral :=
calc (f.map (λa, x * a)).integral = f.range.sum (λr, x * r * volume (f ⁻¹' {r})) :
by rw [map_integral]
... = f.range.sum (λr, x * (r * volume (f ⁻¹' {r}))) :
finset.sum_congr rfl (assume a ha, mul_assoc _ _ _)
... = x * f.integral :
finset.mul_sum.symm
lemma mem_restrict_range [has_zero β] {r : β} {s : set α} {f : α →ₛ β} (hs : is_measurable s) :
r ∈ (restrict f s).range ↔ (r = 0 ∧ s ≠ univ) ∨ (∃a∈s, f a = r) :=
begin
simp only [mem_range, restrict_apply, hs],
split,
{ rintros ⟨a, ha⟩,
split_ifs at ha,
{ exact or.inr ⟨a, h, ha⟩ },
{ exact or.inl ⟨ha.symm, assume eq, h $ eq.symm ▸ trivial⟩ } },
{ rintros (⟨rfl, h⟩ | ⟨a, ha, rfl⟩),
{ have : ¬ ∀a, a ∈ s := assume this, h $ eq_univ_of_forall this,
rcases not_forall.1 this with ⟨a, ha⟩,
refine ⟨a, _⟩,
rw [if_neg ha] },
{ refine ⟨a, _⟩,
rw [if_pos ha] } }
end
lemma restrict_preimage' {r : ennreal} {s : set α}
(f : α →ₛ ennreal) (hs : is_measurable s) (hr : r ≠ 0) :
(restrict f s) ⁻¹' {r} = (f ⁻¹' {r} ∩ s) :=
begin
ext a,
by_cases a ∈ s; simp [hs, h, hr.symm]
end
lemma restrict_integral (f : α →ₛ ennreal) (s : set α) (hs : is_measurable s) :
(restrict f s).integral = f.range.sum (λr, r * volume (f ⁻¹' {r} ∩ s)) :=
begin
refine finset.sum_bij_ne_zero (λr _ _, r) _ _ _ _,
{ assume r hr,
rcases (mem_restrict_range hs).1 hr with ⟨rfl, h⟩ | ⟨a, ha, rfl⟩,
{ simp },
{ assume _, exact mem_range.2 ⟨a, rfl⟩ } },
{ assume a b _ _ _ _ h, exact h },
{ assume r hr,
by_cases r0 : r = 0, { simp [r0] },
assume h0,
rcases mem_range.1 hr with ⟨a, rfl⟩,
have : f ⁻¹' {f a} ∩ s ≠ ∅,
{ assume h, simpa [h] using h0 },
rcases ne_empty_iff_nonempty.1 this with ⟨a', eq', ha'⟩,
refine ⟨_, (mem_restrict_range hs).2 (or.inr ⟨a', ha', _⟩), _, rfl⟩,
{ simpa using eq' },
{ rwa [restrict_preimage' _ hs r0] } },
{ assume r hr ne,
by_cases r = 0, { simp [h] },
rw [restrict_preimage' _ hs h] }
end
lemma restrict_const_integral (c : ennreal) (s : set α) (hs : is_measurable s) :
(restrict (const α c) s).integral = c * volume s :=
have (@const α ennreal _ c) ⁻¹' {c} = univ,
begin
refine eq_univ_of_forall (assume a, _),
simp,
end,
calc (restrict (const α c) s).integral = c * volume ((const α c) ⁻¹' {c} ∩ s) :
begin
rw [restrict_integral (const α c) s hs],
refine finset.sum_eq_single c _ _,
{ assume r hr, rcases mem_range.1 hr with ⟨a, rfl⟩, contradiction },
{ by_cases nonempty α,
{ assume ne,
rcases h with ⟨a⟩,
exfalso,
exact ne (mem_range.2 ⟨a, rfl⟩) },
{ assume empty,
have : (@const α ennreal _ c) ⁻¹' {c} ∩ s = ∅,
{ ext a, exfalso, exact h ⟨a⟩ },
simp only [this, volume_empty, mul_zero] } }
end
... = c * volume s : by rw [this, univ_inter]
lemma integral_sup_le (f g : α →ₛ ennreal) : f.integral ⊔ g.integral ≤ (f ⊔ g).integral :=
calc f.integral ⊔ g.integral =
((pair f g).map prod.fst).integral ⊔ ((pair f g).map prod.snd).integral : rfl
... ≤ (pair f g).range.sum (λx, (x.1 ⊔ x.2) * volume (pair f g ⁻¹' {x})) :
begin
rw [map_integral, map_integral],
refine sup_le _ _;
refine finset.sum_le_sum (λ a _, canonically_ordered_semiring.mul_le_mul _ (le_refl _)),
exact le_sup_left,
exact le_sup_right
end
... = (f ⊔ g).integral : by rw [sup_eq_map₂, map_integral]
lemma integral_le_integral (f g : α →ₛ ennreal) (h : f ≤ g) : f.integral ≤ g.integral :=
calc f.integral ≤ f.integral ⊔ g.integral : le_sup_left
... ≤ (f ⊔ g).integral : integral_sup_le _ _
... = g.integral : by rw [sup_of_le_right h]
lemma integral_congr (f g : α →ₛ ennreal) (h : ∀ₘ a, f a = g a) :
f.integral = g.integral :=
show ((pair f g).map prod.fst).integral = ((pair f g).map prod.snd).integral, from
begin
rw [map_integral, map_integral],
refine finset.sum_congr rfl (assume p hp, _),
rcases mem_range.1 hp with ⟨a, rfl⟩,
by_cases eq : f a = g a,
{ dsimp only [pair_apply], rw eq },
{ have : volume ((pair f g) ⁻¹' {(f a, g a)}) = 0,
{ refine volume_mono_null (assume a' ha', _) h,
simp at ha',
show f a' ≠ g a',
rwa [ha'.1, ha'.2] },
simp [this] }
end
lemma integral_map {β} [measure_space β] (f : α →ₛ ennreal) (g : β →ₛ ennreal)(m : α → β)
(eq : ∀a:α, f a = g (m a)) (h : ∀s:set β, is_measurable s → volume s = volume (m ⁻¹' s)) :
f.integral = g.integral :=
have f_eq : (f : α → ennreal) = g ∘ m := funext eq,
have vol_f : ∀r, volume (f ⁻¹' {r}) = volume (g ⁻¹' {r}),
by { assume r, rw [h, f_eq, preimage_comp], exact measurable_sn _ _ },
begin
simp [integral, vol_f],
refine finset.sum_subset _ _,
{ simp [finset.subset_iff, f_eq],
rintros r a rfl, exact ⟨_, rfl⟩ },
{ assume r hrg hrf,
rw [simple_func.mem_range, not_exists] at hrf,
have : f ⁻¹' {r} = ∅ := set.eq_empty_of_subset_empty (assume a, by simpa using hrf a),
simp [(vol_f _).symm, this] }
end
end measure
section fin_vol_supp
variables [measure_space α] [has_zero β] [has_zero γ]
open finset ennreal
protected def fin_vol_supp (f : α →ₛ β) : Prop := ∀b ≠ 0, volume (f ⁻¹' {b}) < ⊤
lemma fin_vol_supp_map {f : α →ₛ β} {g : β → γ} (hf : f.fin_vol_supp) (hg : g 0 = 0) :
(f.map g).fin_vol_supp :=
begin
assume c hc,
simp only [map_preimage, volume_bUnion_preimage],
apply sum_lt_top,
intro b,
simp only [mem_filter, mem_range, mem_singleton_iff, and_imp, exists_imp_distrib],
intros a fab gbc,
apply hf,
intro b0,
rw [b0, hg] at gbc, rw gbc at hc,
contradiction
end
lemma fin_vol_supp_of_fin_vol_supp_map (f : α →ₛ β) {g : β → γ} (h : (f.map g).fin_vol_supp)
(hg : ∀b, g b = 0 → b = 0) : f.fin_vol_supp :=
begin
assume b hb,
by_cases b_mem : b ∈ f.range,
{ have gb0 : g b ≠ 0, { assume h, have := hg b h, contradiction },
have : f ⁻¹' {b} ⊆ (f.map g) ⁻¹' {g b},
rw [coe_map, @preimage_comp _ _ _ f g, preimage_subset_preimage_iff],
{ simp only [set.mem_preimage, set.mem_singleton, set.singleton_subset_iff] },
{ rw set.singleton_subset_iff, rw mem_range at b_mem, exact b_mem },
exact lt_of_le_of_lt (volume_mono this) (h (g b) gb0) },
{ rw ← preimage_eq_empty_iff at b_mem,
rw [b_mem, volume_empty],
exact with_top.zero_lt_top }
end
lemma fin_vol_supp_pair {f : α →ₛ β} {g : α →ₛ γ} (hf : f.fin_vol_supp) (hg : g.fin_vol_supp) :
(pair f g).fin_vol_supp :=
begin
rintros ⟨b, c⟩ hbc,
rw [pair_preimage_singleton],
rw [ne.def, prod.eq_iff_fst_eq_snd_eq, not_and_distrib] at hbc,
refine or.elim hbc (λ h : b≠0, _) (λ h : c≠0, _),
{ calc _ ≤ volume (f ⁻¹' {b}) : volume_mono (set.inter_subset_left _ _)
... < ⊤ : hf _ h },
{ calc _ ≤ volume (g ⁻¹' {c}) : volume_mono (set.inter_subset_right _ _)
... < ⊤ : hg _ h },
end
lemma integral_lt_top_of_fin_vol_supp {f : α →ₛ ennreal} (h₁ : ∀ₘ a, f a < ⊤) (h₂ : f.fin_vol_supp) :
integral f < ⊤ :=
begin
rw integral, apply sum_lt_top,
intros a ha,
have : f ⁻¹' {⊤} = -{a : α | f a < ⊤}, { ext, simp },
have vol_top : volume (f ⁻¹' {⊤}) = 0, { rw [this, volume, ← measure.mem_a_e_iff], exact h₁ },
by_cases hat : a = ⊤,
{ rw [hat, vol_top, mul_zero], exact with_top.zero_lt_top },
{ by_cases haz : a = 0,
{ rw [haz, zero_mul], exact with_top.zero_lt_top },
apply mul_lt_top,
{ rw ennreal.lt_top_iff_ne_top, exact hat },
apply h₂,
exact haz }
end
lemma fin_vol_supp_of_integral_lt_top {f : α →ₛ ennreal} (h : integral f < ⊤) : f.fin_vol_supp :=
begin
assume b hb,
rw [integral, sum_lt_top_iff] at h,
by_cases b_mem : b ∈ f.range,
{ rw ennreal.lt_top_iff_ne_top,
have h : ¬ _ = ⊤ := ennreal.lt_top_iff_ne_top.1 (h b b_mem),
simp only [mul_eq_top, not_or_distrib, not_and_distrib] at h,
rcases h with ⟨h, h'⟩,
refine or.elim h (λh, by contradiction) (λh, h) },
{ rw ← preimage_eq_empty_iff at b_mem,
rw [b_mem, volume_empty],
exact with_top.zero_lt_top }
end
/-- A technical lemma dealing with the definition of `integrable` in `l1_space.lean`. -/
lemma integral_map_coe_lt_top {f : α →ₛ β} {g : β → nnreal} (h : f.fin_vol_supp) (hg : g 0 = 0) :
integral (f.map ((coe : nnreal → ennreal) ∘ g)) < ⊤ :=
integral_lt_top_of_fin_vol_supp
(by { filter_upwards[], assume a, simp only [mem_set_of_eq, map_apply], exact ennreal.coe_lt_top})
(by { apply fin_vol_supp_map h, simp only [hg, function.comp_app, ennreal.coe_zero] })
end fin_vol_supp
end simple_func
section lintegral
open simple_func
variable [measure_space α]
/-- The lower Lebesgue integral -/
def lintegral (f : α → ennreal) : ennreal :=
⨆ (s : α →ₛ ennreal) (hf : ⇑s ≤ f), s.integral
notation `∫⁻` binders `, ` r:(scoped f, lintegral f) := r
theorem simple_func.lintegral_eq_integral (f : α →ₛ ennreal) : (∫⁻ a, f a) = f.integral :=
le_antisymm
(supr_le $ assume s, supr_le $ assume hs, integral_le_integral _ _ hs)
(le_supr_of_le f $ le_supr_of_le (le_refl f) $ le_refl _)
lemma lintegral_mono ⦃f g : α → ennreal⦄ (h : f ≤ g) : (∫⁻ a, f a) ≤ (∫⁻ a, g a) :=
supr_le_supr_of_subset $ assume s hs, le_trans hs h
lemma monotone_lintegral (α : Type*) [measure_space α] :
monotone (@lintegral α _) :=
λ f g h, lintegral_mono h
lemma lintegral_eq_nnreal (f : α → ennreal) :
(∫⁻ a, f a) =
(⨆ (s : α →ₛ nnreal) (hf : f ≥ s.map (coe : nnreal → ennreal)),
(s.map (coe : nnreal → ennreal)).integral) :=
begin
let c : nnreal → ennreal := coe,
refine le_antisymm
(supr_le $ assume s, supr_le $ assume hs, _)
(supr_le $ assume s, supr_le $ assume hs, le_supr_of_le (s.map c) $ le_supr _ hs),
by_cases ∀ₘ a, s a ≠ ⊤,
{ have : f ≥ (s.map ennreal.to_nnreal).map c :=
le_trans (assume a, ennreal.coe_to_nnreal_le_self) hs,
refine le_supr_of_le (s.map ennreal.to_nnreal) (le_supr_of_le this (le_of_eq $ integral_congr _ _ _)),
exact filter.mem_sets_of_superset h (assume a ha, (ennreal.coe_to_nnreal ha).symm) },
{ have h_vol_s : volume {a : α | s a = ⊤} ≠ 0,
from mt volume_zero_iff_all_ae_nmem.1 h,
let n : ℕ → (α →ₛ nnreal) := λn, restrict (const α (n : nnreal)) (s ⁻¹' {⊤}),
have n_le_s : ∀i, (n i).map c ≤ s,
{ assume i a,
dsimp [n, c],
rw [restrict_apply _ (s.preimage_measurable _)],
split_ifs with ha,
{ simp at ha, exact ha.symm ▸ le_top },
{ exact zero_le _ } },
have approx_s : ∀ (i : ℕ), ↑i * volume {a : α | s a = ⊤} ≤ integral (map c (n i)),
{ assume i,
have : {a : α | s a = ⊤} = s ⁻¹' {⊤}, { ext a, simp },
rw [this, ← restrict_const_integral _ _ (s.preimage_measurable _)],
{ refine integral_le_integral _ _ (assume a, le_of_eq _),
simp [n, c, restrict_apply, s.preimage_measurable],
split_ifs; simp [ennreal.coe_nat] },
},
calc s.integral ≤ ⊤ : le_top
... = (⨆i:ℕ, (i : ennreal) * volume {a | s a = ⊤}) :
by rw [← ennreal.supr_mul, ennreal.supr_coe_nat, ennreal.top_mul, if_neg h_vol_s]
... ≤ (⨆i, ((n i).map c).integral) : supr_le_supr approx_s
... ≤ ⨆ (s : α →ₛ nnreal) (hf : f ≥ s.map c), (s.map c).integral :
have ∀i, ((n i).map c : α → ennreal) ≤ f := assume i, le_trans (n_le_s i) hs,
(supr_le $ assume i, le_supr_of_le (n i) (le_supr (λh, ((n i).map c).integral) (this i))) }
end
theorem supr_lintegral_le {ι : Sort*} (f : ι → α → ennreal) :
(⨆i, ∫⁻ a, f i a) ≤ (∫⁻ a, ⨆i, f i a) :=
by { simp only [← supr_apply], exact (monotone_lintegral α).map_supr_ge }
theorem supr2_lintegral_le {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ennreal) :
(⨆i (h : ι' i), ∫⁻ a, f i h a) ≤ (∫⁻ a, ⨆i (h : ι' i), f i h a) :=
by { convert (monotone_lintegral α).map_supr2_ge f, ext1 a, simp only [supr_apply] }
theorem le_infi_lintegral {ι : Sort*} (f : ι → α → ennreal) :
(∫⁻ a, ⨅i, f i a) ≤ (⨅i, ∫⁻ a, f i a) :=
by { simp only [← infi_apply], exact (monotone_lintegral α).map_infi_le }
theorem le_infi2_lintegral {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ennreal) :
(∫⁻ a, ⨅ i (h : ι' i), f i h a) ≤ (⨅ i (h : ι' i), ∫⁻ a, f i h a) :=
by { convert (monotone_lintegral α).map_infi2_le f, ext1 a, simp only [infi_apply] }
/-- Monotone convergence theorem -- sometimes called Beppo-Levi convergence.
See `lintegral_supr_directed` for a more general form. -/
theorem lintegral_supr
{f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : monotone f) :
(∫⁻ a, ⨆n, f n a) = (⨆n, ∫⁻ a, f n a) :=
begin
set c : nnreal → ennreal := coe,
set F := λ a:α, ⨆n, f n a,
have hF : measurable F := measurable_supr hf,
refine le_antisymm _ (supr_lintegral_le _),
rw [lintegral_eq_nnreal],
refine supr_le (assume s, supr_le (assume hsf, _)),
refine ennreal.le_of_forall_lt_one_mul_lt (assume a ha, _),
rcases ennreal.lt_iff_exists_coe.1 ha with ⟨r, rfl, ha⟩,
have ha : r < 1 := ennreal.coe_lt_coe.1 ha,
let rs := s.map (λa, r * a),
have eq_rs : (const α r : α →ₛ ennreal) * map c s = rs.map c,
{ ext1 a, exact ennreal.coe_mul.symm },
have eq : ∀p, (rs.map c) ⁻¹' {p} = (⋃n, (rs.map c) ⁻¹' {p} ∩ {a | p ≤ f n a}),
{ assume p,
rw [← inter_Union, ← inter_univ ((map c rs) ⁻¹' {p})] {occs := occurrences.pos [1]},
refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _),
by_cases p_eq : p = 0, { simp [p_eq] },
simp at hx, subst hx,
have : r * s x ≠ 0, { rwa [(≠), ← ennreal.coe_eq_zero] },
have : s x ≠ 0, { refine mt _ this, assume h, rw [h, mul_zero] },
have : (rs.map c) x < ⨆ (n : ℕ), f n x,
{ refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x),
suffices : r * s x < 1 * s x, simpa [rs],
exact mul_lt_mul_of_pos_right ha (zero_lt_iff_ne_zero.2 this) },
rcases lt_supr_iff.1 this with ⟨i, hi⟩,
exact mem_Union.2 ⟨i, le_of_lt hi⟩ },
have mono : ∀r:ennreal, monotone (λn, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}),
{ assume r i j h,
refine inter_subset_inter (subset.refl _) _,
assume x hx, exact le_trans hx (h_mono h x) },
have h_meas : ∀n, is_measurable {a : α | ⇑(map c rs) a ≤ f n a} :=
assume n, is_measurable_le (simple_func.measurable _) (hf n),
calc (r:ennreal) * integral (s.map c) = (rs.map c).range.sum (λr, r * volume ((rs.map c) ⁻¹' {r})) :
by rw [← const_mul_integral, integral, eq_rs]
... ≤ (rs.map c).range.sum (λr, r * volume (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) :
le_of_eq (finset.sum_congr rfl $ assume x hx, by rw ← eq)
... ≤ (rs.map c).range.sum (λr, (⨆n, r * volume ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}))) :
le_of_eq (finset.sum_congr rfl $ assume x hx,
begin
rw [volume, measure_Union_eq_supr_nat _ (mono x), ennreal.mul_supr],
{ assume i,
refine ((rs.map c).preimage_measurable _).inter _,
exact (hf i).preimage is_measurable_Ici }
end)
... ≤ ⨆n, (rs.map c).range.sum (λr, r * volume ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) :
begin
refine le_of_eq _,
rw [ennreal.finset_sum_supr_nat],
assume p i j h,
exact canonically_ordered_semiring.mul_le_mul (le_refl _) (volume_mono $ mono p h)
end
... ≤ (⨆n:ℕ, ((rs.map c).restrict {a | (rs.map c) a ≤ f n a}).integral) :
begin
refine supr_le_supr (assume n, _),
rw [restrict_integral _ _ (h_meas n)],
{ refine le_of_eq (finset.sum_congr rfl $ assume r hr, _),
congr' 2,
ext a,
refine and_congr_right _,
simp {contextual := tt} }
end
... ≤ (⨆n, ∫⁻ a, f n a) :
begin
refine supr_le_supr (assume n, _),
rw [← simple_func.lintegral_eq_integral],
refine lintegral_mono (assume a, _),
dsimp,
rw [restrict_apply],
split_ifs; simp, simpa using h,
exact h_meas n
end
end
lemma lintegral_eq_supr_eapprox_integral {f : α → ennreal} (hf : measurable f) :
(∫⁻ a, f a) = (⨆n, (eapprox f n).integral) :=
calc (∫⁻ a, f a) = (∫⁻ a, ⨆n, (eapprox f n : α → ennreal) a) :
by congr; ext a; rw [supr_eapprox_apply f hf]
... = (⨆n, ∫⁻ a, (eapprox f n : α → ennreal) a) :
begin
rw [lintegral_supr],
{ assume n, exact (eapprox f n).measurable },
{ assume i j h, exact (monotone_eapprox f h) }
end
... = (⨆n, (eapprox f n).integral) : by congr; ext n; rw [(eapprox f n).lintegral_eq_integral]
lemma lintegral_add {f g : α → ennreal} (hf : measurable f) (hg : measurable g) :
(∫⁻ a, f a + g a) = (∫⁻ a, f a) + (∫⁻ a, g a) :=
calc (∫⁻ a, f a + g a) =
(∫⁻ a, (⨆n, (eapprox f n : α → ennreal) a) + (⨆n, (eapprox g n : α → ennreal) a)) :
by congr; funext a; rw [supr_eapprox_apply f hf, supr_eapprox_apply g hg]
... = (∫⁻ a, (⨆n, (eapprox f n + eapprox g n : α → ennreal) a)) :
begin
congr, funext a,
rw [ennreal.supr_add_supr_of_monotone], { refl },
{ assume i j h, exact monotone_eapprox _ h a },
{ assume i j h, exact monotone_eapprox _ h a },
end
... = (⨆n, (eapprox f n).integral + (eapprox g n).integral) :
begin
rw [lintegral_supr],
{ congr, funext n, rw [← simple_func.add_integral, ← simple_func.lintegral_eq_integral], refl },
{ assume n, exact measurable.add (eapprox f n).measurable (eapprox g n).measurable },
{ assume i j h a, exact add_le_add' (monotone_eapprox _ h _) (monotone_eapprox _ h _) }
end
... = (⨆n, (eapprox f n).integral) + (⨆n, (eapprox g n).integral) :
by refine (ennreal.supr_add_supr_of_monotone _ _).symm;
{ assume i j h, exact simple_func.integral_le_integral _ _ (monotone_eapprox _ h) }
... = (∫⁻ a, f a) + (∫⁻ a, g a) :
by rw [lintegral_eq_supr_eapprox_integral hf, lintegral_eq_supr_eapprox_integral hg]
@[simp] lemma lintegral_zero : (∫⁻ a:α, 0) = 0 :=
show (∫⁻ a:α, (0 : α →ₛ ennreal) a) = 0, by rw [simple_func.lintegral_eq_integral, zero_integral]
lemma lintegral_finset_sum (s : finset β) {f : β → α → ennreal} (hf : ∀b, measurable (f b)) :
(∫⁻ a, s.sum (λb, f b a)) = s.sum (λb, ∫⁻ a, f b a) :=
begin
refine finset.induction_on s _ _,
{ simp },
{ assume a s has ih,
simp only [finset.sum_insert has],
rw [lintegral_add (hf _) (s.measurable_sum hf), ih] }
end
lemma lintegral_const_mul (r : ennreal) {f : α → ennreal} (hf : measurable f) :
(∫⁻ a, r * f a) = r * (∫⁻ a, f a) :=
calc (∫⁻ a, r * f a) = (∫⁻ a, (⨆n, (const α r * eapprox f n) a)) :
by { congr, funext a, rw [← supr_eapprox_apply f hf, ennreal.mul_supr], refl }
... = (⨆n, r * (eapprox f n).integral) :
begin
rw [lintegral_supr],
{ congr, funext n, rw [← simple_func.const_mul_integral, ← simple_func.lintegral_eq_integral] },
{ assume n, dsimp, exact simple_func.measurable _ },
{ assume i j h a, exact canonically_ordered_semiring.mul_le_mul (le_refl _)
(monotone_eapprox _ h _) }
end
... = r * (∫⁻ a, f a) : by rw [← ennreal.mul_supr, lintegral_eq_supr_eapprox_integral hf]
lemma lintegral_const_mul_le (r : ennreal) (f : α → ennreal) : r * (∫⁻ a, f a) ≤ (∫⁻ a, r * f a) :=
begin
rw [lintegral, ennreal.mul_supr],
refine supr_le (λs, _),
rw [ennreal.mul_supr],
simp only [supr_le_iff, ge_iff_le],
assume hs,
rw ← simple_func.const_mul_integral,
refine le_supr_of_le (const α r * s) (le_supr_of_le (λx, _) (le_refl _)),
exact canonically_ordered_semiring.mul_le_mul (le_refl _) (hs x)
end
lemma lintegral_const_mul' (r : ennreal) (f : α → ennreal) (hr : r ≠ ⊤) :
(∫⁻ a, r * f a) = r * (∫⁻ a, f a) :=
begin
by_cases h : r = 0,
{ simp [h] },
apply le_antisymm _ (lintegral_const_mul_le r f),
have rinv : r * r⁻¹ = 1 := ennreal.mul_inv_cancel h hr,
have rinv' : r ⁻¹ * r = 1, by { rw mul_comm, exact rinv },
have := lintegral_const_mul_le (r⁻¹) (λx, r * f x),
simp [(mul_assoc _ _ _).symm, rinv'] at this,
simpa [(mul_assoc _ _ _).symm, rinv]
using canonically_ordered_semiring.mul_le_mul (le_refl r) this
end
lemma lintegral_supr_const (r : ennreal) {s : set α} (hs : is_measurable s) :
(∫⁻ a, ⨆(h : a ∈ s), r) = r * volume s :=
begin
rw [← restrict_const_integral r s hs, ← (restrict (const α r) s).lintegral_eq_integral],
congr; ext a; by_cases a ∈ s; simp [h, hs]
end
lemma lintegral_le_lintegral_ae {f g : α → ennreal} (h : ∀ₘ a, f a ≤ g a) :
(∫⁻ a, f a) ≤ (∫⁻ a, g a) :=
begin
rcases exists_is_measurable_superset_of_measure_eq_zero h with ⟨t, hts, ht, ht0⟩,
have : - t ∈ (@measure_space.μ α _).a_e,
{ rw [measure.mem_a_e_iff, compl_compl, ht0] },
refine (supr_le $ assume s, supr_le $ assume hfs,
le_supr_of_le (s.restrict (- t)) $ le_supr_of_le _ _),
{ assume a,
by_cases a ∈ t;
simp [h, restrict_apply, ht.compl],
exact le_trans (hfs a) (by_contradiction $ assume hnfg, h (hts hnfg)) },
{ refine le_of_eq (s.integral_congr _ _),
filter_upwards [this],
refine assume a hnt, _,
by_cases hat : a ∈ t; simp [hat, ht.compl],
exact (hnt hat).elim }
end
lemma lintegral_congr_ae {f g : α → ennreal} (h : ∀ₘ a, f a = g a) :
(∫⁻ a, f a) = (∫⁻ a, g a) :=
le_antisymm
(lintegral_le_lintegral_ae $ h.mono $ assume a h, le_of_eq h)
(lintegral_le_lintegral_ae $ h.mono $ assume a h, le_of_eq h.symm)
lemma lintegral_congr {f g : α → ennreal} (h : ∀ a, f a = g a) :
(∫⁻ a, f a) = (∫⁻ a, g a) :=
by simp only [h]
-- TODO: Need a better way of rewriting inside of a integral
lemma lintegral_rw₁ {f f' : α → β} (h : ∀ₘ a, f a = f' a) (g : β → ennreal) :
(∫⁻ a, g (f a)) = (∫⁻ a, g (f' a)) :=
lintegral_congr_ae $ h.mono $ λ a h, by rw h
-- TODO: Need a better way of rewriting inside of a integral
lemma lintegral_rw₂ {f₁ f₁' : α → β} {f₂ f₂' : α → γ} (h₁ : ∀ₘ a, f₁ a = f₁' a)
(h₂ : ∀ₘ a, f₂ a = f₂' a) (g : β → γ → ennreal) :
(∫⁻ a, g (f₁ a) (f₂ a)) = (∫⁻ a, g (f₁' a) (f₂' a)) :=
lintegral_congr_ae $ h₁.mp $ h₂.mono $ λ _ h₂ h₁, by rw [h₁, h₂]
lemma simple_func.lintegral_map (f : α →ₛ β) (g : β → ennreal) :
(∫⁻ a, (f.map g) a) = ∫⁻ a, g (f a) :=
by simp only [map_apply]
/-- Chebyshev's inequality -/
lemma mul_volume_ge_le_lintegral {f : α → ennreal} (hf : measurable f) (ε : ennreal) :
ε * volume {x | ε ≤ f x} ≤ ∫⁻ a, f a :=
begin
have : is_measurable {a : α | ε ≤ f a }, from hf.preimage is_measurable_Ici,
rw [← simple_func.restrict_const_integral _ _ this, ← simple_func.lintegral_eq_integral],
refine lintegral_mono (λ a, _),
simp only [restrict_apply _ this],
split_ifs; [assumption, exact zero_le _]
end
lemma volume_ge_le_lintegral_div {f : α → ennreal} (hf : measurable f) {ε : ennreal}
(hε : ε ≠ 0) (hε' : ε ≠ ⊤) :
volume {x | ε ≤ f x} ≤ (∫⁻ a, f a) / ε :=
(ennreal.le_div_iff_mul_le (or.inl hε) (or.inl hε')).2 $
by { rw [mul_comm], exact mul_volume_ge_le_lintegral hf ε }
lemma lintegral_eq_zero_iff {f : α → ennreal} (hf : measurable f) :
lintegral f = 0 ↔ (∀ₘ a, f a = 0) :=
begin
refine iff.intro (assume h, _) (assume h, _),
{ have : ∀n:ℕ, ∀ₘ a, f a < n⁻¹,
{ assume n,
rw [all_ae_iff, ← le_zero_iff_eq, ← @ennreal.zero_div n⁻¹,
ennreal.le_div_iff_mul_le, mul_comm],
simp only [not_lt],
-- TODO: why `rw ← h` fails with "not an equality or an iff"?
exacts [h ▸ mul_volume_ge_le_lintegral hf n⁻¹,
or.inl (ennreal.inv_ne_zero.2 ennreal.coe_nat_ne_top),
or.inr ennreal.zero_ne_top] },
refine (all_ae_all_iff.2 this).mono (λ a ha, _),
by_contradiction h,
rcases ennreal.exists_inv_nat_lt h with ⟨n, hn⟩,
exact (lt_irrefl _ $ lt_trans hn $ ha n).elim },
{ calc lintegral f = lintegral (λa:α, 0) : lintegral_congr_ae h
... = 0 : lintegral_zero }
end
/-- Weaker version of the monotone convergence theorem-/
lemma lintegral_supr_ae {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n))
(h_mono : ∀n, ∀ₘ a, f n a ≤ f n.succ a) :
(∫⁻ a, ⨆n, f n a) = (⨆n, ∫⁻ a, f n a) :=
let ⟨s, hs⟩ := exists_is_measurable_superset_of_measure_eq_zero
(all_ae_iff.1 (all_ae_all_iff.2 h_mono)) in
let g := λ n a, if a ∈ s then 0 else f n a in
have g_eq_f : ∀ₘ a, ∀n, g n a = f n a,
begin
have := hs.2.2, rw [← compl_compl s] at this,
filter_upwards [(measure.mem_a_e_iff (-s)).2 this] assume a ha n, if_neg ha
end,
calc
(∫⁻ a, ⨆n, f n a) = (∫⁻ a, ⨆n, g n a) :
lintegral_congr_ae
begin
filter_upwards [g_eq_f], assume a ha, congr, funext, exact (ha n).symm
end
... = ⨆n, (∫⁻ a, g n a) :
lintegral_supr
(assume n, measurable.if hs.2.1 measurable_const (hf n))
(monotone_of_monotone_nat $ assume n a, classical.by_cases
(assume h : a ∈ s, by simp [g, if_pos h])
(assume h : a ∉ s,
begin
simp only [g, if_neg h], have := hs.1, rw subset_def at this, have := mt (this a) h,
simp only [not_not, mem_set_of_eq] at this, exact this n
end))
... = ⨆n, (∫⁻ a, f n a) :
begin
congr, funext, apply lintegral_congr_ae, filter_upwards [g_eq_f] assume a ha, ha n
end
lemma lintegral_sub {f g : α → ennreal} (hf : measurable f) (hg : measurable g)
(hg_fin : lintegral g < ⊤) (h_le : ∀ₘ a, g a ≤ f a) :
(∫⁻ a, f a - g a) = (∫⁻ a, f a) - (∫⁻ a, g a) :=
begin
rw [← ennreal.add_right_inj hg_fin,
ennreal.sub_add_cancel_of_le (lintegral_le_lintegral_ae h_le),
← lintegral_add (hf.ennreal_sub hg) hg],
show (∫⁻ (a : α), f a - g a + g a) = ∫⁻ (a : α), f a,
apply lintegral_congr_ae, filter_upwards [h_le], simp only [add_comm, mem_set_of_eq],
assume a ha, exact ennreal.add_sub_cancel_of_le ha
end
/-- Monotone convergence theorem for nonincreasing sequences of functions -/
lemma lintegral_infi_ae
{f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n))
(h_mono : ∀n:ℕ, ∀ₘ a, f n.succ a ≤ f n a) (h_fin : lintegral (f 0) < ⊤) :
(∫⁻ a, ⨅n, f n a) = (⨅n, ∫⁻ a, f n a) :=
have fn_le_f0 : (∫⁻ a, ⨅n, f n a) ≤ lintegral (f 0), from
lintegral_mono (assume a, infi_le_of_le 0 (le_refl _)),
have fn_le_f0' : (⨅n, ∫⁻ a, f n a) ≤ lintegral (f 0), from infi_le_of_le 0 (le_refl _),
(ennreal.sub_left_inj h_fin fn_le_f0 fn_le_f0').1 $
show lintegral (f 0) - (∫⁻ a, ⨅n, f n a) = lintegral (f 0) - (⨅n, ∫⁻ a, f n a), from
calc
lintegral (f 0) - (∫⁻ a, ⨅n, f n a) = ∫⁻ a, f 0 a - ⨅n, f n a :
(lintegral_sub (h_meas 0) (measurable_infi h_meas)
(calc
(∫⁻ a, ⨅n, f n a) ≤ lintegral (f 0) : lintegral_mono (assume a, infi_le _ _)
... < ⊤ : h_fin )
(all_ae_of_all $ assume a, infi_le _ _)).symm
... = ∫⁻ a, ⨆n, f 0 a - f n a : congr rfl (funext (assume a, ennreal.sub_infi))
... = ⨆n, ∫⁻ a, f 0 a - f n a :
lintegral_supr_ae
(assume n, (h_meas 0).ennreal_sub (h_meas n))
(assume n, by
filter_upwards [h_mono n] assume a ha, ennreal.sub_le_sub (le_refl _) ha)
... = ⨆n, lintegral (f 0) - ∫⁻ a, f n a :
have h_mono : ∀ₘ a, ∀n:ℕ, f n.succ a ≤ f n a := all_ae_all_iff.2 h_mono,
have h_mono : ∀n, ∀ₘa, f n a ≤ f 0 a := assume n,
begin
filter_upwards [h_mono], simp only [mem_set_of_eq], assume a, assume h, induction n with n ih,
{exact le_refl _}, {exact le_trans (h n) ih}
end,
congr rfl (funext $ assume n, lintegral_sub (h_meas _) (h_meas _)
(calc
(∫⁻ a, f n a) ≤ ∫⁻ a, f 0 a : lintegral_le_lintegral_ae $ h_mono n
... < ⊤ : h_fin)
(h_mono n))
... = lintegral (f 0) - (⨅n, ∫⁻ a, f n a) : ennreal.sub_infi.symm
/-- Monotone convergence theorem for nonincreasing sequences of functions -/
lemma lintegral_infi
{f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n))
(h_mono : ∀ ⦃m n⦄, m ≤ n → f n ≤ f m) (h_fin : lintegral (f 0) < ⊤) :
(∫⁻ a, ⨅n, f n a) = (⨅n, ∫⁻ a, f n a) :=
lintegral_infi_ae h_meas (λ n, all_ae_of_all $ h_mono $ le_of_lt n.lt_succ_self) h_fin
section priority
-- for some reason the next proof fails without changing the priority of this instance
local attribute [instance, priority 1000] classical.prop_decidable
/-- Known as Fatou's lemma -/
lemma lintegral_liminf_le {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) :
(∫⁻ a, liminf at_top (λ n, f n a)) ≤ liminf at_top (λ n, lintegral (f n)) :=
calc
(∫⁻ a, liminf at_top (λ n, f n a)) = ∫⁻ a, ⨆n:ℕ, ⨅i≥n, f i a :
by simp only [liminf_eq_supr_infi_of_nat]
... = ⨆n:ℕ, ∫⁻ a, ⨅i≥n, f i a :
lintegral_supr
(assume n, measurable_binfi _ h_meas)
(assume n m hnm a, infi_le_infi_of_subset $ λ i hi, le_trans hnm hi)
... ≤ ⨆n:ℕ, ⨅i≥n, lintegral (f i) :
supr_le_supr $ λ n, le_infi2_lintegral _
... = liminf at_top (λ n, lintegral (f n)) : liminf_eq_supr_infi_of_nat.symm
end priority
lemma limsup_lintegral_le {f : ℕ → α → ennreal} {g : α → ennreal}
(hf_meas : ∀ n, measurable (f n)) (h_bound : ∀n, ∀ₘa, f n a ≤ g a) (h_fin : lintegral g < ⊤) :
limsup at_top (λn, lintegral (f n)) ≤ ∫⁻ a, limsup at_top (λn, f n a) :=
calc
limsup at_top (λn, lintegral (f n)) = ⨅n:ℕ, ⨆i≥n, lintegral (f i) :
limsup_eq_infi_supr_of_nat
... ≤ ⨅n:ℕ, ∫⁻ a, ⨆i≥n, f i a :
infi_le_infi $ assume n, supr2_lintegral_le _
... = ∫⁻ a, ⨅n:ℕ, ⨆i≥n, f i a :
begin
refine (lintegral_infi _ _ _).symm,
{ assume n, exact measurable_bsupr _ hf_meas },
{ assume n m hnm a, exact (supr_le_supr_of_subset $ λ i hi, le_trans hnm hi) },
{ refine lt_of_le_of_lt (lintegral_le_lintegral_ae _) h_fin,
refine (all_ae_all_iff.2 h_bound).mono (λ n hn, _),
exact supr_le (λ i, supr_le $ λ hi, hn i) }
end
... = ∫⁻ a, limsup at_top (λn, f n a) :
by simp only [limsup_eq_infi_supr_of_nat]
/-- Dominated convergence theorem for nonnegative functions -/
lemma tendsto_lintegral_of_dominated_convergence
{F : ℕ → α → ennreal} {f : α → ennreal} (bound : α → ennreal)
(hF_meas : ∀n, measurable (F n)) (h_bound : ∀n, ∀ₘ a, F n a ≤ bound a)
(h_fin : lintegral bound < ⊤)
(h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) :
tendsto (λn, lintegral (F n)) at_top (𝓝 (lintegral f)) :=
begin
have limsup_le_lintegral :=
calc
limsup at_top (λ (n : ℕ), lintegral (F n)) ≤ ∫⁻ (a : α), limsup at_top (λn, F n a) :
limsup_lintegral_le hF_meas h_bound h_fin
... = lintegral f :
lintegral_congr_ae $
by filter_upwards [h_lim] assume a h, limsup_eq_of_tendsto at_top_ne_bot h,
have lintegral_le_liminf :=
calc
lintegral f = ∫⁻ (a : α), liminf at_top (λ (n : ℕ), F n a) :
lintegral_congr_ae $
by filter_upwards [h_lim] assume a h, (liminf_eq_of_tendsto at_top_ne_bot h).symm
... ≤ liminf at_top (λ n, lintegral (F n)) :
lintegral_liminf_le hF_meas,
have liminf_eq_limsup :=
le_antisymm
(liminf_le_limsup (map_ne_bot at_top_ne_bot))
(le_trans limsup_le_lintegral lintegral_le_liminf),
have liminf_eq_lintegral : liminf at_top (λ n, lintegral (F n)) = lintegral f :=
le_antisymm (by convert limsup_le_lintegral) lintegral_le_liminf,
have limsup_eq_lintegral : limsup at_top (λ n, lintegral (F n)) = lintegral f :=
le_antisymm
limsup_le_lintegral
begin convert lintegral_le_liminf, exact liminf_eq_limsup.symm end,
exact tendsto_of_liminf_eq_limsup ⟨liminf_eq_lintegral, limsup_eq_lintegral⟩
end
/-- Dominated convergence theorem for filters with a countable basis -/
lemma tendsto_lintegral_filter_of_dominated_convergence {ι} {l : filter ι}
{F : ι → α → ennreal} {f : α → ennreal} (bound : α → ennreal)
(hl_cb : l.is_countably_generated)
(hF_meas : ∀ᶠ n in l, measurable (F n))
(h_bound : ∀ᶠ n in l, ∀ₘ a, F n a ≤ bound a)
(h_fin : lintegral bound < ⊤)
(h_lim : ∀ₘ a, tendsto (λ n, F n a) l (nhds (f a))) :
tendsto (λn, lintegral (F n)) l (nhds (lintegral f)) :=
begin
rw hl_cb.tendsto_iff_seq_tendsto,
{ intros x xl,
have hxl, { rw tendsto_at_top' at xl, exact xl },
have h := inter_mem_sets hF_meas h_bound,
replace h := hxl _ h,
rcases h with ⟨k, h⟩,
rw ← tendsto_add_at_top_iff_nat k,
refine tendsto_lintegral_of_dominated_convergence _ _ _ _ _,
{ exact bound },
{ intro, refine (h _ _).1, exact nat.le_add_left _ _ },
{ intro, refine (h _ _).2, exact nat.le_add_left _ _ },
{ assumption },
{ filter_upwards [h_lim],
simp only [mem_set_of_eq],
assume a h_lim,
apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a),
{ assumption },
rw tendsto_add_at_top_iff_nat,
assumption } },
end
section
open encodable
/-- Monotone convergence for a suprema over a directed family and indexed by an encodable type -/
theorem lintegral_supr_directed [encodable β] {f : β → α → ennreal}
(hf : ∀b, measurable (f b)) (h_directed : directed (≤) f) :
(∫⁻ a, ⨆b, f b a) = (⨆b, ∫⁻ a, f b a) :=
begin
by_cases hβ : ¬ nonempty β,
{ have : ∀f : β → ennreal, (⨆(b : β), f b) = 0 :=
assume f, supr_eq_bot.2 (assume b, (hβ ⟨b⟩).elim),
simp [this] },
cases of_not_not hβ with b,
haveI iβ : inhabited β := ⟨b⟩, clear hβ b,
have : ∀a, (⨆ b, f b a) = (⨆ n, f (h_directed.sequence f n) a),
{ assume a,
refine le_antisymm (supr_le $ assume b, _) (supr_le $ assume n, le_supr (λn, f n a) _),
exact le_supr_of_le (encode b + 1) (h_directed.le_sequence b a) },
calc (∫⁻ a, ⨆ b, f b a) = (∫⁻ a, ⨆ n, f (h_directed.sequence f n) a) :
by simp only [this]
... = (⨆ n, ∫⁻ a, f (h_directed.sequence f n) a) :
lintegral_supr (assume n, hf _) h_directed.sequence_mono
... = (⨆ b, ∫⁻ a, f b a) :
begin
refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume b, _),
{ exact le_supr (λb, lintegral (f b)) _ },
{ exact le_supr_of_le (encode b + 1)
(lintegral_mono $ h_directed.le_sequence b) }
end
end
end
lemma lintegral_tsum [encodable β] {f : β → α → ennreal} (hf : ∀i, measurable (f i)) :
(∫⁻ a, ∑' i, f i a) = (∑' i, ∫⁻ a, f i a) :=
begin
simp only [ennreal.tsum_eq_supr_sum],
rw [lintegral_supr_directed],
{ simp [lintegral_finset_sum _ hf] },
{ assume b, exact finset.measurable_sum _ hf },
{ assume s t,
use [s ∪ t],
split,
exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_left _ _),
exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_right _ _) }
end
end lintegral
namespace measure
def integral [measurable_space α] (m : measure α) (f : α → ennreal) : ennreal :=
@lintegral α { μ := m } f
variables [measurable_space α] {m : measure α}
@[simp] lemma integral_zero : m.integral (λa, 0) = 0 := @lintegral_zero α { μ := m }
lemma integral_map [measurable_space β] {f : β → ennreal} {g : α → β}
(hf : measurable f) (hg : measurable g) : (map g m).integral f = m.integral (f ∘ g) :=
begin
rw [integral, integral, lintegral_eq_supr_eapprox_integral, lintegral_eq_supr_eapprox_integral],
{ congr, funext n, symmetry,
apply simple_func.integral_map,
{ assume a, exact congr_fun (simple_func.eapprox_comp hf hg) a },
{ assume s hs, exact map_apply hg hs } },
exact hf.comp hg,
assumption
end
lemma integral_dirac (a : α) {f : α → ennreal} (hf : measurable f) : (dirac a).integral f = f a :=
have ∀f:α →ₛ ennreal, @simple_func.integral α {μ := dirac a} f = f a,
begin
assume f,
have : ∀r, @volume α { μ := dirac a } (⇑f ⁻¹' {r}) = ⨆ h : f a = r, 1,
{ assume r,
transitivity,
apply dirac_apply,
apply simple_func.measurable_sn,
refine supr_congr_Prop _ _; simp },
transitivity,
apply finset.sum_eq_single (f a),
{ assume b hb h, simp [this, ne.symm h], },
{ assume h, simp at h, exact (h a rfl).elim },
{ rw [this], simp }
end,
begin
rw [integral, lintegral_eq_supr_eapprox_integral],
{ simp [this, simple_func.supr_eapprox_apply f hf] },
assumption
end
def with_density (m : measure α) (f : α → ennreal) : measure α :=
if hf : measurable f then
measure.of_measurable (λs hs, m.integral (λa, ⨆(h : a ∈ s), f a))
(by simp)
begin
assume s hs hd,
have : ∀a, (⨆ (h : a ∈ ⋃i, s i), f a) = (∑'i, (⨆ (h : a ∈ s i), f a)),
{ assume a,
by_cases ha : ∃j, a ∈ s j,
{ rcases ha with ⟨j, haj⟩,
have : ∀i, a ∈ s i ↔ j = i := assume i,
iff.intro
(assume hai, by_contradiction $ assume hij, hd j i hij ⟨haj, hai⟩)
(by rintros rfl; assumption),
simp [this, ennreal.tsum_supr_eq] },
{ have : ∀i, ¬ a ∈ s i, { simpa using ha },
simp [this] } },
simp only [this],
apply lintegral_tsum,
{ assume i,
simp [supr_eq_if],
exact measurable.if (hs i) hf measurable_const }
end
else 0
lemma with_density_apply {m : measure α} {f : α → ennreal} {s : set α}
(hf : measurable f) (hs : is_measurable s) :
m.with_density f s = m.integral (λa, ⨆(h : a ∈ s), f a) :=
by rw [with_density, dif_pos hf]; exact measure.of_measurable_apply s hs
end measure
end measure_theory
|
5e9eba3d1d6fe5d3e52ae473e9f40ef6fb8c95d1 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/topology/uniform_space/basic_auto.lean | f5f5cce0295ed6348a6e9aabef23be73652b3c46 | [] | 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 | 63,568 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.order.filter.lift
import Mathlib.topology.separation
import Mathlib.PostPort
universes u_1 u u_2 l u_3 u_4 u_6
namespace Mathlib
/-!
# Uniform spaces
Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly
generalize to uniform spaces, e.g.
* uniform continuity (in this file)
* completeness (in `cauchy.lean`)
* extension of uniform continuous functions to complete spaces (in `uniform_embedding.lean`)
* totally bounded sets (in `cauchy.lean`)
* totally bounded complete sets are compact (in `cauchy.lean`)
A uniform structure on a type `X` is a filter `𝓤 X` on `X × X` satisfying some conditions
which makes it reasonable to say that `∀ᶠ (p : X × X) in 𝓤 X, ...` means
"for all p.1 and p.2 in X close enough, ...". Elements of this filter are called entourages
of `X`. The two main examples are:
* If `X` is a metric space, `V ∈ 𝓤 X ↔ ∃ ε > 0, { p | dist p.1 p.2 < ε } ⊆ V`
* If `G` is an additive topological group, `V ∈ 𝓤 G ↔ ∃ U ∈ 𝓝 (0 : G), {p | p.2 - p.1 ∈ U} ⊆ V`
Those examples are generalizations in two different directions of the elementary example where
`X = ℝ` and `V ∈ 𝓤 ℝ ↔ ∃ ε > 0, { p | |p.2 - p.1| < ε } ⊆ V` which features both the topological
group structure on `ℝ` and its metric space structure.
Each uniform structure on `X` induces a topology on `X` characterized by
> `nhds_eq_comap_uniformity : ∀ {x : X}, 𝓝 x = comap (prod.mk x) (𝓤 X)`
where `prod.mk x : X → X × X := (λ y, (x, y))` is the partial evaluation of the product
constructor.
The dictionary with metric spaces includes:
* an upper bound for `dist x y` translates into `(x, y) ∈ V` for some `V ∈ 𝓤 X`
* a ball `ball x r` roughly corresponds to `uniform_space.ball x V := {y | (x, y) ∈ V}`
for some `V ∈ 𝓤 X`, but the later is more general (it includes in
particular both open and closed balls for suitable `V`).
In particular we have:
`is_open_iff_ball_subset {s : set X} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 X, ball x V ⊆ s`
The triangle inequality is abstracted to a statement involving the composition of relations in `X`.
First note that the triangle inequality in a metric space is equivalent to
`∀ (x y z : X) (r r' : ℝ), dist x y ≤ r → dist y z ≤ r' → dist x z ≤ r + r'`.
Then, for any `V` and `W` with type `set (X × X)`, the composition `V ○ W : set (X × X)` is
defined as `{ p : X × X | ∃ z, (p.1, z) ∈ V ∧ (z, p.2) ∈ W }`.
In the metric space case, if `V = { p | dist p.1 p.2 ≤ r }` and `W = { p | dist p.1 p.2 ≤ r' }`
then the triangle inequality, as reformulated above, says `V ○ W` is contained in
`{p | dist p.1 p.2 ≤ r + r'}` which is the entourage associated to the radius `r + r'`.
In general we have `mem_ball_comp (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W)`.
Note that this discussion does not depend on any axiom imposed on the uniformity filter,
it is simply captured by the definition of composition.
The uniform space axioms ask the filter `𝓤 X` to satisfy the following:
* every `V ∈ 𝓤 X` contains the diagonal `id_rel = { p | p.1 = p.2 }`. This abstracts the fact
that `dist x x ≤ r` for every non-negative radius `r` in the metric space case and also that
`x - x` belongs to every neighborhood of zero in the topological group case.
* `V ∈ 𝓤 X → prod.swap '' V ∈ 𝓤 X`. This is tightly related the fact that `dist x y = dist y x`
in a metric space, and to continuity of negation in the topological group case.
* `∀ V ∈ 𝓤 X, ∃ W ∈ 𝓤 X, W ○ W ⊆ V`. In the metric space case, it corresponds
to cutting the radius of a ball in half and applying the triangle inequality.
In the topological group case, it comes from continuity of addition at `(0, 0)`.
These three axioms are stated more abstractly in the definition below, in terms of
operations on filters, without directly manipulating entourages.
## Main definitions
* `uniform_space X` is a uniform space structure on a type `X`
* `uniform_continuous f` is a predicate saying a function `f : α → β` between uniform spaces
is uniformly continuous : `∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r`
In this file we also define a complete lattice structure on the type `uniform_space X`
of uniform structures on `X`, as well as the pullback (`uniform_space.comap`) of uniform structures
coming from the pullback of filters.
Like distance functions, uniform structures cannot be pushed forward in general.
## Notations
Localized in `uniformity`, we have the notation `𝓤 X` for the uniformity on a uniform space `X`,
and `○` for composition of relations, seen as terms with type `set (X × X)`.
## Implementation notes
There is already a theory of relations in `data/rel.lean` where the main definition is
`def rel (α β : Type*) := α → β → Prop`.
The relations used in the current file involve only one type, but this is not the reason why
we don't reuse `data/rel.lean`. We use `set (α × α)`
instead of `rel α α` because we really need sets to use the filter library, and elements
of filters on `α × α` have type `set (α × α)`.
The structure `uniform_space X` bundles a uniform structure on `X`, a topology on `X` and
an assumption saying those are compatible. This may not seem mathematically reasonable at first,
but is in fact an instance of the forgetful inheritance pattern. See Note [forgetful inheritance]
below.
## References
The formalization uses the books:
* [N. Bourbaki, *General Topology*][bourbaki1966]
* [I. M. James, *Topologies and Uniformities*][james1999]
But it makes a more systematic use of the filter library.
-/
/-!
### Relations, seen as `set (α × α)`
-/
/-- The identity relation, or the graph of the identity function -/
def id_rel {α : Type u_1} : set (α × α) := set_of fun (p : α × α) => prod.fst p = prod.snd p
@[simp] theorem mem_id_rel {α : Type u_1} {a : α} {b : α} : (a, b) ∈ id_rel ↔ a = b := iff.rfl
@[simp] theorem id_rel_subset {α : Type u_1} {s : set (α × α)} :
id_rel ⊆ s ↔ ∀ (a : α), (a, a) ∈ s :=
sorry
/-- The composition of relations -/
def comp_rel {α : Type u} (r₁ : set (α × α)) (r₂ : set (α × α)) : set (α × α) :=
set_of fun (p : α × α) => ∃ (z : α), (prod.fst p, z) ∈ r₁ ∧ (z, prod.snd p) ∈ r₂
@[simp] theorem mem_comp_rel {α : Type u_1} {r₁ : set (α × α)} {r₂ : set (α × α)} {x : α} {y : α} :
(x, y) ∈ comp_rel r₁ r₂ ↔ ∃ (z : α), (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ :=
iff.rfl
@[simp] theorem swap_id_rel {α : Type u_1} : prod.swap '' id_rel = id_rel := sorry
theorem monotone_comp_rel {α : Type u_1} {β : Type u_2} [preorder β] {f : β → set (α × α)}
{g : β → set (α × α)} (hf : monotone f) (hg : monotone g) :
monotone fun (x : β) => comp_rel (f x) (g x) :=
sorry
theorem comp_rel_mono {α : Type u_1} {f : set (α × α)} {g : set (α × α)} {h : set (α × α)}
{k : set (α × α)} (h₁ : f ⊆ h) (h₂ : g ⊆ k) : comp_rel f g ⊆ comp_rel h k :=
sorry
theorem prod_mk_mem_comp_rel {α : Type u_1} {a : α} {b : α} {c : α} {s : set (α × α)}
{t : set (α × α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ comp_rel s t :=
Exists.intro c { left := h₁, right := h₂ }
@[simp] theorem id_comp_rel {α : Type u_1} {r : set (α × α)} : comp_rel id_rel r = r := sorry
theorem comp_rel_assoc {α : Type u_1} {r : set (α × α)} {s : set (α × α)} {t : set (α × α)} :
comp_rel (comp_rel r s) t = comp_rel r (comp_rel s t) :=
sorry
theorem subset_comp_self {α : Type u_1} {s : set (α × α)} (h : id_rel ⊆ s) : s ⊆ comp_rel s s :=
sorry
/-- The relation is invariant under swapping factors. -/
def symmetric_rel {α : Type u_1} (V : set (α × α)) := prod.swap ⁻¹' V = V
/-- The maximal symmetric relation contained in a given relation. -/
def symmetrize_rel {α : Type u_1} (V : set (α × α)) : set (α × α) := V ∩ prod.swap ⁻¹' V
theorem symmetric_symmetrize_rel {α : Type u_1} (V : set (α × α)) :
symmetric_rel (symmetrize_rel V) :=
sorry
theorem symmetrize_rel_subset_self {α : Type u_1} (V : set (α × α)) : symmetrize_rel V ⊆ V :=
set.sep_subset V fun (a : α × α) => a ∈ prod.swap ⁻¹' V
theorem symmetrize_mono {α : Type u_1} {V : set (α × α)} {W : set (α × α)} (h : V ⊆ W) :
symmetrize_rel V ⊆ symmetrize_rel W :=
set.inter_subset_inter h (set.preimage_mono h)
theorem symmetric_rel_inter {α : Type u_1} {U : set (α × α)} {V : set (α × α)}
(hU : symmetric_rel U) (hV : symmetric_rel V) : symmetric_rel (U ∩ V) :=
sorry
/-- This core description of a uniform space is outside of the type class hierarchy. It is useful
for constructions of uniform spaces, when the topology is derived from the uniform space. -/
structure uniform_space.core (α : Type u) where
uniformity : filter (α × α)
refl : filter.principal id_rel ≤ uniformity
symm : filter.tendsto prod.swap uniformity uniformity
comp : (filter.lift' uniformity fun (s : set (α × α)) => comp_rel s s) ≤ uniformity
/-- An alternative constructor for `uniform_space.core`. This version unfolds various
`filter`-related definitions. -/
def uniform_space.core.mk' {α : Type u} (U : filter (α × α))
(refl : ∀ (r : set (α × α)), r ∈ U → ∀ (x : α), (x, x) ∈ r)
(symm : ∀ (r : set (α × α)), r ∈ U → prod.swap ⁻¹' r ∈ U)
(comp : ∀ (r : set (α × α)) (H : r ∈ U), ∃ (t : set (α × α)), ∃ (H : t ∈ U), comp_rel t t ⊆ r) :
uniform_space.core α :=
uniform_space.core.mk U sorry symm sorry
/-- A uniform space generates a topological space -/
def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) :
topological_space α :=
topological_space.mk
(fun (s : set α) =>
∀ (x : α),
x ∈ s →
(set_of fun (p : α × α) => prod.fst p = x → prod.snd p ∈ s) ∈
uniform_space.core.uniformity u)
sorry sorry sorry
theorem uniform_space.core_eq {α : Type u_1} {u₁ : uniform_space.core α}
{u₂ : uniform_space.core α} :
uniform_space.core.uniformity u₁ = uniform_space.core.uniformity u₂ → u₁ = u₂ :=
sorry
/-- Suppose that one can put two mathematical structures on a type, a rich one `R` and a poor one
`P`, and that one can deduce the poor structure from the rich structure through a map `F` (called a
forgetful functor) (think `R = metric_space` and `P = topological_space`). A possible
implementation would be to have a type class `rich` containing a field `R`, a type class `poor`
containing a field `P`, and an instance from `rich` to `poor`. However, this creates diamond
problems, and a better approach is to let `rich` extend `poor` and have a field saying that
`F R = P`.
To illustrate this, consider the pair `metric_space` / `topological_space`. Consider the topology
on a product of two metric spaces. With the first approach, it could be obtained by going first from
each metric space to its topology, and then taking the product topology. But it could also be
obtained by considering the product metric space (with its sup distance) and then the topology
coming from this distance. These would be the same topology, but not definitionally, which means
that from the point of view of Lean's kernel, there would be two different `topological_space`
instances on the product. This is not compatible with the way instances are designed and used:
there should be at most one instance of a kind on each type. This approach has created an instance
diamond that does not commute definitionally.
The second approach solves this issue. Now, a metric space contains both a distance, a topology, and
a proof that the topology coincides with the one coming from the distance. When one defines the
product of two metric spaces, one uses the sup distance and the product topology, and one has to
give the proof that the sup distance induces the product topology. Following both sides of the
instance diamond then gives rise (definitionally) to the product topology on the product space.
Another approach would be to have the rich type class take the poor type class as an instance
parameter. It would solve the diamond problem, but it would lead to a blow up of the number
of type classes one would need to declare to work with complicated classes, say a real inner
product space, and would create exponential complexity when working with products of
such complicated spaces, that are avoided by bundling things carefully as above.
Note that this description of this specific case of the product of metric spaces is oversimplified
compared to mathlib, as there is an intermediate typeclass between `metric_space` and
`topological_space` called `uniform_space`. The above scheme is used at both levels, embedding a
topology in the uniform space structure, and a uniform structure in the metric space structure.
Note also that, when `P` is a proposition, there is no such issue as any two proofs of `P` are
definitionally equivalent in Lean.
To avoid boilerplate, there are some designs that can automatically fill the poor fields when
creating a rich structure if one doesn't want to do something special about them. For instance,
in the definition of metric spaces, default tactics fill the uniform space fields if they are
not given explicitly. One can also have a helper function creating the rich structure from a
structure with less fields, where the helper function fills the remaining fields. See for instance
`uniform_space.of_core` or `real_inner_product.of_core`.
For more details on this question, called the forgetful inheritance pattern, see [Competing
inheritance paths in dependent type theory: a case study in functional
analysis](https://hal.inria.fr/hal-02463336).
-/
/-- A uniform space is a generalization of the "uniform" topological aspects of a
metric space. It consists of a filter on `α × α` called the "uniformity", which
satisfies properties analogous to the reflexivity, symmetry, and triangle properties
of a metric.
A metric space has a natural uniformity, and a uniform space has a natural topology.
A topological group also has a natural uniformity, even when it is not metrizable. -/
class uniform_space (α : Type u) extends uniform_space.core α, topological_space α where
is_open_uniformity :
∀ (s : set α),
topological_space.is_open _to_topological_space s ↔
∀ (x : α),
x ∈ s →
(set_of fun (p : α × α) => prod.fst p = x → prod.snd p ∈ s) ∈
uniform_space.core.uniformity _to_core
/-- Alternative constructor for `uniform_space α` when a topology is already given. -/
def uniform_space.mk' {α : Type u_1} (t : topological_space α) (c : uniform_space.core α)
(is_open_uniformity :
∀ (s : set α),
topological_space.is_open t s ↔
∀ (x : α),
x ∈ s →
(set_of fun (p : α × α) => prod.fst p = x → prod.snd p ∈ s) ∈
uniform_space.core.uniformity c) :
uniform_space α :=
uniform_space.mk c is_open_uniformity
/-- Construct a `uniform_space` from a `uniform_space.core`. -/
def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α :=
uniform_space.mk u sorry
/-- Construct a `uniform_space` from a `u : uniform_space.core` and a `topological_space` structure
that is equal to `u.to_topological_space`. -/
def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α)
(h : t = uniform_space.core.to_topological_space u) : uniform_space α :=
uniform_space.mk u sorry
theorem uniform_space.to_core_to_topological_space {α : Type u_1} (u : uniform_space α) :
uniform_space.core.to_topological_space uniform_space.to_core =
uniform_space.to_topological_space :=
sorry
theorem uniform_space_eq {α : Type u_1} {u₁ : uniform_space α} {u₂ : uniform_space α} :
uniform_space.core.uniformity uniform_space.to_core =
uniform_space.core.uniformity uniform_space.to_core →
u₁ = u₂ :=
sorry
theorem uniform_space.of_core_eq_to_core {α : Type u_1} (u : uniform_space α)
(t : topological_space α)
(h : t = uniform_space.core.to_topological_space uniform_space.to_core) :
uniform_space.of_core_eq uniform_space.to_core t h = u :=
uniform_space_eq rfl
/-- The uniformity is a filter on α × α (inferred from an ambient uniform space
structure on α). -/
def uniformity (α : Type u) [uniform_space α] : filter (α × α) :=
uniform_space.core.uniformity uniform_space.to_core
theorem is_open_uniformity {α : Type u_1} [uniform_space α] {s : set α} :
is_open s ↔
∀ (x : α),
x ∈ s → (set_of fun (p : α × α) => prod.fst p = x → prod.snd p ∈ s) ∈ uniformity α :=
uniform_space.is_open_uniformity s
theorem refl_le_uniformity {α : Type u_1} [uniform_space α] :
filter.principal id_rel ≤ uniformity α :=
uniform_space.core.refl uniform_space.to_core
theorem refl_mem_uniformity {α : Type u_1} [uniform_space α] {x : α} {s : set (α × α)}
(h : s ∈ uniformity α) : (x, x) ∈ s :=
refl_le_uniformity h rfl
theorem symm_le_uniformity {α : Type u_1} [uniform_space α] :
filter.map prod.swap (uniformity α) ≤ uniformity α :=
uniform_space.core.symm uniform_space.to_core
theorem comp_le_uniformity {α : Type u_1} [uniform_space α] :
(filter.lift' (uniformity α) fun (s : set (α × α)) => comp_rel s s) ≤ uniformity α :=
uniform_space.core.comp uniform_space.to_core
theorem tendsto_swap_uniformity {α : Type u_1} [uniform_space α] :
filter.tendsto prod.swap (uniformity α) (uniformity α) :=
symm_le_uniformity
theorem comp_mem_uniformity_sets {α : Type u_1} [uniform_space α] {s : set (α × α)}
(hs : s ∈ uniformity α) : ∃ (t : set (α × α)), ∃ (H : t ∈ uniformity α), comp_rel t t ⊆ s :=
(fun (this : s ∈ filter.lift' (uniformity α) fun (t : set (α × α)) => comp_rel t t) =>
iff.mp (filter.mem_lift'_sets (monotone_comp_rel monotone_id monotone_id)) this)
(comp_le_uniformity hs)
/-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is transitive. -/
theorem filter.tendsto.uniformity_trans {α : Type u_1} {β : Type u_2} [uniform_space α]
{l : filter β} {f₁ : β → α} {f₂ : β → α} {f₃ : β → α}
(h₁₂ : filter.tendsto (fun (x : β) => (f₁ x, f₂ x)) l (uniformity α))
(h₂₃ : filter.tendsto (fun (x : β) => (f₂ x, f₃ x)) l (uniformity α)) :
filter.tendsto (fun (x : β) => (f₁ x, f₃ x)) l (uniformity α) :=
sorry
/-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is symmetric -/
theorem filter.tendsto.uniformity_symm {α : Type u_1} {β : Type u_2} [uniform_space α]
{l : filter β} {f : β → α × α} (h : filter.tendsto f l (uniformity α)) :
filter.tendsto (fun (x : β) => (prod.snd (f x), prod.fst (f x))) l (uniformity α) :=
filter.tendsto.comp tendsto_swap_uniformity h
/-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is reflexive. -/
theorem tendsto_diag_uniformity {α : Type u_1} {β : Type u_2} [uniform_space α] (f : β → α)
(l : filter β) : filter.tendsto (fun (x : β) => (f x, f x)) l (uniformity α) :=
fun (s : set (α × α)) (hs : s ∈ uniformity α) =>
iff.mpr filter.mem_map (filter.univ_mem_sets' fun (x : β) => refl_mem_uniformity hs)
theorem tendsto_const_uniformity {α : Type u_1} {β : Type u_2} [uniform_space α] {a : α}
{f : filter β} : filter.tendsto (fun (_x : β) => (a, a)) f (uniformity α) :=
tendsto_diag_uniformity (fun (_x : β) => a) f
theorem symm_of_uniformity {α : Type u_1} [uniform_space α] {s : set (α × α)}
(hs : s ∈ uniformity α) :
∃ (t : set (α × α)), ∃ (H : t ∈ uniformity α), (∀ (a b : α), (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s :=
sorry
theorem comp_symm_of_uniformity {α : Type u_1} [uniform_space α] {s : set (α × α)}
(hs : s ∈ uniformity α) :
∃ (t : set (α × α)),
∃ (H : t ∈ uniformity α), (∀ {a b : α}, (a, b) ∈ t → (b, a) ∈ t) ∧ comp_rel t t ⊆ s :=
sorry
theorem uniformity_le_symm {α : Type u_1} [uniform_space α] :
uniformity α ≤ prod.swap <$> uniformity α :=
eq.mpr
(id
(Eq._oldrec (Eq.refl (uniformity α ≤ prod.swap <$> uniformity α))
filter.map_swap_eq_comap_swap))
(iff.mp filter.map_le_iff_le_comap tendsto_swap_uniformity)
theorem uniformity_eq_symm {α : Type u_1} [uniform_space α] :
uniformity α = prod.swap <$> uniformity α :=
le_antisymm uniformity_le_symm symm_le_uniformity
theorem symmetrize_mem_uniformity {α : Type u_1} [uniform_space α] {V : set (α × α)}
(h : V ∈ uniformity α) : symmetrize_rel V ∈ uniformity α :=
sorry
theorem uniformity_lift_le_swap {α : Type u_1} {β : Type u_2} [uniform_space α]
{g : set (α × α) → filter β} {f : filter β} (hg : monotone g)
(h : (filter.lift (uniformity α) fun (s : set (α × α)) => g (prod.swap ⁻¹' s)) ≤ f) :
filter.lift (uniformity α) g ≤ f :=
sorry
theorem uniformity_lift_le_comp {α : Type u_1} {β : Type u_2} [uniform_space α]
{f : set (α × α) → filter β} (h : monotone f) :
(filter.lift (uniformity α) fun (s : set (α × α)) => f (comp_rel s s)) ≤
filter.lift (uniformity α) f :=
sorry
theorem comp_le_uniformity3 {α : Type u_1} [uniform_space α] :
(filter.lift' (uniformity α) fun (s : set (α × α)) => comp_rel s (comp_rel s s)) ≤
uniformity α :=
sorry
theorem comp_symm_mem_uniformity_sets {α : Type u_1} [uniform_space α] {s : set (α × α)}
(hs : s ∈ uniformity α) :
∃ (t : set (α × α)), ∃ (H : t ∈ uniformity α), symmetric_rel t ∧ comp_rel t t ⊆ s :=
sorry
theorem subset_comp_self_of_mem_uniformity {α : Type u_1} [uniform_space α] {s : set (α × α)}
(h : s ∈ uniformity α) : s ⊆ comp_rel s s :=
subset_comp_self (refl_le_uniformity h)
theorem comp_comp_symm_mem_uniformity_sets {α : Type u_1} [uniform_space α] {s : set (α × α)}
(hs : s ∈ uniformity α) :
∃ (t : set (α × α)),
∃ (H : t ∈ uniformity α), symmetric_rel t ∧ comp_rel (comp_rel t t) t ⊆ s :=
sorry
/-!
### Balls in uniform spaces
-/
/-- The ball around `(x : β)` with respect to `(V : set (β × β))`. Intended to be
used for `V ∈ 𝓤 β`, but this is not needed for the definition. Recovers the
notions of metric space ball when `V = {p | dist p.1 p.2 < r }`. -/
def uniform_space.ball {β : Type u_2} (x : β) (V : set (β × β)) : set β := Prod.mk x ⁻¹' V
theorem uniform_space.mem_ball_self {α : Type u_1} [uniform_space α] (x : α) {V : set (α × α)}
(hV : V ∈ uniformity α) : x ∈ uniform_space.ball x V :=
refl_mem_uniformity hV
/-- The triangle inequality for `uniform_space.ball` -/
theorem mem_ball_comp {β : Type u_2} {V : set (β × β)} {W : set (β × β)} {x : β} {y : β} {z : β}
(h : y ∈ uniform_space.ball x V) (h' : z ∈ uniform_space.ball y W) :
z ∈ uniform_space.ball x (comp_rel V W) :=
prod_mk_mem_comp_rel h h'
theorem ball_subset_of_comp_subset {β : Type u_2} {V : set (β × β)} {W : set (β × β)} {x : β}
{y : β} (h : x ∈ uniform_space.ball y W) (h' : comp_rel W W ⊆ V) :
uniform_space.ball x W ⊆ uniform_space.ball y V :=
fun (z : β) (z_in : z ∈ uniform_space.ball x W) => h' (mem_ball_comp h z_in)
theorem ball_mono {β : Type u_2} {V : set (β × β)} {W : set (β × β)} (h : V ⊆ W) (x : β) :
uniform_space.ball x V ⊆ uniform_space.ball x W :=
id fun (a : β) (ᾰ : a ∈ uniform_space.ball x V) => h ᾰ
theorem mem_ball_symmetry {β : Type u_2} {V : set (β × β)} (hV : symmetric_rel V) {x : β} {y : β} :
x ∈ uniform_space.ball y V ↔ y ∈ uniform_space.ball x V :=
sorry
theorem ball_eq_of_symmetry {β : Type u_2} {V : set (β × β)} (hV : symmetric_rel V) {x : β} :
uniform_space.ball x V = set_of fun (y : β) => (y, x) ∈ V :=
sorry
theorem mem_comp_of_mem_ball {β : Type u_2} {V : set (β × β)} {W : set (β × β)} {x : β} {y : β}
{z : β} (hV : symmetric_rel V) (hx : x ∈ uniform_space.ball z V)
(hy : y ∈ uniform_space.ball z W) : (x, y) ∈ comp_rel V W :=
Exists.intro z
{ left :=
eq.mp (Eq._oldrec (Eq.refl (x ∈ uniform_space.ball z V)) (propext (mem_ball_symmetry hV)))
hx,
right := hy }
theorem uniform_space.is_open_ball {α : Type u_1} [uniform_space α] (x : α) {V : set (α × α)}
(hV : is_open V) : is_open (uniform_space.ball x V) :=
is_open.preimage (continuous.prod_mk continuous_const continuous_id) hV
theorem mem_comp_comp {β : Type u_2} {V : set (β × β)} {W : set (β × β)} {M : set (β × β)}
(hW' : symmetric_rel W) {p : β × β} :
p ∈ comp_rel (comp_rel V M) W ↔
set.nonempty
(set.prod (uniform_space.ball (prod.fst p) V) (uniform_space.ball (prod.snd p) W) ∩ M) :=
sorry
/-!
### Neighborhoods in uniform spaces
-/
theorem mem_nhds_uniformity_iff_right {α : Type u_1} [uniform_space α] {x : α} {s : set α} :
s ∈ nhds x ↔ (set_of fun (p : α × α) => prod.fst p = x → prod.snd p ∈ s) ∈ uniformity α :=
sorry
theorem mem_nhds_uniformity_iff_left {α : Type u_1} [uniform_space α] {x : α} {s : set α} :
s ∈ nhds x ↔ (set_of fun (p : α × α) => prod.snd p = x → prod.fst p ∈ s) ∈ uniformity α :=
sorry
theorem nhds_eq_comap_uniformity_aux {α : Type u} {x : α} {s : set α} {F : filter (α × α)} :
(set_of fun (p : α × α) => prod.fst p = x → prod.snd p ∈ s) ∈ F ↔
s ∈ filter.comap (Prod.mk x) F :=
sorry
theorem nhds_eq_comap_uniformity {α : Type u_1} [uniform_space α] {x : α} :
nhds x = filter.comap (Prod.mk x) (uniformity α) :=
sorry
theorem is_open_iff_ball_subset {α : Type u_1} [uniform_space α] {s : set α} :
is_open s ↔
∀ (x : α) (H : x ∈ s),
∃ (V : set (α × α)), ∃ (H : V ∈ uniformity α), uniform_space.ball x V ⊆ s :=
sorry
theorem nhds_basis_uniformity' {α : Type u_1} {β : Type u_2} [uniform_space α] {p : β → Prop}
{s : β → set (α × α)} (h : filter.has_basis (uniformity α) p s) {x : α} :
filter.has_basis (nhds x) p fun (i : β) => uniform_space.ball x (s i) :=
sorry
theorem nhds_basis_uniformity {α : Type u_1} {β : Type u_2} [uniform_space α] {p : β → Prop}
{s : β → set (α × α)} (h : filter.has_basis (uniformity α) p s) {x : α} :
filter.has_basis (nhds x) p fun (i : β) => set_of fun (y : α) => (y, x) ∈ s i :=
sorry
theorem uniform_space.mem_nhds_iff {α : Type u_1} [uniform_space α] {x : α} {s : set α} :
s ∈ nhds x ↔ ∃ (V : set (α × α)), ∃ (H : V ∈ uniformity α), uniform_space.ball x V ⊆ s :=
sorry
theorem uniform_space.ball_mem_nhds {α : Type u_1} [uniform_space α] (x : α) {V : set (α × α)}
(V_in : V ∈ uniformity α) : uniform_space.ball x V ∈ nhds x :=
eq.mpr
(id
(Eq._oldrec (Eq.refl (uniform_space.ball x V ∈ nhds x)) (propext uniform_space.mem_nhds_iff)))
(Exists.intro V (Exists.intro V_in (set.subset.refl (uniform_space.ball x V))))
theorem uniform_space.mem_nhds_iff_symm {α : Type u_1} [uniform_space α] {x : α} {s : set α} :
s ∈ nhds x ↔
∃ (V : set (α × α)),
∃ (H : V ∈ uniformity α), symmetric_rel V ∧ uniform_space.ball x V ⊆ s :=
sorry
theorem uniform_space.has_basis_nhds {α : Type u_1} [uniform_space α] (x : α) :
filter.has_basis (nhds x) (fun (s : set (α × α)) => s ∈ uniformity α ∧ symmetric_rel s)
fun (s : set (α × α)) => uniform_space.ball x s :=
sorry
theorem uniform_space.has_basis_nhds_prod {α : Type u_1} [uniform_space α] (x : α) (y : α) :
filter.has_basis (nhds (x, y)) (fun (s : set (α × α)) => s ∈ uniformity α ∧ symmetric_rel s)
fun (s : set (α × α)) => set.prod (uniform_space.ball x s) (uniform_space.ball y s) :=
sorry
theorem nhds_eq_uniformity {α : Type u_1} [uniform_space α] {x : α} :
nhds x = filter.lift' (uniformity α) (uniform_space.ball x) :=
filter.has_basis.eq_binfi (nhds_basis_uniformity' (filter.basis_sets (uniformity α)))
theorem mem_nhds_left {α : Type u_1} [uniform_space α] (x : α) {s : set (α × α)}
(h : s ∈ uniformity α) : (set_of fun (y : α) => (x, y) ∈ s) ∈ nhds x :=
uniform_space.ball_mem_nhds x h
theorem mem_nhds_right {α : Type u_1} [uniform_space α] (y : α) {s : set (α × α)}
(h : s ∈ uniformity α) : (set_of fun (x : α) => (x, y) ∈ s) ∈ nhds y :=
mem_nhds_left y (symm_le_uniformity h)
theorem tendsto_right_nhds_uniformity {α : Type u_1} [uniform_space α] {a : α} :
filter.tendsto (fun (a' : α) => (a', a)) (nhds a) (uniformity α) :=
fun (s : set (α × α)) => mem_nhds_right a
theorem tendsto_left_nhds_uniformity {α : Type u_1} [uniform_space α] {a : α} :
filter.tendsto (fun (a' : α) => (a, a')) (nhds a) (uniformity α) :=
fun (s : set (α × α)) => mem_nhds_left a
theorem lift_nhds_left {α : Type u_1} {β : Type u_2} [uniform_space α] {x : α}
{g : set α → filter β} (hg : monotone g) :
filter.lift (nhds x) g =
filter.lift (uniformity α) fun (s : set (α × α)) => g (set_of fun (y : α) => (x, y) ∈ s) :=
sorry
theorem lift_nhds_right {α : Type u_1} {β : Type u_2} [uniform_space α] {x : α}
{g : set α → filter β} (hg : monotone g) :
filter.lift (nhds x) g =
filter.lift (uniformity α) fun (s : set (α × α)) => g (set_of fun (y : α) => (y, x) ∈ s) :=
sorry
theorem nhds_nhds_eq_uniformity_uniformity_prod {α : Type u_1} [uniform_space α] {a : α} {b : α} :
filter.prod (nhds a) (nhds b) =
filter.lift (uniformity α)
fun (s : set (α × α)) =>
filter.lift' (uniformity α)
fun (t : set (α × α)) =>
set.prod (set_of fun (y : α) => (y, a) ∈ s) (set_of fun (y : α) => (b, y) ∈ t) :=
sorry
theorem nhds_eq_uniformity_prod {α : Type u_1} [uniform_space α] {a : α} {b : α} :
nhds (a, b) =
filter.lift' (uniformity α)
fun (s : set (α × α)) =>
set.prod (set_of fun (y : α) => (y, a) ∈ s) (set_of fun (y : α) => (b, y) ∈ s) :=
sorry
theorem nhdset_of_mem_uniformity {α : Type u_1} [uniform_space α] {d : set (α × α)}
(s : set (α × α)) (hd : d ∈ uniformity α) :
∃ (t : set (α × α)),
is_open t ∧
s ⊆ t ∧
t ⊆
set_of
fun (p : α × α) =>
∃ (x : α), ∃ (y : α), (prod.fst p, x) ∈ d ∧ (x, y) ∈ s ∧ (y, prod.snd p) ∈ d :=
sorry
/-- Entourages are neighborhoods of the diagonal. -/
theorem nhds_le_uniformity {α : Type u_1} [uniform_space α] (x : α) : nhds (x, x) ≤ uniformity α :=
sorry
/-- Entourages are neighborhoods of the diagonal. -/
theorem supr_nhds_le_uniformity {α : Type u_1} [uniform_space α] :
(supr fun (x : α) => nhds (x, x)) ≤ uniformity α :=
supr_le nhds_le_uniformity
/-!
### Closure and interior in uniform spaces
-/
theorem closure_eq_uniformity {α : Type u_1} [uniform_space α] (s : set (α × α)) :
closure s =
set.Inter
fun (V : set (α × α)) =>
set.Inter
fun (H : V ∈ set_of fun (V : set (α × α)) => V ∈ uniformity α ∧ symmetric_rel V) =>
comp_rel (comp_rel V s) V :=
sorry
theorem uniformity_has_basis_closed {α : Type u_1} [uniform_space α] :
filter.has_basis (uniformity α) (fun (V : set (α × α)) => V ∈ uniformity α ∧ is_closed V) id :=
sorry
/-- Closed entourages form a basis of the uniformity filter. -/
theorem uniformity_has_basis_closure {α : Type u_1} [uniform_space α] :
filter.has_basis (uniformity α) (fun (V : set (α × α)) => V ∈ uniformity α) closure :=
sorry
theorem closure_eq_inter_uniformity {α : Type u_1} [uniform_space α] {t : set (α × α)} :
closure t =
set.Inter
fun (d : set (α × α)) =>
set.Inter fun (H : d ∈ uniformity α) => comp_rel d (comp_rel t d) :=
sorry
theorem uniformity_eq_uniformity_closure {α : Type u_1} [uniform_space α] :
uniformity α = filter.lift' (uniformity α) closure :=
sorry
theorem uniformity_eq_uniformity_interior {α : Type u_1} [uniform_space α] :
uniformity α = filter.lift' (uniformity α) interior :=
sorry
theorem interior_mem_uniformity {α : Type u_1} [uniform_space α] {s : set (α × α)}
(hs : s ∈ uniformity α) : interior s ∈ uniformity α :=
eq.mpr (id (Eq._oldrec (Eq.refl (interior s ∈ uniformity α)) uniformity_eq_uniformity_interior))
(filter.mem_lift' hs)
theorem mem_uniformity_is_closed {α : Type u_1} [uniform_space α] {s : set (α × α)}
(h : s ∈ uniformity α) : ∃ (t : set (α × α)), ∃ (H : t ∈ uniformity α), is_closed t ∧ t ⊆ s :=
sorry
/-- The uniform neighborhoods of all points of a dense set cover the whole space. -/
theorem dense.bUnion_uniformity_ball {α : Type u_1} [uniform_space α] {s : set α} {U : set (α × α)}
(hs : dense s) (hU : U ∈ uniformity α) :
(set.Union fun (x : α) => set.Union fun (H : x ∈ s) => uniform_space.ball x U) = set.univ :=
sorry
/-!
### Uniformity bases
-/
/-- Open elements of `𝓤 α` form a basis of `𝓤 α`. -/
theorem uniformity_has_basis_open {α : Type u_1} [uniform_space α] :
filter.has_basis (uniformity α) (fun (V : set (α × α)) => V ∈ uniformity α ∧ is_open V) id :=
sorry
theorem filter.has_basis.mem_uniformity_iff {α : Type u_1} {β : Type u_2} [uniform_space α]
{p : β → Prop} {s : β → set (α × α)} (h : filter.has_basis (uniformity α) p s)
{t : set (α × α)} :
t ∈ uniformity α ↔ ∃ (i : β), ∃ (hi : p i), ∀ (a b : α), (a, b) ∈ s i → (a, b) ∈ t :=
sorry
/-- Symmetric entourages form a basis of `𝓤 α` -/
theorem uniform_space.has_basis_symmetric {α : Type u_1} [uniform_space α] :
filter.has_basis (uniformity α) (fun (s : set (α × α)) => s ∈ uniformity α ∧ symmetric_rel s)
id :=
sorry
/-- Open elements `s : set (α × α)` of `𝓤 α` such that `(x, y) ∈ s ↔ (y, x) ∈ s` form a basis
of `𝓤 α`. -/
theorem uniformity_has_basis_open_symmetric {α : Type u_1} [uniform_space α] :
filter.has_basis (uniformity α)
(fun (V : set (α × α)) => V ∈ uniformity α ∧ is_open V ∧ symmetric_rel V) id :=
sorry
theorem uniform_space.has_seq_basis {α : Type u_1} [uniform_space α]
(h : filter.is_countably_generated (uniformity α)) :
∃ (V : ℕ → set (α × α)),
filter.has_antimono_basis (uniformity α) (fun (_x : ℕ) => True) V ∧
∀ (n : ℕ), symmetric_rel (V n) :=
sorry
/-! ### Uniform continuity -/
/-- A function `f : α → β` is *uniformly continuous* if `(f x, f y)` tends to the diagonal
as `(x, y)` tends to the diagonal. In other words, if `x` is sufficiently close to `y`, then
`f x` is close to `f y` no matter where `x` and `y` are located in `α`. -/
def uniform_continuous {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β]
(f : α → β) :=
filter.tendsto (fun (x : α × α) => (f (prod.fst x), f (prod.snd x))) (uniformity α) (uniformity β)
/-- A function `f : α → β` is *uniformly continuous* on `s : set α` if `(f x, f y)` tends to
the diagonal as `(x, y)` tends to the diagonal while remaining in `s.prod s`.
In other words, if `x` is sufficiently close to `y`, then `f x` is close to
`f y` no matter where `x` and `y` are located in `s`.-/
def uniform_continuous_on {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β]
(f : α → β) (s : set α) :=
filter.tendsto (fun (x : α × α) => (f (prod.fst x), f (prod.snd x)))
(uniformity α ⊓ filter.principal (set.prod s s)) (uniformity β)
theorem uniform_continuous_def {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β]
{f : α → β} :
uniform_continuous f ↔
∀ (r : set (β × β)),
r ∈ uniformity β →
(set_of fun (x : α × α) => (f (prod.fst x), f (prod.snd x)) ∈ r) ∈ uniformity α :=
iff.rfl
theorem uniform_continuous_iff_eventually {α : Type u_1} {β : Type u_2} [uniform_space α]
[uniform_space β] {f : α → β} :
uniform_continuous f ↔
∀ (r : set (β × β)),
r ∈ uniformity β →
filter.eventually (fun (x : α × α) => (f (prod.fst x), f (prod.snd x)) ∈ r)
(uniformity α) :=
iff.rfl
theorem uniform_continuous_of_const {α : Type u_1} {β : Type u_2} [uniform_space α]
[uniform_space β] {c : α → β} (h : ∀ (a b : α), c a = c b) : uniform_continuous c :=
sorry
theorem uniform_continuous_id {α : Type u_1} [uniform_space α] : uniform_continuous id := sorry
theorem uniform_continuous_const {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β]
{b : β} : uniform_continuous fun (a : α) => b :=
uniform_continuous_of_const fun (_x _x : α) => rfl
theorem uniform_continuous.comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} [uniform_space α]
[uniform_space β] [uniform_space γ] {g : β → γ} {f : α → β} (hg : uniform_continuous g)
(hf : uniform_continuous f) : uniform_continuous (g ∘ f) :=
filter.tendsto.comp hg hf
theorem filter.has_basis.uniform_continuous_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3}
{δ : Type u_4} [uniform_space α] [uniform_space β] {p : γ → Prop} {s : γ → set (α × α)}
(ha : filter.has_basis (uniformity α) p s) {q : δ → Prop} {t : δ → set (β × β)}
(hb : filter.has_basis (uniformity β) q t) {f : α → β} :
uniform_continuous f ↔
∀ (i : δ), q i → ∃ (j : γ), ∃ (hj : p j), ∀ (x y : α), (x, y) ∈ s j → (f x, f y) ∈ t i :=
sorry
theorem filter.has_basis.uniform_continuous_on_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3}
{δ : Type u_4} [uniform_space α] [uniform_space β] {p : γ → Prop} {s : γ → set (α × α)}
(ha : filter.has_basis (uniformity α) p s) {q : δ → Prop} {t : δ → set (β × β)}
(hb : filter.has_basis (uniformity β) q t) {f : α → β} {S : set α} :
uniform_continuous_on f S ↔
∀ (i : δ),
q i →
∃ (j : γ), ∃ (hj : p j), ∀ (x y : α), x ∈ S → y ∈ S → (x, y) ∈ s j → (f x, f y) ∈ t i :=
sorry
protected instance uniform_space.partial_order {α : Type u_1} : partial_order (uniform_space α) :=
partial_order.mk
(fun (t s : uniform_space α) =>
uniform_space.core.uniformity uniform_space.to_core ≤
uniform_space.core.uniformity uniform_space.to_core)
(preorder.lt._default
fun (t s : uniform_space α) =>
uniform_space.core.uniformity uniform_space.to_core ≤
uniform_space.core.uniformity uniform_space.to_core)
sorry sorry sorry
protected instance uniform_space.has_Inf {α : Type u_1} : has_Inf (uniform_space α) :=
has_Inf.mk
fun (s : set (uniform_space α)) =>
uniform_space.of_core
(uniform_space.core.mk
(infi fun (u : uniform_space α) => infi fun (H : u ∈ s) => uniformity α) sorry sorry
sorry)
protected instance uniform_space.has_top {α : Type u_1} : has_top (uniform_space α) :=
has_top.mk (uniform_space.of_core (uniform_space.core.mk ⊤ sorry sorry sorry))
protected instance uniform_space.has_bot {α : Type u_1} : has_bot (uniform_space α) :=
has_bot.mk
(uniform_space.mk (uniform_space.core.mk (filter.principal id_rel) sorry sorry sorry) sorry)
protected instance uniform_space.complete_lattice {α : Type u_1} :
complete_lattice (uniform_space α) :=
complete_lattice.mk
(fun (a b : uniform_space α) => Inf (set_of fun (x : uniform_space α) => a ≤ x ∧ b ≤ x))
partial_order.le partial_order.lt sorry sorry sorry sorry sorry sorry
(fun (a b : uniform_space α) => Inf (insert a (singleton b))) sorry sorry sorry ⊤ sorry ⊥ sorry
(fun (tt : set (uniform_space α)) =>
Inf (set_of fun (t : uniform_space α) => ∀ (t' : uniform_space α), t' ∈ tt → t' ≤ t))
Inf sorry sorry sorry sorry
theorem infi_uniformity {α : Type u_1} {ι : Sort u_2} {u : ι → uniform_space α} :
uniform_space.core.uniformity uniform_space.to_core =
infi fun (i : ι) => uniform_space.core.uniformity uniform_space.to_core :=
sorry
theorem inf_uniformity {α : Type u_1} {u : uniform_space α} {v : uniform_space α} :
uniform_space.core.uniformity uniform_space.to_core =
uniform_space.core.uniformity uniform_space.to_core ⊓
uniform_space.core.uniformity uniform_space.to_core :=
sorry
protected instance inhabited_uniform_space {α : Type u_1} : Inhabited (uniform_space α) :=
{ default := ⊥ }
protected instance inhabited_uniform_space_core {α : Type u_1} : Inhabited (uniform_space.core α) :=
{ default := uniform_space.to_core }
/-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f`
is the inverse image in the filter sense of the induced function `α × α → β × β`. -/
def uniform_space.comap {α : Type u_1} {β : Type u_2} (f : α → β) (u : uniform_space β) :
uniform_space α :=
uniform_space.mk
(uniform_space.core.mk
(filter.comap (fun (p : α × α) => (f (prod.fst p), f (prod.snd p)))
(uniform_space.core.uniformity uniform_space.to_core))
sorry sorry sorry)
sorry
theorem uniformity_comap {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β]
{f : α → β} (h : _inst_1 = uniform_space.comap f _inst_2) :
uniformity α = filter.comap (prod.map f f) (uniformity β) :=
eq.mpr (id (Eq._oldrec (Eq.refl (uniformity α = filter.comap (prod.map f f) (uniformity β))) h))
(Eq.refl (uniformity α))
theorem uniform_space_comap_id {α : Type u_1} : uniform_space.comap id = id := sorry
theorem uniform_space.comap_comap {α : Type u_1} {β : Type u_2} {γ : Type u_3}
[uγ : uniform_space γ] {f : α → β} {g : β → γ} :
uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) :=
sorry
theorem uniform_continuous_iff {α : Type u_1} {β : Type u_2} [uα : uniform_space α]
[uβ : uniform_space β] {f : α → β} : uniform_continuous f ↔ uα ≤ uniform_space.comap f uβ :=
filter.map_le_iff_le_comap
theorem uniform_continuous_comap {α : Type u_1} {β : Type u_2} {f : α → β} [u : uniform_space β] :
uniform_continuous f :=
filter.tendsto_comap
theorem to_topological_space_comap {α : Type u_1} {β : Type u_2} {f : α → β} {u : uniform_space β} :
uniform_space.to_topological_space =
topological_space.induced f uniform_space.to_topological_space :=
rfl
theorem uniform_continuous_comap' {α : Type u_1} {β : Type u_2} {γ : Type u_3} {f : γ → β}
{g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) :
uniform_continuous g :=
iff.mpr filter.tendsto_comap_iff h
theorem to_topological_space_mono {α : Type u_1} {u₁ : uniform_space α} {u₂ : uniform_space α}
(h : u₁ ≤ u₂) : uniform_space.to_topological_space ≤ uniform_space.to_topological_space :=
sorry
theorem uniform_continuous.continuous {α : Type u_1} {β : Type u_2} [uniform_space α]
[uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f :=
iff.mpr continuous_iff_le_induced (to_topological_space_mono (iff.mp uniform_continuous_iff hf))
theorem to_topological_space_bot {α : Type u_1} : uniform_space.to_topological_space = ⊥ := rfl
theorem to_topological_space_top {α : Type u_1} : uniform_space.to_topological_space = ⊤ := sorry
theorem to_topological_space_infi {α : Type u_1} {ι : Sort u_2} {u : ι → uniform_space α} :
uniform_space.to_topological_space = infi fun (i : ι) => uniform_space.to_topological_space :=
sorry
theorem to_topological_space_Inf {α : Type u_1} {s : set (uniform_space α)} :
uniform_space.to_topological_space =
infi
fun (i : uniform_space α) => infi fun (H : i ∈ s) => uniform_space.to_topological_space :=
sorry
theorem to_topological_space_inf {α : Type u_1} {u : uniform_space α} {v : uniform_space α} :
uniform_space.to_topological_space =
uniform_space.to_topological_space ⊓ uniform_space.to_topological_space :=
sorry
protected instance empty.uniform_space : uniform_space empty := ⊥
protected instance unit.uniform_space : uniform_space Unit := ⊥
protected instance bool.uniform_space : uniform_space Bool := ⊥
protected instance nat.uniform_space : uniform_space ℕ := ⊥
protected instance int.uniform_space : uniform_space ℤ := ⊥
protected instance subtype.uniform_space {α : Type u_1} {p : α → Prop} [t : uniform_space α] :
uniform_space (Subtype p) :=
uniform_space.comap subtype.val t
theorem uniformity_subtype {α : Type u_1} {p : α → Prop} [t : uniform_space α] :
uniformity (Subtype p) =
filter.comap
(fun (q : Subtype p × Subtype p) => (subtype.val (prod.fst q), subtype.val (prod.snd q)))
(uniformity α) :=
rfl
theorem uniform_continuous_subtype_val {α : Type u_1} {p : α → Prop} [uniform_space α] :
uniform_continuous subtype.val :=
uniform_continuous_comap
theorem uniform_continuous_subtype_mk {α : Type u_1} {β : Type u_2} {p : α → Prop} [uniform_space α]
[uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀ (x : β), p (f x)) :
uniform_continuous fun (x : β) => { val := f x, property := h x } :=
uniform_continuous_comap' hf
theorem uniform_continuous_on_iff_restrict {α : Type u_1} {β : Type u_2} [uniform_space α]
[uniform_space β] {f : α → β} {s : set α} :
uniform_continuous_on f s ↔ uniform_continuous (set.restrict f s) :=
sorry
theorem tendsto_of_uniform_continuous_subtype {α : Type u_1} {β : Type u_2} [uniform_space α]
[uniform_space β] {f : α → β} {s : set α} {a : α}
(hf : uniform_continuous fun (x : ↥s) => f (subtype.val x)) (ha : s ∈ nhds a) :
filter.tendsto f (nhds a) (nhds (f a)) :=
sorry
theorem uniform_continuous_on.continuous_on {α : Type u_1} {β : Type u_2} [uniform_space α]
[uniform_space β] {f : α → β} {s : set α} (h : uniform_continuous_on f s) : continuous_on f s :=
eq.mpr
(id (Eq._oldrec (Eq.refl (continuous_on f s)) (propext continuous_on_iff_continuous_restrict)))
(uniform_continuous.continuous
(eq.mp
(Eq._oldrec (Eq.refl (uniform_continuous_on f s))
(propext uniform_continuous_on_iff_restrict))
h))
/- a similar product space is possible on the function space (uniformity of pointwise convergence),
but we want to have the uniformity of uniform convergence on function spaces -/
protected instance prod.uniform_space {α : Type u_1} {β : Type u_2} [u₁ : uniform_space α]
[u₂ : uniform_space β] : uniform_space (α × β) :=
uniform_space.of_core_eq uniform_space.to_core prod.topological_space sorry
theorem uniformity_prod {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] :
uniformity (α × β) =
filter.comap (fun (p : (α × β) × α × β) => (prod.fst (prod.fst p), prod.fst (prod.snd p)))
(uniformity α) ⊓
filter.comap (fun (p : (α × β) × α × β) => (prod.snd (prod.fst p), prod.snd (prod.snd p)))
(uniformity β) :=
inf_uniformity
theorem uniformity_prod_eq_prod {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] :
uniformity (α × β) =
filter.map
(fun (p : (α × α) × β × β) =>
((prod.fst (prod.fst p), prod.fst (prod.snd p)), prod.snd (prod.fst p),
prod.snd (prod.snd p)))
(filter.prod (uniformity α) (uniformity β)) :=
sorry
theorem mem_map_sets_iff' {α : Type u_1} {β : Type u_2} {f : filter α} {m : α → β} {t : set β} :
t ∈ filter.sets (filter.map m f) ↔ ∃ (s : set α), ∃ (H : s ∈ f), m '' s ⊆ t :=
filter.mem_map_sets_iff
theorem mem_uniformity_of_uniform_continuous_invariant {α : Type u_1} [uniform_space α]
{s : set (α × α)} {f : α → α → α}
(hf : uniform_continuous fun (p : α × α) => f (prod.fst p) (prod.snd p))
(hs : s ∈ uniformity α) :
∃ (u : set (α × α)), ∃ (H : u ∈ uniformity α), ∀ (a b c : α), (a, b) ∈ u → (f a c, f b c) ∈ s :=
sorry
theorem mem_uniform_prod {α : Type u_1} {β : Type u_2} [t₁ : uniform_space α] [t₂ : uniform_space β]
{a : set (α × α)} {b : set (β × β)} (ha : a ∈ uniformity α) (hb : b ∈ uniformity β) :
(set_of
fun (p : (α × β) × α × β) =>
(prod.fst (prod.fst p), prod.fst (prod.snd p)) ∈ a ∧
(prod.snd (prod.fst p), prod.snd (prod.snd p)) ∈ b) ∈
uniformity (α × β) :=
sorry
theorem tendsto_prod_uniformity_fst {α : Type u_1} {β : Type u_2} [uniform_space α]
[uniform_space β] :
filter.tendsto (fun (p : (α × β) × α × β) => (prod.fst (prod.fst p), prod.fst (prod.snd p)))
(uniformity (α × β)) (uniformity α) :=
le_trans (filter.map_mono inf_le_left) filter.map_comap_le
theorem tendsto_prod_uniformity_snd {α : Type u_1} {β : Type u_2} [uniform_space α]
[uniform_space β] :
filter.tendsto (fun (p : (α × β) × α × β) => (prod.snd (prod.fst p), prod.snd (prod.snd p)))
(uniformity (α × β)) (uniformity β) :=
le_trans (filter.map_mono inf_le_right) filter.map_comap_le
theorem uniform_continuous_fst {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] :
uniform_continuous fun (p : α × β) => prod.fst p :=
tendsto_prod_uniformity_fst
theorem uniform_continuous_snd {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] :
uniform_continuous fun (p : α × β) => prod.snd p :=
tendsto_prod_uniformity_snd
theorem uniform_continuous.prod_mk {α : Type u_1} {β : Type u_2} {γ : Type u_3} [uniform_space α]
[uniform_space β] [uniform_space γ] {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁)
(h₂ : uniform_continuous f₂) : uniform_continuous fun (a : α) => (f₁ a, f₂ a) :=
sorry
theorem uniform_continuous.prod_mk_left {α : Type u_1} {β : Type u_2} {γ : Type u_3}
[uniform_space α] [uniform_space β] [uniform_space γ] {f : α × β → γ} (h : uniform_continuous f)
(b : β) : uniform_continuous fun (a : α) => f (a, b) :=
uniform_continuous.comp h
(uniform_continuous.prod_mk uniform_continuous_id uniform_continuous_const)
theorem uniform_continuous.prod_mk_right {α : Type u_1} {β : Type u_2} {γ : Type u_3}
[uniform_space α] [uniform_space β] [uniform_space γ] {f : α × β → γ} (h : uniform_continuous f)
(a : α) : uniform_continuous fun (b : β) => f (a, b) :=
uniform_continuous.comp h
(uniform_continuous.prod_mk uniform_continuous_const uniform_continuous_id)
theorem uniform_continuous.prod_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4}
[uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] {f : α → γ} {g : β → δ}
(hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (prod.map f g) :=
uniform_continuous.prod_mk (uniform_continuous.comp hf uniform_continuous_fst)
(uniform_continuous.comp hg uniform_continuous_snd)
theorem to_topological_space_prod {α : Type u_1} {β : Type u_2} [u : uniform_space α]
[v : uniform_space β] : uniform_space.to_topological_space = prod.topological_space :=
rfl
/-- Uniform continuity for functions of two variables. -/
def uniform_continuous₂ {α : Type u_1} {β : Type u_2} {γ : Type u_3} [uniform_space α]
[uniform_space β] [uniform_space γ] (f : α → β → γ) :=
uniform_continuous (function.uncurry f)
theorem uniform_continuous₂_def {α : Type u_1} {β : Type u_2} {γ : Type u_3} [uniform_space α]
[uniform_space β] [uniform_space γ] (f : α → β → γ) :
uniform_continuous₂ f ↔ uniform_continuous (function.uncurry f) :=
iff.rfl
theorem uniform_continuous₂.uniform_continuous {α : Type u_1} {β : Type u_2} {γ : Type u_3}
[uniform_space α] [uniform_space β] [uniform_space γ] {f : α → β → γ}
(h : uniform_continuous₂ f) : uniform_continuous (function.uncurry f) :=
h
theorem uniform_continuous₂_curry {α : Type u_1} {β : Type u_2} {γ : Type u_3} [uniform_space α]
[uniform_space β] [uniform_space γ] (f : α × β → γ) :
uniform_continuous₂ (function.curry f) ↔ uniform_continuous f :=
sorry
theorem uniform_continuous₂.comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4}
[uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] {f : α → β → γ}
{g : γ → δ} (hg : uniform_continuous g) (hf : uniform_continuous₂ f) :
uniform_continuous₂ (function.bicompr g f) :=
uniform_continuous.comp hg hf
theorem uniform_continuous₂.bicompl {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4}
{δ' : Type u_6} [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ]
[uniform_space δ'] {f : α → β → γ} {ga : δ → α} {gb : δ' → β} (hf : uniform_continuous₂ f)
(hga : uniform_continuous ga) (hgb : uniform_continuous gb) :
uniform_continuous₂ (function.bicompl f ga gb) :=
uniform_continuous.comp (uniform_continuous₂.uniform_continuous hf)
(uniform_continuous.prod_map hga hgb)
theorem to_topological_space_subtype {α : Type u_1} [u : uniform_space α] {p : α → Prop} :
uniform_space.to_topological_space = subtype.topological_space :=
rfl
/-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained
by taking independently an entourage of the diagonal in the first part, and an entourage of
the diagonal in the second part. -/
def uniform_space.core.sum {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] :
uniform_space.core (α ⊕ β) :=
uniform_space.core.mk'
(filter.map (fun (p : α × α) => (sum.inl (prod.fst p), sum.inl (prod.snd p))) (uniformity α) ⊔
filter.map (fun (p : β × β) => (sum.inr (prod.fst p), sum.inr (prod.snd p))) (uniformity β))
sorry sorry sorry
/-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage
of the diagonal. -/
theorem union_mem_uniformity_sum {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β]
{a : set (α × α)} (ha : a ∈ uniformity α) {b : set (β × β)} (hb : b ∈ uniformity β) :
(fun (p : α × α) => (sum.inl (prod.fst p), sum.inl (prod.snd p))) '' a ∪
(fun (p : β × β) => (sum.inr (prod.fst p), sum.inr (prod.snd p))) '' b ∈
uniform_space.core.uniformity uniform_space.core.sum :=
sorry
/- To prove that the topology defined by the uniform structure on the disjoint union coincides with
the disjoint union topology, we need two lemmas saying that open sets can be characterized by
the uniform structure -/
theorem uniformity_sum_of_open_aux {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β]
{s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) :
(set_of fun (p : (α ⊕ β) × (α ⊕ β)) => prod.fst p = x → prod.snd p ∈ s) ∈
uniform_space.core.uniformity uniform_space.core.sum :=
sorry
theorem open_of_uniformity_sum_aux {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β]
{s : set (α ⊕ β)}
(hs :
∀ (x : α ⊕ β),
x ∈ s →
(set_of fun (p : (α ⊕ β) × (α ⊕ β)) => prod.fst p = x → prod.snd p ∈ s) ∈
uniform_space.core.uniformity uniform_space.core.sum) :
is_open s :=
sorry
/- We can now define the uniform structure on the disjoint union -/
protected instance sum.uniform_space {α : Type u_1} {β : Type u_2} [uniform_space α]
[uniform_space β] : uniform_space (α ⊕ β) :=
uniform_space.mk uniform_space.core.sum sorry
theorem sum.uniformity {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] :
uniformity (α ⊕ β) =
filter.map (fun (p : α × α) => (sum.inl (prod.fst p), sum.inl (prod.snd p)))
(uniformity α) ⊔
filter.map (fun (p : β × β) => (sum.inr (prod.fst p), sum.inr (prod.snd p)))
(uniformity β) :=
rfl
-- For a version of the Lebesgue number lemma assuming only a sequentially compact space,
-- see topology/sequences.lean
/-- Let `c : ι → set α` be an open cover of a compact set `s`. Then there exists an entourage
`n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `c i`. -/
theorem lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι : Sort u_1}
{c : ι → set α} (hs : is_compact s) (hc₁ : ∀ (i : ι), is_open (c i))
(hc₂ : s ⊆ set.Union fun (i : ι) => c i) :
∃ (n : set (α × α)),
∃ (H : n ∈ uniformity α),
∀ (x : α), x ∈ s → ∃ (i : ι), (set_of fun (y : α) => (x, y) ∈ n) ⊆ c i :=
sorry
/-- Let `c : set (set α)` be an open cover of a compact set `s`. Then there exists an entourage
`n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `t ∈ c`. -/
theorem lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)}
(hs : is_compact s) (hc₁ : ∀ (t : set α), t ∈ c → is_open t) (hc₂ : s ⊆ ⋃₀c) :
∃ (n : set (α × α)),
∃ (H : n ∈ uniformity α),
∀ (x : α) (H : x ∈ s), ∃ (t : set α), ∃ (H : t ∈ c), ∀ (y : α), (x, y) ∈ n → y ∈ t :=
sorry
/-!
### Expressing continuity properties in uniform spaces
We reformulate the various continuity properties of functions taking values in a uniform space
in terms of the uniformity in the target. Since the same lemmas (essentially with the same names)
also exist for metric spaces and emetric spaces (reformulating things in terms of the distance or
the edistance in the target), we put them in a namespace `uniform` here.
In the metric and emetric space setting, there are also similar lemmas where one assumes that
both the source and the target are metric spaces, reformulating things in terms of the distance
on both sides. These lemmas are generally written without primes, and the versions where only
the target is a metric space is primed. We follow the same convention here, thus giving lemmas
with primes.
-/
namespace uniform
theorem tendsto_nhds_right {α : Type u_1} {β : Type u_2} [uniform_space α] {f : filter β}
{u : β → α} {a : α} :
filter.tendsto u f (nhds a) ↔ filter.tendsto (fun (x : β) => (a, u x)) f (uniformity α) :=
sorry
theorem tendsto_nhds_left {α : Type u_1} {β : Type u_2} [uniform_space α] {f : filter β} {u : β → α}
{a : α} :
filter.tendsto u f (nhds a) ↔ filter.tendsto (fun (x : β) => (u x, a)) f (uniformity α) :=
sorry
theorem continuous_at_iff'_right {α : Type u_1} {β : Type u_2} [uniform_space α]
[topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔ filter.tendsto (fun (x : β) => (f b, f x)) (nhds b) (uniformity α) :=
sorry
theorem continuous_at_iff'_left {α : Type u_1} {β : Type u_2} [uniform_space α]
[topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔ filter.tendsto (fun (x : β) => (f x, f b)) (nhds b) (uniformity α) :=
sorry
theorem continuous_at_iff_prod {α : Type u_1} {β : Type u_2} [uniform_space α] [topological_space β]
{f : β → α} {b : β} :
continuous_at f b ↔
filter.tendsto (fun (x : β × β) => (f (prod.fst x), f (prod.snd x))) (nhds (b, b))
(uniformity α) :=
sorry
theorem continuous_within_at_iff'_right {α : Type u_1} {β : Type u_2} [uniform_space α]
[topological_space β] {f : β → α} {b : β} {s : set β} :
continuous_within_at f s b ↔
filter.tendsto (fun (x : β) => (f b, f x)) (nhds_within b s) (uniformity α) :=
sorry
theorem continuous_within_at_iff'_left {α : Type u_1} {β : Type u_2} [uniform_space α]
[topological_space β] {f : β → α} {b : β} {s : set β} :
continuous_within_at f s b ↔
filter.tendsto (fun (x : β) => (f x, f b)) (nhds_within b s) (uniformity α) :=
sorry
theorem continuous_on_iff'_right {α : Type u_1} {β : Type u_2} [uniform_space α]
[topological_space β] {f : β → α} {s : set β} :
continuous_on f s ↔
∀ (b : β),
b ∈ s → filter.tendsto (fun (x : β) => (f b, f x)) (nhds_within b s) (uniformity α) :=
sorry
theorem continuous_on_iff'_left {α : Type u_1} {β : Type u_2} [uniform_space α]
[topological_space β] {f : β → α} {s : set β} :
continuous_on f s ↔
∀ (b : β),
b ∈ s → filter.tendsto (fun (x : β) => (f x, f b)) (nhds_within b s) (uniformity α) :=
sorry
theorem continuous_iff'_right {α : Type u_1} {β : Type u_2} [uniform_space α] [topological_space β]
{f : β → α} :
continuous f ↔ ∀ (b : β), filter.tendsto (fun (x : β) => (f b, f x)) (nhds b) (uniformity α) :=
iff.trans continuous_iff_continuous_at (forall_congr fun (b : β) => tendsto_nhds_right)
theorem continuous_iff'_left {α : Type u_1} {β : Type u_2} [uniform_space α] [topological_space β]
{f : β → α} :
continuous f ↔ ∀ (b : β), filter.tendsto (fun (x : β) => (f x, f b)) (nhds b) (uniformity α) :=
iff.trans continuous_iff_continuous_at (forall_congr fun (b : β) => tendsto_nhds_left)
end uniform
theorem filter.tendsto.congr_uniformity {α : Type u_1} {β : Type u_2} [uniform_space β] {f : α → β}
{g : α → β} {l : filter α} {b : β} (hf : filter.tendsto f l (nhds b))
(hg : filter.tendsto (fun (x : α) => (f x, g x)) l (uniformity β)) :
filter.tendsto g l (nhds b) :=
iff.mpr uniform.tendsto_nhds_right
(filter.tendsto.uniformity_trans (iff.mp uniform.tendsto_nhds_right hf) hg)
theorem uniform.tendsto_congr {α : Type u_1} {β : Type u_2} [uniform_space β] {f : α → β}
{g : α → β} {l : filter α} {b : β}
(hfg : filter.tendsto (fun (x : α) => (f x, g x)) l (uniformity β)) :
filter.tendsto f l (nhds b) ↔ filter.tendsto g l (nhds b) :=
{ mp := fun (h : filter.tendsto f l (nhds b)) => filter.tendsto.congr_uniformity h hfg,
mpr :=
fun (h : filter.tendsto g l (nhds b)) =>
filter.tendsto.congr_uniformity h (filter.tendsto.uniformity_symm hfg) }
end Mathlib |
7e9d68d1fe22fc3d2b8f2c150cd276b681f2bf37 | 59cb0b250f036506a327b29abf0b51ff1efbb0c9 | /src/hamcode_widget.lean | 180c1de3cfda3d4f7f2427e0ba05d11f3ae4ded6 | [] | no_license | GeorgeTillisch/coding_theory_lean | ea26861a3d5d8ca897ca50b056d9cae53104bc27 | 920e14b433080854d4248714c93a09ce4e391522 | refs/heads/main | 1,681,707,926,918 | 1,619,008,763,000 | 1,619,008,763,000 | 343,145,352 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,513 | lean | import binary
import syndrome_decoding
open B BW
open hamming_code
open widget
/-!
# A widget for expoloring the Hamming(7,4) code.
Requires Lean extension for VSCode.
Click on the `#html` command to see the widget in the infoview panel.
(The widget looks best on a dark theme)
-/
variables {π α : Type}
def get_ith : Π {n : ℕ} (i : ℕ), BW n → string
| 0 _ _ := ""
| _ 1 (hd::ᴮtl) := hd.repr
| _ (i+1) (hd::ᴮtl) := get_ith i tl
def flip' : Π {n : ℕ} (i : ℕ), BW n → BW n
| 0 _ x := x
| _ 1 (hd::ᴮtl) := hd.flip ::ᴮ tl
| _ (i+1) (hd::ᴮtl) := hd ::ᴮ (flip' i tl)
inductive hamcode_action
| flip_first | flip_second | flip_third | flip_fourth
| pos1 | pos2 | pos3 | pos4 | pos5 | pos6 | pos7
open hamcode_action
meta def hamcode_init : π → (BW 4) × ℕ
| _ := ⟨ᴮ[O,O,O,O], 0⟩
meta def hamcode_props_changed : π → π → (BW 4) × ℕ → (BW 4) × ℕ
| _ _ word_and_errpos := word_and_errpos
meta def hamcode_update : π → (BW 4) × ℕ → hamcode_action → ((BW 4) × ℕ) × option α
| _ ⟨x, errpos⟩ flip_first := ⟨⟨x.flip 1 (by simp), errpos⟩, none⟩
| _ ⟨x, errpos⟩ flip_second := ⟨⟨x.flip 2 (by simp), errpos⟩, none⟩
| _ ⟨x, errpos⟩ flip_third := ⟨⟨x.flip 3 (by simp), errpos⟩, none⟩
| _ ⟨x, errpos⟩ flip_fourth := ⟨⟨x.flip 4 (by simp), errpos⟩, none⟩
| _ ⟨x, errpos⟩ pos1 := ⟨⟨x, 1⟩, none⟩
| _ ⟨x, errpos⟩ pos2 := ⟨⟨x, 2⟩, none⟩
| _ ⟨x, errpos⟩ pos3 := ⟨⟨x, 3⟩, none⟩
| _ ⟨x, errpos⟩ pos4 := ⟨⟨x, 4⟩, none⟩
| _ ⟨x, errpos⟩ pos5 := ⟨⟨x, 5⟩, none⟩
| _ ⟨x, errpos⟩ pos6 := ⟨⟨x, 6⟩, none⟩
| _ ⟨x, errpos⟩ pos7 := ⟨⟨x, 7⟩, none⟩
meta def hamcode_view : (((BW 4) × ℕ) × π) → list (html hamcode_action)
| ⟨⟨x, errpos⟩, _⟩ :=
h "section" [className "mw5 mw7-ns center bg-transparent pa3 ph5-ns"] [
h "h2" [className "mt0"] ["The Hamming(7,4) Code"],
h "p" [className "lh-copy measure"] ["Click on bits of the message to flip them. Click on error positions to flip a bit in the received word."],
h "h3" [] ["Message:"],
h "div" [className "dtc code"] [
h "button" [className "f3 br2 ph3 pv2 mb2 dib blue bg-white", on_click (λ ⟨⟩, flip_first)]
[get_ith 1 x],
h "button" [className "f3 br2 ph3 pv2 mb2 dib blue bg-white", on_click (λ ⟨⟩, flip_second)]
[get_ith 2 x],
h "button" [className "f3 br2 ph3 pv2 mb2 dib blue bg-white", on_click (λ ⟨⟩, flip_third)]
[get_ith 3 x],
h "button" [className "f3 br2 ph3 pv2 mb2 dib blue bg-white", on_click (λ ⟨⟩, flip_fourth)]
[get_ith 4 x]
],
h "h3" [] ["Encoded Word:"],
h "div" [className "dtc code"] [
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib green bg-white"]
[get_ith 1 (hamming74code.encode x)],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib green bg-white"]
[get_ith 2 (hamming74code.encode x)],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib blue bg-white"]
[get_ith 3 (hamming74code.encode x)],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib green bg-white"]
[get_ith 4 (hamming74code.encode x)],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib blue bg-white"]
[get_ith 5 (hamming74code.encode x)],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib blue bg-white"]
[get_ith 6 (hamming74code.encode x)],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib blue bg-white"]
[get_ith 7 (hamming74code.encode x)]
],
h "h3" [className "dib mr2"] ["Error Position"], html.of_string $ to_string $ errpos,
h "div" [className "dtc code"] [
h "button" [className "f3 dim br2 ph3 pv2 mb2 dib bg-white", on_click (λ ⟨⟩, pos1)] ["_"],
h "button" [className "f3 dim br2 ph3 pv2 mb2 dib bg-white", on_click (λ ⟨⟩, pos2)] ["_"],
h "button" [className "f3 dim br2 ph3 pv2 mb2 dib bg-white", on_click (λ ⟨⟩, pos3)] ["_"],
h "button" [className "f3 dim br2 ph3 pv2 mb2 dib bg-white", on_click (λ ⟨⟩, pos4)] ["_"],
h "button" [className "f3 dim br2 ph3 pv2 mb2 dib bg-white", on_click (λ ⟨⟩, pos5)] ["_"],
h "button" [className "f3 dim br2 ph3 pv2 mb2 dib bg-white", on_click (λ ⟨⟩, pos6)] ["_"],
h "button" [className "f3 dim br2 ph3 pv2 mb2 dib bg-white", on_click (λ ⟨⟩, pos7)] ["_"]
],
h "h3" [] ["Received Word:"],
h "div" [className "dtc code"] [
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib black bg-white"]
[get_ith 1 (flip' errpos (hamming74code.encode x))],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib black bg-white"]
[get_ith 2 (flip' errpos (hamming74code.encode x))],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib black bg-white"]
[get_ith 3 (flip' errpos (hamming74code.encode x))],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib black bg-white"]
[get_ith 4 (flip' errpos (hamming74code.encode x))],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib black bg-white"]
[get_ith 5 (flip' errpos (hamming74code.encode x))],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib black bg-white"]
[get_ith 6 (flip' errpos (hamming74code.encode x))],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib black bg-white"]
[get_ith 7 (flip' errpos (hamming74code.encode x))]
],
h "h3" [] ["Syndrome:"],
h "div" [className "dtc code"] [
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib black bg-white"]
[get_ith 1 (H × (flip' errpos (hamming74code.encode x))).reverse],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib black bg-white"]
[get_ith 2 (H × (flip' errpos (hamming74code.encode x))).reverse],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib black bg-white"]
[get_ith 3 (H × (flip' errpos (hamming74code.encode x))).reverse]
],
h "h3" [] ["Corrected Word:"],
h "div" [className "dtc code"] [
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib black bg-white"]
[get_ith 1 (hamming74code.error_correct (flip' errpos (hamming74code.encode x)))],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib black bg-white"]
[get_ith 2 (hamming74code.error_correct (flip' errpos (hamming74code.encode x)))],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib black bg-white"]
[get_ith 3 (hamming74code.error_correct (flip' errpos (hamming74code.encode x)))],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib black bg-white"]
[get_ith 4 (hamming74code.error_correct (flip' errpos (hamming74code.encode x)))],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib black bg-white"]
[get_ith 5 (hamming74code.error_correct (flip' errpos (hamming74code.encode x)))],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib black bg-white"]
[get_ith 6 (hamming74code.error_correct (flip' errpos (hamming74code.encode x)))],
h "div" [className "f3 br2 ph3 pv2 mb2 mr1 dib black bg-white"]
[get_ith 7 (hamming74code.error_correct (flip' errpos (hamming74code.encode x)))]
]
]
meta def HamcodeDemo : component π α :=
component.with_state
hamcode_action
((BW 4) × ℕ)
hamcode_init
hamcode_props_changed
hamcode_update
$ component.pure hamcode_view
-- Click on the #html part to see the widget
#html HamcodeDemo |
3fcfb3deedf0ffccc76cf41a7697b0616c11500b | a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7 | /src/tactic/equiv_rw.lean | df427b2808836846edbaad6c42e828803d9ef26f | [
"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 | 12,058 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import control.equiv_functor.instances
/-!
# The `equiv_rw` tactic transports goals or hypotheses along equivalences.
The basic syntax is `equiv_rw e`, where `e : α ≃ β` is an equivalence.
This will try to replace occurrences of `α` in the goal with `β`, for example
transforming
* `⊢ α` to `⊢ β`,
* `⊢ option α` to `⊢ option β`
* `⊢ {a // P}` to `{b // P (⇑(equiv.symm e) b)}`
The tactic can also be used to rewrite hypotheses, using the syntax `equiv_rw e at h`.
## Implementation details
The main internal function is `equiv_rw_type e t`,
which attempts to turn an expression `e : α ≃ β` into a new equivalence with left hand side `t`.
As an example, with `t = option α`, it will generate `functor.map_equiv option e`.
This is achieved by generating a new synthetic goal `%%t ≃ _`,
and calling `solve_by_elim` with an appropriate set of congruence lemmas.
To avoid having to specify the relevant congruence lemmas by hand,
we mostly rely on `equiv_functor.map_equiv` and `bifunctor.map_equiv`
along with some structural congruence lemmas such as
* `equiv.arrow_congr'`,
* `equiv.subtype_equiv_of_subtype'`,
* `equiv.sigma_congr_left'`, and
* `equiv.Pi_congr_left'`.
The main `equiv_rw` function, when operating on the goal, simply generates a new equivalence `e'`
with left hand side matching the target, and calls `apply e'.inv_fun`.
When operating on a hypothesis `x : α`, we introduce a new fact `h : x = e.symm (e x)`,
revert this, and then attempt to `generalize`, replacing all occurrences of `e x` with a new constant `y`,
before `intro`ing and `subst`ing `h`, and renaming `y` back to `x`.
## Future improvements
In a future PR I anticipate that `derive equiv_functor` should work on many examples,
(internally using `transport`, which is in turn based on `equiv_rw`)
and we can incrementally bootstrap the strength of `equiv_rw`.
An ambitious project might be to add `equiv_rw!`,
a tactic which, when failing to find appropriate `equiv_functor` instances,
attempts to `derive` them on the spot.
For now `equiv_rw` is entirely based on `equiv`,
but the framework can readily be generalised to also work with other types of equivalences,
for example specific notations such as ring equivalence (`≃+*`),
or general categorical isomorphisms (`≅`).
This will allow us to transport across more general types of equivalences,
but this will wait for another subsequent PR.
-/
namespace tactic
/-- A list of lemmas used for constructing congruence equivalences. -/
-- Although this looks 'hard-coded', in fact the lemma `equiv_functor.map_equiv`
-- allows us to extend `equiv_rw` simply by constructing new instance so `equiv_functor`.
-- TODO: We should also use `category_theory.functorial` and `category_theory.hygienic` instances.
-- (example goal: we could rewrite along an isomorphism of rings (either as `R ≅ S` or `R ≃+* S`)
-- and turn an `x : mv_polynomial σ R` into an `x : mv_polynomial σ S`.).
meta def equiv_congr_lemmas : tactic (list expr) :=
do exprs ←
[
`equiv.of_iff,
-- TODO decide what to do with this; it's an equiv_bifunctor?
`equiv.equiv_congr,
-- The function arrow is technically a bifunctor `Typeᵒᵖ → Type → Type`,
-- but the pattern matcher will never see this.
`equiv.arrow_congr',
-- Allow rewriting in subtypes:
`equiv.subtype_equiv_of_subtype',
-- Allow rewriting in the first component of a sigma-type:
`equiv.sigma_congr_left',
-- Allow rewriting ∀s:
-- (You might think that repeated application of `equiv.forall_congr'
-- would handle the higher arity cases, but unfortunately unification is not clever enough.)
`equiv.forall₃_congr',
`equiv.forall₂_congr',
`equiv.forall_congr',
-- Allow rewriting in argument of Pi types:
`equiv.Pi_congr_left',
-- Handles `sum` and `prod`, and many others:
`bifunctor.map_equiv,
-- Handles `list`, `option`, `unique`, and many others:
`equiv_functor.map_equiv,
-- We have to filter results to ensure we don't cheat and use exclusively `equiv.refl` and `iff.refl`!
`equiv.refl,
`iff.refl
].mmap (λ n, try_core (mk_const n)),
return (exprs.map option.to_list).join -- TODO: implement `.mfilter_map mk_const`?
declare_trace equiv_rw_type
/--
Configuration structure for `equiv_rw`.
* `max_depth` bounds the search depth for equivalences to rewrite along.
The default value is 10.
(e.g., if you're rewriting along `e : α ≃ β`, and `max_depth := 2`,
you can rewrite `option (option α))` but not `option (option (option α))`.
-/
meta structure equiv_rw_cfg :=
(max_depth : ℕ := 10)
/--
Implementation of `equiv_rw_type`, using `solve_by_elim`.
Expects a goal of the form `t ≃ _`,
and tries to solve it using `eq : α ≃ β` and congruence lemmas.
-/
meta def equiv_rw_type_core (eq : expr) (cfg : equiv_rw_cfg) : tactic unit :=
do
-- Assemble the relevant lemmas.
equiv_congr_lemmas ← equiv_congr_lemmas,
/-
We now call `solve_by_elim` to try to generate the requested equivalence.
There are a few subtleties!
* We make sure that `eq` is the first lemma, so it is applied whenever possible.
* In `equiv_congr_lemmas`, we put `equiv.refl` last so it is only used when it is not possible
to descend further.
* Since some congruence lemmas generate subgoals with `∀` statements,
we use the `pre_apply` subtactic of `solve_by_elim` to preprocess each new goal with `intros`.
-/
solve_by_elim
{ use_symmetry := false,
use_exfalso := false,
lemmas := some (eq :: equiv_congr_lemmas),
max_depth := cfg.max_depth,
-- Subgoals may contain function types,
-- and we want to continue trying to construct equivalences after the binders.
pre_apply := tactic.intros >> skip,
-- If solve_by_elim gets stuck, make sure it isn't because there's a later `≃` or `↔` goal
-- that we should still attempt.
discharger := `[show _ ≃ _] <|> `[show _ ↔ _] <|>
trace_if_enabled `equiv_rw_type "Failed, no congruence lemma applied!" >> failed,
-- We use the `accept` tactic in `solve_by_elim` to provide tracing.
accept := λ goals, lock_tactic_state (do
when_tracing `equiv_rw_type (do
goals.mmap pp >>= λ goals, trace format!"So far, we've built: {goals}"),
done <|>
when_tracing `equiv_rw_type (do
gs ← get_goals,
gs ← gs.mmap (λ g, infer_type g >>= pp),
trace format!"Attempting to adapt to {gs}")) }
/--
`equiv_rw_type e t` rewrites the type `t` using the equivalence `e : α ≃ β`,
returning a new equivalence `t ≃ t'`.
-/
meta def equiv_rw_type (eqv : expr) (ty : expr) (cfg : equiv_rw_cfg) : tactic expr :=
do
when_tracing `equiv_rw_type (do
ty_pp ← pp ty,
eqv_pp ← pp eqv,
eqv_ty_pp ← infer_type eqv >>= pp,
trace format!"Attempting to rewrite the type `{ty_pp}` using `{eqv_pp} : {eqv_ty_pp}`."),
`(_ ≃ _) ← infer_type eqv | fail format!"{eqv} must be an `equiv`",
-- We prepare a synthetic goal of type `(%%ty ≃ _)`, for some placeholder right hand side.
equiv_ty ← to_expr ``(%%ty ≃ _),
-- Now call `equiv_rw_type_core`.
new_eqv ← prod.snd <$> (solve_aux equiv_ty $ equiv_rw_type_core eqv cfg),
-- Check that we actually used the equivalence `eq`
-- (`equiv_rw_type_core` will always find `equiv.refl`, but hopefully only after all other possibilities)
new_eqv ← instantiate_mvars new_eqv,
-- We previously had `guard (eqv.occurs new_eqv)` here, but `kdepends_on` is more reliable.
kdepends_on new_eqv eqv >>= guardb <|> (do
eqv_pp ← pp eqv,
ty_pp ← pp ty,
fail format!"Could not construct an equivalence from {eqv_pp} of the form: {ty_pp} ≃ _"),
-- Finally we simplify the resulting equivalence,
-- to compress away some `map_equiv equiv.refl` subexpressions.
prod.fst <$> new_eqv.simp {fail_if_unchanged := ff}
mk_simp_attribute equiv_rw_simp "The simpset `equiv_rw_simp` is used by the tactic `equiv_rw` to
simplify applications of equivalences and their inverses."
attribute [equiv_rw_simp] equiv.symm_symm equiv.apply_symm_apply equiv.symm_apply_apply
/--
Attempt to replace the hypothesis with name `x`
by transporting it along the equivalence in `e : α ≃ β`.
-/
meta def equiv_rw_hyp (x : name) (e : expr) (cfg : equiv_rw_cfg := {}) : tactic unit :=
-- We call `dsimp_result` to perform the beta redex introduced by `revert`
dsimp_result (do
x' ← get_local x,
x_ty ← infer_type x',
-- Adapt `e` to an equivalence with left-hand-side `x_ty`.
e ← equiv_rw_type e x_ty cfg,
eq ← to_expr ``(%%x' = equiv.symm %%e (equiv.to_fun %%e %%x')),
prf ← to_expr ``((equiv.symm_apply_apply %%e %%x').symm),
h ← note_anon eq prf,
-- Revert the new hypothesis, so it is also part of the goal.
revert h,
ex ← to_expr ``(equiv.to_fun %%e %%x'),
-- Now call `generalize`,
-- attempting to replace all occurrences of `e x`,
-- calling it for now `j : β`, with `k : x = e.symm j`.
generalize ex (by apply_opt_param) transparency.none,
-- Reintroduce `x` (now of type `b`), and the hypothesis `h`.
intro x,
h ← intro1,
-- Finally, if we're working on properties, substitute along `h`, then do some cleanup,
-- and if we're working on data, just throw out the old `x`.
b ← target >>= is_prop,
if b then do
subst h,
`[try { simp only with equiv_rw_simp }]
else
-- We may need to unfreeze `x` before we can `clear` it.
unfreezing_hyp x' (clear' tt [x']) <|>
fail format!"equiv_rw expected to be able to clear the original hypothesis {x}, but couldn't.",
skip)
{fail_if_unchanged := ff} tt -- call `dsimp_result` with `no_defaults := tt`.
/-- Rewrite the goal using an equiv `e`. -/
meta def equiv_rw_target (e : expr) (cfg : equiv_rw_cfg := {}) : tactic unit :=
do
t ← target,
e ← equiv_rw_type e t cfg,
s ← to_expr ``(equiv.inv_fun %%e),
tactic.eapply s,
skip
end tactic
namespace tactic.interactive
open lean.parser
open interactive interactive.types
open tactic
local postfix `?`:9001 := optional
/--
`equiv_rw e at h`, where `h : α` is a hypothesis, and `e : α ≃ β`,
will attempt to transport `h` along `e`, producing a new hypothesis `h : β`,
with all occurrences of `h` in other hypotheses and the goal replaced with `e.symm h`.
`equiv_rw e` will attempt to transport the goal along an equivalence `e : α ≃ β`.
In its minimal form it replaces the goal `⊢ α` with `⊢ β` by calling `apply e.inv_fun`.
`equiv_rw` will also try rewriting under (equiv_)functors, so can turn
a hypothesis `h : list α` into `h : list β` or
a goal `⊢ unique α` into `⊢ unique β`.
The maximum search depth for rewriting in subexpressions is controlled by
`equiv_rw e {max_depth := n}`.
-/
meta def equiv_rw (e : parse texpr) (loc : parse $ (tk "at" *> ident)?) (cfg : equiv_rw_cfg := {}) : itactic :=
do e ← to_expr e,
match loc with
| (some hyp) := equiv_rw_hyp hyp e cfg
| none := equiv_rw_target e cfg
end
add_tactic_doc
{ name := "equiv_rw",
category := doc_category.tactic,
decl_names := [`tactic.interactive.equiv_rw],
tags := ["rewriting", "equiv", "transport"] }
/--
Solve a goal of the form `t ≃ _`,
by constructing an equivalence from `e : α ≃ β`.
This is the same equivalence that `equiv_rw` would use to rewrite a term of type `t`.
A typical usage might be:
```
have e' : option α ≃ option β := by equiv_rw_type e
```
-/
meta def equiv_rw_type (e : parse texpr) (cfg : equiv_rw_cfg := {}) : itactic :=
do
`(%%t ≃ _) ← target | fail "`equiv_rw_type` solves goals of the form `t ≃ _`.",
e ← to_expr e,
tactic.equiv_rw_type e t cfg >>= tactic.exact
add_tactic_doc
{ name := "equiv_rw_type",
category := doc_category.tactic,
decl_names := [`tactic.interactive.equiv_rw_type],
tags := ["rewriting", "equiv", "transport"] }
end tactic.interactive
|
f4e7658682f9c6a6319f036cf9df2b5dcc42ec4f | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/rewrite_search/default.lean | 79f22730bd9541e02cf91bb2e4a7bd31cf512b17 | [] | 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 | 150 | lean | import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.rewrite_search.frontend
import Mathlib.PostPort
namespace Mathlib
|
9b4899cc5a88736dca04d6ceda97620f844e518f | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /library/data/int/div.lean | 5e88ea063320cf43de76ae9f4f7fcd2bf19e9bcc | [
"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 | 29,477 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
Definitions and properties of div and mod, following the SSReflect library.
Following SSReflect and the SMTlib standard, we define a mod b so that 0 ≤ a mod b < |b| when b ≠ 0.
-/
import data.int.order data.nat.div
open [coercions] [reduce-hints] nat
open [declarations] nat (succ)
open eq.ops
namespace int
/- definitions -/
definition divide (a b : ℤ) : ℤ :=
sign b *
(match a with
| of_nat m := #nat m div (nat_abs b)
| -[1+m] := -[1+ (#nat m div (nat_abs b))]
end)
notation [priority int.prio] a div b := divide a b
definition modulo (a b : ℤ) : ℤ := a - a div b * b
notation [priority int.prio] a mod b := modulo a b
notation [priority int.prio] a ≡ b `[mod `:100 c `]`:0 := a mod c = b mod c
/- div -/
theorem of_nat_div (m n : nat) : of_nat (#nat m div n) = m div n :=
nat.cases_on n
(by rewrite [↑divide, sign_zero, zero_mul, nat.div_zero])
(take n, by rewrite [↑divide, sign_of_succ, one_mul])
theorem neg_succ_of_nat_div (m : nat) {b : ℤ} (H : b > 0) :
-[1+m] div b = -(m div b + 1) :=
calc
-[1+m] div b = sign b * _ : rfl
... = -[1+(#nat m div (nat_abs b))] : by rewrite [sign_of_pos H, one_mul]
... = -(m div b + 1) : by rewrite [↑divide, sign_of_pos H, one_mul]
theorem div_neg (a b : ℤ) : a div -b = -(a div b) :=
by rewrite [↑divide, sign_neg, neg_mul_eq_neg_mul, nat_abs_neg]
theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a div b = -((-a - 1) div b + 1) :=
obtain m (H1 : a = -[1+m]), from exists_eq_neg_succ_of_nat Ha,
calc
a div b = -(m div b + 1) : by rewrite [H1, neg_succ_of_nat_div _ Hb]
... = -((-a -1) div b + 1) : by rewrite [H1, neg_succ_of_nat_eq', neg_sub, sub_neg_eq_add,
add.comm 1, add_sub_cancel]
theorem div_nonneg {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≥ 0) : a div b ≥ 0 :=
obtain (m : ℕ) (Hm : a = m), from exists_eq_of_nat Ha,
obtain (n : ℕ) (Hn : b = n), from exists_eq_of_nat Hb,
calc
a div b = (#nat m div n) : by rewrite [Hm, Hn, of_nat_div]
... ≥ 0 : begin change (0 ≤ #nat m div n), apply trivial end
theorem div_nonpos {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≤ 0) : a div b ≤ 0 :=
calc
a div b = -(a div -b) : by rewrite [div_neg, neg_neg]
... ≤ 0 : neg_nonpos_of_nonneg (div_nonneg Ha (neg_nonneg_of_nonpos Hb))
theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a div b < 0 :=
have -a - 1 ≥ 0, from le_sub_one_of_lt (neg_pos_of_neg Ha),
have (-a - 1) div b + 1 > 0, from lt_add_one_of_le (div_nonneg this (le_of_lt Hb)),
calc
a div b = -((-a - 1) div b + 1) : div_of_neg_of_pos Ha Hb
... < 0 : neg_neg_of_pos this
set_option pp.coercions true
theorem zero_div (b : ℤ) : 0 div b = 0 :=
calc
0 div b = sign b * (#nat 0 div (nat_abs b)) : rfl
... = sign b * (0:nat) : nat.zero_div
... = 0 : mul_zero
theorem div_zero (a : ℤ) : a div 0 = 0 :=
by rewrite [↑divide, sign_zero, zero_mul]
theorem div_one (a : ℤ) :a div 1 = a :=
assert 1 > 0, from dec_trivial,
int.cases_on a
(take m, by rewrite [-of_nat_div, nat.div_one])
(take m, by rewrite [!neg_succ_of_nat_div this, -of_nat_div, nat.div_one])
theorem eq_div_mul_add_mod (a b : ℤ) : a = a div b * b + a mod b :=
!add.comm ▸ eq_add_of_sub_eq rfl
theorem div_eq_zero_of_lt {a b : ℤ} : 0 ≤ a → a < b → a div b = 0 :=
int.cases_on a
(take m, assume H,
int.cases_on b
(take n,
assume H : m < n,
calc
m div n = #nat m div n : of_nat_div
... = (0:nat) : nat.div_eq_zero_of_lt (lt_of_of_nat_lt_of_nat H))
(take n,
assume H : m < -[1+n],
have H1 : ¬(m < -[1+n]), from dec_trivial,
absurd H H1))
(take m,
assume H : 0 ≤ -[1+m],
have ¬ (0 ≤ -[1+m]), from dec_trivial,
absurd H this)
theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a div b = 0 :=
lt.by_cases
(suppose b < 0,
assert a < -b, from abs_of_neg this ▸ H2,
calc
a div b = - (a div -b) : by rewrite [div_neg, neg_neg]
... = 0 : by rewrite [div_eq_zero_of_lt H1 this, neg_zero])
(suppose b = 0, this⁻¹ ▸ !div_zero)
(suppose b > 0,
have a < b, from abs_of_pos this ▸ H2,
div_eq_zero_of_lt H1 this)
private theorem add_mul_div_self_aux1 {a : ℤ} {k : ℕ} (n : ℕ)
(H1 : a ≥ 0) (H2 : #nat k > 0) :
(a + n * k) div k = a div k + n :=
obtain m (Hm : a = of_nat m), from exists_eq_of_nat H1,
Hm⁻¹ ▸ (calc
(m + n * k) div k = (#nat (m + n * k)) div k : rfl
... = (#nat (m + n * k) div k) : of_nat_div
... = (#nat m div k + n) : !nat.add_mul_div_self H2
... = (#nat m div k) + n : rfl
... = m div k + n : of_nat_div)
private theorem add_mul_div_self_aux2 {a : ℤ} {k : ℕ} (n : ℕ)
(H1 : a < 0) (H2 : #nat k > 0) :
(a + n * k) div k = a div k + n :=
obtain m (Hm : a = -[1+m]), from exists_eq_neg_succ_of_nat H1,
or.elim (nat.lt_or_ge m (#nat n * k))
(assume m_lt_nk : #nat m < n * k,
have H3 : #nat (m + 1 ≤ n * k), from nat.succ_le_of_lt m_lt_nk,
have H4 : #nat m div k + 1 ≤ n,
from nat.succ_le_of_lt (nat.div_lt_of_lt_mul m_lt_nk),
Hm⁻¹ ▸ (calc
(-[1+m] + n * k) div k = (n * k - (m + 1)) div k : by rewrite [add.comm, neg_succ_of_nat_eq]
... = ((#nat n * k) - (#nat m + 1)) div k : rfl
... = (#nat n * k - (m + 1)) div k : {(of_nat_sub H3)⁻¹}
... = #nat (n * k - (m + 1)) div k : of_nat_div
... = #nat (k * n - (m + 1)) div k : nat.mul.comm
... = #nat n - m div k - 1 :
nat.mul_sub_div_of_lt (!nat.mul.comm ▸ m_lt_nk)
... = #nat n - (m div k + 1) : nat.sub_sub
... = n - (#nat m div k + 1) : of_nat_sub H4
... = -(m div k + 1) + n :
by rewrite [add.comm, -sub_eq_add_neg, of_nat_add, of_nat_div]
... = -[1+m] div k + n :
neg_succ_of_nat_div m (of_nat_lt_of_nat_of_lt H2)))
(assume nk_le_m : #nat n * k ≤ m,
eq.symm (Hm⁻¹ ▸ (calc
-[1+m] div k + n = -(m div k + 1) + n :
neg_succ_of_nat_div m (of_nat_lt_of_nat_of_lt H2)
... = -((#nat m div k) + 1) + n : of_nat_div
... = -((#nat (m - n * k + n * k) div k) + 1) + n : nat.sub_add_cancel nk_le_m
... = -((#nat (m - n * k) div k + n) + 1) + n : nat.add_mul_div_self H2
... = -((#nat m - n * k) div k + 1) :
by rewrite [of_nat_add, *neg_add, add.right_comm, neg_add_cancel_right,
of_nat_div]
... = -[1+(#nat m - n * k)] div k :
neg_succ_of_nat_div _ (of_nat_lt_of_nat_of_lt H2)
... = -((#nat m - n * k) + 1) div k : rfl
... = -(m - (#nat n * k) + 1) div k : of_nat_sub nk_le_m
... = (-(m + 1) + n * k) div k :
by rewrite [sub_eq_add_neg, -*add.assoc, *neg_add, neg_neg, add.right_comm]
... = (-[1+m] + n * k) div k : rfl)))
private theorem add_mul_div_self_aux3 (a : ℤ) {b c : ℤ} (H1 : b ≥ 0) (H2 : c > 0) :
(a + b * c) div c = a div c + b :=
obtain n (Hn : b = of_nat n), from exists_eq_of_nat H1,
obtain k (Hk : c = of_nat k), from exists_eq_of_nat (le_of_lt H2),
have knz : k ≠ 0, from assume kz, !lt.irrefl (kz ▸ Hk ▸ H2),
have kgt0 : (#nat k > 0), from nat.pos_of_ne_zero knz,
have H3 : (a + n * k) div k = a div k + n, from
or.elim (lt_or_ge a 0)
(assume Ha : a < 0, add_mul_div_self_aux2 _ Ha kgt0)
(assume Ha : a ≥ 0, add_mul_div_self_aux1 _ Ha kgt0),
Hn⁻¹ ▸ Hk⁻¹ ▸ H3
private theorem add_mul_div_self_aux4 (a b : ℤ) {c : ℤ} (H : c > 0) :
(a + b * c) div c = a div c + b :=
or.elim (le.total 0 b)
(assume H1 : 0 ≤ b, add_mul_div_self_aux3 _ H1 H)
(assume H1 : 0 ≥ b,
eq.symm (calc
a div c + b = (a + b * c + -b * c) div c + b :
by rewrite [-neg_mul_eq_neg_mul, add_neg_cancel_right]
... = (a + b * c) div c + - b + b :
add_mul_div_self_aux3 _ (neg_nonneg_of_nonpos H1) H
... = (a + b * c) div c : neg_add_cancel_right))
theorem add_mul_div_self (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) div c = a div c + b :=
lt.by_cases
(assume H1 : 0 < c, !add_mul_div_self_aux4 H1)
(assume H1 : 0 = c, absurd H1⁻¹ H)
(assume H1 : 0 > c,
have H2 : -c > 0, from neg_pos_of_neg H1,
calc
(a + b * c) div c = - ((a + -b * -c) div -c) : by rewrite [div_neg, neg_mul_neg, neg_neg]
... = -(a div -c + -b) : !add_mul_div_self_aux4 H2
... = a div c + b : by rewrite [div_neg, neg_add, *neg_neg])
theorem add_mul_div_self_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) :
(a + b * c) div b = a div b + c :=
!mul.comm ▸ !add_mul_div_self H
theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b div b = a :=
calc
a * b div b = (0 + a * b) div b : zero_add
... = 0 div b + a : !add_mul_div_self H
... = a : by rewrite [zero_div, zero_add]
theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b div a = b :=
!mul.comm ▸ mul_div_cancel b H
theorem div_self {a : ℤ} (H : a ≠ 0) : a div a = 1 :=
!mul_one ▸ !mul_div_cancel_left H
/- mod -/
theorem of_nat_mod (m n : nat) : m mod n = (#nat m mod n) :=
have H : m = (#nat m mod n) + m div n * n, from calc
m = of_nat (#nat m div n * n + m mod n) : nat.eq_div_mul_add_mod
... = (#nat m div n) * n + (#nat m mod n) : rfl
... = m div n * n + (#nat m mod n) : of_nat_div
... = (#nat m mod n) + m div n * n : add.comm,
calc
m mod n = m - m div n * n : rfl
... = (#nat m mod n) : sub_eq_of_eq_add H
theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : b > 0) :
-[1+m] mod b = b - 1 - m mod b :=
calc
-[1+m] mod b = -(m + 1) - -[1+m] div b * b : rfl
... = -(m + 1) - -(m div b + 1) * b : neg_succ_of_nat_div _ bpos
... = -m + -1 + (b + m div b * b) :
by rewrite [neg_add, -neg_mul_eq_neg_mul, sub_neg_eq_add, mul.right_distrib,
one_mul, (add.comm b)]
... = b + -1 + (-m + m div b * b) :
by rewrite [-*add.assoc, add.comm (-m), add.right_comm (-1), (add.comm b)]
... = b - 1 - m mod b :
by rewrite [↑modulo, *sub_eq_add_neg, neg_add, neg_neg]
theorem mod_neg (a b : ℤ) : a mod -b = a mod b :=
calc
a mod -b = a - (a div -b) * -b : rfl
... = a - -(a div b) * -b : div_neg
... = a - a div b * b : neg_mul_neg
... = a mod b : rfl
theorem mod_abs (a b : ℤ) : a mod (abs b) = a mod b :=
abs.by_cases rfl !mod_neg
theorem zero_mod (b : ℤ) : 0 mod b = 0 :=
by rewrite [↑modulo, zero_div, zero_mul, sub_zero]
theorem mod_zero (a : ℤ) : a mod 0 = a :=
by rewrite [↑modulo, mul_zero, sub_zero]
theorem mod_one (a : ℤ) : a mod 1 = 0 :=
calc
a mod 1 = a - a div 1 * 1 : rfl
... = 0 : by rewrite [mul_one, div_one, sub_self]
private lemma of_nat_mod_abs (m : ℕ) (b : ℤ) : m mod (abs b) = (#nat m mod (nat_abs b)) :=
calc
m mod (abs b) = m mod (nat_abs b) : of_nat_nat_abs
... = (#nat m mod (nat_abs b)) : of_nat_mod
private lemma of_nat_mod_abs_lt (m : ℕ) {b : ℤ} (H : b ≠ 0) : m mod (abs b) < (abs b) :=
have H1 : abs b > 0, from abs_pos_of_ne_zero H,
have H2 : (#nat nat_abs b > 0), from lt_of_of_nat_lt_of_nat (!of_nat_nat_abs⁻¹ ▸ H1),
calc
m mod (abs b) = (#nat m mod (nat_abs b)) : of_nat_mod_abs m b
... < nat_abs b : of_nat_lt_of_nat_of_lt (!nat.mod_lt H2)
... = abs b : of_nat_nat_abs _
theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a mod b = a :=
obtain m (Hm : a = of_nat m), from exists_eq_of_nat H1,
obtain n (Hn : b = of_nat n), from exists_eq_of_nat (le_of_lt (lt_of_le_of_lt H1 H2)),
begin
revert H2,
rewrite [Hm, Hn, of_nat_mod, of_nat_lt_of_nat_iff, of_nat_eq_of_nat_iff],
apply nat.mod_eq_of_lt
end
theorem mod_nonneg (a : ℤ) {b : ℤ} (H : b ≠ 0) : a mod b ≥ 0 :=
have H1 : abs b > 0, from abs_pos_of_ne_zero H,
have H2 : a mod (abs b) ≥ 0, from
int.cases_on a
(take m, (of_nat_mod_abs m b)⁻¹ ▸ of_nat_nonneg (nat.modulo m (nat_abs b)))
(take m,
have H3 : 1 + m mod (abs b) ≤ (abs b),
from (!add.comm ▸ add_one_le_of_lt (of_nat_mod_abs_lt m H)),
calc
-[1+m] mod (abs b) = abs b - 1 - m mod (abs b) : neg_succ_of_nat_mod _ H1
... = abs b - (1 + m mod (abs b)) : by rewrite [*sub_eq_add_neg, neg_add, add.assoc]
... ≥ 0 : iff.mpr !sub_nonneg_iff_le H3),
!mod_abs ▸ H2
theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a mod b < (abs b) :=
have H1 : abs b > 0, from abs_pos_of_ne_zero H,
have H2 : a mod (abs b) < abs b, from
int.cases_on a
(take m, of_nat_mod_abs_lt m H)
(take m,
have H3 : abs b ≠ 0, from assume H', H (eq_zero_of_abs_eq_zero H'),
have H4 : 1 + m mod (abs b) > 0, from add_pos_of_pos_of_nonneg dec_trivial (mod_nonneg _ H3),
calc
-[1+m] mod (abs b) = abs b - 1 - m mod (abs b) : neg_succ_of_nat_mod _ H1
... = abs b - (1 + m mod (abs b)) : by rewrite [*sub_eq_add_neg, neg_add, add.assoc]
... < abs b : sub_lt_self _ H4),
!mod_abs ▸ H2
theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) mod c = a mod c :=
decidable.by_cases
(assume cz : c = 0, by rewrite [cz, mul_zero, add_zero])
(assume cnz, by rewrite [↑modulo, !add_mul_div_self cnz, mul.right_distrib,
sub_add_eq_sub_sub_swap, add_sub_cancel])
theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) mod b = a mod b :=
!mul.comm ▸ !add_mul_mod_self
theorem add_mod_self {a b : ℤ} : (a + b) mod b = a mod b :=
by rewrite -(int.mul_one b) at {1}; apply add_mul_mod_self_left
theorem add_mod_self_left {a b : ℤ} : (a + b) mod a = b mod a :=
!add.comm ▸ !add_mod_self
theorem mod_add_mod (m n k : ℤ) : (m mod n + k) mod n = (m + k) mod n :=
by rewrite [eq_div_mul_add_mod m n at {2}, add.assoc, add.comm (m div n * n), add_mul_mod_self]
theorem add_mod_mod (m n k : ℤ) : (m + n mod k) mod k = (m + n) mod k :=
by rewrite [add.comm, mod_add_mod, add.comm]
theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m mod n = k mod n) :
(m + i) mod n = (k + i) mod n :=
by rewrite [-mod_add_mod, -mod_add_mod k, H]
theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m mod n = k mod n) :
(i + m) mod n = (i + k) mod n :=
by rewrite [add.comm, add_mod_eq_add_mod_right _ H, add.comm]
theorem mod_eq_mod_of_add_mod_eq_add_mod_right {m n k i : ℤ}
(H : (m + i) mod n = (k + i) mod n) :
m mod n = k mod n :=
assert H1 : (m + i + (-i)) mod n = (k + i + (-i)) mod n, from add_mod_eq_add_mod_right _ H,
by rewrite [*add_neg_cancel_right at H1]; apply H1
theorem mod_eq_mod_of_add_mod_eq_add_mod_left {m n k i : ℤ} :
(i + m) mod n = (i + k) mod n → m mod n = k mod n :=
by rewrite [add.comm i m, add.comm i k]; apply mod_eq_mod_of_add_mod_eq_add_mod_right
theorem mul_mod_left (a b : ℤ) : (a * b) mod b = 0 :=
by rewrite [-zero_add (a * b), add_mul_mod_self, zero_mod]
theorem mul_mod_right (a b : ℤ) : (a * b) mod a = 0 :=
!mul.comm ▸ !mul_mod_left
theorem mod_self {a : ℤ} : a mod a = 0 :=
decidable.by_cases
(assume H : a = 0, H⁻¹ ▸ !mod_zero)
(assume H : a ≠ 0,
calc
a mod a = a - a div a * a : rfl
... = 0 : by rewrite [!div_self H, one_mul, sub_self])
theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : b > 0) : a mod b < b :=
!abs_of_pos H ▸ !mod_lt (ne.symm (ne_of_lt H))
/- properties of div and mod -/
theorem mul_div_mul_of_pos_aux {a : ℤ} (b : ℤ) {c : ℤ}
(H1 : a > 0) (H2 : c > 0) : a * b div (a * c) = b div c :=
have H3 : a * c ≠ 0, from ne.symm (ne_of_lt (mul_pos H1 H2)),
have H4 : a * (b mod c) < a * c, from mul_lt_mul_of_pos_left (!mod_lt_of_pos H2) H1,
have H5 : a * (b mod c) ≥ 0, from mul_nonneg (le_of_lt H1) (!mod_nonneg (ne.symm (ne_of_lt H2))),
calc
a * b div (a * c) = a * (b div c * c + b mod c) div (a * c) : eq_div_mul_add_mod
... = (a * (b mod c) + a * c * (b div c)) div (a * c) :
by rewrite [!add.comm, mul.left_distrib, mul.comm _ c, -!mul.assoc]
... = a * (b mod c) div (a * c) + b div c : !add_mul_div_self_left H3
... = 0 + b div c : {!div_eq_zero_of_lt H5 H4}
... = b div c : zero_add
theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b div (a * c) = b div c :=
lt.by_cases
(assume H1 : c < 0,
have H2 : -c > 0, from neg_pos_of_neg H1,
calc
a * b div (a * c) = - (a * b div (a * -c)) :
by rewrite [!neg_mul_eq_mul_neg⁻¹, div_neg, neg_neg]
... = - (b div -c) : mul_div_mul_of_pos_aux _ H H2
... = b div c : by rewrite [div_neg, neg_neg])
(assume H1 : c = 0,
calc
a * b div (a * c) = 0 : by rewrite [H1, mul_zero, div_zero]
... = b div c : by rewrite [H1, div_zero])
(assume H1 : c > 0,
mul_div_mul_of_pos_aux _ H H1)
theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b > 0) :
a * b div (c * b) = a div c :=
!mul.comm ▸ !mul.comm ▸ !mul_div_mul_of_pos H
theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b mod (a * c) = a * (b mod c) :=
by rewrite [↑modulo, !mul_div_mul_of_pos H, mul_sub_left_distrib, mul.left_comm]
theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : b > 0) : a < (a div b + 1) * b :=
have H : a - a div b * b < b, from !mod_lt_of_pos H,
calc
a < a div b * b + b : iff.mpr !lt_add_iff_sub_lt_left H
... = (a div b + 1) * b : by rewrite [mul.right_distrib, one_mul]
theorem div_le_of_nonneg_of_nonneg {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≥ 0) : a div b ≤ a :=
obtain (m : ℕ) (Hm : a = m), from exists_eq_of_nat Ha,
obtain (n : ℕ) (Hn : b = n), from exists_eq_of_nat Hb,
calc
a div b = #nat m div n : by rewrite [Hm, Hn, of_nat_div]
... ≤ m : of_nat_le_of_nat_of_le !nat.div_le_self
... = a : Hm
theorem abs_div_le_abs (a b : ℤ) : abs (a div b) ≤ abs a :=
have H : ∀a b, b > 0 → abs (a div b) ≤ abs a, from
take a b,
assume H1 : b > 0,
or.elim (le_or_gt 0 a)
(assume H2 : 0 ≤ a,
have H3 : 0 ≤ b, from le_of_lt H1,
calc
abs (a div b) = a div b : abs_of_nonneg (div_nonneg H2 H3)
... ≤ a : div_le_of_nonneg_of_nonneg H2 H3
... = abs a : abs_of_nonneg H2)
(assume H2 : a < 0,
have H3 : -a - 1 ≥ 0, from le_sub_one_of_lt (neg_pos_of_neg H2),
have H4 : (-a - 1) div b + 1 ≥ 0,
from add_nonneg (div_nonneg H3 (le_of_lt H1)) (of_nat_le_of_nat_of_le !nat.zero_le),
have H5 : (-a - 1) div b ≤ -a - 1, from div_le_of_nonneg_of_nonneg H3 (le_of_lt H1),
calc
abs (a div b) = abs ((-a - 1) div b + 1) : by rewrite [div_of_neg_of_pos H2 H1, abs_neg]
... = (-a - 1) div b + 1 : abs_of_nonneg H4
... ≤ -a - 1 + 1 : add_le_add_right H5 _
... = abs a : by rewrite [sub_add_cancel, abs_of_neg H2]),
lt.by_cases
(assume H1 : b < 0,
calc
abs (a div b) = abs (a div -b) : by rewrite [div_neg, abs_neg]
... ≤ abs a : H _ _ (neg_pos_of_neg H1))
(assume H1 : b = 0,
calc
abs (a div b) = 0 : by rewrite [H1, div_zero, abs_zero]
... ≤ abs a : abs_nonneg)
(assume H1 : b > 0, H _ _ H1)
theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a mod b = 0) : a div b * b = a :=
by rewrite [eq_div_mul_add_mod a b at {2}, H, add_zero]
theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a mod b = 0) : b * (a div b) = a :=
!mul.comm ▸ div_mul_cancel_of_mod_eq_zero H
/- dvd -/
theorem dvd_of_of_nat_dvd_of_nat {m n : ℕ} : of_nat m ∣ of_nat n → (#nat m ∣ n) :=
nat.by_cases_zero_pos n
(assume H, nat.dvd_zero m)
(take n',
assume H1 : (#nat n' > 0),
have H2 : of_nat n' > 0, from of_nat_pos H1,
assume H3 : of_nat m ∣ of_nat n',
dvd.elim H3
(take c,
assume H4 : of_nat n' = of_nat m * c,
have H5 : c > 0, from pos_of_mul_pos_left (H4 ▸ H2) !of_nat_nonneg,
obtain k (H6 : c = of_nat k), from exists_eq_of_nat (le_of_lt H5),
have H7 : n' = (#nat m * k), from (of_nat.inj (H6 ▸ H4)),
nat.dvd.intro H7⁻¹))
theorem of_nat_dvd_of_nat_of_dvd {m n : ℕ} (H : #nat m ∣ n) : of_nat m ∣ of_nat n :=
nat.dvd.elim H
(take k, assume H1 : #nat n = m * k,
dvd.intro (H1⁻¹ ▸ rfl))
theorem of_nat_dvd_of_nat_iff (m n : ℕ) : of_nat m ∣ of_nat n ↔ (#nat m ∣ n) :=
iff.intro dvd_of_of_nat_dvd_of_nat of_nat_dvd_of_nat_of_dvd
theorem dvd.antisymm {a b : ℤ} (H1 : a ≥ 0) (H2 : b ≥ 0) : a ∣ b → b ∣ a → a = b :=
begin
rewrite [-abs_of_nonneg H1, -abs_of_nonneg H2, -*of_nat_nat_abs],
rewrite [*of_nat_dvd_of_nat_iff, *of_nat_eq_of_nat_iff],
apply nat.dvd.antisymm
end
theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b mod a = 0) : a ∣ b :=
dvd.intro (!mul.comm ▸ div_mul_cancel_of_mod_eq_zero H)
theorem mod_eq_zero_of_dvd {a b : ℤ} (H : a ∣ b) : b mod a = 0 :=
dvd.elim H (take z, assume H1 : b = a * z, H1⁻¹ ▸ !mul_mod_right)
theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b mod a = 0 :=
iff.intro mod_eq_zero_of_dvd dvd_of_mod_eq_zero
definition dvd.decidable_rel [instance] : decidable_rel dvd :=
take a n, decidable_of_decidable_of_iff _ (iff.symm !dvd_iff_mod_eq_zero)
theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a div b * b = a :=
div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H)
theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b div a) = b :=
!mul.comm ▸ !div_mul_cancel H
theorem mul_div_assoc (a : ℤ) {b c : ℤ} (H : c ∣ b) : (a * b) div c = a * (b div c) :=
decidable.by_cases
(assume cz : c = 0, by rewrite [cz, *div_zero, mul_zero])
(assume cnz : c ≠ 0,
obtain d (H' : b = d * c), from exists_eq_mul_left_of_dvd H,
by rewrite [H', -mul.assoc, *(!mul_div_cancel cnz)])
theorem div_dvd_div {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c) : b div a ∣ c div a :=
have H3 : b = b div a * a, from (div_mul_cancel H1)⁻¹,
have H4 : c = c div a * a, from (div_mul_cancel (dvd.trans H1 H2))⁻¹,
decidable.by_cases
(assume H5 : a = 0,
have H6: c div a = 0, from (congr_arg _ H5 ⬝ !div_zero),
H6⁻¹ ▸ !dvd_zero)
(assume H5 : a ≠ 0,
dvd_of_mul_dvd_mul_right H5 (H3 ▸ H4 ▸ H2))
theorem div_eq_iff_eq_mul_right {a b : ℤ} (c : ℤ) (H : b ≠ 0) (H' : b ∣ a) :
a div b = c ↔ a = b * c :=
iff.intro
(assume H1, by rewrite [-H1, mul_div_cancel' H'])
(assume H1, by rewrite [H1, !mul_div_cancel_left H])
theorem div_eq_iff_eq_mul_left {a b : ℤ} (c : ℤ) (H : b ≠ 0) (H' : b ∣ a) :
a div b = c ↔ a = c * b :=
!mul.comm ▸ !div_eq_iff_eq_mul_right H H'
theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a div b = c) :
a = b * c :=
calc
a = b * (a div b) : mul_div_cancel' H1
... = b * c : H2
theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) :
a div b = c :=
calc
a div b = b * c div b : H2
... = c : !mul_div_cancel_left H1
theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a div b = c) :
a = c * b :=
!mul.comm ▸ !eq_mul_of_div_eq_right H1 H2
theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) :
a div b = c :=
div_eq_of_eq_mul_right H1 (!mul.comm ▸ H2)
theorem neg_div_of_dvd {a b : ℤ} (H : b ∣ a) : -a div b = -(a div b) :=
decidable.by_cases
(assume H1 : b = 0, by rewrite [H1, *div_zero, neg_zero])
(assume H1 : b ≠ 0,
dvd.elim H
(take c, assume H' : a = b * c,
by rewrite [H', neg_mul_eq_mul_neg, *!mul_div_cancel_left H1]))
theorem sign_eq_div_abs (a : ℤ) : sign a = a div (abs a) :=
decidable.by_cases
(suppose a = 0, by subst a)
(suppose a ≠ 0,
have abs a ≠ 0, from assume H, this (eq_zero_of_abs_eq_zero H),
have abs a ∣ a, from abs_dvd_of_dvd !dvd.refl,
eq.symm (iff.mpr (!div_eq_iff_eq_mul_left `abs a ≠ 0` this) !eq_sign_mul_abs))
theorem le_of_dvd {a b : ℤ} (bpos : b > 0) (H : a ∣ b) : a ≤ b :=
or.elim !le_or_gt
(suppose a ≤ 0, le.trans this (le_of_lt bpos))
(suppose a > 0,
obtain c (Hc : b = a * c), from exists_eq_mul_right_of_dvd H,
have a * c > 0, by rewrite -Hc; exact bpos,
have c > 0, from int.pos_of_mul_pos_left this (le_of_lt `a > 0`),
show a ≤ b, from calc
a = a * 1 : mul_one
... ≤ a * c : mul_le_mul_of_nonneg_left (add_one_le_of_lt `c > 0`) (le_of_lt `a > 0`)
... = b : Hc)
/- div and ordering -/
theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a div b * b ≤ a :=
calc
a = a div b * b + a mod b : eq_div_mul_add_mod
... ≥ a div b * b : le_add_of_nonneg_right (!mod_nonneg H)
theorem div_le_of_le_mul {a b c : ℤ} (H : c > 0) (H' : a ≤ b * c) : a div c ≤ b :=
le_of_mul_le_mul_right (calc
a div c * c = a div c * c + 0 : add_zero
... ≤ a div c * c + a mod c : add_le_add_left (!mod_nonneg (ne_of_gt H))
... = a : eq_div_mul_add_mod
... ≤ b * c : H') H
theorem div_le_self (a : ℤ) {b : ℤ} (H1 : a ≥ 0) (H2 : b ≥ 0) : a div b ≤ a :=
or.elim (lt_or_eq_of_le H2)
(assume H3 : b > 0,
have H4 : b ≥ 1, from add_one_le_of_lt H3,
have H5 : a ≤ a * b, from calc
a = a * 1 : mul_one
... ≤ a * b : !mul_le_mul_of_nonneg_left H4 H1,
div_le_of_le_mul H3 H5)
(assume H3 : 0 = b,
by rewrite [-H3, div_zero]; apply H1)
theorem mul_le_of_le_div {a b c : ℤ} (H1 : c > 0) (H2 : a ≤ b div c) : a * c ≤ b :=
calc
a * c ≤ b div c * c : !mul_le_mul_of_nonneg_right H2 (le_of_lt H1)
... ≤ b : !div_mul_le (ne_of_gt H1)
theorem le_div_of_mul_le {a b c : ℤ} (H1 : c > 0) (H2 : a * c ≤ b) : a ≤ b div c :=
have H3 : a * c < (b div c + 1) * c, from
calc
a * c ≤ b : H2
... = b div c * c + b mod c : eq_div_mul_add_mod
... < b div c * c + c : add_lt_add_left (!mod_lt_of_pos H1)
... = (b div c + 1) * c : by rewrite [mul.right_distrib, one_mul],
le_of_lt_add_one (lt_of_mul_lt_mul_right H3 (le_of_lt H1))
theorem le_div_iff_mul_le {a b c : ℤ} (H : c > 0) : a ≤ b div c ↔ a * c ≤ b :=
iff.intro (!mul_le_of_le_div H) (!le_div_of_mul_le H)
theorem div_le_div {a b c : ℤ} (H : c > 0) (H' : a ≤ b) : a div c ≤ b div c :=
le_div_of_mul_le H (le.trans (!div_mul_le (ne_of_gt H)) H')
theorem div_lt_of_lt_mul {a b c : ℤ} (H : c > 0) (H' : a < b * c) : a div c < b :=
lt_of_mul_lt_mul_right
(calc
a div c * c = a div c * c + 0 : add_zero
... ≤ a div c * c + a mod c : add_le_add_left (!mod_nonneg (ne_of_gt H))
... = a : eq_div_mul_add_mod
... < b * c : H')
(le_of_lt H)
theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : c > 0) (H2 : a div c < b) : a < b * c :=
assert H3 : (a div c + 1) * c ≤ b * c,
from !mul_le_mul_of_nonneg_right (add_one_le_of_lt H2) (le_of_lt H1),
have H4 : a div c * c + c ≤ b * c, by rewrite [mul.right_distrib at H3, one_mul at H3]; apply H3,
calc
a = a div c * c + a mod c : eq_div_mul_add_mod
... < a div c * c + c : add_lt_add_left (!mod_lt_of_pos H1)
... ≤ b * c : H4
theorem div_lt_iff_lt_mul {a b c : ℤ} (H : c > 0) : a div c < b ↔ a < b * c :=
iff.intro (!lt_mul_of_div_lt H) (!div_lt_of_lt_mul H)
theorem div_le_iff_le_mul_of_div {a b : ℤ} (c : ℤ) (H : b > 0) (H' : b ∣ a) :
a div b ≤ c ↔ a ≤ c * b :=
by rewrite [propext (!le_iff_mul_le_mul_right H), !div_mul_cancel H']
theorem le_mul_of_div_le_of_div {a b c : ℤ} (H1 : b > 0) (H2 : b ∣ a) (H3 : a div b ≤ c) :
a ≤ c * b :=
iff.mp (!div_le_iff_le_mul_of_div H1 H2) H3
theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : a > 0) (H2 : b ≥ 0) (H3 : b ∣ a) : a div b > 0 :=
have H4 : b ≠ 0, from
(assume H5 : b = 0,
have H6 : a = 0, from eq_zero_of_zero_dvd (H5 ▸ H3),
ne_of_gt H1 H6),
have H6 : (a div b) * b > 0, by rewrite (div_mul_cancel H3); apply H1,
pos_of_mul_pos_right H6 H2
theorem div_eq_div_of_dvd_of_dvd {a b c d : ℤ} (H1 : b ∣ a) (H2 : d ∣ c) (H3 : b ≠ 0)
(H4 : d ≠ 0) (H5 : a * d = b * c) :
a div b = c div d :=
begin
apply div_eq_of_eq_mul_right H3,
rewrite [-!mul_div_assoc H2],
apply eq.symm,
apply div_eq_of_eq_mul_left H4,
apply eq.symm H5
end
end int
|
09295e72268cd0caec4a237c1f8fd80a9a578528 | 4b846d8dabdc64e7ea03552bad8f7fa74763fc67 | /library/tools/super/inhabited.lean | 6a9af2fef987ae7081122e309e3535dbee8d3070 | [
"Apache-2.0"
] | permissive | pacchiano/lean | 9324b33f3ac3b5c5647285160f9f6ea8d0d767dc | fdadada3a970377a6df8afcd629a6f2eab6e84e8 | refs/heads/master | 1,611,357,380,399 | 1,489,870,101,000 | 1,489,870,101,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,508 | lean | /-
Copyright (c) 2016 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import .clause_ops .prover_state
open expr tactic monad
namespace super
meta def try_assumption_lookup_left (c : clause) : tactic (list clause) :=
on_first_left c $ λtype, do
ass ← find_assumption type,
return [([], ass)]
meta def try_nonempty_lookup_left (c : clause) : tactic (list clause) :=
on_first_left_dn c $ λhnx,
match is_local_not c^.local_false hnx^.local_type with
| some type := do
univ ← infer_univ type,
lf_univ ← infer_univ c^.local_false,
guard $ lf_univ = level.zero,
inst ← mk_instance (app (const ``nonempty [univ]) type),
instt ← infer_type inst,
return [([], app_of_list (const ``nonempty.elim [univ])
[type, c^.local_false, inst, hnx])]
| _ := failed
end
meta def try_nonempty_left (c : clause) : tactic (list clause) :=
on_first_left c $ λprop,
match prop with
| (app (const ``nonempty [u]) type) := do
x ← mk_local_def `x type,
return [([x], app_of_list (const ``nonempty.intro [u]) [type, x])]
| _ := failed
end
meta def try_nonempty_right (c : clause) : tactic (list clause) :=
on_first_right c $ λhnonempty,
match hnonempty^.local_type with
| (app (const ``nonempty [u]) type) := do
lf_univ ← infer_univ c^.local_false,
guard $ lf_univ = level.zero,
hnx ← mk_local_def `nx (imp type c^.local_false),
return [([hnx], app_of_list (const ``nonempty.elim [u])
[type, c^.local_false, hnonempty, hnx])]
| _ := failed
end
meta def try_inhabited_left (c : clause) : tactic (list clause) :=
on_first_left c $ λprop,
match prop with
| (app (const ``inhabited [u]) type) := do
x ← mk_local_def `x type,
return [([x], app_of_list (const ``inhabited.mk [u]) [type, x])]
| _ := failed
end
meta def try_inhabited_right (c : clause) : tactic (list clause) :=
on_first_right' c $ λhinh,
match hinh^.local_type with
| (app (const ``inhabited [u]) type) :=
return [([], app_of_list (const ``inhabited.default [u]) [type, hinh])]
| _ := failed
end
@[super.inf]
meta def inhabited_infs : inf_decl := inf_decl.mk 10 $ take given, do
for' [try_assumption_lookup_left,
try_nonempty_lookup_left,
try_nonempty_left, try_nonempty_right,
try_inhabited_left, try_inhabited_right] $ λr,
simp_if_successful given (r given^.c)
end super
|
75ff29dee50cae1a95955a2e820507ba9eda3c8b | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/ring_theory/ideal/quotient.lean | 1eafbe3513dfb33893f122f87c3e1df964136def | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 16,273 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Chris Hughes, Mario Carneiro, Anne Baanen
-/
import linear_algebra.quotient
import ring_theory.ideal.basic
/-!
# Ideal quotients
This file defines ideal quotients as a special case of submodule quotients and proves some basic
results about these quotients.
See `algebra.ring_quot` for quotients of non-commutative rings.
## Main definitions
- `ideal.quotient`: the quotient of a commutative ring `R` by an ideal `I : ideal R`
## Main results
- `ideal.quotient_inf_ring_equiv_pi_quotient`: the **Chinese Remainder Theorem**
-/
universes u v w
namespace ideal
open set
open_locale big_operators
variables {R : Type u} [comm_ring R] (I : ideal R) {a b : R}
variables {S : Type v}
/-- The quotient `R/I` of a ring `R` by an ideal `I`.
The ideal quotient of `I` is defined to equal the quotient of `I` as an `R`-submodule of `R`.
This definition is marked `reducible` so that typeclass instances can be shared between
`ideal.quotient I` and `submodule.quotient I`.
-/
-- Note that at present `ideal` means a left-ideal,
-- so this quotient is only useful in a commutative ring.
-- We should develop quotients by two-sided ideals as well.
@[reducible]
instance : has_quotient R (ideal R) := submodule.has_quotient
namespace quotient
variables {I} {x y : R}
instance has_one (I : ideal R) : has_one (R ⧸ I) := ⟨submodule.quotient.mk 1⟩
instance has_mul (I : ideal R) : has_mul (R ⧸ I) :=
⟨λ a b, quotient.lift_on₂' a b (λ a b, submodule.quotient.mk (a * b)) $
λ a₁ a₂ b₁ b₂ h₁ h₂, quot.sound $ begin
rw submodule.quotient_rel_r_def at h₁ h₂ ⊢,
have F := I.add_mem (I.mul_mem_left a₂ h₁) (I.mul_mem_right b₁ h₂),
have : a₁ * a₂ - b₁ * b₂ = a₂ * (a₁ - b₁) + (a₂ - b₂) * b₁,
{ rw [mul_sub, sub_mul, sub_add_sub_cancel, mul_comm, mul_comm b₁] },
rw ← this at F,
change _ ∈ _, convert F,
end⟩
instance comm_ring (I : ideal R) : comm_ring (R ⧸ I) :=
{ mul := (*),
one := 1,
nat_cast := λ n, submodule.quotient.mk n,
nat_cast_zero := by simp [nat.cast],
nat_cast_succ := by simp [nat.cast]; refl,
mul_assoc := λ a b c, quotient.induction_on₃' a b c $
λ a b c, congr_arg submodule.quotient.mk (mul_assoc a b c),
mul_comm := λ a b, quotient.induction_on₂' a b $
λ a b, congr_arg submodule.quotient.mk (mul_comm a b),
one_mul := λ a, quotient.induction_on' a $
λ a, congr_arg submodule.quotient.mk (one_mul a),
mul_one := λ a, quotient.induction_on' a $
λ a, congr_arg submodule.quotient.mk (mul_one a),
left_distrib := λ a b c, quotient.induction_on₃' a b c $
λ a b c, congr_arg submodule.quotient.mk (left_distrib a b c),
right_distrib := λ a b c, quotient.induction_on₃' a b c $
λ a b c, congr_arg submodule.quotient.mk (right_distrib a b c),
..submodule.quotient.add_comm_group I }
/-- The ring homomorphism from a ring `R` to a quotient ring `R/I`. -/
def mk (I : ideal R) : R →+* (R ⧸ I) :=
⟨λ a, submodule.quotient.mk a, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩
/- Two `ring_homs`s from the quotient by an ideal are equal if their
compositions with `ideal.quotient.mk'` are equal.
See note [partially-applied ext lemmas]. -/
@[ext]
lemma ring_hom_ext [non_assoc_semiring S] ⦃f g : R ⧸ I →+* S⦄
(h : f.comp (mk I) = g.comp (mk I)) : f = g :=
ring_hom.ext $ λ x, quotient.induction_on' x $ (ring_hom.congr_fun h : _)
instance inhabited : inhabited (R ⧸ I) := ⟨mk I 37⟩
protected theorem eq : mk I x = mk I y ↔ x - y ∈ I := submodule.quotient.eq I
@[simp] theorem mk_eq_mk (x : R) : (submodule.quotient.mk x : R ⧸ I) = mk I x := rfl
lemma eq_zero_iff_mem {I : ideal R} : mk I a = 0 ↔ a ∈ I :=
submodule.quotient.mk_eq_zero _
theorem zero_eq_one_iff {I : ideal R} : (0 : R ⧸ I) = 1 ↔ I = ⊤ :=
eq_comm.trans $ eq_zero_iff_mem.trans (eq_top_iff_one _).symm
theorem zero_ne_one_iff {I : ideal R} : (0 : R ⧸ I) ≠ 1 ↔ I ≠ ⊤ :=
not_congr zero_eq_one_iff
protected theorem nontrivial {I : ideal R} (hI : I ≠ ⊤) : nontrivial (R ⧸ I) :=
⟨⟨0, 1, zero_ne_one_iff.2 hI⟩⟩
lemma subsingleton_iff {I : ideal R} : subsingleton (R ⧸ I) ↔ I = ⊤ :=
by rw [eq_top_iff_one, ← subsingleton_iff_zero_eq_one, eq_comm,
← I^.quotient.mk^.map_one, quotient.eq_zero_iff_mem]
instance : unique (R ⧸ (⊤ : ideal R)) :=
⟨⟨0⟩, by rintro ⟨x⟩; exact quotient.eq_zero_iff_mem.mpr submodule.mem_top⟩
lemma mk_surjective : function.surjective (mk I) :=
λ y, quotient.induction_on' y (λ x, exists.intro x rfl)
/-- If `I` is an ideal of a commutative ring `R`, if `q : R → R/I` is the quotient map, and if
`s ⊆ R` is a subset, then `q⁻¹(q(s)) = ⋃ᵢ(i + s)`, the union running over all `i ∈ I`. -/
lemma quotient_ring_saturate (I : ideal R) (s : set R) :
mk I ⁻¹' (mk I '' s) = (⋃ x : I, (λ y, x.1 + y) '' s) :=
begin
ext x,
simp only [mem_preimage, mem_image, mem_Union, ideal.quotient.eq],
exact ⟨λ ⟨a, a_in, h⟩, ⟨⟨_, I.neg_mem h⟩, a, a_in, by simp⟩,
λ ⟨⟨i, hi⟩, a, ha, eq⟩,
⟨a, ha, by rw [← eq, sub_add_eq_sub_sub_swap, sub_self, zero_sub]; exact I.neg_mem hi⟩⟩
end
instance is_domain (I : ideal R) [hI : I.is_prime] : is_domain (R ⧸ I) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ a b,
quotient.induction_on₂' a b $ λ a b hab,
(hI.mem_or_mem (eq_zero_iff_mem.1 hab)).elim
(or.inl ∘ eq_zero_iff_mem.2)
(or.inr ∘ eq_zero_iff_mem.2),
.. quotient.nontrivial hI.1 }
lemma is_domain_iff_prime (I : ideal R) : is_domain (R ⧸ I) ↔ I.is_prime :=
⟨ λ ⟨h1, h2⟩, ⟨zero_ne_one_iff.1 $ @zero_ne_one _ _ ⟨h2⟩, λ x y h,
by { simp only [←eq_zero_iff_mem, (mk I).map_mul] at ⊢ h, exact h1 h}⟩,
λ h, by { resetI, apply_instance }⟩
lemma exists_inv {I : ideal R} [hI : I.is_maximal] :
∀ {a : (R ⧸ I)}, a ≠ 0 → ∃ b : (R ⧸ I), a * b = 1 :=
begin
rintro ⟨a⟩ h,
rcases hI.exists_inv (mt eq_zero_iff_mem.2 h) with ⟨b, c, hc, abc⟩,
rw [mul_comm] at abc,
refine ⟨mk _ b, quot.sound _⟩, --quot.sound hb
rw ← eq_sub_iff_add_eq' at abc,
rw [abc, ← neg_mem_iff, neg_sub] at hc,
rw submodule.quotient_rel_r_def,
convert hc,
end
open_locale classical
/-- quotient by maximal ideal is a field. def rather than instance, since users will have
computable inverses in some applications.
See note [reducible non-instances]. -/
@[reducible]
protected noncomputable def field (I : ideal R) [hI : I.is_maximal] : field (R ⧸ I) :=
{ inv := λ a, if ha : a = 0 then 0 else classical.some (exists_inv ha),
mul_inv_cancel := λ a (ha : a ≠ 0), show a * dite _ _ _ = _,
by rw dif_neg ha;
exact classical.some_spec (exists_inv ha),
inv_zero := dif_pos rfl,
..quotient.comm_ring I,
..quotient.is_domain I }
/-- If the quotient by an ideal is a field, then the ideal is maximal. -/
theorem maximal_of_is_field (I : ideal R)
(hqf : is_field (R ⧸ I)) : I.is_maximal :=
begin
apply ideal.is_maximal_iff.2,
split,
{ intro h,
rcases hqf.exists_pair_ne with ⟨⟨x⟩, ⟨y⟩, hxy⟩,
exact hxy (ideal.quotient.eq.2 (mul_one (x - y) ▸ I.mul_mem_left _ h)) },
{ intros J x hIJ hxnI hxJ,
rcases hqf.mul_inv_cancel (mt ideal.quotient.eq_zero_iff_mem.1 hxnI) with ⟨⟨y⟩, hy⟩,
rw [← zero_add (1 : R), ← sub_self (x * y), sub_add],
refine J.sub_mem (J.mul_mem_right _ hxJ) (hIJ (ideal.quotient.eq.1 hy)) }
end
/-- The quotient of a ring by an ideal is a field iff the ideal is maximal. -/
theorem maximal_ideal_iff_is_field_quotient (I : ideal R) : I.is_maximal ↔ is_field (R ⧸ I) :=
⟨λ h, by { letI := @quotient.field _ _ I h, exact field.to_is_field _ }, maximal_of_is_field _⟩
variable [comm_ring S]
/-- Given a ring homomorphism `f : R →+* S` sending all elements of an ideal to zero,
lift it to the quotient by this ideal. -/
def lift (I : ideal R) (f : R →+* S) (H : ∀ (a : R), a ∈ I → f a = 0) :
R ⧸ I →+* S :=
{ map_one' := f.map_one,
map_zero' := f.map_zero,
map_add' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_add,
map_mul' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_mul,
.. quotient_add_group.lift I.to_add_subgroup f.to_add_monoid_hom H }
@[simp] lemma lift_mk (I : ideal R) (f : R →+* S) (H : ∀ (a : R), a ∈ I → f a = 0) :
lift I f H (mk I a) = f a := rfl
/-- The ring homomorphism from the quotient by a smaller ideal to the quotient by a larger ideal.
This is the `ideal.quotient` version of `quot.factor` -/
def factor (S T : ideal R) (H : S ≤ T) : R ⧸ S →+* R ⧸ T :=
ideal.quotient.lift S (T^.quotient.mk) (λ x hx, eq_zero_iff_mem.2 (H hx))
@[simp] lemma factor_mk (S T : ideal R) (H : S ≤ T) (x : R) :
factor S T H (mk S x) = mk T x := rfl
@[simp] lemma factor_comp_mk (S T : ideal R) (H : S ≤ T) : (factor S T H).comp (mk S) = mk T :=
by { ext x, rw [ring_hom.comp_apply, factor_mk] }
end quotient
/-- Quotienting by equal ideals gives equivalent rings.
See also `submodule.quot_equiv_of_eq`.
-/
def quot_equiv_of_eq {R : Type*} [comm_ring R] {I J : ideal R} (h : I = J) :
(R ⧸ I) ≃+* R ⧸ J :=
{ map_mul' := by { rintro ⟨x⟩ ⟨y⟩, refl },
.. submodule.quot_equiv_of_eq I J h }
@[simp]
lemma quot_equiv_of_eq_mk {R : Type*} [comm_ring R] {I J : ideal R} (h : I = J) (x : R) :
quot_equiv_of_eq h (ideal.quotient.mk I x) = ideal.quotient.mk J x :=
rfl
@[simp]
lemma quot_equiv_of_eq_symm {R : Type*} [comm_ring R] {I J : ideal R} (h : I = J) :
(ideal.quot_equiv_of_eq h).symm = ideal.quot_equiv_of_eq h.symm :=
by ext; refl
section pi
variables (ι : Type v)
/-- `R^n/I^n` is a `R/I`-module. -/
instance module_pi : module (R ⧸ I) ((ι → R) ⧸ I.pi ι) :=
{ smul := λ c m, quotient.lift_on₂' c m (λ r m, submodule.quotient.mk $ r • m) begin
intros c₁ m₁ c₂ m₂ hc hm,
apply ideal.quotient.eq.2,
rw submodule.quotient_rel_r_def at hc hm,
intro i,
exact I.mul_sub_mul_mem hc (hm i),
end,
one_smul := begin
rintro ⟨a⟩,
change ideal.quotient.mk _ _ = ideal.quotient.mk _ _,
congr' with i, exact one_mul (a i),
end,
mul_smul := begin
rintro ⟨a⟩ ⟨b⟩ ⟨c⟩,
change ideal.quotient.mk _ _ = ideal.quotient.mk _ _,
simp only [(•)],
congr' with i, exact mul_assoc a b (c i),
end,
smul_add := begin
rintro ⟨a⟩ ⟨b⟩ ⟨c⟩,
change ideal.quotient.mk _ _ = ideal.quotient.mk _ _,
congr' with i, exact mul_add a (b i) (c i),
end,
smul_zero := begin
rintro ⟨a⟩,
change ideal.quotient.mk _ _ = ideal.quotient.mk _ _,
congr' with i, exact mul_zero a,
end,
add_smul := begin
rintro ⟨a⟩ ⟨b⟩ ⟨c⟩,
change ideal.quotient.mk _ _ = ideal.quotient.mk _ _,
congr' with i, exact add_mul a b (c i),
end,
zero_smul := begin
rintro ⟨a⟩,
change ideal.quotient.mk _ _ = ideal.quotient.mk _ _,
congr' with i, exact zero_mul (a i),
end, }
/-- `R^n/I^n` is isomorphic to `(R/I)^n` as an `R/I`-module. -/
noncomputable def pi_quot_equiv : ((ι → R) ⧸ I.pi ι) ≃ₗ[(R ⧸ I)] (ι → (R ⧸ I)) :=
{ to_fun := λ x, quotient.lift_on' x (λ f i, ideal.quotient.mk I (f i)) $
λ a b hab, funext (λ i, (submodule.quotient.eq' _).2
(quotient_add_group.left_rel_apply.mp hab i)),
map_add' := by { rintros ⟨_⟩ ⟨_⟩, refl },
map_smul' := by { rintros ⟨_⟩ ⟨_⟩, refl },
inv_fun := λ x, ideal.quotient.mk (I.pi ι) $ λ i, quotient.out' (x i),
left_inv :=
begin
rintro ⟨x⟩,
exact ideal.quotient.eq.2 (λ i, ideal.quotient.eq.1 (quotient.out_eq' _))
end,
right_inv :=
begin
intro x,
ext i,
obtain ⟨r, hr⟩ := @quot.exists_rep _ _ (x i),
simp_rw ←hr,
convert quotient.out_eq' _
end }
/-- If `f : R^n → R^m` is an `R`-linear map and `I ⊆ R` is an ideal, then the image of `I^n` is
contained in `I^m`. -/
lemma map_pi {ι} [fintype ι] {ι' : Type w} (x : ι → R) (hi : ∀ i, x i ∈ I)
(f : (ι → R) →ₗ[R] (ι' → R)) (i : ι') : f x i ∈ I :=
begin
classical,
rw pi_eq_sum_univ x,
simp only [finset.sum_apply, smul_eq_mul, linear_map.map_sum, pi.smul_apply, linear_map.map_smul],
exact I.sum_mem (λ j hj, I.mul_mem_right _ (hi j))
end
end pi
section chinese_remainder
variables {ι : Type v}
theorem exists_sub_one_mem_and_mem (s : finset ι) {f : ι → ideal R}
(hf : ∀ i ∈ s, ∀ j ∈ s, i ≠ j → f i ⊔ f j = ⊤) (i : ι) (his : i ∈ s) :
∃ r : R, r - 1 ∈ f i ∧ ∀ j ∈ s, j ≠ i → r ∈ f j :=
begin
have : ∀ j ∈ s, j ≠ i → ∃ r : R, ∃ H : r - 1 ∈ f i, r ∈ f j,
{ intros j hjs hji, specialize hf i his j hjs hji.symm,
rw [eq_top_iff_one, submodule.mem_sup] at hf,
rcases hf with ⟨r, hri, s, hsj, hrs⟩, refine ⟨1 - r, _, _⟩,
{ rw [sub_right_comm, sub_self, zero_sub], exact (f i).neg_mem hri },
{ rw [← hrs, add_sub_cancel'], exact hsj } },
classical,
have : ∃ g : ι → R, (∀ j, g j - 1 ∈ f i) ∧ ∀ j ∈ s, j ≠ i → g j ∈ f j,
{ choose g hg1 hg2,
refine ⟨λ j, if H : j ∈ s ∧ j ≠ i then g j H.1 H.2 else 1, λ j, _, λ j, _⟩,
{ split_ifs with h, { apply hg1 }, rw sub_self, exact (f i).zero_mem },
{ intros hjs hji, rw dif_pos, { apply hg2 }, exact ⟨hjs, hji⟩ } },
rcases this with ⟨g, hgi, hgj⟩, use (∏ x in s.erase i, g x), split,
{ rw [← quotient.eq, ring_hom.map_one, ring_hom.map_prod],
apply finset.prod_eq_one, intros, rw [← ring_hom.map_one, quotient.eq], apply hgi },
intros j hjs hji, rw [← quotient.eq_zero_iff_mem, ring_hom.map_prod],
refine finset.prod_eq_zero (finset.mem_erase_of_ne_of_mem hji hjs) _,
rw quotient.eq_zero_iff_mem, exact hgj j hjs hji
end
theorem exists_sub_mem [fintype ι] {f : ι → ideal R}
(hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) (g : ι → R) :
∃ r : R, ∀ i, r - g i ∈ f i :=
begin
have : ∃ φ : ι → R, (∀ i, φ i - 1 ∈ f i) ∧ (∀ i j, i ≠ j → φ i ∈ f j),
{ have := exists_sub_one_mem_and_mem (finset.univ : finset ι) (λ i _ j _ hij, hf i j hij),
choose φ hφ,
existsi λ i, φ i (finset.mem_univ i),
exact ⟨λ i, (hφ i _).1, λ i j hij, (hφ i _).2 j (finset.mem_univ j) hij.symm⟩ },
rcases this with ⟨φ, hφ1, hφ2⟩,
use ∑ i, g i * φ i,
intros i,
rw [← quotient.eq, ring_hom.map_sum],
refine eq.trans (finset.sum_eq_single i _ _) _,
{ intros j _ hji, rw quotient.eq_zero_iff_mem, exact (f i).mul_mem_left _ (hφ2 j i hji) },
{ intros hi, exact (hi $ finset.mem_univ i).elim },
specialize hφ1 i, rw [← quotient.eq, ring_hom.map_one] at hφ1,
rw [ring_hom.map_mul, hφ1, mul_one]
end
/-- The homomorphism from `R/(⋂ i, f i)` to `∏ i, (R / f i)` featured in the Chinese
Remainder Theorem. It is bijective if the ideals `f i` are comaximal. -/
def quotient_inf_to_pi_quotient (f : ι → ideal R) :
R ⧸ (⨅ i, f i) →+* Π i, R ⧸ f i :=
quotient.lift (⨅ i, f i)
(pi.ring_hom (λ i : ι, (quotient.mk (f i) : _))) $
λ r hr, begin
rw submodule.mem_infi at hr,
ext i,
exact quotient.eq_zero_iff_mem.2 (hr i)
end
theorem quotient_inf_to_pi_quotient_bijective [fintype ι] {f : ι → ideal R}
(hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) :
function.bijective (quotient_inf_to_pi_quotient f) :=
⟨λ x y, quotient.induction_on₂' x y $ λ r s hrs, quotient.eq.2 $
(submodule.mem_infi _).2 $ λ i, quotient.eq.1 $
show quotient_inf_to_pi_quotient f (quotient.mk' r) i = _, by rw hrs; refl,
λ g, let ⟨r, hr⟩ := exists_sub_mem hf (λ i, quotient.out' (g i)) in
⟨quotient.mk _ r, funext $ λ i, quotient.out_eq' (g i) ▸ quotient.eq.2 (hr i)⟩⟩
/-- Chinese Remainder Theorem. Eisenbud Ex.2.6. Similar to Atiyah-Macdonald 1.10 and Stacks 00DT -/
noncomputable def quotient_inf_ring_equiv_pi_quotient [fintype ι] (f : ι → ideal R)
(hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) :
R ⧸ (⨅ i, f i) ≃+* Π i, R ⧸ f i :=
{ .. equiv.of_bijective _ (quotient_inf_to_pi_quotient_bijective hf),
.. quotient_inf_to_pi_quotient f }
end chinese_remainder
end ideal
|
d67c53447772a7313b27eacf8572a51d26e87574 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/doIfLet.lean | 5e41922744c882d30d69977b75fd6af03c246fc4 | [
"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 | 368 | lean | #eval Id.run do
let mut x := 2
if let n + 1 := x then
x := n
return x
#eval Id.run do
let mut x := 2
if let 0 := x then
x := 0
else if let n + 1 := x then
x := n
else
x := x + 1
return x
#eval Id.run do
let mut some x ← pure $ some 2 | 0
x := x - 1
pure x
#eval Id.run do
let mut some x := some 2 | 0
x := x - 1
pure x
|
c09337ab3700ecf3a9ebf2e03b9c17faf416dd4c | 649957717d58c43b5d8d200da34bf374293fe739 | /src/category_theory/limits/over.lean | df9a3e6209b318c159ad12c6ed7565c98067672e | [
"Apache-2.0"
] | permissive | Vtec234/mathlib | b50c7b21edea438df7497e5ed6a45f61527f0370 | fb1848bbbfce46152f58e219dc0712f3289d2b20 | refs/heads/master | 1,592,463,095,113 | 1,562,737,749,000 | 1,562,737,749,000 | 196,202,858 | 0 | 0 | Apache-2.0 | 1,562,762,338,000 | 1,562,762,337,000 | null | UTF-8 | Lean | false | false | 5,937 | lean | -- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Johan Commelin, Reid Barton
import category_theory.comma
import category_theory.limits.preserves
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+1} C]
include 𝒞
variable {X : C}
namespace category_theory.functor
def to_cocone (F : J ⥤ over X) : cocone (F ⋙ over.forget) :=
{ X := X,
ι := { app := λ j, (F.obj j).hom } }
@[simp] lemma to_cocone_X (F : J ⥤ over X) : F.to_cocone.X = X := rfl
@[simp] lemma to_cocone_ι (F : J ⥤ over X) (j : J) : F.to_cocone.ι.app j = (F.obj j).hom := rfl
def to_cone (F : J ⥤ under X) : cone (F ⋙ under.forget) :=
{ X := X,
π := { app := λ j, (F.obj j).hom } }
@[simp] lemma to_cone_X (F : J ⥤ under X) : F.to_cone.X = X := rfl
@[simp] lemma to_cone_π (F : J ⥤ under X) (j : J) : F.to_cone.π.app j = (F.obj j).hom := rfl
end category_theory.functor
namespace category_theory.over
def colimit (F : J ⥤ over X) [has_colimit (F ⋙ forget)] : cocone F :=
{ X := mk $ colimit.desc (F ⋙ forget) F.to_cocone,
ι :=
{ app := λ j, hom_mk $ colimit.ι (F ⋙ forget) j,
naturality' :=
begin
intros j j' f,
have := colimit.w (F ⋙ forget) f,
tidy
end } }
@[simp] lemma colimit_X_hom (F : J ⥤ over X) [has_colimit (F ⋙ forget)] :
((colimit F).X).hom = colimit.desc (F ⋙ forget) F.to_cocone := rfl
@[simp] lemma colimit_ι_app (F : J ⥤ over X) [has_colimit (F ⋙ forget)] (j : J) :
((colimit F).ι).app j = hom_mk (colimit.ι (F ⋙ forget) j) := rfl
def forget_colimit_is_colimit (F : J ⥤ over X) [has_colimit (F ⋙ forget)] :
is_colimit (forget.map_cocone (colimit F)) :=
is_colimit.of_iso_colimit (colimit.is_colimit (F ⋙ forget)) (cocones.ext (iso.refl _) (by tidy))
instance : reflects_colimits (forget : over X ⥤ C) :=
{ reflects_colimits_of_shape := λ J 𝒥,
{ reflects_colimit := λ F,
by constructor; exactI λ t ht,
{ desc := λ s, hom_mk (ht.desc (forget.map_cocone s))
begin
apply ht.hom_ext, intro j,
rw [←category.assoc, ht.fac],
transitivity (F.obj j).hom,
exact w (s.ι.app j), -- TODO: How to write (s.ι.app j).w?
exact (w (t.ι.app j)).symm,
end,
fac' := begin
intros s j, ext, exact ht.fac (forget.map_cocone s) j
-- TODO: Ask Simon about multiple ext lemmas for defeq types (comma_morphism & over.category.hom)
end,
uniq' :=
begin
intros s m w,
ext1 j,
exact ht.uniq (forget.map_cocone s) m.left (λ j, congr_arg comma_morphism.left (w j))
end } } }
instance has_colimit {F : J ⥤ over X} [has_colimit (F ⋙ forget)] : has_colimit F :=
{ cocone := colimit F,
is_colimit := reflects_colimit.reflects (forget_colimit_is_colimit F) }
instance has_colimits_of_shape [has_colimits_of_shape J C] :
has_colimits_of_shape J (over X) :=
{ has_colimit := λ F, by apply_instance }
instance has_colimits [has_colimits.{v} C] : has_colimits.{v} (over X) :=
{ has_colimits_of_shape := λ J 𝒥, by resetI; apply_instance }
instance forget_preserves_colimits [has_colimits.{v} C] {X : C} :
preserves_colimits (forget : over X ⥤ C) :=
{ preserves_colimits_of_shape := λ J 𝒥,
{ preserves_colimit := λ F, by exactI
preserves_colimit_of_preserves_colimit_cocone (colimit.is_colimit F) (forget_colimit_is_colimit F) } }
end category_theory.over
namespace category_theory.under
def limit (F : J ⥤ under X) [has_limit (F ⋙ forget)] : cone F :=
{ X := mk $ limit.lift (F ⋙ forget) F.to_cone,
π :=
{ app := λ j, hom_mk $ limit.π (F ⋙ forget) j,
naturality' :=
begin
intros j j' f,
have := (limit.w (F ⋙ forget) f).symm,
tidy
end } }
@[simp] lemma limit_X_hom (F : J ⥤ under X) [has_limit (F ⋙ forget)] :
((limit F).X).hom = limit.lift (F ⋙ forget) F.to_cone := rfl
@[simp] lemma limit_π_app (F : J ⥤ under X) [has_limit (F ⋙ forget)] (j : J) :
((limit F).π).app j = hom_mk (limit.π (F ⋙ forget) j) := rfl
def forget_limit_is_limit (F : J ⥤ under X) [has_limit (F ⋙ forget)] :
is_limit (forget.map_cone (limit F)) :=
is_limit.of_iso_limit (limit.is_limit (F ⋙ forget)) (cones.ext (iso.refl _) (by tidy))
instance : reflects_limits (forget : under X ⥤ C) :=
{ reflects_limits_of_shape := λ J 𝒥,
{ reflects_limit := λ F,
by constructor; exactI λ t ht,
{ lift := λ s, hom_mk (ht.lift (forget.map_cone s))
begin
apply ht.hom_ext, intro j,
rw [category.assoc, ht.fac],
transitivity (F.obj j).hom,
exact w (s.π.app j),
exact (w (t.π.app j)).symm,
end,
fac' := begin
intros s j, ext, exact ht.fac (forget.map_cone s) j
end,
uniq' :=
begin
intros s m w,
ext1 j,
exact ht.uniq (forget.map_cone s) m.right (λ j, congr_arg comma_morphism.right (w j))
end } } }
instance has_limit {F : J ⥤ under X} [has_limit (F ⋙ forget)] : has_limit F :=
{ cone := limit F,
is_limit := reflects_limit.reflects (forget_limit_is_limit F) }
instance has_limits_of_shape [has_limits_of_shape J C] :
has_limits_of_shape J (under X) :=
{ has_limit := λ F, by apply_instance }
instance has_limits [has_limits.{v} C] : has_limits.{v} (under X) :=
{ has_limits_of_shape := λ J 𝒥, by resetI; apply_instance }
instance forget_preserves_limits [has_limits.{v} C] {X : C} :
preserves_limits (forget : under X ⥤ C) :=
{ preserves_limits_of_shape := λ J 𝒥,
{ preserves_limit := λ F, by exactI
preserves_limit_of_preserves_limit_cone (limit.is_limit F) (forget_limit_is_limit F) } }
end category_theory.under
|
ece4b3df5d473f8e9e76cbc35a5d9734613cf4de | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/seminorm.lean | b55e5f5b27a5a489ebed3a107c5c6b606bc3222b | [
"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 | 43,412 | lean | /-
Copyright (c) 2019 Jean Lo. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jean Lo, Yaël Dillies, Moritz Doll
-/
import data.real.pointwise
import analysis.convex.function
import analysis.locally_convex.basic
import analysis.normed.group.add_torsor
/-!
# Seminorms
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines seminorms.
A seminorm is a function to the reals which is positive-semidefinite, absolutely homogeneous, and
subadditive. They are closely related to convex sets and a topological vector space is locally
convex if and only if its topology is induced by a family of seminorms.
## Main declarations
For a module over a normed ring:
* `seminorm`: A function to the reals that is positive-semidefinite, absolutely homogeneous, and
subadditive.
* `norm_seminorm 𝕜 E`: The norm on `E` as a seminorm.
## References
* [H. H. Schaefer, *Topological Vector Spaces*][schaefer1966]
## Tags
seminorm, locally convex, LCTVS
-/
set_option old_structure_cmd true
open normed_field set
open_locale big_operators nnreal pointwise topology
variables {R R' 𝕜 𝕜₂ 𝕜₃ 𝕝 E E₂ E₃ F G ι : Type*}
/-- A seminorm on a module over a normed ring is a function to the reals that is positive
semidefinite, positive homogeneous, and subadditive. -/
structure seminorm (𝕜 : Type*) (E : Type*) [semi_normed_ring 𝕜] [add_group E] [has_smul 𝕜 E]
extends add_group_seminorm E :=
(smul' : ∀ (a : 𝕜) (x : E), to_fun (a • x) = ‖a‖ * to_fun x)
attribute [nolint doc_blame] seminorm.to_add_group_seminorm
/-- `seminorm_class F 𝕜 E` states that `F` is a type of seminorms on the `𝕜`-module E.
You should extend this class when you extend `seminorm`. -/
class seminorm_class (F : Type*) (𝕜 E : out_param $ Type*) [semi_normed_ring 𝕜] [add_group E]
[has_smul 𝕜 E] extends add_group_seminorm_class F E ℝ :=
(map_smul_eq_mul (f : F) (a : 𝕜) (x : E) : f (a • x) = ‖a‖ * f x)
export seminorm_class (map_smul_eq_mul)
-- `𝕜` is an `out_param`, so this is a false positive.
attribute [nolint dangerous_instance] seminorm_class.to_add_group_seminorm_class
section of
/-- Alternative constructor for a `seminorm` on an `add_comm_group E` that is a module over a
`semi_norm_ring 𝕜`. -/
def seminorm.of [semi_normed_ring 𝕜] [add_comm_group E] [module 𝕜 E] (f : E → ℝ)
(add_le : ∀ (x y : E), f (x + y) ≤ f x + f y)
(smul : ∀ (a : 𝕜) (x : E), f (a • x) = ‖a‖ * f x) : seminorm 𝕜 E :=
{ to_fun := f,
map_zero' := by rw [←zero_smul 𝕜 (0 : E), smul, norm_zero, zero_mul],
add_le' := add_le,
smul' := smul,
neg' := λ x, by rw [←neg_one_smul 𝕜, smul, norm_neg, ← smul, one_smul] }
/-- Alternative constructor for a `seminorm` over a normed field `𝕜` that only assumes `f 0 = 0`
and an inequality for the scalar multiplication. -/
def seminorm.of_smul_le [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] (f : E → ℝ)
(map_zero : f 0 = 0) (add_le : ∀ x y, f (x + y) ≤ f x + f y)
(smul_le : ∀ (r : 𝕜) x, f (r • x) ≤ ‖r‖ * f x) : seminorm 𝕜 E :=
seminorm.of f add_le
(λ r x, begin
refine le_antisymm (smul_le r x) _,
by_cases r = 0,
{ simp [h, map_zero] },
rw ←mul_le_mul_left (inv_pos.mpr (norm_pos_iff.mpr h)),
rw inv_mul_cancel_left₀ (norm_ne_zero_iff.mpr h),
specialize smul_le r⁻¹ (r • x),
rw norm_inv at smul_le,
convert smul_le,
simp [h],
end)
end of
namespace seminorm
section semi_normed_ring
variables [semi_normed_ring 𝕜]
section add_group
variables [add_group E]
section has_smul
variables [has_smul 𝕜 E]
instance seminorm_class : seminorm_class (seminorm 𝕜 E) 𝕜 E :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h, by cases f; cases g; congr',
map_zero := λ f, f.map_zero',
map_add_le_add := λ f, f.add_le',
map_neg_eq_map := λ f, f.neg',
map_smul_eq_mul := λ f, f.smul' }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`. -/
instance : has_coe_to_fun (seminorm 𝕜 E) (λ _, E → ℝ) := fun_like.has_coe_to_fun
@[ext] lemma ext {p q : seminorm 𝕜 E} (h : ∀ x, (p : E → ℝ) x = q x) : p = q := fun_like.ext p q h
instance : has_zero (seminorm 𝕜 E) :=
⟨{ smul' := λ _ _, (mul_zero _).symm,
..add_group_seminorm.has_zero.zero }⟩
@[simp] lemma coe_zero : ⇑(0 : seminorm 𝕜 E) = 0 := rfl
@[simp] lemma zero_apply (x : E) : (0 : seminorm 𝕜 E) x = 0 := rfl
instance : inhabited (seminorm 𝕜 E) := ⟨0⟩
variables (p : seminorm 𝕜 E) (c : 𝕜) (x y : E) (r : ℝ)
/-- Any action on `ℝ` which factors through `ℝ≥0` applies to a seminorm. -/
instance [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] :
has_smul R (seminorm 𝕜 E) :=
{ smul := λ r p,
{ to_fun := λ x, r • p x,
smul' := λ _ _, begin
simp only [←smul_one_smul ℝ≥0 r (_ : ℝ), nnreal.smul_def, smul_eq_mul],
rw [map_smul_eq_mul, mul_left_comm],
end,
..(r • p.to_add_group_seminorm) }}
instance [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
[has_smul R' ℝ] [has_smul R' ℝ≥0] [is_scalar_tower R' ℝ≥0 ℝ]
[has_smul R R'] [is_scalar_tower R R' ℝ] :
is_scalar_tower R R' (seminorm 𝕜 E) :=
{ smul_assoc := λ r a p, ext $ λ x, smul_assoc r a (p x) }
lemma coe_smul [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
(r : R) (p : seminorm 𝕜 E) : ⇑(r • p) = r • p := rfl
@[simp] lemma smul_apply [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
(r : R) (p : seminorm 𝕜 E) (x : E) : (r • p) x = r • p x := rfl
instance : has_add (seminorm 𝕜 E) :=
{ add := λ p q,
{ to_fun := λ x, p x + q x,
smul' := λ a x, by simp only [map_smul_eq_mul, map_smul_eq_mul, mul_add],
..(p.to_add_group_seminorm + q.to_add_group_seminorm) }}
lemma coe_add (p q : seminorm 𝕜 E) : ⇑(p + q) = p + q := rfl
@[simp] lemma add_apply (p q : seminorm 𝕜 E) (x : E) : (p + q) x = p x + q x := rfl
instance : add_monoid (seminorm 𝕜 E) :=
fun_like.coe_injective.add_monoid _ rfl coe_add (λ p n, coe_smul n p)
instance : ordered_cancel_add_comm_monoid (seminorm 𝕜 E) :=
fun_like.coe_injective.ordered_cancel_add_comm_monoid _ rfl coe_add (λ p n, coe_smul n p)
instance [monoid R] [mul_action R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] :
mul_action R (seminorm 𝕜 E) :=
fun_like.coe_injective.mul_action _ coe_smul
variables (𝕜 E)
/-- `coe_fn` as an `add_monoid_hom`. Helper definition for showing that `seminorm 𝕜 E` is
a module. -/
@[simps]
def coe_fn_add_monoid_hom : add_monoid_hom (seminorm 𝕜 E) (E → ℝ) := ⟨coe_fn, coe_zero, coe_add⟩
lemma coe_fn_add_monoid_hom_injective : function.injective (coe_fn_add_monoid_hom 𝕜 E) :=
show @function.injective (seminorm 𝕜 E) (E → ℝ) coe_fn, from fun_like.coe_injective
variables {𝕜 E}
instance [monoid R] [distrib_mul_action R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] :
distrib_mul_action R (seminorm 𝕜 E) :=
(coe_fn_add_monoid_hom_injective 𝕜 E).distrib_mul_action _ coe_smul
instance [semiring R] [module R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ] :
module R (seminorm 𝕜 E) :=
(coe_fn_add_monoid_hom_injective 𝕜 E).module R _ coe_smul
instance : has_sup (seminorm 𝕜 E) :=
{ sup := λ p q,
{ to_fun := p ⊔ q,
smul' := λ x v, (congr_arg2 max (map_smul_eq_mul p x v) (map_smul_eq_mul q x v)).trans $
(mul_max_of_nonneg _ _ $ norm_nonneg x).symm,
..(p.to_add_group_seminorm ⊔ q.to_add_group_seminorm) } }
@[simp] lemma coe_sup (p q : seminorm 𝕜 E) : ⇑(p ⊔ q) = p ⊔ q := rfl
lemma sup_apply (p q : seminorm 𝕜 E) (x : E) : (p ⊔ q) x = p x ⊔ q x := rfl
lemma smul_sup [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
(r : R) (p q : seminorm 𝕜 E) :
r • (p ⊔ q) = r • p ⊔ r • q :=
have real.smul_max : ∀ x y : ℝ, r • max x y = max (r • x) (r • y),
from λ x y, by simpa only [←smul_eq_mul, ←nnreal.smul_def, smul_one_smul ℝ≥0 r (_ : ℝ)]
using mul_max_of_nonneg x y (r • 1 : ℝ≥0).coe_nonneg,
ext $ λ x, real.smul_max _ _
instance : partial_order (seminorm 𝕜 E) :=
partial_order.lift _ fun_like.coe_injective
@[simp, norm_cast] lemma coe_le_coe {p q : seminorm 𝕜 E} : (p : E → ℝ) ≤ q ↔ p ≤ q := iff.rfl
@[simp, norm_cast] lemma coe_lt_coe {p q : seminorm 𝕜 E} : (p : E → ℝ) < q ↔ p < q := iff.rfl
lemma le_def {p q : seminorm 𝕜 E} : p ≤ q ↔ ∀ x, p x ≤ q x := iff.rfl
lemma lt_def {p q : seminorm 𝕜 E} : p < q ↔ p ≤ q ∧ ∃ x, p x < q x := pi.lt_def
instance : semilattice_sup (seminorm 𝕜 E) :=
function.injective.semilattice_sup _ fun_like.coe_injective coe_sup
end has_smul
end add_group
section module
variables [semi_normed_ring 𝕜₂] [semi_normed_ring 𝕜₃]
variables {σ₁₂ : 𝕜 →+* 𝕜₂} [ring_hom_isometric σ₁₂]
variables {σ₂₃ : 𝕜₂ →+* 𝕜₃} [ring_hom_isometric σ₂₃]
variables {σ₁₃ : 𝕜 →+* 𝕜₃} [ring_hom_isometric σ₁₃]
variables [add_comm_group E] [add_comm_group E₂] [add_comm_group E₃]
variables [add_comm_group F] [add_comm_group G]
variables [module 𝕜 E] [module 𝕜₂ E₂] [module 𝕜₃ E₃] [module 𝕜 F] [module 𝕜 G]
variables [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
/-- Composition of a seminorm with a linear map is a seminorm. -/
def comp (p : seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) : seminorm 𝕜 E :=
{ to_fun := λ x, p (f x),
smul' := λ _ _, by rw [map_smulₛₗ, map_smul_eq_mul, ring_hom_isometric.is_iso],
..(p.to_add_group_seminorm.comp f.to_add_monoid_hom) }
lemma coe_comp (p : seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) : ⇑(p.comp f) = p ∘ f := rfl
@[simp] lemma comp_apply (p : seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) (x : E) :
(p.comp f) x = p (f x) := rfl
@[simp] lemma comp_id (p : seminorm 𝕜 E) : p.comp linear_map.id = p :=
ext $ λ _, rfl
@[simp] lemma comp_zero (p : seminorm 𝕜₂ E₂) : p.comp (0 : E →ₛₗ[σ₁₂] E₂) = 0 :=
ext $ λ _, map_zero p
@[simp] lemma zero_comp (f : E →ₛₗ[σ₁₂] E₂) : (0 : seminorm 𝕜₂ E₂).comp f = 0 :=
ext $ λ _, rfl
lemma comp_comp [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] (p : seminorm 𝕜₃ E₃)
(g : E₂ →ₛₗ[σ₂₃] E₃) (f : E →ₛₗ[σ₁₂] E₂) :
p.comp (g.comp f) = (p.comp g).comp f :=
ext $ λ _, rfl
lemma add_comp (p q : seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) : (p + q).comp f = p.comp f + q.comp f :=
ext $ λ _, rfl
lemma comp_add_le (p : seminorm 𝕜₂ E₂) (f g : E →ₛₗ[σ₁₂] E₂) :
p.comp (f + g) ≤ p.comp f + p.comp g :=
λ _, map_add_le_add p _ _
lemma smul_comp (p : seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) (c : R) :
(c • p).comp f = c • (p.comp f) :=
ext $ λ _, rfl
lemma comp_mono {p q : seminorm 𝕜₂ E₂} (f : E →ₛₗ[σ₁₂] E₂) (hp : p ≤ q) :
p.comp f ≤ q.comp f := λ _, hp _
/-- The composition as an `add_monoid_hom`. -/
@[simps] def pullback (f : E →ₛₗ[σ₁₂] E₂) : seminorm 𝕜₂ E₂ →+ seminorm 𝕜 E :=
⟨λ p, p.comp f, zero_comp f, λ p q, add_comp p q f⟩
instance : order_bot (seminorm 𝕜 E) := ⟨0, map_nonneg⟩
@[simp] lemma coe_bot : ⇑(⊥ : seminorm 𝕜 E) = 0 := rfl
lemma bot_eq_zero : (⊥ : seminorm 𝕜 E) = 0 := rfl
lemma smul_le_smul {p q : seminorm 𝕜 E} {a b : ℝ≥0} (hpq : p ≤ q) (hab : a ≤ b) :
a • p ≤ b • q :=
begin
simp_rw [le_def, coe_smul],
intros x,
simp_rw [pi.smul_apply, nnreal.smul_def, smul_eq_mul],
exact mul_le_mul hab (hpq x) (map_nonneg p x) (nnreal.coe_nonneg b),
end
lemma finset_sup_apply (p : ι → seminorm 𝕜 E) (s : finset ι) (x : E) :
s.sup p x = ↑(s.sup (λ i, ⟨p i x, map_nonneg (p i) x⟩) : ℝ≥0) :=
begin
induction s using finset.cons_induction_on with a s ha ih,
{ rw [finset.sup_empty, finset.sup_empty, coe_bot, _root_.bot_eq_zero, pi.zero_apply,
nonneg.coe_zero] },
{ rw [finset.sup_cons, finset.sup_cons, coe_sup, sup_eq_max, pi.sup_apply, sup_eq_max,
nnreal.coe_max, subtype.coe_mk, ih] }
end
lemma finset_sup_le_sum (p : ι → seminorm 𝕜 E) (s : finset ι) : s.sup p ≤ ∑ i in s, p i :=
begin
classical,
refine finset.sup_le_iff.mpr _,
intros i hi,
rw [finset.sum_eq_sum_diff_singleton_add hi, le_add_iff_nonneg_left],
exact bot_le,
end
lemma finset_sup_apply_le {p : ι → seminorm 𝕜 E} {s : finset ι} {x : E} {a : ℝ} (ha : 0 ≤ a)
(h : ∀ i, i ∈ s → p i x ≤ a) : s.sup p x ≤ a :=
begin
lift a to ℝ≥0 using ha,
rw [finset_sup_apply, nnreal.coe_le_coe],
exact finset.sup_le h,
end
lemma finset_sup_apply_lt {p : ι → seminorm 𝕜 E} {s : finset ι} {x : E} {a : ℝ} (ha : 0 < a)
(h : ∀ i, i ∈ s → p i x < a) : s.sup p x < a :=
begin
lift a to ℝ≥0 using ha.le,
rw [finset_sup_apply, nnreal.coe_lt_coe, finset.sup_lt_iff],
{ exact h },
{ exact nnreal.coe_pos.mpr ha },
end
lemma norm_sub_map_le_sub (p : seminorm 𝕜 E) (x y : E) : ‖p x - p y‖ ≤ p (x - y) :=
abs_sub_map_le_sub p x y
end module
end semi_normed_ring
section semi_normed_comm_ring
variables [semi_normed_ring 𝕜] [semi_normed_comm_ring 𝕜₂]
variables {σ₁₂ : 𝕜 →+* 𝕜₂} [ring_hom_isometric σ₁₂]
variables [add_comm_group E] [add_comm_group E₂] [module 𝕜 E] [module 𝕜₂ E₂]
lemma comp_smul (p : seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) (c : 𝕜₂) :
p.comp (c • f) = ‖c‖₊ • p.comp f :=
ext $ λ _, by rw [comp_apply, smul_apply, linear_map.smul_apply, map_smul_eq_mul, nnreal.smul_def,
coe_nnnorm, smul_eq_mul, comp_apply]
lemma comp_smul_apply (p : seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) (c : 𝕜₂) (x : E) :
p.comp (c • f) x = ‖c‖ * p (f x) := map_smul_eq_mul p _ _
end semi_normed_comm_ring
section normed_field
variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] {p q : seminorm 𝕜 E} {x : E}
/-- Auxiliary lemma to show that the infimum of seminorms is well-defined. -/
lemma bdd_below_range_add : bdd_below (range $ λ u, p u + q (x - u)) :=
⟨0, by { rintro _ ⟨x, rfl⟩, dsimp, positivity }⟩
noncomputable instance : has_inf (seminorm 𝕜 E) :=
{ inf := λ p q,
{ to_fun := λ x, ⨅ u : E, p u + q (x-u),
smul' :=
begin
intros a x,
obtain rfl | ha := eq_or_ne a 0,
{ rw [norm_zero, zero_mul, zero_smul],
refine cinfi_eq_of_forall_ge_of_forall_gt_exists_lt (λ i, by positivity)
(λ x hx, ⟨0, by rwa [map_zero, sub_zero, map_zero, add_zero]⟩) },
simp_rw [real.mul_infi_of_nonneg (norm_nonneg a), mul_add, ←map_smul_eq_mul p,
←map_smul_eq_mul q, smul_sub],
refine function.surjective.infi_congr ((•) a⁻¹ : E → E) (λ u, ⟨a • u, inv_smul_smul₀ ha u⟩)
(λ u, _),
rw smul_inv_smul₀ ha
end,
..(p.to_add_group_seminorm ⊓ q.to_add_group_seminorm) }}
@[simp] lemma inf_apply (p q : seminorm 𝕜 E) (x : E) : (p ⊓ q) x = ⨅ u : E, p u + q (x-u) := rfl
noncomputable instance : lattice (seminorm 𝕜 E) :=
{ inf := (⊓),
inf_le_left := λ p q x, cinfi_le_of_le bdd_below_range_add x $
by simp only [sub_self, map_zero, add_zero],
inf_le_right := λ p q x, cinfi_le_of_le bdd_below_range_add 0 $
by simp only [sub_self, map_zero, zero_add, sub_zero],
le_inf := λ a b c hab hac x,
le_cinfi $ λ u, (le_map_add_map_sub a _ _).trans $ add_le_add (hab _) (hac _),
..seminorm.semilattice_sup }
lemma smul_inf [has_smul R ℝ] [has_smul R ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ]
(r : R) (p q : seminorm 𝕜 E) :
r • (p ⊓ q) = r • p ⊓ r • q :=
begin
ext,
simp_rw [smul_apply, inf_apply, smul_apply, ←smul_one_smul ℝ≥0 r (_ : ℝ), nnreal.smul_def,
smul_eq_mul, real.mul_infi_of_nonneg (subtype.prop _), mul_add],
end
section classical
open_locale classical
/-- We define the supremum of an arbitrary subset of `seminorm 𝕜 E` as follows:
* if `s` is `bdd_above` *as a set of functions `E → ℝ`* (that is, if `s` is pointwise bounded
above), we take the pointwise supremum of all elements of `s`, and we prove that it is indeed a
seminorm.
* otherwise, we take the zero seminorm `⊥`.
There are two things worth mentionning here:
* First, it is not trivial at first that `s` being bounded above *by a function* implies
being bounded above *as a seminorm*. We show this in `seminorm.bdd_above_iff` by using
that the `Sup s` as defined here is then a bounding seminorm for `s`. So it is important to make
the case disjunction on `bdd_above (coe_fn '' s : set (E → ℝ))` and not `bdd_above s`.
* Since the pointwise `Sup` already gives `0` at points where a family of functions is
not bounded above, one could hope that just using the pointwise `Sup` would work here, without the
need for an additional case disjunction. As discussed on Zulip, this doesn't work because this can
give a function which does *not* satisfy the seminorm axioms (typically sub-additivity).
-/
noncomputable instance : has_Sup (seminorm 𝕜 E) :=
{ Sup := λ s, if h : bdd_above (coe_fn '' s : set (E → ℝ)) then
{ to_fun := ⨆ p : s, ((p : seminorm 𝕜 E) : E → ℝ),
map_zero' :=
begin
rw [supr_apply, ← @real.csupr_const_zero s],
congrm ⨆ i, _,
exact map_zero i.1
end,
add_le' := λ x y,
begin
rcases h with ⟨q, hq⟩,
obtain rfl | h := s.eq_empty_or_nonempty,
{ simp [real.csupr_empty] },
haveI : nonempty ↥s := h.coe_sort,
simp only [supr_apply],
refine csupr_le (λ i, ((i : seminorm 𝕜 E).add_le' x y).trans $
add_le_add (le_csupr ⟨q x, _⟩ i) (le_csupr ⟨q y, _⟩ i));
rw [mem_upper_bounds, forall_range_iff];
exact λ j, hq (mem_image_of_mem _ j.2) _,
end,
neg' := λ x,
begin
simp only [supr_apply],
congrm ⨆ i, _,
exact i.1.neg' _
end,
smul' := λ a x,
begin
simp only [supr_apply],
rw [← smul_eq_mul, real.smul_supr_of_nonneg (norm_nonneg a) (λ i : s, (i : seminorm 𝕜 E) x)],
congrm ⨆ i, _,
exact i.1.smul' a x
end }
else ⊥ }
protected lemma coe_Sup_eq' {s : set $ seminorm 𝕜 E} (hs : bdd_above (coe_fn '' s : set (E → ℝ))) :
coe_fn (Sup s) = ⨆ p : s, p :=
congr_arg _ (dif_pos hs)
protected lemma bdd_above_iff {s : set $ seminorm 𝕜 E} :
bdd_above s ↔ bdd_above (coe_fn '' s : set (E → ℝ)) :=
⟨λ ⟨q, hq⟩, ⟨q, ball_image_of_ball $ λ p hp, hq hp⟩,
λ H, ⟨Sup s, λ p hp x,
begin
rw [seminorm.coe_Sup_eq' H, supr_apply],
rcases H with ⟨q, hq⟩,
exact le_csupr ⟨q x, forall_range_iff.mpr $ λ i : s, hq (mem_image_of_mem _ i.2) x⟩ ⟨p, hp⟩
end ⟩⟩
protected lemma coe_Sup_eq {s : set $ seminorm 𝕜 E} (hs : bdd_above s) :
coe_fn (Sup s) = ⨆ p : s, p :=
seminorm.coe_Sup_eq' (seminorm.bdd_above_iff.mp hs)
protected lemma coe_supr_eq {ι : Type*} {p : ι → seminorm 𝕜 E} (hp : bdd_above (range p)) :
coe_fn (⨆ i, p i) = ⨆ i, p i :=
by rw [← Sup_range, seminorm.coe_Sup_eq hp]; exact supr_range' (coe_fn : seminorm 𝕜 E → E → ℝ) p
private lemma seminorm.is_lub_Sup (s : set (seminorm 𝕜 E)) (hs₁ : bdd_above s) (hs₂ : s.nonempty) :
is_lub s (Sup s) :=
begin
refine ⟨λ p hp x, _, λ p hp x, _⟩;
haveI : nonempty ↥s := hs₂.coe_sort;
rw [seminorm.coe_Sup_eq hs₁, supr_apply],
{ rcases hs₁ with ⟨q, hq⟩,
exact le_csupr ⟨q x, forall_range_iff.mpr $ λ i : s, hq i.2 x⟩ ⟨p, hp⟩ },
{ exact csupr_le (λ q, hp q.2 x) }
end
/-- `seminorm 𝕜 E` is a conditionally complete lattice.
Note that, while `inf`, `sup` and `Sup` have good definitional properties (corresponding to
`seminorm.has_inf`, `seminorm.has_sup` and `seminorm.has_Sup` respectively), `Inf s` is just
defined as the supremum of the lower bounds of `s`, which is not really useful in practice. If you
need to use `Inf` on seminorms, then you should probably provide a more workable definition first,
but this is unlikely to happen so we keep the "bad" definition for now. -/
noncomputable instance : conditionally_complete_lattice (seminorm 𝕜 E) :=
conditionally_complete_lattice_of_lattice_of_Sup (seminorm 𝕜 E) seminorm.is_lub_Sup
end classical
end normed_field
/-! ### Seminorm ball -/
section semi_normed_ring
variables [semi_normed_ring 𝕜]
section add_comm_group
variables [add_comm_group E]
section has_smul
variables [has_smul 𝕜 E] (p : seminorm 𝕜 E)
/-- The ball of radius `r` at `x` with respect to seminorm `p` is the set of elements `y` with
`p (y - x) < r`. -/
def ball (x : E) (r : ℝ) := { y : E | p (y - x) < r }
/-- The closed ball of radius `r` at `x` with respect to seminorm `p` is the set of elements `y`
with `p (y - x) ≤ r`. -/
def closed_ball (x : E) (r : ℝ) := { y : E | p (y - x) ≤ r }
variables {x y : E} {r : ℝ}
@[simp] lemma mem_ball : y ∈ ball p x r ↔ p (y - x) < r := iff.rfl
@[simp] lemma mem_closed_ball : y ∈ closed_ball p x r ↔ p (y - x) ≤ r := iff.rfl
lemma mem_ball_self (hr : 0 < r) : x ∈ ball p x r := by simp [hr]
lemma mem_closed_ball_self (hr : 0 ≤ r) : x ∈ closed_ball p x r := by simp [hr]
lemma mem_ball_zero : y ∈ ball p 0 r ↔ p y < r := by rw [mem_ball, sub_zero]
lemma mem_closed_ball_zero : y ∈ closed_ball p 0 r ↔ p y ≤ r := by rw [mem_closed_ball, sub_zero]
lemma ball_zero_eq : ball p 0 r = { y : E | p y < r } := set.ext $ λ x, p.mem_ball_zero
lemma closed_ball_zero_eq : closed_ball p 0 r = { y : E | p y ≤ r } :=
set.ext $ λ x, p.mem_closed_ball_zero
lemma ball_subset_closed_ball (x r) : ball p x r ⊆ closed_ball p x r := λ y (hy : _ < _), hy.le
lemma closed_ball_eq_bInter_ball (x r) : closed_ball p x r = ⋂ ρ > r, ball p x ρ :=
by ext y; simp_rw [mem_closed_ball, mem_Inter₂, mem_ball, ← forall_lt_iff_le']
@[simp] lemma ball_zero' (x : E) (hr : 0 < r) : ball (0 : seminorm 𝕜 E) x r = set.univ :=
begin
rw [set.eq_univ_iff_forall, ball],
simp [hr],
end
@[simp] lemma closed_ball_zero' (x : E) (hr : 0 < r) :
closed_ball (0 : seminorm 𝕜 E) x r = set.univ :=
eq_univ_of_subset (ball_subset_closed_ball _ _ _) (ball_zero' x hr)
lemma ball_smul (p : seminorm 𝕜 E) {c : nnreal} (hc : 0 < c) (r : ℝ) (x : E) :
(c • p).ball x r = p.ball x (r / c) :=
by { ext, rw [mem_ball, mem_ball, smul_apply, nnreal.smul_def, smul_eq_mul, mul_comm,
lt_div_iff (nnreal.coe_pos.mpr hc)] }
lemma closed_ball_smul (p : seminorm 𝕜 E) {c : nnreal} (hc : 0 < c) (r : ℝ) (x : E) :
(c • p).closed_ball x r = p.closed_ball x (r / c) :=
by { ext, rw [mem_closed_ball, mem_closed_ball, smul_apply, nnreal.smul_def, smul_eq_mul, mul_comm,
le_div_iff (nnreal.coe_pos.mpr hc)] }
lemma ball_sup (p : seminorm 𝕜 E) (q : seminorm 𝕜 E) (e : E) (r : ℝ) :
ball (p ⊔ q) e r = ball p e r ∩ ball q e r :=
by simp_rw [ball, ←set.set_of_and, coe_sup, pi.sup_apply, sup_lt_iff]
lemma closed_ball_sup (p : seminorm 𝕜 E) (q : seminorm 𝕜 E) (e : E) (r : ℝ) :
closed_ball (p ⊔ q) e r = closed_ball p e r ∩ closed_ball q e r :=
by simp_rw [closed_ball, ←set.set_of_and, coe_sup, pi.sup_apply, sup_le_iff]
lemma ball_finset_sup' (p : ι → seminorm 𝕜 E) (s : finset ι) (H : s.nonempty) (e : E) (r : ℝ) :
ball (s.sup' H p) e r = s.inf' H (λ i, ball (p i) e r) :=
begin
induction H using finset.nonempty.cons_induction with a a s ha hs ih,
{ classical, simp },
{ rw [finset.sup'_cons hs, finset.inf'_cons hs, ball_sup, inf_eq_inter, ih] },
end
lemma closed_ball_finset_sup' (p : ι → seminorm 𝕜 E) (s : finset ι) (H : s.nonempty) (e : E)
(r : ℝ) : closed_ball (s.sup' H p) e r = s.inf' H (λ i, closed_ball (p i) e r) :=
begin
induction H using finset.nonempty.cons_induction with a a s ha hs ih,
{ classical, simp },
{ rw [finset.sup'_cons hs, finset.inf'_cons hs, closed_ball_sup, inf_eq_inter, ih] },
end
lemma ball_mono {p : seminorm 𝕜 E} {r₁ r₂ : ℝ} (h : r₁ ≤ r₂) : p.ball x r₁ ⊆ p.ball x r₂ :=
λ _ (hx : _ < _), hx.trans_le h
lemma closed_ball_mono {p : seminorm 𝕜 E} {r₁ r₂ : ℝ} (h : r₁ ≤ r₂) :
p.closed_ball x r₁ ⊆ p.closed_ball x r₂ :=
λ _ (hx : _ ≤ _), hx.trans h
lemma ball_antitone {p q : seminorm 𝕜 E} (h : q ≤ p) : p.ball x r ⊆ q.ball x r :=
λ _, (h _).trans_lt
lemma closed_ball_antitone {p q : seminorm 𝕜 E} (h : q ≤ p) :
p.closed_ball x r ⊆ q.closed_ball x r :=
λ _, (h _).trans
lemma ball_add_ball_subset (p : seminorm 𝕜 E) (r₁ r₂ : ℝ) (x₁ x₂ : E):
p.ball (x₁ : E) r₁ + p.ball (x₂ : E) r₂ ⊆ p.ball (x₁ + x₂) (r₁ + r₂) :=
begin
rintros x ⟨y₁, y₂, hy₁, hy₂, rfl⟩,
rw [mem_ball, add_sub_add_comm],
exact (map_add_le_add p _ _).trans_lt (add_lt_add hy₁ hy₂),
end
lemma closed_ball_add_closed_ball_subset (p : seminorm 𝕜 E) (r₁ r₂ : ℝ) (x₁ x₂ : E) :
p.closed_ball (x₁ : E) r₁ + p.closed_ball (x₂ : E) r₂ ⊆ p.closed_ball (x₁ + x₂) (r₁ + r₂) :=
begin
rintros x ⟨y₁, y₂, hy₁, hy₂, rfl⟩,
rw [mem_closed_ball, add_sub_add_comm],
exact (map_add_le_add p _ _).trans (add_le_add hy₁ hy₂)
end
lemma sub_mem_ball (p : seminorm 𝕜 E) (x₁ x₂ y : E) (r : ℝ) :
x₁ - x₂ ∈ p.ball y r ↔ x₁ ∈ p.ball (x₂ + y) r :=
by simp_rw [mem_ball, sub_sub]
/-- The image of a ball under addition with a singleton is another ball. -/
lemma vadd_ball (p : seminorm 𝕜 E) :
x +ᵥ p.ball y r = p.ball (x +ᵥ y) r :=
begin
letI := add_group_seminorm.to_seminormed_add_comm_group p.to_add_group_seminorm,
exact metric.vadd_ball x y r,
end
/-- The image of a closed ball under addition with a singleton is another closed ball. -/
lemma vadd_closed_ball (p : seminorm 𝕜 E) :
x +ᵥ p.closed_ball y r = p.closed_ball (x +ᵥ y) r :=
begin
letI := add_group_seminorm.to_seminormed_add_comm_group p.to_add_group_seminorm,
exact metric.vadd_closed_ball x y r,
end
end has_smul
section module
variables [module 𝕜 E]
variables [semi_normed_ring 𝕜₂] [add_comm_group E₂] [module 𝕜₂ E₂]
variables {σ₁₂ : 𝕜 →+* 𝕜₂} [ring_hom_isometric σ₁₂]
lemma ball_comp (p : seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) (x : E) (r : ℝ) :
(p.comp f).ball x r = f ⁻¹' (p.ball (f x) r) :=
begin
ext,
simp_rw [ball, mem_preimage, comp_apply, set.mem_set_of_eq, map_sub],
end
lemma closed_ball_comp (p : seminorm 𝕜₂ E₂) (f : E →ₛₗ[σ₁₂] E₂) (x : E) (r : ℝ) :
(p.comp f).closed_ball x r = f ⁻¹' (p.closed_ball (f x) r) :=
begin
ext,
simp_rw [closed_ball, mem_preimage, comp_apply, set.mem_set_of_eq, map_sub],
end
variables (p : seminorm 𝕜 E)
lemma preimage_metric_ball {r : ℝ} :
p ⁻¹' (metric.ball 0 r) = {x | p x < r} :=
begin
ext x,
simp only [mem_set_of, mem_preimage, mem_ball_zero_iff, real.norm_of_nonneg (map_nonneg p _)]
end
lemma preimage_metric_closed_ball {r : ℝ} :
p ⁻¹' (metric.closed_ball 0 r) = {x | p x ≤ r} :=
begin
ext x,
simp only [mem_set_of, mem_preimage, mem_closed_ball_zero_iff,
real.norm_of_nonneg (map_nonneg p _)]
end
lemma ball_zero_eq_preimage_ball {r : ℝ} :
p.ball 0 r = p ⁻¹' (metric.ball 0 r) :=
by rw [ball_zero_eq, preimage_metric_ball]
lemma closed_ball_zero_eq_preimage_closed_ball {r : ℝ} :
p.closed_ball 0 r = p ⁻¹' (metric.closed_ball 0 r) :=
by rw [closed_ball_zero_eq, preimage_metric_closed_ball]
@[simp] lemma ball_bot {r : ℝ} (x : E) (hr : 0 < r) :
ball (⊥ : seminorm 𝕜 E) x r = set.univ :=
ball_zero' x hr
@[simp] lemma closed_ball_bot {r : ℝ} (x : E) (hr : 0 < r) :
closed_ball (⊥ : seminorm 𝕜 E) x r = set.univ :=
closed_ball_zero' x hr
/-- Seminorm-balls at the origin are balanced. -/
lemma balanced_ball_zero (r : ℝ) : balanced 𝕜 (ball p 0 r) :=
begin
rintro a ha x ⟨y, hy, hx⟩,
rw [mem_ball_zero, ←hx, map_smul_eq_mul],
calc _ ≤ p y : mul_le_of_le_one_left (map_nonneg p _) ha
... < r : by rwa mem_ball_zero at hy,
end
/-- Closed seminorm-balls at the origin are balanced. -/
lemma balanced_closed_ball_zero (r : ℝ) : balanced 𝕜 (closed_ball p 0 r) :=
begin
rintro a ha x ⟨y, hy, hx⟩,
rw [mem_closed_ball_zero, ←hx, map_smul_eq_mul],
calc _ ≤ p y : mul_le_of_le_one_left (map_nonneg p _) ha
... ≤ r : by rwa mem_closed_ball_zero at hy
end
lemma ball_finset_sup_eq_Inter (p : ι → seminorm 𝕜 E) (s : finset ι) (x : E) {r : ℝ} (hr : 0 < r) :
ball (s.sup p) x r = ⋂ (i ∈ s), ball (p i) x r :=
begin
lift r to nnreal using hr.le,
simp_rw [ball, Inter_set_of, finset_sup_apply, nnreal.coe_lt_coe,
finset.sup_lt_iff (show ⊥ < r, from hr), ←nnreal.coe_lt_coe, subtype.coe_mk],
end
lemma closed_ball_finset_sup_eq_Inter (p : ι → seminorm 𝕜 E) (s : finset ι) (x : E) {r : ℝ}
(hr : 0 ≤ r) : closed_ball (s.sup p) x r = ⋂ (i ∈ s), closed_ball (p i) x r :=
begin
lift r to nnreal using hr,
simp_rw [closed_ball, Inter_set_of, finset_sup_apply, nnreal.coe_le_coe,
finset.sup_le_iff, ←nnreal.coe_le_coe, subtype.coe_mk]
end
lemma ball_finset_sup (p : ι → seminorm 𝕜 E) (s : finset ι) (x : E) {r : ℝ} (hr : 0 < r) :
ball (s.sup p) x r = s.inf (λ i, ball (p i) x r) :=
begin
rw finset.inf_eq_infi,
exact ball_finset_sup_eq_Inter _ _ _ hr,
end
lemma closed_ball_finset_sup (p : ι → seminorm 𝕜 E) (s : finset ι) (x : E) {r : ℝ} (hr : 0 ≤ r) :
closed_ball (s.sup p) x r = s.inf (λ i, closed_ball (p i) x r) :=
begin
rw finset.inf_eq_infi,
exact closed_ball_finset_sup_eq_Inter _ _ _ hr,
end
lemma ball_smul_ball (p : seminorm 𝕜 E) (r₁ r₂ : ℝ) :
metric.ball (0 : 𝕜) r₁ • p.ball 0 r₂ ⊆ p.ball 0 (r₁ * r₂) :=
begin
rw set.subset_def,
intros x hx,
rw set.mem_smul at hx,
rcases hx with ⟨a, y, ha, hy, hx⟩,
rw [←hx, mem_ball_zero, map_smul_eq_mul],
exact mul_lt_mul'' (mem_ball_zero_iff.mp ha) (p.mem_ball_zero.mp hy) (norm_nonneg a)
(map_nonneg p y),
end
lemma closed_ball_smul_closed_ball (p : seminorm 𝕜 E) (r₁ r₂ : ℝ) :
metric.closed_ball (0 : 𝕜) r₁ • p.closed_ball 0 r₂ ⊆ p.closed_ball 0 (r₁ * r₂) :=
begin
rw set.subset_def,
intros x hx,
rw set.mem_smul at hx,
rcases hx with ⟨a, y, ha, hy, hx⟩,
rw [←hx, mem_closed_ball_zero, map_smul_eq_mul],
rw mem_closed_ball_zero_iff at ha,
exact mul_le_mul ha (p.mem_closed_ball_zero.mp hy) (map_nonneg _ y) ((norm_nonneg a).trans ha)
end
@[simp] lemma ball_eq_emptyset (p : seminorm 𝕜 E) {x : E} {r : ℝ} (hr : r ≤ 0) : p.ball x r = ∅ :=
begin
ext,
rw [seminorm.mem_ball, set.mem_empty_iff_false, iff_false, not_lt],
exact hr.trans (map_nonneg p _),
end
@[simp] lemma closed_ball_eq_emptyset (p : seminorm 𝕜 E) {x : E} {r : ℝ} (hr : r < 0) :
p.closed_ball x r = ∅ :=
begin
ext,
rw [seminorm.mem_closed_ball, set.mem_empty_iff_false, iff_false, not_le],
exact hr.trans_le (map_nonneg _ _),
end
end module
end add_comm_group
end semi_normed_ring
section normed_field
variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] (p : seminorm 𝕜 E) {A B : set E}
{a : 𝕜} {r : ℝ} {x : E}
lemma ball_norm_mul_subset {p : seminorm 𝕜 E} {k : 𝕜} {r : ℝ} :
p.ball 0 (‖k‖ * r) ⊆ k • p.ball 0 r :=
begin
rcases eq_or_ne k 0 with (rfl | hk),
{ rw [norm_zero, zero_mul, ball_eq_emptyset _ le_rfl],
exact empty_subset _ },
{ intro x,
rw [set.mem_smul_set, seminorm.mem_ball_zero],
refine λ hx, ⟨k⁻¹ • x, _, _⟩,
{ rwa [seminorm.mem_ball_zero, map_smul_eq_mul, norm_inv,
←(mul_lt_mul_left $ norm_pos_iff.mpr hk), ←mul_assoc, ←(div_eq_mul_inv ‖k‖ ‖k‖),
div_self (ne_of_gt $ norm_pos_iff.mpr hk), one_mul] },
rw [←smul_assoc, smul_eq_mul, ←div_eq_mul_inv, div_self hk, one_smul] }
end
lemma smul_ball_zero {p : seminorm 𝕜 E} {k : 𝕜} {r : ℝ} (hk : k ≠ 0) :
k • p.ball 0 r = p.ball 0 (‖k‖ * r) :=
begin
ext,
rw [mem_smul_set_iff_inv_smul_mem₀ hk, p.mem_ball_zero, p.mem_ball_zero, map_smul_eq_mul,
norm_inv, ← div_eq_inv_mul, div_lt_iff (norm_pos_iff.2 hk), mul_comm]
end
lemma smul_closed_ball_subset {p : seminorm 𝕜 E} {k : 𝕜} {r : ℝ} :
k • p.closed_ball 0 r ⊆ p.closed_ball 0 (‖k‖ * r) :=
begin
rintros x ⟨y, hy, h⟩,
rw [seminorm.mem_closed_ball_zero, ←h, map_smul_eq_mul],
rw seminorm.mem_closed_ball_zero at hy,
exact mul_le_mul_of_nonneg_left hy (norm_nonneg _)
end
lemma smul_closed_ball_zero {p : seminorm 𝕜 E} {k : 𝕜} {r : ℝ} (hk : 0 < ‖k‖) :
k • p.closed_ball 0 r = p.closed_ball 0 (‖k‖ * r) :=
begin
refine subset_antisymm smul_closed_ball_subset _,
intro x,
rw [set.mem_smul_set, seminorm.mem_closed_ball_zero],
refine λ hx, ⟨k⁻¹ • x, _, _⟩,
{ rwa [seminorm.mem_closed_ball_zero, map_smul_eq_mul, norm_inv, ←(mul_le_mul_left hk),
←mul_assoc, ←(div_eq_mul_inv ‖k‖ ‖k‖), div_self (ne_of_gt hk), one_mul] },
rw [←smul_assoc, smul_eq_mul, ←div_eq_mul_inv, div_self (norm_pos_iff.mp hk), one_smul],
end
lemma ball_zero_absorbs_ball_zero (p : seminorm 𝕜 E) {r₁ r₂ : ℝ} (hr₁ : 0 < r₁) :
absorbs 𝕜 (p.ball 0 r₁) (p.ball 0 r₂) :=
begin
rcases exists_pos_lt_mul hr₁ r₂ with ⟨r, hr₀, hr⟩,
refine ⟨r, hr₀, λ a ha x hx, _⟩,
rw [smul_ball_zero (norm_pos_iff.1 $ hr₀.trans_le ha), p.mem_ball_zero],
rw p.mem_ball_zero at hx,
exact hx.trans (hr.trans_le $ mul_le_mul_of_nonneg_right ha hr₁.le)
end
/-- Seminorm-balls at the origin are absorbent. -/
protected lemma absorbent_ball_zero (hr : 0 < r) : absorbent 𝕜 (ball p (0 : E) r) :=
absorbent_iff_forall_absorbs_singleton.2 $ λ x, (p.ball_zero_absorbs_ball_zero hr).mono_right $
singleton_subset_iff.2 $ p.mem_ball_zero.2 $ lt_add_one _
/-- Closed seminorm-balls at the origin are absorbent. -/
protected lemma absorbent_closed_ball_zero (hr : 0 < r) : absorbent 𝕜 (closed_ball p (0 : E) r) :=
(p.absorbent_ball_zero hr).subset (p.ball_subset_closed_ball _ _)
/-- Seminorm-balls containing the origin are absorbent. -/
protected lemma absorbent_ball (hpr : p x < r) : absorbent 𝕜 (ball p x r) :=
begin
refine (p.absorbent_ball_zero $ sub_pos.2 hpr).subset (λ y hy, _),
rw p.mem_ball_zero at hy,
exact p.mem_ball.2 ((map_sub_le_add p _ _).trans_lt $ add_lt_of_lt_sub_right hy),
end
/-- Seminorm-balls containing the origin are absorbent. -/
protected lemma absorbent_closed_ball (hpr : p x < r) : absorbent 𝕜 (closed_ball p x r) :=
begin
refine (p.absorbent_closed_ball_zero $ sub_pos.2 hpr).subset (λ y hy, _),
rw p.mem_closed_ball_zero at hy,
exact p.mem_closed_ball.2 ((map_sub_le_add p _ _).trans $ add_le_of_le_sub_right hy),
end
lemma symmetric_ball_zero (r : ℝ) (hx : x ∈ ball p 0 r) : -x ∈ ball p 0 r :=
balanced_ball_zero p r (-1) (by rw [norm_neg, norm_one]) ⟨x, hx, by rw [neg_smul, one_smul]⟩
@[simp]
lemma neg_ball (p : seminorm 𝕜 E) (r : ℝ) (x : E) :
-ball p x r = ball p (-x) r :=
by { ext, rw [mem_neg, mem_ball, mem_ball, ←neg_add', sub_neg_eq_add, map_neg_eq_map] }
@[simp]
lemma smul_ball_preimage (p : seminorm 𝕜 E) (y : E) (r : ℝ) (a : 𝕜) (ha : a ≠ 0) :
((•) a) ⁻¹' p.ball y r = p.ball (a⁻¹ • y) (r / ‖a‖) :=
set.ext $ λ _, by rw [mem_preimage, mem_ball, mem_ball,
lt_div_iff (norm_pos_iff.mpr ha), mul_comm, ←map_smul_eq_mul p, smul_sub, smul_inv_smul₀ ha]
end normed_field
section convex
variables [normed_field 𝕜] [add_comm_group E] [normed_space ℝ 𝕜] [module 𝕜 E]
section has_smul
variables [has_smul ℝ E] [is_scalar_tower ℝ 𝕜 E] (p : seminorm 𝕜 E)
/-- A seminorm is convex. Also see `convex_on_norm`. -/
protected lemma convex_on : convex_on ℝ univ p :=
begin
refine ⟨convex_univ, λ x _ y _ a b ha hb hab, _⟩,
calc p (a • x + b • y) ≤ p (a • x) + p (b • y) : map_add_le_add p _ _
... = ‖a • (1 : 𝕜)‖ * p x + ‖b • (1 : 𝕜)‖ * p y
: by rw [←map_smul_eq_mul p, ←map_smul_eq_mul p, smul_one_smul, smul_one_smul]
... = a * p x + b * p y
: by rw [norm_smul, norm_smul, norm_one, mul_one, mul_one, real.norm_of_nonneg ha,
real.norm_of_nonneg hb],
end
end has_smul
section module
variables [module ℝ E] [is_scalar_tower ℝ 𝕜 E] (p : seminorm 𝕜 E) (x : E) (r : ℝ)
/-- Seminorm-balls are convex. -/
lemma convex_ball : convex ℝ (ball p x r) :=
begin
convert (p.convex_on.translate_left (-x)).convex_lt r,
ext y,
rw [preimage_univ, sep_univ, p.mem_ball, sub_eq_add_neg],
refl,
end
/-- Closed seminorm-balls are convex. -/
lemma convex_closed_ball : convex ℝ (closed_ball p x r) :=
begin
rw closed_ball_eq_bInter_ball,
exact convex_Inter₂ (λ _ _, convex_ball _ _ _)
end
end module
end convex
section restrict_scalars
variables (𝕜) {𝕜' : Type*} [normed_field 𝕜] [semi_normed_ring 𝕜'] [normed_algebra 𝕜 𝕜']
[norm_one_class 𝕜'] [add_comm_group E] [module 𝕜' E] [has_smul 𝕜 E] [is_scalar_tower 𝕜 𝕜' E]
/-- Reinterpret a seminorm over a field `𝕜'` as a seminorm over a smaller field `𝕜`. This will
typically be used with `is_R_or_C 𝕜'` and `𝕜 = ℝ`. -/
protected def restrict_scalars (p : seminorm 𝕜' E) :
seminorm 𝕜 E :=
{ smul' := λ a x, by rw [← smul_one_smul 𝕜' a x, p.smul', norm_smul, norm_one, mul_one],
..p }
@[simp] lemma coe_restrict_scalars (p : seminorm 𝕜' E) :
(p.restrict_scalars 𝕜 : E → ℝ) = p :=
rfl
@[simp] lemma restrict_scalars_ball (p : seminorm 𝕜' E) :
(p.restrict_scalars 𝕜).ball = p.ball :=
rfl
@[simp] lemma restrict_scalars_closed_ball (p : seminorm 𝕜' E) :
(p.restrict_scalars 𝕜).closed_ball = p.closed_ball :=
rfl
end restrict_scalars
/-! ### Continuity criterions for seminorms -/
section continuity
variables [nontrivially_normed_field 𝕜] [semi_normed_ring 𝕝] [add_comm_group E] [module 𝕜 E]
variables [module 𝕝 E]
lemma continuous_at_zero' [topological_space E] [has_continuous_const_smul 𝕜 E] {p : seminorm 𝕜 E}
{r : ℝ} (hr : 0 < r) (hp : p.closed_ball 0 r ∈ (𝓝 0 : filter E)) :
continuous_at p 0 :=
begin
refine metric.nhds_basis_closed_ball.tendsto_right_iff.mpr _,
intros ε hε,
rw map_zero,
suffices : p.closed_ball 0 ε ∈ (𝓝 0 : filter E),
{ rwa seminorm.closed_ball_zero_eq_preimage_closed_ball at this },
rcases exists_norm_lt 𝕜 (div_pos hε hr) with ⟨k, hk0, hkε⟩,
have hk0' := norm_pos_iff.mp hk0,
have := (set_smul_mem_nhds_zero_iff hk0').mpr hp,
refine filter.mem_of_superset this (smul_set_subset_iff.mpr $ λ x hx, _),
rw [mem_closed_ball_zero, map_smul_eq_mul, ← div_mul_cancel ε hr.ne.symm],
exact mul_le_mul hkε.le (p.mem_closed_ball_zero.mp hx) (map_nonneg _ _) (div_nonneg hε.le hr.le)
end
lemma continuous_at_zero [topological_space E] [has_continuous_const_smul 𝕜 E] {p : seminorm 𝕜 E}
{r : ℝ} (hr : 0 < r) (hp : p.ball 0 r ∈ (𝓝 0 : filter E)) :
continuous_at p 0 :=
continuous_at_zero' hr (filter.mem_of_superset hp $ p.ball_subset_closed_ball _ _)
protected lemma uniform_continuous_of_continuous_at_zero [uniform_space E] [uniform_add_group E]
{p : seminorm 𝕝 E} (hp : continuous_at p 0) :
uniform_continuous p :=
begin
have hp : filter.tendsto p (𝓝 0) (𝓝 0) := map_zero p ▸ hp,
rw [uniform_continuous, uniformity_eq_comap_nhds_zero_swapped,
metric.uniformity_eq_comap_nhds_zero, filter.tendsto_comap_iff],
exact tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds
(hp.comp filter.tendsto_comap) (λ xy, dist_nonneg) (λ xy, p.norm_sub_map_le_sub _ _)
end
protected lemma continuous_of_continuous_at_zero [topological_space E] [topological_add_group E]
{p : seminorm 𝕝 E} (hp : continuous_at p 0) :
continuous p :=
begin
letI := topological_add_group.to_uniform_space E,
haveI : uniform_add_group E := topological_add_comm_group_is_uniform,
exact (seminorm.uniform_continuous_of_continuous_at_zero hp).continuous
end
protected lemma uniform_continuous [uniform_space E] [uniform_add_group E]
[has_continuous_const_smul 𝕜 E] {p : seminorm 𝕜 E} {r : ℝ} (hr : 0 < r)
(hp : p.ball 0 r ∈ (𝓝 0 : filter E)) : uniform_continuous p :=
seminorm.uniform_continuous_of_continuous_at_zero (continuous_at_zero hr hp)
protected lemma uniform_continuous' [uniform_space E] [uniform_add_group E]
[has_continuous_const_smul 𝕜 E] {p : seminorm 𝕜 E} {r : ℝ} (hr : 0 < r)
(hp : p.closed_ball 0 r ∈ (𝓝 0 : filter E)) : uniform_continuous p :=
seminorm.uniform_continuous_of_continuous_at_zero (continuous_at_zero' hr hp)
protected lemma continuous [topological_space E] [topological_add_group E]
[has_continuous_const_smul 𝕜 E] {p : seminorm 𝕜 E} {r : ℝ} (hr : 0 < r)
(hp : p.ball 0 r ∈ (𝓝 0 : filter E)) : continuous p :=
seminorm.continuous_of_continuous_at_zero (continuous_at_zero hr hp)
protected lemma continuous' [topological_space E] [topological_add_group E]
[has_continuous_const_smul 𝕜 E] {p : seminorm 𝕜 E} {r : ℝ} (hr : 0 < r)
(hp : p.closed_ball 0 r ∈ (𝓝 0 : filter E)) : continuous p :=
seminorm.continuous_of_continuous_at_zero (continuous_at_zero' hr hp)
lemma continuous_of_le [topological_space E] [topological_add_group E]
[has_continuous_const_smul 𝕜 E] {p q : seminorm 𝕜 E} (hq : continuous q) (hpq : p ≤ q) :
continuous p :=
begin
refine seminorm.continuous one_pos (filter.mem_of_superset
(is_open.mem_nhds _ $ q.mem_ball_self zero_lt_one) (ball_antitone hpq)),
rw ball_zero_eq,
exact is_open_lt hq continuous_const
end
end continuity
end seminorm
/-! ### The norm as a seminorm -/
section norm_seminorm
variables (𝕜) (E) [normed_field 𝕜] [seminormed_add_comm_group E] [normed_space 𝕜 E] {r : ℝ}
/-- The norm of a seminormed group as a seminorm. -/
def norm_seminorm : seminorm 𝕜 E :=
{ smul' := norm_smul,
..(norm_add_group_seminorm E)}
@[simp] lemma coe_norm_seminorm : ⇑(norm_seminorm 𝕜 E) = norm := rfl
@[simp] lemma ball_norm_seminorm : (norm_seminorm 𝕜 E).ball = metric.ball :=
by { ext x r y, simp only [seminorm.mem_ball, metric.mem_ball, coe_norm_seminorm, dist_eq_norm] }
variables {𝕜 E} {x : E}
/-- Balls at the origin are absorbent. -/
lemma absorbent_ball_zero (hr : 0 < r) : absorbent 𝕜 (metric.ball (0 : E) r) :=
by { rw ←ball_norm_seminorm 𝕜, exact (norm_seminorm _ _).absorbent_ball_zero hr }
/-- Balls containing the origin are absorbent. -/
lemma absorbent_ball (hx : ‖x‖ < r) : absorbent 𝕜 (metric.ball x r) :=
by { rw ←ball_norm_seminorm 𝕜, exact (norm_seminorm _ _).absorbent_ball hx }
/-- Balls at the origin are balanced. -/
lemma balanced_ball_zero : balanced 𝕜 (metric.ball (0 : E) r) :=
by { rw ←ball_norm_seminorm 𝕜, exact (norm_seminorm _ _).balanced_ball_zero r }
end norm_seminorm
-- Guard against import creep.
assert_not_exists balanced_core
|
0fc77e93614dfb14c9948b53e36fcd010f94661a | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/topology/metric_space/closeds.lean | 32c7f872b40d2348654ea2b6aa052575a073f559 | [
"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 | 24,077 | 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
The metric and emetric space structure on the types of closed subsets and nonempty compact
subsets of a metric or emetric space
The Hausdorff distance induces an emetric space structure on the type of closed subsets
of an emetric space, called `closeds`. Its completeness, resp. compactness, resp.
second-countability, follow from the corresponding properties of the original space.
In a metric space, the type of nonempty compact subsets (called `nonempty_compacts`) also
inherits a metric space structure from the Hausdorff distance, as the Hausdorff edistance is
always finite in this context.
-/
import topology.metric_space.hausdorff_distance topology.opens
noncomputable theory
local attribute [instance, priority 0] classical.prop_decidable
universe u
open classical lattice set function topological_space filter
namespace emetric
section
variables {α : Type u} [emetric_space α] {s : set α}
/-- In emetric spaces, the Hausdorff edistance defines an emetric space structure
on the type of closed subsets -/
instance closeds.emetric_space : emetric_space (closeds α) :=
{ edist := λs t, Hausdorff_edist s.val t.val,
edist_self := λs, Hausdorff_edist_self,
edist_comm := λs t, Hausdorff_edist_comm,
edist_triangle := λs t u, Hausdorff_edist_triangle,
eq_of_edist_eq_zero :=
λs t h, subtype.eq ((Hausdorff_edist_zero_iff_eq_of_closed s.property t.property).1 h) }
/-- The edistance to a closed set depends continuously on the point and the set -/
lemma continuous_inf_edist_Hausdorff_edist :
continuous (λp : α × (closeds α), inf_edist p.1 (p.2).val) :=
begin
refine continuous_of_le_add_edist 2 (by simp) _,
rintros ⟨x, s⟩ ⟨y, t⟩,
calc inf_edist x (s.val) ≤ inf_edist x (t.val) + Hausdorff_edist (t.val) (s.val) :
inf_edist_le_inf_edist_add_Hausdorff_edist
... ≤ (inf_edist y (t.val) + edist x y) + Hausdorff_edist (t.val) (s.val) :
add_le_add_right' inf_edist_le_inf_edist_add_edist
... = inf_edist y (t.val) + (edist x y + Hausdorff_edist (s.val) (t.val)) :
by simp [add_comm, Hausdorff_edist_comm]
... ≤ inf_edist y (t.val) + (edist (x, s) (y, t) + edist (x, s) (y, t)) :
add_le_add_left' (add_le_add' (by simp [edist, le_refl]) (by simp [edist, le_refl]))
... = inf_edist y (t.val) + 2 * edist (x, s) (y, t) :
by rw [← mul_two, mul_comm]
end
/-- Subsets of a given closed subset form a closed set -/
lemma is_closed_subsets_of_is_closed (hs : is_closed s) :
is_closed {t : closeds α | t.val ⊆ s} :=
begin
refine is_closed_of_closure_subset (λt ht x hx, _),
-- t : closeds α, ht : t ∈ closure {t : closeds α | t.val ⊆ s},
-- x : α, hx : x ∈ t.val
-- goal : x ∈ s
have : x ∈ closure s,
{ refine mem_closure_iff'.2 (λε εpos, _),
rcases mem_closure_iff'.1 ht ε εpos with ⟨u, hu, Dtu⟩,
-- u : closeds α, hu : u ∈ {t : closeds α | t.val ⊆ s}, hu' : edist t u < ε
rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dtu with ⟨y, hy, Dxy⟩,
-- y : α, hy : y ∈ u.val, Dxy : edist x y < ε
exact ⟨y, hu hy, Dxy⟩ },
rwa closure_eq_of_is_closed hs at this,
end
/-- By definition, the edistance on `closeds α` is given by the Hausdorff edistance -/
lemma closeds.edist_eq {s t : closeds α} : edist s t = Hausdorff_edist s.val t.val := rfl
/-- In a complete space, the type of closed subsets is complete for the
Hausdorff edistance. -/
instance closeds.complete_space [complete_space α] : complete_space (closeds α) :=
begin
/- We will show that, if a sequence of sets `s n` satisfies
`edist (s n) (s (n+1)) < 2^{-n}`, then it converges. This is enough to guarantee
completeness, by a standard completeness criterion.
We use the shorthand `B n = 2^{-n}` in ennreal. -/
let B : ℕ → ennreal := ennreal.half_pow,
/- Consider a sequence of closed sets `s n` with `edist (s n) (s (n+1)) < B n`.
We will show that it converges. The limit set is t0 = ⋂n, closure (⋃m≥n, s m).
We will have to show that a point in `s n` is close to a point in `t0`, and a point
in `t0` is close to a point in `s n`. The completeness then follows from a
standard criterion. -/
refine complete_of_convergent_controlled_sequences _ ennreal.half_pow_pos (λs hs, _),
let t0 := ⋂n, closure (⋃m≥n, (s m).val),
have : is_closed t0 := is_closed_Inter (λ_, is_closed_closure),
let t : closeds α := ⟨t0, this⟩,
use t,
have I1 : ∀n:ℕ, ∀x ∈ (s n).val, ∃y ∈ t0, edist x y ≤ 2 * B n,
{ /- This is the main difficulty of the proof. Starting from `x ∈ s n`, we want
to find a point in `t0` which is close to `x`. Define inductively a sequence of
points `z m` with `z n = x` and `z m ∈ s m` and `edist (z m) (z (m+1)) ≤ B m`. This is
possible since the Hausdorff distance between `s m` and `s (m+1)` is at most `B m`.
This sequence is a Cauchy sequence, therefore converging as the space is complete, to
a limit which satisfies the required properties. -/
assume n x hx,
haveI : nonempty α := ⟨x⟩,
let z : ℕ → α := λk, nat.rec_on k x (λl z, if l < n then x else
epsilon (λy, y ∈ (s (l+1)).val ∧ edist z y < B l)),
have z_le_n : ∀l≤n, z l = x,
{ assume l hl,
cases l with m,
{ show z 0 = x, from rfl },
{ have : z (nat.succ m) = ite (m < n) x (epsilon (λ (y : α), y ∈ (s (m + 1)).val ∧ edist (z m) y < B m))
:= rfl,
rw this,
simp [nat.lt_of_succ_le hl] }},
have : z n = x := z_le_n n (le_refl n),
-- check by induction that the sequence `z m` satisfies the required properties
have I : ∀m≥n, z m ∈ (s m).val → (z (m+1) ∈ (s (m+1)).val ∧ edist (z m) (z (m+1)) < B m),
{ assume m hm hz,
have E : ∃y, y ∈ (s (m+1)).val ∧ edist (z m) y < B m,
{ have : Hausdorff_edist (s m).val (s (m+1)).val < B m := hs m m (m+1) (le_refl _) (by simp),
rcases exists_edist_lt_of_Hausdorff_edist_lt hz this with ⟨y, hy, Dy⟩,
exact ⟨y, ⟨hy, Dy⟩⟩ },
have : z (m+1) = ite (m < n) x (epsilon (λ (y : α), y ∈ (s (m + 1)).val ∧ edist (z m) y < B m)) := rfl,
rw this,
simp only [not_lt_of_le hm, if_false],
exact epsilon_spec E },
have z_in_s : ∀m≥n, z m ∈ (s m).val :=
nat.le_induction (by rwa ‹z n = x›) (λm hm zm, (I m hm zm).1),
-- for all `m`, the distance between `z m` and `z (m+1)` is controlled by `B m`:
-- for `m ≥ n`, this follows from the construction, while for `m < n` all points are `x`.
have Im_succm : ∀m, edist (z m) (z (m+1)) ≤ B m,
{ assume m,
by_cases hm : n≤m,
{ exact le_of_lt (I m hm (z_in_s m hm)).2 },
{ rw not_le at hm,
have Im : z m = x := z_le_n m (le_of_lt hm),
have Im' : z (m+1) = x := z_le_n (m+1) (nat.succ_le_of_lt hm),
simp [Im, Im', ennreal.half_pow_pos] }},
/- From the distance control between `z m` and `z (m+1)`, we deduce a distance control
between `z k` and `z l` by summing the geometric series. -/
have Iz : ∀k l N, N ≤ k → N ≤ l → edist (z k) (z l) ≤ 2 * B N :=
λk l N hk hl, ennreal.edist_le_two_mul_half_pow hk hl Im_succm,
-- it follows from the previous bound that `z` is a Cauchy sequence
have : cauchy_seq z := ennreal.cauchy_seq_of_edist_le_half_pow Im_succm,
-- therefore, it converges
rcases cauchy_seq_tendsto_of_complete this with ⟨y, y_lim⟩,
-- the limit point `y` will be the desired point, in `t0` and close to our initial point `x`.
-- First, we check it belongs to `t0`.
have : y ∈ t0 := mem_Inter.2 (λk, mem_closure_of_tendsto (by simp) y_lim
begin
simp only [exists_prop, set.mem_Union, filter.mem_at_top_sets, set.mem_preimage, set.preimage_Union],
exact ⟨max n k, λm hm, ⟨m, ⟨le_trans (le_max_right _ _) hm, z_in_s m (le_trans (le_max_left _ _) hm)⟩⟩⟩,
end),
-- Then, we check that `y` is close to `x = z n`. This follows from the fact that `y`
-- is the limit of `z k`, and the distance between `z n` and `z k` has already been estimated.
have : edist x y ≤ 2 * B n,
{ refine le_of_tendsto (by simp) (tendsto_edist tendsto_const_nhds y_lim) _,
simp [‹z n = x›.symm],
exact ⟨n, λm hm, Iz n m n (le_refl n) hm⟩ },
-- Conclusion of this argument: the point `y` satisfies the required properties.
exact ⟨y, ‹y ∈ t0›, ‹edist x y ≤ 2 * B n›⟩ },
have I2 : ∀n:ℕ, ∀x ∈ t0, ∃y ∈ (s n).val, edist x y ≤ 2 * B n,
{ /- For the (much easier) reverse inequality, we start from a point `x ∈ t0` and we want
to find a point `y ∈ s n` which is close to `x`.
`x` belongs to `t0`, the intersection of the closures. In particular, it is well
approximated by a point `z` in `⋃m≥n, s m`, say in `s m`. Since `s m` and
`s n` are close, this point is itself well approximated by a point `y` in `s n`,
as required. -/
assume n x xt0,
have : x ∈ closure (⋃m≥n, (s m).val), by apply mem_Inter.1 xt0 n,
rcases mem_closure_iff'.1 this (B n) (ennreal.half_pow_pos n) with ⟨z, hz, Dxz⟩,
-- z : α, Dxz : edist x z < B n,
simp only [exists_prop, set.mem_Union] at hz,
rcases hz with ⟨m, ⟨m_ge_n, hm⟩⟩,
-- m : ℕ, m_ge_n : m ≥ n, hm : z ∈ (s m).val
have : Hausdorff_edist (s m).val (s n).val < B n := hs n m n m_ge_n (le_refl n),
rcases exists_edist_lt_of_Hausdorff_edist_lt hm this with ⟨y, hy, Dzy⟩,
-- y : α, hy : y ∈ (s n).val, Dzy : edist z y < B n
exact ⟨y, hy, calc
edist x y ≤ edist x z + edist z y : edist_triangle _ _ _
... ≤ B n + B n : add_le_add' (le_of_lt Dxz) (le_of_lt Dzy)
... = 2 * B n : (two_mul _).symm ⟩ },
-- Deduce from the above inequalities that the distance between `s n` and `t0` is at most `2 B n`.
have main : ∀n:ℕ, edist (s n) t ≤ 2 * B n := λn, Hausdorff_edist_le_of_mem_edist (I1 n) (I2 n),
-- from this, the convergence of `s n` to `t0` follows.
refine (tendsto_at_top _).2 (λε εpos, _),
have : tendsto (λn, 2 * ennreal.half_pow n) at_top (nhds (2 * 0)) :=
ennreal.tendsto_mul_right ennreal.half_pow_tendsto_zero (by simp),
rw mul_zero at this,
have Z := (tendsto_orderable.1 this).2 ε εpos,
simp only [filter.mem_at_top_sets, set.mem_set_of_eq] at Z,
rcases Z with ⟨N, hN⟩, -- ∀ (b : ℕ), b ≥ N → ε > 2 * B b
exact ⟨N, λn hn, lt_of_le_of_lt (main n) (hN n hn)⟩
end
/-- In a compact space, the type of closed subsets is compact. -/
instance closeds.compact_space [compact_space α] : compact_space (closeds α) :=
⟨begin
/- by completeness, it suffices to show that it is totally bounded,
i.e., for all ε>0, there is a finite set which is ε-dense.
start from a set `s` which is ε-dense in α. Then the subsets of `s`
are finitely many, and ε-dense for the Hausdorff distance. -/
refine compact_of_totally_bounded_is_closed (emetric.totally_bounded_iff.2 (λε εpos, _)) is_closed_univ,
rcases dense εpos with ⟨δ, δpos, δlt⟩,
rcases emetric.totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 (@compact_univ α _ _ _)).1 δ δpos
with ⟨s, fs, hs⟩,
-- s : set α, fs : finite s, hs : univ ⊆ ⋃ (y : α) (H : y ∈ s), eball y δ
-- we first show that any set is well approximated by a subset of `s`.
have main : ∀ u : set α, ∃v ⊆ s, Hausdorff_edist u v ≤ δ,
{ assume u,
let v := {x : α | x ∈ s ∧ ∃y∈u, edist x y < δ},
existsi [v, ((λx hx, hx.1) : v ⊆ s)],
refine Hausdorff_edist_le_of_mem_edist _ _,
{ assume x hx,
have : x ∈ ⋃y ∈ s, ball y δ := hs (by simp),
rcases mem_bUnion_iff.1 this with ⟨y, ⟨ys, dy⟩⟩,
have : edist y x < δ := by simp at dy; rwa [edist_comm] at dy,
exact ⟨y, ⟨ys, ⟨x, hx, this⟩⟩, le_of_lt dy⟩ },
{ rintros x ⟨hx1, ⟨y, yu, hy⟩⟩,
exact ⟨y, yu, le_of_lt hy⟩ }},
-- introduce the set F of all subsets of `s` (seen as members of `closeds α`).
let F := {f : closeds α | f.val ⊆ s},
use F,
split,
-- `F` is finite
{ apply @finite_of_finite_image _ _ F (λf, f.val),
{ apply set.inj_on_of_injective, simp [subtype.val_injective] },
{ refine finite_subset (finite_subsets_of_finite fs) (λb, _),
simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib],
assume x hx hx',
rwa hx' at hx }},
-- `F` is ε-dense
{ assume u _,
rcases main u.val with ⟨t0, t0s, Dut0⟩,
have : finite t0 := finite_subset fs t0s,
have : is_closed t0 := closed_of_compact _ (compact_of_finite this),
let t : closeds α := ⟨t0, this⟩,
have : t ∈ F := t0s,
have : edist u t < ε := lt_of_le_of_lt Dut0 δlt,
apply mem_bUnion_iff.2,
exact ⟨t, ‹t ∈ F›, this⟩ }
end⟩
/-- In an emetric space, the type of non-empty compact subsets is an emetric space,
where the edistance is the Hausdorff edistance -/
instance nonempty_compacts.emetric_space : emetric_space (nonempty_compacts α) :=
{ edist := λs t, Hausdorff_edist s.val t.val,
edist_self := λs, Hausdorff_edist_self,
edist_comm := λs t, Hausdorff_edist_comm,
edist_triangle := λs t u, Hausdorff_edist_triangle,
eq_of_edist_eq_zero := λs t h, subtype.eq $ begin
have : closure (s.val) = closure (t.val) := Hausdorff_edist_zero_iff_closure_eq_closure.1 h,
rwa [closure_eq_iff_is_closed.2 (closed_of_compact _ s.property.2),
closure_eq_iff_is_closed.2 (closed_of_compact _ t.property.2)] at this,
end }
/-- `nonempty_compacts.to_closeds` is a uniform embedding (as it is an isometry) -/
lemma nonempty_compacts.to_closeds.uniform_embedding :
uniform_embedding (@nonempty_compacts.to_closeds α _ _) :=
isometry.uniform_embedding $ λx y, rfl
/-- The range of `nonempty_compacts.to_closeds` is closed in a complete space -/
lemma nonempty_compacts.is_closed_in_closeds [complete_space α] :
is_closed (nonempty_compacts.to_closeds '' (univ : set (nonempty_compacts α))) :=
begin
have : nonempty_compacts.to_closeds '' univ = {s : closeds α | s.val ≠ ∅ ∧ compact s.val},
{ ext,
simp only [set.image_univ, set.mem_range, ne.def, set.mem_set_of_eq],
split,
{ rintros ⟨y, hy⟩,
have : x.val = y.val := by rcases hy; simp,
rw this,
exact y.property },
{ rintros ⟨hx1, hx2⟩,
existsi (⟨x.val, ⟨hx1, hx2⟩⟩ : nonempty_compacts α),
apply subtype.eq,
refl }},
rw this,
refine is_closed_of_closure_subset (λs hs, _),
split,
{ -- take a set set t which is nonempty and at distance at most 1 of s
rcases mem_closure_iff'.1 hs 1 ennreal.zero_lt_one with ⟨t, ht, Dst⟩,
rw edist_comm at Dst,
-- this set t contains a point x
rcases ne_empty_iff_exists_mem.1 ht.1 with ⟨x, hx⟩,
-- by the Hausdorff distance control, this point x is at distance at most 1
-- of a point y in s
rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨y, hy, _⟩,
-- this shows that s is not empty
exact ne_empty_of_mem hy },
{ refine compact_iff_totally_bounded_complete.2 ⟨_, is_complete_of_is_closed s.property⟩,
refine totally_bounded_iff.2 (λε εpos, _),
-- we have to show that s is covered by finitely many eballs of radius ε
-- pick a nonempty compact set t at distance at most ε/2 of s
rcases mem_closure_iff'.1 hs (ε/2) (ennreal.half_pos εpos) with ⟨t, ht, Dst⟩,
-- cover this space with finitely many balls of radius ε/2
rcases totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 ht.2).1 (ε/2) (ennreal.half_pos εpos)
with ⟨u, fu, ut⟩,
refine ⟨u, ⟨fu, λx hx, _⟩⟩,
-- u : set α, fu : finite u, ut : t.val ⊆ ⋃ (y : α) (H : y ∈ u), eball y (ε / 2)
-- then s is covered by the union of the balls centered at u of radius ε
rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨z, hz, Dxz⟩,
rcases mem_bUnion_iff.1 (ut hz) with ⟨y, hy, Dzy⟩,
have : edist x y < ε := calc
edist x y ≤ edist x z + edist z y : edist_triangle _ _ _
... < ε/2 + ε/2 : ennreal.add_lt_add Dxz Dzy
... = ε : ennreal.add_halves _,
exact mem_bUnion hy this },
end
/-- In a complete space, the type of nonempty compact subsets is complete. This follows
from the same statement for closed subsets -/
instance nonempty_compacts.complete_space [complete_space α] : complete_space (nonempty_compacts α) :=
begin
apply complete_space_of_is_complete_univ,
apply (is_complete_image_iff nonempty_compacts.to_closeds.uniform_embedding).1,
apply is_complete_of_is_closed,
exact nonempty_compacts.is_closed_in_closeds
end
/-- In a compact space, the type of nonempty compact subsets is compact. This follows from
the same statement for closed subsets -/
instance nonempty_compacts.compact_space [compact_space α] : compact_space (nonempty_compacts α) :=
⟨begin
rw compact_iff_compact_image_of_embedding nonempty_compacts.to_closeds.uniform_embedding.embedding,
exact compact_of_closed nonempty_compacts.is_closed_in_closeds
end⟩
/-- In a second countable space, the type of nonempty compact subsets is second countable -/
instance nonempty_compacts.second_countable_topology [second_countable_topology α] :
second_countable_topology (nonempty_compacts α) :=
begin
haveI : separable_space (nonempty_compacts α) :=
begin
/- To obtain a countable dense subset of `nonempty_compacts α`, start from
a countable dense subset `s` of α, and then consider all its finite nonempty subsets.
This set is countable and made of nonempty compact sets. It turns out to be dense:
by total boundedness, any compact set `t` can be covered by finitely many small balls, and
approximations in `s` of the centers of these balls give the required finite approximation
of `t`. -/
have : separable_space α := by apply_instance,
rcases this.exists_countable_closure_eq_univ with ⟨s, cs, s_dense⟩,
let v0 := {t : set α | finite t ∧ t ⊆ s},
let v : set (nonempty_compacts α) := {t : nonempty_compacts α | t.val ∈ v0},
refine ⟨⟨v, ⟨_, _⟩⟩⟩,
{ have : countable (subtype.val '' v),
{ refine countable_subset (λx hx, _) (countable_set_of_finite_subset cs),
rcases (mem_image _ _ _).1 hx with ⟨y, ⟨hy, yx⟩⟩,
rw ← yx,
exact hy },
apply countable_of_injective_of_countable_image _ this,
apply inj_on_of_inj_on_of_subset (injective_iff_inj_on_univ.1 subtype.val_injective)
(subset_univ _) },
{ refine subset.antisymm (subset_univ _) (λt ht, mem_closure_iff'.2 (λε εpos, _)),
-- t is a compact nonempty set, that we have to approximate uniformly by a a set in `v`.
rcases dense εpos with ⟨δ, δpos, δlt⟩,
-- construct a map F associating to a point in α an approximating point in s, up to δ/2.
have Exy : ∀x, ∃y, y ∈ s ∧ edist x y < δ/2,
{ assume x,
have : x ∈ closure s := by rw s_dense; exact mem_univ _,
rcases mem_closure_iff'.1 this (δ/2) (ennreal.half_pos δpos) with ⟨y, ys, hy⟩,
exact ⟨y, ⟨ys, hy⟩⟩ },
let F := λx, some (Exy x),
have Fspec : ∀x, F x ∈ s ∧ edist x (F x) < δ/2 := λx, some_spec (Exy x),
-- cover `t` with finitely many balls. Their centers form a set `a`
have : totally_bounded t.val := (compact_iff_totally_bounded_complete.1 t.property.2).1,
rcases totally_bounded_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨a, af, ta⟩,
-- a : set α, af : finite a, ta : t.val ⊆ ⋃ (y : α) (H : y ∈ a), eball y (δ / 2)
-- replace each center by a nearby approximation in `s`, giving a new set `b`
let b := F '' a,
have : finite b := finite_image _ af,
have tb : ∀x ∈ t.val, ∃y ∈ b, edist x y < δ,
{ assume x hx,
rcases mem_bUnion_iff.1 (ta hx) with ⟨z, za, Dxz⟩,
existsi [F z, mem_image_of_mem _ za],
calc edist x (F z) ≤ edist x z + edist z (F z) : edist_triangle _ _ _
... < δ/2 + δ/2 : ennreal.add_lt_add Dxz (Fspec z).2
... = δ : ennreal.add_halves _ },
-- keep only the points in `b` that are close to point in `t`, yielding a new set `c`
let c := {y ∈ b | ∃x∈t.val, edist x y < δ},
have : finite c := finite_subset ‹finite b› (λx hx, hx.1),
-- points in `t` are well approximated by points in `c`
have tc : ∀x ∈ t.val, ∃y ∈ c, edist x y ≤ δ,
{ assume x hx,
rcases tb x hx with ⟨y, yv, Dxy⟩,
have : y ∈ c := by simp [c, -mem_image]; exact ⟨yv, ⟨x, hx, Dxy⟩⟩,
exact ⟨y, this, le_of_lt Dxy⟩ },
-- points in `c` are well approximated by points in `t`
have ct : ∀y ∈ c, ∃x ∈ t.val, edist y x ≤ δ,
{ rintros y ⟨hy1, ⟨x, xt, Dyx⟩⟩,
have : edist y x ≤ δ := calc
edist y x = edist x y : edist_comm _ _
... ≤ δ : le_of_lt Dyx,
exact ⟨x, xt, this⟩ },
-- it follows that their Hausdorff distance is small
have : Hausdorff_edist t.val c ≤ δ :=
Hausdorff_edist_le_of_mem_edist tc ct,
have Dtc : Hausdorff_edist t.val c < ε := lt_of_le_of_lt this δlt,
-- the set `c` is not empty, as it is well approximated by a nonempty set
have : c ≠ ∅,
{ by_contradiction h,
simp only [not_not, ne.def] at h,
rw [h, Hausdorff_edist_empty t.property.1] at Dtc,
exact not_top_lt Dtc },
-- let `d` be the version of `c` in the type `nonempty_compacts α`
let d : nonempty_compacts α := ⟨c, ⟨‹c ≠ ∅›, compact_of_finite ‹finite c›⟩⟩,
have : c ⊆ s,
{ assume x hx,
rcases (mem_image _ _ _).1 hx.1 with ⟨y, ⟨ya, yx⟩⟩,
rw ← yx,
exact (Fspec y).1 },
have : d ∈ v := ⟨‹finite c›, this⟩,
-- we have proved that `d` is a good approximation of `t` as requested
exact ⟨d, ‹d ∈ v›, Dtc⟩ },
end,
apply second_countable_of_separable,
end
end --section
end emetric --namespace
namespace metric
section
variables {α : Type u} [metric_space α]
/-- `nonempty_compacts α` inherits a metric space structure, as the Hausdorff
edistance between two such sets is finite. -/
instance nonempty_compacts.metric_space : metric_space (nonempty_compacts α) :=
emetric_space.to_metric_space $ λx y, Hausdorff_edist_ne_top_of_ne_empty_of_bounded x.2.1 y.2.1
(bounded_of_compact x.2.2) (bounded_of_compact y.2.2)
/-- The distance on `nonempty_compacts α` is the Hausdorff distance, by construction -/
lemma nonempty_compacts.dist_eq {x y : nonempty_compacts α} :
dist x y = Hausdorff_dist x.val y.val := rfl
lemma uniform_continuous_inf_dist_Hausdorff_dist :
uniform_continuous (λp : α × (nonempty_compacts α), inf_dist p.1 (p.2).val) :=
begin
refine uniform_continuous_of_le_add 2 _,
rintros ⟨x, s⟩ ⟨y, t⟩,
calc inf_dist x (s.val) ≤ inf_dist x (t.val) + Hausdorff_dist (t.val) (s.val) :
inf_dist_le_inf_dist_add_Hausdorff_dist (edist_ne_top t s)
... ≤ (inf_dist y (t.val) + dist x y) + Hausdorff_dist (t.val) (s.val) :
add_le_add_right inf_dist_le_inf_dist_add_dist _
... = inf_dist y (t.val) + (dist x y + Hausdorff_dist (s.val) (t.val)) :
by simp [add_comm, Hausdorff_dist_comm]
... ≤ inf_dist y (t.val) + (dist (x, s) (y, t) + dist (x, s) (y, t)) :
add_le_add_left (add_le_add (by simp [dist, le_refl]) (by simp [dist, nonempty_compacts.dist_eq, le_refl])) _
... = inf_dist y (t.val) + 2 * dist (x, s) (y, t) :
by rw [← mul_two, mul_comm]
end
end --section
end metric --namespace
|
ef00f83a450ec7074874cc59ba59a32713927039 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/sec.lean | 599b3f0371bccd761c226d9c3cf89c0b5988d309 | [
"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 | 123 | lean | --
open prod
section
variable A : Type
variable a : A
variable A : Type
variable b : A
definition foo := a
end
|
f150499b3fa076c6baab7025051a4a8564a2e733 | aa5a655c05e5359a70646b7154e7cac59f0b4132 | /stage0/src/Lean/Elab/Do.lean | 88cfb131421b469bee294edf8445ff465ac0fadb | [
"Apache-2.0"
] | permissive | lambdaxymox/lean4 | ae943c960a42247e06eff25c35338268d07454cb | 278d47c77270664ef29715faab467feac8a0f446 | refs/heads/master | 1,677,891,867,340 | 1,612,500,005,000 | 1,612,500,005,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 66,130 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Term
import Lean.Elab.Binders
import Lean.Elab.Match
import Lean.Elab.Quotation.Util
import Lean.Parser.Do
namespace Lean.Elab.Term
open Lean.Parser.Term
open Meta
private def getDoSeqElems (doSeq : Syntax) : List Syntax :=
if doSeq.getKind == `Lean.Parser.Term.doSeqBracketed then
doSeq[1].getArgs.toList.map fun arg => arg[0]
else if doSeq.getKind == `Lean.Parser.Term.doSeqIndent then
doSeq[0].getArgs.toList.map fun arg => arg[0]
else
[]
private def getDoSeq (doStx : Syntax) : Syntax :=
doStx[1]
@[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ =>
throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression"
/-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/
private def liftMethodDelimiter (k : SyntaxNodeKind) : Bool :=
k == `Lean.Parser.Term.do ||
k == `Lean.Parser.Term.doSeqIndent ||
k == `Lean.Parser.Term.doSeqBracketed ||
k == `Lean.Parser.Term.termReturn ||
k == `Lean.Parser.Term.termUnless ||
k == `Lean.Parser.Term.termTry ||
k == `Lean.Parser.Term.termFor
private partial def hasLiftMethod : Syntax → Bool
| Syntax.node k args =>
if liftMethodDelimiter k then false
-- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a
-- bit slower
else if k == `Lean.Parser.Term.liftMethod then true
else args.any hasLiftMethod
| _ => false
structure ExtractMonadResult where
m : Expr
α : Expr
hasBindInst : Expr
expectedType : Expr
private def mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do
let u ← getDecLevel type
let id := Lean.mkConst `Id [u]
let idBindVal := Lean.mkConst `Id.hasBind [u]
pure { m := id, hasBindInst := idBindVal, α := type, expectedType := mkApp id type }
private def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do
match expectedType? with
| none => throwError "invalid 'do' notation, expected type is not available"
| some expectedType =>
let type ← withReducible $ whnf expectedType
if type.getAppFn.isMVar then throwError "invalid 'do' notation, expected type is not available"
match type with
| Expr.app m α _ =>
try
let bindInstType ← mkAppM `Bind #[m]
let bindInstVal ← synthesizeInst bindInstType
pure { m := m, hasBindInst := bindInstVal, α := α, expectedType := expectedType }
catch _ =>
mkIdBindFor type
| _ => mkIdBindFor type
namespace Do
/- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/
structure Alt (σ : Type) where
ref : Syntax
vars : Array Name
patterns : Syntax
rhs : σ
deriving Inhabited
/-
Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`).
We convert `Code` into a `Syntax` term representing the:
- `do`-block, or
- the visitor argument for the `forIn` combinator.
We say the following constructors are terminals:
- `break`: for interrupting a `for x in s`
- `continue`: for interrupting the current iteration of a `for x in s`
- `return e`: for returning `e` as the result for the whole `do` computation block
- `action a`: for executing action `a` as a terminal
- `ite`: if-then-else
- `match`: pattern matching
- `jmp` a goto to a join-point
We say the terminals `break`, `continue`, `action`, and `return` are "exit points"
Note that, `return e` is not equivalent to `action (pure e)`. Here is an example:
```
def f (x : Nat) : IO Unit := do
if x == 0 then
return ()
IO.println "hello"
```
Executing `#eval f 0` will not print "hello". Now, consider
```
def g (x : Nat) : IO Unit := do
if x == 0 then
pure ()
IO.println "hello"
```
The `if` statement is essentially a noop, and "hello" is printed when we execute `g 0`.
- `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`).
The field `stx` is the actual `doElem`,
`vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block.
`vars` is an array since we have declarations such as `let (a, b) := s`.
- `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`).
- `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow.
- `seq a k` executes action `a`, ignores its result, and then executes `k`.
We also store the do-elements `dbgTrace!` and `assert!` as actions in a `seq`.
A code block `C` is well-formed if
- For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and
`ps.size == as.size` -/
inductive Code where
| decl (xs : Array Name) (doElem : Syntax) (k : Code)
| reassign (xs : Array Name) (doElem : Syntax) (k : Code)
/- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/
| joinpoint (name : Name) (params : Array (Name × Bool)) (body : Code) (k : Code)
| seq (action : Syntax) (k : Code)
| action (action : Syntax)
| «break» (ref : Syntax)
| «continue» (ref : Syntax)
| «return» (ref : Syntax) (val : Syntax)
/- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/
| ite (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code)
| «match» (ref : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt Code))
| jmp (ref : Syntax) (jpName : Name) (args : Array Syntax)
deriving Inhabited
/- A code block, and the collection of variables updated by it. -/
structure CodeBlock where
code : Code
uvars : NameSet := {} -- set of variables updated by `code`
private def nameSetToArray (s : NameSet) : Array Name :=
s.fold (fun (xs : Array Name) x => xs.push x) #[]
private def varsToMessageData (vars : Array Name) : MessageData :=
MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) " "
partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData :=
let us := MessageData.ofList $ (nameSetToArray codeBlock.uvars).toList.map MessageData.ofName
let rec loop : Code → MessageData
| Code.decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}"
| Code.reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}"
| Code.joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}"
| Code.seq e k => m!"{e}\n{loop k}"
| Code.action e => e
| Code.ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}"
| Code.jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}"
| Code.«break» _ => m!"break {us}"
| Code.«continue» _ => m!"continue {us}"
| Code.«return» _ v => m!"return {v} {us}"
| Code.«match» _ ds t alts =>
m!"match {ds} with"
++ alts.foldl (init := m!"") fun acc alt => acc ++ m!"\n| {alt.patterns} => {loop alt.rhs}"
loop codeBlock.code
/- Return true if the give code contains an exit point that satisfies `p` -/
@[inline] partial def hasExitPointPred (c : Code) (p : Code → Bool) : Bool :=
let rec @[specialize] loop : Code → Bool
| Code.decl _ _ k => loop k
| Code.reassign _ _ k => loop k
| Code.joinpoint _ _ b k => loop b || loop k
| Code.seq _ k => loop k
| Code.ite _ _ _ _ t e => loop t || loop e
| Code.«match» _ _ _ alts => alts.any (loop ·.rhs)
| Code.jmp _ _ _ => false
| c => p c
loop c
def hasExitPoint (c : Code) : Bool :=
hasExitPointPred c fun c => true
def hasReturn (c : Code) : Bool :=
hasExitPointPred c fun
| Code.«return» _ _ => true
| _ => false
def hasTerminalAction (c : Code) : Bool :=
hasExitPointPred c fun
| Code.«action» _ => true
| _ => false
def hasBreakContinue (c : Code) : Bool :=
hasExitPointPred c fun
| Code.«break» _ => true
| Code.«continue» _ => true
| _ => false
def hasBreakContinueReturn (c : Code) : Bool :=
hasExitPointPred c fun
| Code.«break» _ => true
| Code.«continue» _ => true
| Code.«return» _ _ => true
| _ => false
def mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax → m Code) : m Code := withRef e <| withFreshMacroScope do
let y ← `(y)
let yName := y.getId
let doElem ← `(doElem| let y ← $e:term)
-- Add elaboration hint for producing sane error message
let y ← `(ensureExpectedType! "type mismatch, result value" $y)
let k ← mkCont y
pure $ Code.decl #[yName] doElem k
/- Convert `action _ e` instructions in `c` into `let y ← e; jmp _ jp (xs y)`. -/
partial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Name) : MacroM Code :=
let rec loop : Code → MacroM Code
| Code.decl xs stx k => do Code.decl xs stx (← loop k)
| Code.reassign xs stx k => do Code.reassign xs stx (← loop k)
| Code.joinpoint n ps b k => do Code.joinpoint n ps (← loop b) (← loop k)
| Code.seq e k => do Code.seq e (← loop k)
| Code.ite ref x? h c t e => do Code.ite ref x? h c (← loop t) (← loop e)
| Code.«match» ref ds t alts => do Code.«match» ref ds t (← alts.mapM fun alt => do pure { alt with rhs := (← loop alt.rhs) })
| Code.action e => mkAuxDeclFor e fun y =>
let ref := e
-- We jump to `jp` with xs **and** y
let jmpArgs := xs.map $ mkIdentFrom ref
let jmpArgs := jmpArgs.push y
pure $ Code.jmp ref jp jmpArgs
| c => pure c
loop code
structure JPDecl where
name : Name
params : Array (Name × Bool)
body : Code
def attachJP (jpDecl : JPDecl) (k : Code) : Code :=
Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k
def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code :=
jpDecls.foldr attachJP k
def mkFreshJP (ps : Array (Name × Bool)) (body : Code) : TermElabM JPDecl := do
let ps ←
if ps.isEmpty then
let y ← mkFreshUserName `y
pure #[(y, false)]
else
pure ps
-- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by
-- the "do" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp`
-- We will remove this hack when we re-implement the compiler frontend in Lean.
let name ← mkFreshUserName `_do_jp
pure { name := name, params := ps, body := body }
def mkFreshJP' (xs : Array Name) (body : Code) : TermElabM JPDecl :=
mkFreshJP (xs.map fun x => (x, true)) body
def addFreshJP (ps : Array (Name × Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do
let jp ← mkFreshJP ps body
modify fun (jps : Array JPDecl) => jps.push jp
pure jp.name
def insertVars (rs : NameSet) (xs : Array Name) : NameSet :=
xs.foldl (·.insert ·) rs
def eraseVars (rs : NameSet) (xs : Array Name) : NameSet :=
xs.foldl (·.erase ·) rs
def eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet :=
match x? with
| none => rs
| some x => rs.insert x
/- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/
def mkSimpleJmp (ref : Syntax) (rs : NameSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do
let xs := nameSetToArray rs
let jp ← addFreshJP (xs.map fun x => (x, true)) c
if xs.isEmpty then
let unit ← `(Unit.unit)
return Code.jmp ref jp #[unit]
else
return Code.jmp ref jp (xs.map $ mkIdentFrom ref)
/- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value.
The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh`
is a fresh variable created by this method. -/
def mkJmp (ref : Syntax) (rs : NameSet) (val : Syntax) (mkJPBody : Syntax → MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do
let xs := nameSetToArray rs
let args := xs.map $ mkIdentFrom ref
let args := args.push val
let yFresh ← mkFreshUserName `y
let ps := xs.map fun x => (x, true)
let ps := ps.push (yFresh, false)
let jpBody ← liftMacroM $ mkJPBody (mkIdentFrom ref yFresh)
let jp ← addFreshJP ps jpBody
pure $ Code.jmp ref jp args
/- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/
partial def pullExitPointsAux : NameSet → Code → StateRefT (Array JPDecl) TermElabM Code
| rs, Code.decl xs stx k => do Code.decl xs stx (← pullExitPointsAux (eraseVars rs xs) k)
| rs, Code.reassign xs stx k => do Code.reassign xs stx (← pullExitPointsAux (insertVars rs xs) k)
| rs, Code.joinpoint j ps b k => do Code.joinpoint j ps (← pullExitPointsAux rs b) (← pullExitPointsAux rs k)
| rs, Code.seq e k => do Code.seq e (← pullExitPointsAux rs k)
| rs, Code.ite ref x? o c t e => do Code.ite ref x? o c (← pullExitPointsAux (eraseOptVar rs x?) t) (← pullExitPointsAux (eraseOptVar rs x?) e)
| rs, Code.«match» ref ds t alts => do
Code.«match» ref ds t (← alts.mapM fun alt => do pure { alt with rhs := (← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) })
| rs, c@(Code.jmp _ _ _) => pure c
| rs, Code.«break» ref => mkSimpleJmp ref rs (Code.«break» ref)
| rs, Code.«continue» ref => mkSimpleJmp ref rs (Code.«continue» ref)
| rs, Code.«return» ref val => mkJmp ref rs val (fun y => pure $ Code.«return» ref y)
| rs, Code.action e =>
-- We use `mkAuxDeclFor` because `e` is not pure.
mkAuxDeclFor e fun y =>
let ref := e
mkJmp ref rs y (fun yFresh => do pure $ Code.action (← `(Pure.pure $yFresh)))
/-
Auxiliary operation for adding new variables to the collection of updated variables in a CodeBlock.
When a new variable is not already in the collection, but is shadowed by some declaration in `c`,
we create auxiliary join points to make sure we preserve the semantics of the code block.
Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it
with the reassignment `x := x + 1`. We first use `pullExitPoints` to create
```
let jp (x!1) := return x!1;
print x;
let x := 10;
jmp jp x
```
and then we add the reassignment
```
x := x + 1
let jp (x!1) := return x!1;
print x;
let x := 10;
jmp jp x
```
Note that we created a fresh variable `x!1` to avoid accidental name capture.
As another example, consider
```
print x;
let x := 10
y := y + 1;
return x;
```
We transform it into
```
let jp (y x!1) := return x!1;
print x;
let x := 10
y := y + 1;
jmp jp y x
```
and then we add the reassignment as in the previous example.
We need to include `y` in the jump, because each exit point is implicitly returning the set of
update variables.
We implement the method as follows. Let `us` be `c.uvars`, then
1- for each `return _ y` in `c`, we create a join point
`let j (us y!1) := return y!1`
and replace the `return _ y` with `jmp us y`
2- for each `break`, we create a join point
`let j (us) := break`
and replace the `break` with `jmp us`.
3- Same as 2 for `continue`.
-/
def pullExitPoints (c : Code) : TermElabM Code := do
if hasExitPoint c then
let (c, jpDecls) ← (pullExitPointsAux {} c).run #[]
pure $ attachJPs jpDecls c
else
pure c
partial def extendUpdatedVarsAux (c : Code) (ws : NameSet) : TermElabM Code :=
let rec update : Code → TermElabM Code
| Code.joinpoint j ps b k => do Code.joinpoint j ps (← update b) (← update k)
| Code.seq e k => do Code.seq e (← update k)
| c@(Code.«match» ref ds t alts) => do
if alts.any fun alt => alt.vars.any fun x => ws.contains x then
-- If a pattern variable is shadowing a variable in ws, we `pullExitPoints`
pullExitPoints c
else
Code.«match» ref ds t (← alts.mapM fun alt => do pure { alt with rhs := (← update alt.rhs) })
| Code.ite ref none o c t e => do Code.ite ref none o c (← update t) (← update e)
| c@(Code.ite ref (some h) o cond t e) => do
if ws.contains h then
-- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints`
pullExitPoints c
else
Code.ite ref (some h) o cond (← update t) (← update e)
| Code.reassign xs stx k => do Code.reassign xs stx (← update k)
| c@(Code.decl xs stx k) => do
if xs.any fun x => ws.contains x then
-- One the declared variables is shadowing a variable in `ws`
pullExitPoints c
else
Code.decl xs stx (← update k)
| c => pure c
update c
/-
Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`.
We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`.
See discussion at `pullExitPoints`.
-/
partial def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock := do
if ws.any fun x => !c.uvars.contains x then
-- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed)
pure { code := (← extendUpdatedVarsAux c.code ws), uvars := ws }
else
pure { c with uvars := ws }
private def union (s₁ s₂ : NameSet) : NameSet :=
s₁.fold (·.insert ·) s₂
/-
Given two code blocks `c₁` and `c₂`, make sure they have the same set of updated variables.
Let `ws` the union of the updated variables in `c₁‵ and ‵c₂`.
We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars c₂ ws`
-/
def homogenize (c₁ c₂ : CodeBlock) : TermElabM (CodeBlock × CodeBlock) := do
let ws := union c₁.uvars c₂.uvars
let c₁ ← extendUpdatedVars c₁ ws
let c₂ ← extendUpdatedVars c₂ ws
pure (c₁, c₂)
/-
Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`.
We remove `x` from the collection of updated varibles.
Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables
declared by it. It is an array because we have let-declarations that declare multiple variables.
Example: `let (x, y) := t`
-/
def mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock := {
code := Code.decl xs stx c.code,
uvars := eraseVars c.uvars xs
}
/-
Extending code blocks with reassignments: `x : t := v` and `x : t ← v`.
Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables
declared by it. It is an array because we have let-declarations that declare multiple variables.
Example: `(x, y) ← t`
-/
def mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do
let us := c.uvars
let ws := insertVars us xs
-- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`.
-- See discussion at `pullExitPoints`
let code ← if xs.any fun x => !us.contains x then extendUpdatedVarsAux c.code ws else pure c.code
pure { code := Code.reassign xs stx code, uvars := ws }
def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock :=
{ c with code := Code.seq action c.code }
def mkTerminalAction (action : Syntax) : CodeBlock :=
{ code := Code.action action }
def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock :=
{ code := Code.«return» ref val }
def mkBreak (ref : Syntax) : CodeBlock :=
{ code := Code.«break» ref }
def mkContinue (ref : Syntax) : CodeBlock :=
{ code := Code.«continue» ref }
def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do
let x? := if optIdent.isNone then none else some optIdent[0].getId
let (thenBranch, elseBranch) ← homogenize thenBranch elseBranch
pure {
code := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code,
uvars := thenBranch.uvars,
}
private def mkUnit : MacroM Syntax :=
`((⟨⟩ : PUnit))
private def mkPureUnit : MacroM Syntax :=
`(pure PUnit.unit)
def mkPureUnitAction : MacroM CodeBlock := do
mkTerminalAction (← mkPureUnit)
def mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do
let thenBranch ← mkPureUnitAction
pure { c with code := Code.ite (← getRef) none mkNullNode cond thenBranch.code c.code }
def mkMatch (ref : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do
-- nary version of homogenize
let ws := alts.foldl (union · ·.rhs.uvars) {}
let alts ← alts.mapM fun alt => do
let rhs ← extendUpdatedVars alt.rhs ws
pure { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code }
pure { code := Code.«match» ref discrs optType alts, uvars := ws }
/- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`.
This method assumes `terminal` is a terminal -/
def concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Name) (k : CodeBlock) : TermElabM CodeBlock := do
unless hasTerminalAction terminal.code do
throwErrorAt kRef "'do' element is unreachable"
let (terminal, k) ← homogenize terminal k
let xs := nameSetToArray k.uvars
let y ← match y? with | some y => pure y | none => mkFreshUserName `y
let ps := xs.map fun x => (x, true)
let ps := ps.push (y, false)
let jpDecl ← mkFreshJP ps k.code
let jp := jpDecl.name
let terminal ← liftMacroM $ convertTerminalActionIntoJmp terminal.code jp xs
pure { code := attachJP jpDecl terminal, uvars := k.uvars }
def getLetIdDeclVar (letIdDecl : Syntax) : Name :=
letIdDecl[0].getId
def getPatternVarNames (pvars : Array PatternVar) : Array Name :=
pvars.filterMap fun
| PatternVar.localVar x => some x
| _ => none
-- support both regular and syntax match
def getPatternVarsEx (pattern : Syntax) : TermElabM (Array Name) :=
getPatternVarNames <$> getPatternVars pattern <|>
Array.map Syntax.getId <$> Quotation.getPatternVars pattern
def getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Name) :=
getPatternVarNames <$> getPatternsVars patterns <|>
Array.map Syntax.getId <$> Quotation.getPatternsVars patterns
def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do
let pattern := letPatDecl[0]
getPatternVarsEx pattern
def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name :=
letEqnsDecl[0].getId
def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do
let arg := letDecl[0]
if arg.getKind == `Lean.Parser.Term.letIdDecl then
pure #[getLetIdDeclVar arg]
else if arg.getKind == `Lean.Parser.Term.letPatDecl then
getLetPatDeclVars arg
else if arg.getKind == `Lean.Parser.Term.letEqnsDecl then
pure #[getLetEqnsDeclVar arg]
else
throwError "unexpected kind of let declaration"
def getDoLetVars (doLet : Syntax) : TermElabM (Array Name) :=
-- parser! "let " >> optional "mut " >> letDecl
getLetDeclVars doLet[2]
def getDoHaveVar (doHave : Syntax) : Name :=
/-
`parser! "have " >> Term.haveDecl`
where
```
haveDecl := optIdent >> termParser >> (haveAssign <|> fromTerm <|> byTactic)
optIdent := optional (try (ident >> " : "))
```
-/
let optIdent := doHave[1]
if optIdent.isNone then
`this
else
optIdent[0].getId
def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Name) := do
-- letRecDecls is an array of `(group (optional attributes >> letDecl))`
let letRecDecls := doLetRec[1].getSepArgs
let letDecls := letRecDecls.map fun p => p[2]
let mut allVars := #[]
for letDecl in letDecls do
let vars ← getLetDeclVars letDecl
allVars := allVars ++ vars
pure allVars
-- ident >> optType >> leftArrow >> termParser
def getDoIdDeclVar (doIdDecl : Syntax) : Name :=
doIdDecl[0].getId
-- termParser >> leftArrow >> termParser >> optional (" | " >> termParser)
def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Name) := do
let pattern := doPatDecl[0]
getPatternVarsEx pattern
-- parser! "let " >> optional "mut " >> (doIdDecl <|> doPatDecl)
def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Name) := do
let decl := doLetArrow[2]
if decl.getKind == `Lean.Parser.Term.doIdDecl then
pure #[getDoIdDeclVar decl]
else if decl.getKind == `Lean.Parser.Term.doPatDecl then
getDoPatDeclVars decl
else
throwError "unexpected kind of 'do' declaration"
def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do
let arg := doReassign[0]
if arg.getKind == `Lean.Parser.Term.letIdDecl then
pure #[getLetIdDeclVar arg]
else if arg.getKind == `Lean.Parser.Term.letPatDecl then
getLetPatDeclVars arg
else
throwError "unexpected kind of reassignment"
def mkDoSeq (doElems : Array Syntax) : Syntax :=
mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode $ doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]]
def mkSingletonDoSeq (doElem : Syntax) : Syntax :=
mkDoSeq #[doElem]
/-
If the given syntax is a `doIf`, return an equivalente `doIf` that has an `else` but no `else if`s or `if let`s. -/
private def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with
| `(doElem|if $p:doIfProp then $t else $e) => pure none
| `(doElem|if%$i $cond:doIfCond then $t $[else if%$is $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do
let mut e := e?.getD (← `(doSeq|pure PUnit.unit))
let mut eIsSeq := true
for (i, cond, t) in Array.zip (is.reverse.push i) (Array.zip (conds.reverse.push cond) (ts.reverse.push t)) do
e ← if eIsSeq then e else `(doSeq|$e:doElem)
e ← withRef cond <| match cond with
| `(doIfCond|let $pat := $d) => `(doElem| match%$i $d:term with | $pat:term => $t | _ => $e)
| `(doIfCond|let $pat ← $d) => `(doElem| match%$i ← $d with | $pat:term => $t | _ => $e)
| _ => `(doElem| if%$i $cond:doIfCond then $t else $e)
eIsSeq := false
return some e
| _ => pure none
structure DoIfView where
ref : Syntax
optIdent : Syntax
cond : Syntax
thenBranch : Syntax
elseBranch : Syntax
/- This method assumes `expandDoIf?` is not applicable. -/
private def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do
pure {
ref := doIf,
optIdent := doIf[1][0],
cond := doIf[1][1],
thenBranch := doIf[3],
elseBranch := doIf[5][1]
}
/-
We use `MProd` instead of `Prod` to group values when expanding the
`do` notation. `MProd` is a universe monomorphic product.
The motivation is to generate simpler universe constraints in code
that was not written by the user.
Note that we are not restricting the macro power since the
`Bind.bind` combinator already forces values computed by monadic
actions to be in the same universe.
-/
private def mkTuple (elems : Array Syntax) : MacroM Syntax := do
if elems.size == 0 then
mkUnit
else if elems.size == 1 then
pure elems[0]
else
(elems.extract 0 (elems.size - 1)).foldrM
(fun elem tuple => `(MProd.mk $elem $tuple))
(elems.back)
/- Return `some action` if `doElem` is a `doExpr <action>`-/
def isDoExpr? (doElem : Syntax) : Option Syntax :=
if doElem.getKind == `Lean.Parser.Term.doExpr then
some doElem[0]
else
none
/--
Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term
```
let a_1 := x.1
let x := x.2
let a_2 := x.1
let x := x.2
...
let a_n := x.1
let a_{n+1} := x.2
body
```
Special cases
- `uvars := #[]` => `body`
- `uvars := #[a]` => `let a := x; body`
We use this method when expanding the `for-in` notation.
-/
private def destructTuple (uvars : Array Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do
if uvars.size == 0 then
return body
else if uvars.size == 1 then
`(let $(← mkIdentFromRef uvars[0]):ident := $x; $body)
else
destruct uvars.toList x body
where
destruct (as : List Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do
match as with
| [a, b] => `(let $(← mkIdentFromRef a):ident := $x.1; let $(← mkIdentFromRef b):ident := $x.2; $body)
| a :: as => withFreshMacroScope do
let rest ← destruct as (← `(x)) body
`(let $(← mkIdentFromRef a):ident := $x.1; let x := $x.2; $rest)
| _ => unreachable!
/-
The procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term.
We use this method to convert
1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of
`CodeBlock` never contains `break` nor `continue`. Moreover, the collection
of updated variables is not packed into the result.
Thus, we have two kinds of exit points
- `Code.action e` which is converted into `e`
- `Code.return _ e` which is converted into `pure e`
We use `Kind.regular` for this case.
2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate
a `Syntax` term representing a function for the `xs.forIn` combinator.
a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term
has type `m (ForInStep (Option α × σ))`, where `a : α`, and the `σ` is the type
of the tuple of variables reassigned by `b`.
We use `Kind.forInWithReturn` for this case
b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated
`Syntax` term has type `m (ForInStep σ)`.
We use `Kind.forIn` for this case.
3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`).
The generated `Syntax` term for `c` must inform whether `c` "exited" using `Code.action`, `Code.return`,
`Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information.
For example, the auxiliary type `DoResultPBC α σ` is used for a code block that exits with `Code.action`,
**and** `Code.break`/`Code.continue`, `α` is the type of values produced by the exit `action`, and
`σ` is the type of the tuple of reassigned variables.
The type `DoResult α β σ` is usedf for code blocks that exit with
`Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `β` is the type of the returned values.
We don't use `DoResult α β σ` for all cases because:
a) The elaborator would not be able to infer all type parameters without extra annotations. For example,
if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `β`.
b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`),
but we don't want to consider "unreachable" cases.
We do not distinguish between cases that contain `break`, but not `continue`, and vice versa.
When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`,
and `b/c` for a code block that contains `Code.break _` or `Code.continue _`.
- `a`: `Kind.regular`, type `m (α × σ)`
- `r`: `Kind.regular`, type `m (α × σ)`
Note that the code that pattern matches on the result will behave differently in this case.
It produces `return a` for this case, and `pure a` for the previous one.
- `b/c`: `Kind.nestedBC`, type `m (DoResultBC σ)`
- `a` and `r`: `Kind.nestedPR`, type `m (DoResultPR α β σ)`
- `a` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)`
- `r` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)`
Again the code that pattern matches on the result will behave differently in this case and
the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for
this case, and `pure a` for the previous case.
- `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC α β σ)`
Here is the recipe for adding new combinators with nested `do`s.
Example: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m α → m α`
1- Convert `doSeq` into `codeBlock : CodeBlock`
2- Create term `term` using `mkNestedTerm code m uvars a r bc` where
`code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`,
`m` is a `Syntax` representing the Monad, and
`a` is true if `code` contains `Code.action _`,
`r` is true if `code` contains `Code.return _ _`,
`bc` is true if `code` contains `Code.break _` or `Code.continue _`.
Remark: for combinators such as `repeat` that take a single `doSeq`, all
arguments, but `m`, are extracted from `codeBlock`.
3- Create the term `repeat $term`
4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc`
-/
namespace ToTerm
inductive Kind where
| regular
| forIn
| forInWithReturn
| nestedBC
| nestedPR
| nestedSBC
| nestedPRBC
instance : Inhabited Kind := ⟨Kind.regular⟩
def Kind.isRegular : Kind → Bool
| Kind.regular => true
| _ => false
structure Context where
m : Syntax -- Syntax to reference the monad associated with the do notation.
uvars : Array Name
kind : Kind
abbrev M := ReaderT Context MacroM
def mkUVarTuple : M Syntax := do
let ctx ← read
let uvarIdents ← ctx.uvars.mapM mkIdentFromRef
mkTuple uvarIdents
def returnToTerm (val : Syntax) : M Syntax := do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| Kind.regular => if ctx.uvars.isEmpty then `(Pure.pure $val) else `(Pure.pure (MProd.mk $val $u))
| Kind.forIn => `(Pure.pure (ForInStep.done $u))
| Kind.forInWithReturn => `(Pure.pure (ForInStep.done (MProd.mk (some $val) $u)))
| Kind.nestedBC => unreachable!
| Kind.nestedPR => `(Pure.pure (DoResultPR.«return» $val $u))
| Kind.nestedSBC => `(Pure.pure (DoResultSBC.«pureReturn» $val $u))
| Kind.nestedPRBC => `(Pure.pure (DoResultPRBC.«return» $val $u))
def continueToTerm : M Syntax := do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| Kind.regular => unreachable!
| Kind.forIn => `(Pure.pure (ForInStep.yield $u))
| Kind.forInWithReturn => `(Pure.pure (ForInStep.yield (MProd.mk none $u)))
| Kind.nestedBC => `(Pure.pure (DoResultBC.«continue» $u))
| Kind.nestedPR => unreachable!
| Kind.nestedSBC => `(Pure.pure (DoResultSBC.«continue» $u))
| Kind.nestedPRBC => `(Pure.pure (DoResultPRBC.«continue» $u))
def breakToTerm : M Syntax := do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| Kind.regular => unreachable!
| Kind.forIn => `(Pure.pure (ForInStep.done $u))
| Kind.forInWithReturn => `(Pure.pure (ForInStep.done (MProd.mk none $u)))
| Kind.nestedBC => `(Pure.pure (DoResultBC.«break» $u))
| Kind.nestedPR => unreachable!
| Kind.nestedSBC => `(Pure.pure (DoResultSBC.«break» $u))
| Kind.nestedPRBC => `(Pure.pure (DoResultPRBC.«break» $u))
def actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| Kind.regular => if ctx.uvars.isEmpty then pure action else `(Bind.bind $action fun y => Pure.pure (MProd.mk y $u))
| Kind.forIn => `(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u))
| Kind.forInWithReturn => `(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u)))
| Kind.nestedBC => unreachable!
| Kind.nestedPR => `(Bind.bind $action fun y => (Pure.pure (DoResultPR.«pure» y $u)))
| Kind.nestedSBC => `(Bind.bind $action fun y => (Pure.pure (DoResultSBC.«pureReturn» y $u)))
| Kind.nestedPRBC => `(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.«pure» y $u)))
def seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do
if action.getKind == `Lean.Parser.Term.doDbgTrace then
let msg := action[1]
`(dbgTrace! $msg; $k)
else if action.getKind == `Lean.Parser.Term.doAssert then
let cond := action[1]
`(assert! $cond; $k)
else
let action ← withRef action `(($action : $((←read).m) PUnit))
`(Bind.bind $action (fun (_ : PUnit) => $k))
def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do
let kind := decl.getKind
if kind == `Lean.Parser.Term.doLet then
let letDecl := decl[2]
`(let $letDecl:letDecl; $k)
else if kind == `Lean.Parser.Term.doLetRec then
let letRecToken := decl[0]
let letRecDecls := decl[1]
pure $ mkNode `Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k]
else if kind == `Lean.Parser.Term.doLetArrow then
let arg := decl[2]
let ref := arg
if arg.getKind == `Lean.Parser.Term.doIdDecl then
let id := arg[0]
let type := expandOptType ref arg[1]
let doElem := arg[3]
-- `doElem` must be a `doExpr action`. See `doLetArrowToCode`
match isDoExpr? doElem with
| some action =>
let action ← withRef action `(($action : $((← read).m) $type))
`(Bind.bind $action (fun ($id:ident : $type) => $k))
| none => Macro.throwErrorAt decl "unexpected kind of 'do' declaration"
else
Macro.throwErrorAt decl "unexpected kind of 'do' declaration"
else if kind == `Lean.Parser.Term.doHave then
-- The `have` term is of the form `"have " >> haveDecl >> optSemicolon termParser`
let args := decl.getArgs
let args := args ++ #[mkNullNode /- optional ';' -/, k]
pure $ mkNode `Lean.Parser.Term.«have» args
else
Macro.throwErrorAt decl "unexpected kind of 'do' declaration"
def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do
let kind := reassign.getKind
if kind == `Lean.Parser.Term.doReassign then
-- doReassign := parser! (letIdDecl <|> letPatDecl)
let arg := reassign[0]
if arg.getKind == `Lean.Parser.Term.letIdDecl then
-- letIdDecl := parser! ident >> many (ppSpace >> bracketedBinder) >> optType >> " := " >> termParser
let x := arg[0]
let val := arg[4]
let newVal ← `(ensureTypeOf! $x $(quote "invalid reassignment, value") $val)
let arg := arg.setArg 4 newVal
let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg]
`(let $letDecl:letDecl; $k)
else
-- TODO: ensure the types did not change
let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg]
`(let $letDecl:letDecl; $k)
else
-- Note that `doReassignArrow` is expanded by `doReassignArrowToCode
Macro.throwErrorAt reassign "unexpected kind of 'do' reassignment"
def mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do
if optIdent.isNone then
`(ite $cond $thenBranch $elseBranch)
else
let h := optIdent[0]
`(dite $cond (fun $h => $thenBranch) (fun $h => $elseBranch))
def mkJoinPoint (j : Name) (ps : Array (Name × Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do
let pTypes ← ps.mapM fun ⟨id, useTypeOf⟩ => do if useTypeOf then `(typeOf! $(← mkIdentFromRef id)) else `(_)
let ps ← ps.mapM fun ⟨id, useTypeOf⟩ => mkIdentFromRef id
/-
We use `let*` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`.
By elaborating `$k` first, we "learn" more about `$body`'s type.
For example, consider the following example `do` expression
```
def f (x : Nat) : IO Unit := do
if x > 0 then
IO.println "x is not zero" -- Error is here
IO.mkRef true
```
it is expanded into
```
def f (x : Nat) : IO Unit := do
let jp (u : Unit) : IO _ :=
IO.mkRef true;
if x > 0 then
IO.println "not zero"
jp ()
else
jp ()
```
If we use the regular `let` instead of `let*`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit → IO (IO.Ref Bool)`.
Then, we get a typing error at `jp ()`. By using `let*`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit → IO Unit`.
Then, we get the expected type mismatch error at `IO.mkRef true`. -/
`(let* $(← mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((← read).m) _ := $body; $k)
def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax :=
Syntax.mkApp (mkIdentFrom ref j) args
partial def toTerm : Code → M Syntax
| Code.«return» ref val => withRef ref <| returnToTerm val
| Code.«continue» ref => withRef ref continueToTerm
| Code.«break» ref => withRef ref breakToTerm
| Code.action e => actionTerminalToTerm e
| Code.joinpoint j ps b k => do mkJoinPoint j ps (← toTerm b) (← toTerm k)
| Code.jmp ref j args => pure $ mkJmp ref j args
| Code.decl _ stx k => do declToTerm stx (← toTerm k)
| Code.reassign _ stx k => do reassignToTerm stx (← toTerm k)
| Code.seq stx k => do seqToTerm stx (← toTerm k)
| Code.ite ref _ o c t e => withRef ref <| do mkIte o c (← toTerm t) (← toTerm e)
| Code.«match» ref discrs optType alts => do
let mut termAlts := #[]
for alt in alts do
let rhs ← toTerm alt.rhs
let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref "|", alt.patterns, mkAtomFrom alt.ref "=>", rhs]
termAlts := termAlts.push termAlt
let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts]
pure $ mkNode `Lean.Parser.Term.«match» #[mkAtomFrom ref "match", discrs, optType, mkAtomFrom ref "with", termMatchAlts]
def run (code : Code) (m : Syntax) (uvars : Array Name := #[]) (kind := Kind.regular) : MacroM Syntax := do
let term ← toTerm code { m := m, kind := kind, uvars := uvars }
pure term
/- Given
- `a` is true if the code block has a `Code.action _` exit point
- `r` is true if the code block has a `Code.return _ _` exit point
- `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point
generate Kind. See comment at the beginning of the `ToTerm` namespace. -/
def mkNestedKind (a r bc : Bool) : Kind :=
match a, r, bc with
| true, false, false => Kind.regular
| false, true, false => Kind.regular
| false, false, true => Kind.nestedBC
| true, true, false => Kind.nestedPR
| true, false, true => Kind.nestedSBC
| false, true, true => Kind.nestedSBC
| true, true, true => Kind.nestedPRBC
| false, false, false => unreachable!
def mkNestedTerm (code : Code) (m : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM Syntax := do
ToTerm.run code m uvars (mkNestedKind a r bc)
/- Given a term `term` produced by `ToTerm.run`, pattern match on its result.
See comment at the beginning of the `ToTerm` namespace.
- `a` is true if the code block has a `Code.action _` exit point
- `r` is true if the code block has a `Code.return _ _` exit point
- `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point
The result is a sequence of `doElem` -/
def matchNestedTermResult (term : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM (List Syntax) := do
let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo)
let u ← mkTuple (← uvars.mapM mkIdentFromRef)
match a, r, bc with
| true, false, false =>
if uvars.isEmpty then
toDoElems (← `(do $term:term))
else
toDoElems (← `(do let r ← $term:term; $u:term := r.2; pure r.1))
| false, true, false =>
if uvars.isEmpty then
toDoElems (← `(do let r ← $term:term; return r))
else
toDoElems (← `(do let r ← $term:term; $u:term := r.2; return r.1))
| false, false, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| DoResultBC.«break» u => $u:term := u; break
| DoResultBC.«continue» u => $u:term := u; continue)
| true, true, false => toDoElems <$>
`(do let r ← $term:term;
match r with
| DoResultPR.«pure» a u => $u:term := u; pure a
| DoResultPR.«return» b u => $u:term := u; return b)
| true, false, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| DoResultSBC.«pureReturn» a u => $u:term := u; pure a
| DoResultSBC.«break» u => $u:term := u; break
| DoResultSBC.«continue» u => $u:term := u; continue)
| false, true, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| DoResultSBC.«pureReturn» a u => $u:term := u; return a
| DoResultSBC.«break» u => $u:term := u; break
| DoResultSBC.«continue» u => $u:term := u; continue)
| true, true, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| DoResultPRBC.«pure» a u => $u:term := u; pure a
| DoResultPRBC.«return» a u => $u:term := u; return a
| DoResultPRBC.«break» u => $u:term := u; break
| DoResultPRBC.«continue» u => $u:term := u; continue)
| false, false, false => unreachable!
end ToTerm
def isMutableLet (doElem : Syntax) : Bool :=
let kind := doElem.getKind
(kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet)
&&
!doElem[1].isNone
namespace ToCodeBlock
structure Context where
ref : Syntax
m : Syntax -- Syntax representing the monad associated with the do notation.
mutableVars : NameSet := {}
insideFor : Bool := false
abbrev M := ReaderT Context TermElabM
@[inline] def withNewMutableVars {α} (newVars : Array Name) (mutable : Bool) (x : M α) : M α :=
withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x
def checkReassignable (xs : Array Name) : M Unit := do
let throwInvalidReassignment (x : Name) : M Unit :=
throwError! "'{x.simpMacroScopes}' cannot be reassigned"
let ctx ← read
for x in xs do
unless ctx.mutableVars.contains x do
throwInvalidReassignment x
@[inline] def withFor {α} (x : M α) : M α :=
withReader (fun ctx => { ctx with insideFor := true }) x
structure ToForInTermResult where
uvars : Array Name
term : Syntax
def mkForInBody (x : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do
let ctx ← read
let uvars := forInBody.uvars
let uvars := nameSetToArray uvars
let term ← liftMacroM $ ToTerm.run forInBody.code ctx.m uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn)
pure ⟨uvars, term⟩
def ensureInsideFor : M Unit :=
unless (← read).insideFor do
throwError "invalid 'do' element, it must be inside 'for'"
def ensureEOS (doElems : List Syntax) : M Unit :=
unless doElems.isEmpty do
throwError "must be last element in a 'do' sequence"
private partial def expandLiftMethodAux (inQuot : Bool) : Syntax → StateT (List Syntax) MacroM Syntax
| stx@(Syntax.node k args) =>
if liftMethodDelimiter k then
pure stx
else if k == `Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do
let term := args[1]
let term ← expandLiftMethodAux inQuot term
let auxDoElem ← `(doElem| let a ← $term:term)
modify fun s => s ++ [auxDoElem]
`(a)
else do
let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot
let args ← args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot))
pure $ Syntax.node k args
| stx => pure stx
def expandLiftMethod (doElem : Syntax) : MacroM (List Syntax × Syntax) := do
if !hasLiftMethod doElem then
pure ([], doElem)
else
let (doElem, doElemsNew) ← (expandLiftMethodAux false doElem).run []
pure (doElemsNew, doElem)
def checkLetArrowRHS (doElem : Syntax) : M Unit := do
let kind := doElem.getKind
if kind == `Lean.Parser.Term.doLetArrow ||
kind == `Lean.Parser.Term.doLet ||
kind == `Lean.Parser.Term.doLetRec ||
kind == `Lean.Parser.Term.doHave ||
kind == `Lean.Parser.Term.doReassign ||
kind == `Lean.Parser.Term.doReassignArrow then
throwErrorAt! doElem "invalid kind of value '{kind}' in an assignment"
/- Generate `CodeBlock` for `doReturn` which is of the form
```
"return " >> optional termParser
```
`doElems` is only used for sanity checking. -/
def doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do
ensureEOS doElems
let argOpt := doReturn[1]
let arg ← if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0]
return mkReturn (← getRef) arg
structure Catch where
x : Syntax
optType : Syntax
codeBlock : CodeBlock
def getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : NameSet :=
let ws := tryCode.uvars
let ws := catches.foldl (fun ws alt => union alt.codeBlock.uvars ws) ws
let ws := match finallyCode? with
| none => ws
| some c => union c.uvars ws
ws
def tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code → Bool) : Bool :=
p tryCode.code ||
catches.any (fun «catch» => p «catch».codeBlock.code) ||
match finallyCode? with
| none => false
| some finallyCode => p finallyCode.code
mutual
/- "Concatenate" `c` with `doSeqToCode doElems` -/
partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock :=
match doElems with
| [] => pure c
| nextDoElem :: _ => do
let k ← doSeqToCode doElems
let ref := nextDoElem
concat c ref none k
/- Generate `CodeBlock` for `doLetArrow; doElems`
`doLetArrow` is of the form
```
"let " >> optional "mut " >> (doIdDecl <|> doPatDecl)
```
where
```
def doIdDecl := parser! ident >> optType >> leftArrow >> doElemParser
def doPatDecl := parser! termParser >> leftArrow >> doElemParser >> optional (" | " >> doElemParser)
```
-/
partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do
let ref := doLetArrow
let decl := doLetArrow[2]
if decl.getKind == `Lean.Parser.Term.doIdDecl then
let y := decl[0].getId
let doElem := decl[3]
let k ← withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems)
match isDoExpr? doElem with
| some action => pure $ mkVarDeclCore #[y] doLetArrow k
| none =>
checkLetArrowRHS doElem
let c ← doSeqToCode [doElem]
match doElems with
| [] => pure c
| kRef::_ => concat c kRef y k
else if decl.getKind == `Lean.Parser.Term.doPatDecl then
let pattern := decl[0]
let doElem := decl[2]
let optElse := decl[3]
if optElse.isNone then withFreshMacroScope do
let auxDo ←
if isMutableLet doLetArrow then
`(do let discr ← $doElem; let mut $pattern:term := discr)
else
`(do let discr ← $doElem; let $pattern:term := discr)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else
if isMutableLet doLetArrow then
throwError! "'mut' is currently not supported in let-decls with 'else' case"
let contSeq := mkDoSeq doElems.toArray
let elseSeq := mkSingletonDoSeq optElse[1]
let auxDo ← `(do let discr ← $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo)
else
throwError "unexpected kind of 'do' declaration"
/- Generate `CodeBlock` for `doReassignArrow; doElems`
`doReassignArrow` is of the form
```
(doIdDecl <|> doPatDecl)
```
-/
partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do
let ref := doReassignArrow
let decl := doReassignArrow[0]
if decl.getKind == `Lean.Parser.Term.doIdDecl then
let doElem := decl[3]
let y := decl[0]
let auxDo ← `(do let r ← $doElem; $y:ident := r)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else if decl.getKind == `Lean.Parser.Term.doPatDecl then
let pattern := decl[0]
let doElem := decl[2]
let optElse := decl[3]
if optElse.isNone then withFreshMacroScope do
let auxDo ← `(do let discr ← $doElem; $pattern:term := discr)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else
throwError "reassignment with `|` (i.e., \"else clause\") is not currently supported"
else
throwError "unexpected kind of 'do' reassignment"
/- Generate `CodeBlock` for `doIf; doElems`
`doIf` is of the form
```
"if " >> optIdent >> termParser >> " then " >> doSeq
>> many (group (try (group (" else " >> " if ")) >> optIdent >> termParser >> " then " >> doSeq))
>> optional (" else " >> doSeq)
``` -/
partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do
let view ← liftMacroM $ mkDoIfView doIf
let thenBranch ← doSeqToCode (getDoSeqElems view.thenBranch)
let elseBranch ← doSeqToCode (getDoSeqElems view.elseBranch)
let ite ← mkIte view.ref view.optIdent view.cond thenBranch elseBranch
concatWith ite doElems
/- Generate `CodeBlock` for `doUnless; doElems`
`doUnless` is of the form
```
"unless " >> termParser >> "do " >> doSeq
``` -/
partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do
let ref := doUnless
let cond := doUnless[1]
let doSeq := doUnless[3]
let body ← doSeqToCode (getDoSeqElems doSeq)
let unlessCode ← liftMacroM <| mkUnless cond body
concatWith unlessCode doElems
/- Generate `CodeBlock` for `doFor; doElems`
`doFor` is of the form
```
def doForDecl := parser! termParser >> " in " >> withForbidden "do" termParser
def doFor := parser! "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq
```
-/
partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do
let doForDecls := doFor[1].getSepArgs
if doForDecls.size > 1 then
/-
Expand
```
for x in xs, y in ys do
body
```
into
```
let s := toStream ys
for x in xs do
match Stream.next? s with
| none => break
| some (y, s') =>
s := s'
body
```
-/
-- Extract second element
let doForDecl := doForDecls[1]
let y := doForDecl[0]
let ys := doForDecl[2]
let doForDecls := doForDecls.eraseIdx 1
let body := doFor[3]
withFreshMacroScope do
let toStreamFn ← withRef ys `(toStream)
let auxDo ←
`(do let mut s := $toStreamFn:ident $ys
for $doForDecls:doForDecl,* do
match Stream.next? s with
| none => break
| some ($y, s') =>
s := s'
do $body)
doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)
else withRef doFor do
let x := doForDecls[0][0]
let xs := doForDecls[0][2]
let forElems := getDoSeqElems doFor[3]
let forInBodyCodeBlock ← withFor (doSeqToCode forElems)
let ⟨uvars, forInBody⟩ ← mkForInBody x forInBodyCodeBlock
let uvarsTuple ← liftMacroM do mkTuple (← uvars.mapM mkIdentFromRef)
if hasReturn forInBodyCodeBlock.code then
let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody
let forInTerm ← `(forIn (m := $((← read).m)) $(xs) (MProd.mk none $uvarsTuple) fun $x r => let r := r.2; $forInBody)
let auxDo ← `(do let r ← $forInTerm:term;
$uvarsTuple:term := r.2;
match r.1 with
| none => Pure.pure (ensureExpectedType! "type mismatch, 'for'" PUnit.unit)
| some a => return ensureExpectedType! "type mismatch, 'for'" a)
doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)
else
let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody
let forInTerm ← `(forIn (m := $((← read).m)) $(xs) $uvarsTuple fun $x r => $forInBody)
if doElems.isEmpty then
let auxDo ← `(do let r ← $forInTerm:term;
$uvarsTuple:term := r;
Pure.pure (ensureExpectedType! "type mismatch, 'for'" PUnit.unit))
doSeqToCode <| getDoSeqElems (getDoSeq auxDo)
else
let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
/-- Generate `CodeBlock` for `doMatch; doElems` -/
partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do
let ref := doMatch
let discrs := doMatch[1]
let optType := doMatch[2]
let matchAlts := doMatch[4][0].getArgs -- Array of `doMatchAlt`
let alts ← matchAlts.mapM fun matchAlt => do
let patterns := matchAlt[1]
let vars ← getPatternsVarsEx patterns.getSepArgs
let rhs := matchAlt[3]
let rhs ← doSeqToCode (getDoSeqElems rhs)
pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock }
let matchCode ← mkMatch ref discrs optType alts
concatWith matchCode doElems
/--
Generate `CodeBlock` for `doTry; doElems`
```
def doTry := parser! "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally
def doCatch := parser! "catch " >> binderIdent >> optional (":" >> termParser) >> darrow >> doSeq
def doCatchMatch := parser! "catch " >> doMatchAlts
def doFinally := parser! "finally " >> doSeq
```
-/
partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do
let ref := doTry
let tryCode ← doSeqToCode (getDoSeqElems doTry[1])
let optFinally := doTry[3]
let catches ← doTry[2].getArgs.mapM fun catchStx => do
if catchStx.getKind == `Lean.Parser.Term.doCatch then
let x := catchStx[1]
let optType := catchStx[2]
let c ← doSeqToCode (getDoSeqElems catchStx[4])
pure { x := x, optType := optType, codeBlock := c : Catch }
else if catchStx.getKind == `Lean.Parser.Term.doCatchMatch then
let matchAlts := catchStx[1]
let x ← `(ex)
let auxDo ← `(do match ex with $matchAlts)
let c ← doSeqToCode (getDoSeqElems (getDoSeq auxDo))
pure { x := x, codeBlock := c, optType := mkNullNode : Catch }
else
throwError "unexpected kind of 'catch'"
let finallyCode? ← if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1])
if catches.isEmpty && finallyCode?.isNone then
throwError "invalid 'try', it must have a 'catch' or 'finally'"
let ctx ← read
let ws := getTryCatchUpdatedVars tryCode catches finallyCode?
let uvars := nameSetToArray ws
let a := tryCatchPred tryCode catches finallyCode? hasTerminalAction
let r := tryCatchPred tryCode catches finallyCode? hasReturn
let bc := tryCatchPred tryCode catches finallyCode? hasBreakContinue
let toTerm (codeBlock : CodeBlock) : M Syntax := do
let codeBlock ← liftM $ extendUpdatedVars codeBlock ws
liftMacroM $ ToTerm.mkNestedTerm codeBlock.code ctx.m uvars a r bc
let term ← toTerm tryCode
let term ← catches.foldlM
(fun term «catch» => do
let catchTerm ← toTerm «catch».codeBlock
if catch.optType.isNone then
`(MonadExcept.tryCatch $term (fun $(«catch».x):ident => $catchTerm))
else
let type := «catch».optType[1]
`(tryCatchThe $type $term (fun $(«catch».x):ident => $catchTerm)))
term
let term ← match finallyCode? with
| none => pure term
| some finallyCode => withRef optFinally do
unless finallyCode.uvars.isEmpty do
throwError "'finally' currently does not support reassignments"
if hasBreakContinueReturn finallyCode.code then
throwError "'finally' currently does 'return', 'break', nor 'continue'"
let finallyTerm ← liftMacroM <| ToTerm.run finallyCode.code ctx.m {} ToTerm.Kind.regular
`(tryFinally $term $finallyTerm)
let doElemsNew ← liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc
doSeqToCode (doElemsNew ++ doElems)
partial def doSeqToCode : List Syntax → M CodeBlock
| [] => do liftMacroM mkPureUnitAction
| doElem::doElems => withRef doElem do
match (← liftMacroM <| expandMacro? doElem) with
| some doElem => doSeqToCode (doElem::doElems)
| none =>
match (← liftMacroM <| expandDoIf? doElem) with
| some doElem => doSeqToCode (doElem::doElems)
| none =>
let (liftedDoElems, doElem) ← liftM (liftMacroM <| expandLiftMethod doElem : TermElabM _)
if !liftedDoElems.isEmpty then
doSeqToCode (liftedDoElems ++ [doElem] ++ doElems)
else
let ref := doElem
let concatWithRest (c : CodeBlock) : M CodeBlock := concatWith c doElems
let k := doElem.getKind
if k == `Lean.Parser.Term.doLet then
let vars ← getDoLetVars doElem
mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems)
else if k == `Lean.Parser.Term.doHave then
let var := getDoHaveVar doElem
mkVarDeclCore #[var] doElem <$> (doSeqToCode doElems)
else if k == `Lean.Parser.Term.doLetRec then
let vars ← getDoLetRecVars doElem
mkVarDeclCore vars doElem <$> (doSeqToCode doElems)
else if k == `Lean.Parser.Term.doReassign then
let vars ← getDoReassignVars doElem
checkReassignable vars
let k ← doSeqToCode doElems
mkReassignCore vars doElem k
else if k == `Lean.Parser.Term.doLetArrow then
doLetArrowToCode doElem doElems
else if k == `Lean.Parser.Term.doReassignArrow then
doReassignArrowToCode doElem doElems
else if k == `Lean.Parser.Term.doIf then
doIfToCode doElem doElems
else if k == `Lean.Parser.Term.doUnless then
doUnlessToCode doElem doElems
else if k == `Lean.Parser.Term.doFor then withFreshMacroScope do
doForToCode doElem doElems
else if k == `Lean.Parser.Term.doMatch then
doMatchToCode doElem doElems
else if k == `Lean.Parser.Term.doTry then
doTryToCode doElem doElems
else if k == `Lean.Parser.Term.doBreak then
ensureInsideFor
ensureEOS doElems
return mkBreak ref
else if k == `Lean.Parser.Term.doContinue then
ensureInsideFor
ensureEOS doElems
return mkContinue ref
else if k == `Lean.Parser.Term.doReturn then
doReturnToCode doElem doElems
else if k == `Lean.Parser.Term.doDbgTrace then
return mkSeq doElem (← doSeqToCode doElems)
else if k == `Lean.Parser.Term.doAssert then
return mkSeq doElem (← doSeqToCode doElems)
else if k == `Lean.Parser.Term.doNested then
let nestedDoSeq := doElem[1]
doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems)
else if k == `Lean.Parser.Term.doExpr then
let term := doElem[0]
if doElems.isEmpty then
return mkTerminalAction term
else
return mkSeq term (← doSeqToCode doElems)
else
throwError! "unexpected do-element\n{doElem}"
end
def run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock :=
(doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m := m }
end ToCodeBlock
/- Create a synthetic metavariable `?m` and assign `m` to it.
We use `?m` to refer to `m` when expanding the `do` notation. -/
private def mkMonadAlias (m : Expr) : TermElabM Syntax := do
let result ← `(?m)
let mType ← inferType m
let mvar ← elabTerm result mType
assignExprMVar mvar.mvarId! m
pure result
@[builtinTermElab «do»]
def elabDo : TermElab := fun stx expectedType? => do
tryPostponeIfNoneOrMVar expectedType?
let bindInfo ← extractBind expectedType?
let m ← mkMonadAlias bindInfo.m
let codeBlock ← ToCodeBlock.run stx m
let stxNew ← liftMacroM $ ToTerm.run codeBlock.code m
trace[Elab.do]! stxNew
withMacroExpansion stx stxNew $ elabTermEnsuringType stxNew bindInfo.expectedType
end Do
builtin_initialize registerTraceClass `Elab.do
private def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do
let stx := stx.setKind newKind
withRef stx `(do $stx:doElem)
@[builtinMacro Lean.Parser.Term.termFor]
def expandTermFor : Macro := toDoElem `Lean.Parser.Term.doFor
@[builtinMacro Lean.Parser.Term.termTry]
def expandTermTry : Macro := toDoElem `Lean.Parser.Term.doTry
@[builtinMacro Lean.Parser.Term.termUnless]
def expandTermUnless : Macro := toDoElem `Lean.Parser.Term.doUnless
@[builtinMacro Lean.Parser.Term.termReturn]
def expandTermReturn : Macro := toDoElem `Lean.Parser.Term.doReturn
end Term
end Elab
end Lean
|
2f3573a69f5e46e754cc3e3968181f5eaf97c4bd | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/1674.lean | 617825978f60dedff0cc772557e81d2ceae875a4 | [
"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 | 147 | lean | inductive T : Prop where
| nil (n: Nat)
| fn (f: Nat → T)
def inc: T → T
| T.nil n => T.nil (n+1)
| T.fn f => T.fn fun n => inc (f n)
|
3475f99f6b2e157e913f3aea1c7f90b7f87f815f | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/category_theory/filtered.lean | 0e8d17eda00ded608e1e2f07360701bfb30339fe | [
"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 | 19,810 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Scott Morrison
-/
import category_theory.fin_category
import category_theory.limits.cones
import category_theory.adjunction.basic
import category_theory.category.preorder
import order.bounded_lattice
/-!
# Filtered categories
A category is filtered if every finite diagram admits a cocone.
We give a simple characterisation of this condition as
1. for every pair of objects there exists another object "to the right",
2. for every pair of parallel morphisms there exists a morphism to the right so the compositions
are equal, and
3. there exists some object.
Filtered colimits are often better behaved than arbitrary colimits.
See `category_theory/limits/types` for some details.
Filtered categories are nice because colimits indexed by filtered categories tend to be
easier to describe than general colimits (and more often preserved by functors).
In this file we show that any functor from a finite category to a filtered category admits a cocone:
* `cocone_nonempty [fin_category J] [is_filtered C] (F : J ⥤ C) : nonempty (cocone F)`
More generally,
for any finite collection of objects and morphisms between them in a filtered category
(even if not closed under composition) there exists some object `Z` receiving maps from all of them,
so that all the triangles (one edge from the finite set, two from morphisms to `Z`) commute.
This formulation is often more useful in practice and is available via `sup_exists`,
which takes a finset of objects, and an indexed family (indexed by source and target)
of finsets of morphisms.
We also provide all of the above API for cofiltered categories.
## See also
In `category_theory.limits.filtered_colimit_commutes_finite_limit` we show that filtered colimits
commute with finite limits.
## Future work
* Forgetful functors for algebraic categories typically preserve filtered colimits.
-/
universes v v₁ u u₁-- declare the `v`'s first; see `category_theory.category` for an explanation
namespace category_theory
variables (C : Type u) [category.{v} C]
/--
A category `is_filtered_or_empty` if
1. for every pair of objects there exists another object "to the right", and
2. for every pair of parallel morphisms there exists a morphism to the right so the compositions
are equal.
-/
class is_filtered_or_empty : Prop :=
(cocone_objs : ∀ (X Y : C), ∃ Z (f : X ⟶ Z) (g : Y ⟶ Z), true)
(cocone_maps : ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), ∃ Z (h : Y ⟶ Z), f ≫ h = g ≫ h)
/--
A category `is_filtered` if
1. for every pair of objects there exists another object "to the right",
2. for every pair of parallel morphisms there exists a morphism to the right so the compositions
are equal, and
3. there exists some object.
See https://stacks.math.columbia.edu/tag/002V. (They also define a diagram being filtered.)
-/
class is_filtered extends is_filtered_or_empty C : Prop :=
[nonempty : nonempty C]
@[priority 100]
instance is_filtered_or_empty_of_semilattice_sup
(α : Type u) [semilattice_sup α] : is_filtered_or_empty α :=
{ cocone_objs := λ X Y, ⟨X ⊔ Y, hom_of_le le_sup_left, hom_of_le le_sup_right, trivial⟩,
cocone_maps := λ X Y f g, ⟨Y, 𝟙 _, (by ext)⟩, }
@[priority 100]
instance is_filtered_of_semilattice_sup_nonempty
(α : Type u) [semilattice_sup α] [nonempty α] : is_filtered α := {}
-- TODO: Define `codirected_order` and provide the dual to this instance.
@[priority 100]
instance is_filtered_or_empty_of_directed_order
(α : Type u) [directed_order α] : is_filtered_or_empty α :=
{ cocone_objs := λ X Y, let ⟨Z,h1,h2⟩ := directed_order.directed X Y in
⟨Z, hom_of_le h1, hom_of_le h2, trivial⟩,
cocone_maps := λ X Y f g, ⟨Y, 𝟙 _, by simp⟩ }
-- TODO: Define `codirected_order` and provide the dual to this instance.
@[priority 100]
instance is_filtered_of_directed_order_nonempty
(α : Type u) [directed_order α] [nonempty α] : is_filtered α := {}
-- Sanity checks
example (α : Type u) [semilattice_sup_bot α] : is_filtered α := by apply_instance
example (α : Type u) [semilattice_sup_top α] : is_filtered α := by apply_instance
namespace is_filtered
variables {C} [is_filtered C]
/--
`max j j'` is an arbitrary choice of object to the right of both `j` and `j'`,
whose existence is ensured by `is_filtered`.
-/
noncomputable def max (j j' : C) : C :=
(is_filtered_or_empty.cocone_objs j j').some
/--
`left_to_max j j'` is an arbitrarily choice of morphism from `j` to `max j j'`,
whose existence is ensured by `is_filtered`.
-/
noncomputable def left_to_max (j j' : C) : j ⟶ max j j' :=
(is_filtered_or_empty.cocone_objs j j').some_spec.some
/--
`right_to_max j j'` is an arbitrarily choice of morphism from `j'` to `max j j'`,
whose existence is ensured by `is_filtered`.
-/
noncomputable def right_to_max (j j' : C) : j' ⟶ max j j' :=
(is_filtered_or_empty.cocone_objs j j').some_spec.some_spec.some
/--
`coeq f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of object
which admits a morphism `coeq_hom f f' : j' ⟶ coeq f f'` such that
`coeq_condition : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`.
Its existence is ensured by `is_filtered`.
-/
noncomputable def coeq {j j' : C} (f f' : j ⟶ j') : C :=
(is_filtered_or_empty.cocone_maps f f').some
/--
`coeq_hom f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of morphism
`coeq_hom f f' : j' ⟶ coeq f f'` such that
`coeq_condition : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`.
Its existence is ensured by `is_filtered`.
-/
noncomputable def coeq_hom {j j' : C} (f f' : j ⟶ j') : j' ⟶ coeq f f' :=
(is_filtered_or_empty.cocone_maps f f').some_spec.some
/--
`coeq_condition f f'`, for morphisms `f f' : j ⟶ j'`, is the proof that
`f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`.
-/
@[simp, reassoc]
lemma coeq_condition {j j' : C} (f f' : j ⟶ j') : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f' :=
(is_filtered_or_empty.cocone_maps f f').some_spec.some_spec
open category_theory.limits
/--
Any finite collection of objects in a filtered category has an object "to the right".
-/
lemma sup_objs_exists (O : finset C) : ∃ (S : C), ∀ {X}, X ∈ O → _root_.nonempty (X ⟶ S) :=
begin
classical,
apply finset.induction_on O,
{ exact ⟨is_filtered.nonempty.some, (by rintros - ⟨⟩)⟩, },
{ rintros X O' nm ⟨S', w'⟩,
use max X S',
rintros Y mY,
by_cases h : X = Y,
{ subst h, exact ⟨left_to_max _ _⟩, },
{ exact ⟨(w' (by finish)).some ≫ right_to_max _ _⟩, }, }
end
variables (O : finset C) (H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y))
/--
Given any `finset` of objects `{X, ...}` and
indexed collection of `finset`s of morphisms `{f, ...}` in `C`,
there exists an object `S`, with a morphism `T X : X ⟶ S` from each `X`,
such that the triangles commute: `f ≫ T Y = T X`, for `f : X ⟶ Y` in the `finset`.
-/
lemma sup_exists :
∃ (S : C) (T : Π {X : C}, X ∈ O → (X ⟶ S)), ∀ {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y},
(⟨X, Y, mX, mY, f⟩ : (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H → f ≫ T mY = T mX :=
begin
classical,
apply finset.induction_on H,
{ obtain ⟨S, f⟩ := sup_objs_exists O,
refine ⟨S, λ X mX, (f mX).some, _⟩,
rintros - - - - - ⟨⟩, },
{ rintros ⟨X, Y, mX, mY, f⟩ H' nmf ⟨S', T', w'⟩,
refine ⟨coeq (f ≫ T' mY) (T' mX), λ Z mZ, T' mZ ≫ coeq_hom (f ≫ T' mY) (T' mX), _⟩,
intros X' Y' mX' mY' f' mf',
rw [←category.assoc],
by_cases h : X = X' ∧ Y = Y',
{ rcases h with ⟨rfl, rfl⟩,
by_cases hf : f = f',
{ subst hf,
apply coeq_condition, },
{ rw @w' _ _ mX mY f' (by simpa [hf ∘ eq.symm] using mf') }, },
{ rw @w' _ _ mX' mY' f' (by finish), }, },
end
/--
An arbitrary choice of object "to the right"
of a finite collection of objects `O` and morphisms `H`,
making all the triangles commute.
-/
noncomputable
def sup : C :=
(sup_exists O H).some
/--
The morphisms to `sup O H`.
-/
noncomputable
def to_sup {X : C} (m : X ∈ O) :
X ⟶ sup O H :=
(sup_exists O H).some_spec.some m
/--
The triangles of consisting of a morphism in `H` and the maps to `sup O H` commute.
-/
lemma to_sup_commutes
{X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y}
(mf : (⟨X, Y, mX, mY, f⟩ : Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) ∈ H) :
f ≫ to_sup O H mY = to_sup O H mX :=
(sup_exists O H).some_spec.some_spec mX mY mf
variables {J : Type v} [small_category J] [fin_category J]
/--
If we have `is_filtered C`, then for any functor `F : J ⥤ C` with `fin_category J`,
there exists a cocone over `F`.
-/
lemma cocone_nonempty (F : J ⥤ C) : _root_.nonempty (cocone F) :=
begin
classical,
let O := (finset.univ.image F.obj),
let H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) :=
finset.univ.bUnion (λ X : J, finset.univ.bUnion (λ Y : J, finset.univ.image (λ f : X ⟶ Y,
⟨F.obj X, F.obj Y, by simp, by simp, F.map f⟩))),
obtain ⟨Z, f, w⟩ := sup_exists O H,
refine ⟨⟨Z, ⟨λ X, f (by simp), _⟩⟩⟩,
intros j j' g,
dsimp,
simp only [category.comp_id],
apply w,
simp only [finset.mem_univ, finset.mem_bUnion, exists_and_distrib_left,
exists_prop_of_true, finset.mem_image],
exact ⟨j, rfl, j', g, (by simp)⟩,
end
/--
An arbitrary choice of cocone over `F : J ⥤ C`, for `fin_category J` and `is_filtered C`.
-/
noncomputable def cocone (F : J ⥤ C) : cocone F :=
(cocone_nonempty F).some
variables {D : Type u₁} [category.{v₁} D]
/--
If `C` is filtered, and we have a functor `R : C ⥤ D` with a left adjoint, then `D` is filtered.
-/
lemma of_right_adjoint {L : D ⥤ C} {R : C ⥤ D} (h : L ⊣ R) : is_filtered D :=
{ cocone_objs := λ X Y,
⟨_, h.hom_equiv _ _ (left_to_max _ _), h.hom_equiv _ _ (right_to_max _ _), ⟨⟩⟩,
cocone_maps := λ X Y f g,
⟨_, h.hom_equiv _ _ (coeq_hom _ _),
by rw [← h.hom_equiv_naturality_left, ← h.hom_equiv_naturality_left, coeq_condition]⟩,
nonempty := is_filtered.nonempty.map R.obj }
/-- If `C` is filtered, and we have a right adjoint functor `R : C ⥤ D`, then `D` is filtered. -/
lemma of_is_right_adjoint (R : C ⥤ D) [is_right_adjoint R] : is_filtered D :=
of_right_adjoint (adjunction.of_right_adjoint R)
/-- Being filtered is preserved by equivalence of categories. -/
lemma of_equivalence (h : C ≌ D) : is_filtered D :=
of_right_adjoint h.symm.to_adjunction
end is_filtered
/--
A category `is_cofiltered_or_empty` if
1. for every pair of objects there exists another object "to the left", and
2. for every pair of parallel morphisms there exists a morphism to the left so the compositions
are equal.
-/
class is_cofiltered_or_empty : Prop :=
(cocone_objs : ∀ (X Y : C), ∃ W (f : W ⟶ X) (g : W ⟶ Y), true)
(cocone_maps : ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), ∃ W (h : W ⟶ X), h ≫ f = h ≫ g)
/--
A category `is_cofiltered` if
1. for every pair of objects there exists another object "to the left",
2. for every pair of parallel morphisms there exists a morphism to the left so the compositions
are equal, and
3. there exists some object.
See https://stacks.math.columbia.edu/tag/04AZ.
-/
class is_cofiltered extends is_cofiltered_or_empty C : Prop :=
[nonempty : nonempty C]
@[priority 100]
instance is_cofiltered_or_empty_of_semilattice_inf
(α : Type u) [semilattice_inf α] : is_cofiltered_or_empty α :=
{ cocone_objs := λ X Y, ⟨X ⊓ Y, hom_of_le inf_le_left, hom_of_le inf_le_right, trivial⟩,
cocone_maps := λ X Y f g, ⟨X, 𝟙 _, (by ext)⟩, }
@[priority 100]
instance is_cofiltered_of_semilattice_inf_nonempty
(α : Type u) [semilattice_inf α] [nonempty α] : is_cofiltered α := {}
-- Sanity checks
example (α : Type u) [semilattice_inf_bot α] : is_cofiltered α := by apply_instance
example (α : Type u) [semilattice_inf_top α] : is_cofiltered α := by apply_instance
namespace is_cofiltered
variables {C} [is_cofiltered C]
/--
`min j j'` is an arbitrary choice of object to the left of both `j` and `j'`,
whose existence is ensured by `is_cofiltered`.
-/
noncomputable def min (j j' : C) : C :=
(is_cofiltered_or_empty.cocone_objs j j').some
/--
`min_to_left j j'` is an arbitrarily choice of morphism from `min j j'` to `j`,
whose existence is ensured by `is_cofiltered`.
-/
noncomputable def min_to_left (j j' : C) : min j j' ⟶ j :=
(is_cofiltered_or_empty.cocone_objs j j').some_spec.some
/--
`min_to_right j j'` is an arbitrarily choice of morphism from `min j j'` to `j'`,
whose existence is ensured by `is_cofiltered`.
-/
noncomputable def min_to_right (j j' : C) : min j j' ⟶ j' :=
(is_cofiltered_or_empty.cocone_objs j j').some_spec.some_spec.some
/--
`eq f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of object
which admits a morphism `eq_hom f f' : eq f f' ⟶ j` such that
`eq_condition : eq_hom f f' ≫ f = eq_hom f f' ≫ f'`.
Its existence is ensured by `is_cofiltered`.
-/
noncomputable def eq {j j' : C} (f f' : j ⟶ j') : C :=
(is_cofiltered_or_empty.cocone_maps f f').some
/--
`eq_hom f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of morphism
`eq_hom f f' : eq f f' ⟶ j` such that
`eq_condition : eq_hom f f' ≫ f = eq_hom f f' ≫ f'`.
Its existence is ensured by `is_cofiltered`.
-/
noncomputable def eq_hom {j j' : C} (f f' : j ⟶ j') : eq f f' ⟶ j :=
(is_cofiltered_or_empty.cocone_maps f f').some_spec.some
/--
`eq_condition f f'`, for morphisms `f f' : j ⟶ j'`, is the proof that
`eq_hom f f' ≫ f = eq_hom f f' ≫ f'`.
-/
@[simp, reassoc]
lemma eq_condition {j j' : C} (f f' : j ⟶ j') : eq_hom f f' ≫ f = eq_hom f f' ≫ f' :=
(is_cofiltered_or_empty.cocone_maps f f').some_spec.some_spec
open category_theory.limits
/--
Any finite collection of objects in a cofiltered category has an object "to the left".
-/
lemma inf_objs_exists (O : finset C) : ∃ (S : C), ∀ {X}, X ∈ O → _root_.nonempty (S ⟶ X) :=
begin
classical,
apply finset.induction_on O,
{ exact ⟨is_cofiltered.nonempty.some, (by rintros - ⟨⟩)⟩, },
{ rintros X O' nm ⟨S', w'⟩,
use min X S',
rintros Y mY,
by_cases h : X = Y,
{ subst h, exact ⟨min_to_left _ _⟩, },
{ exact ⟨min_to_right _ _ ≫ (w' (by finish)).some⟩, }, }
end
variables (O : finset C) (H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y))
/--
Given any `finset` of objects `{X, ...}` and
indexed collection of `finset`s of morphisms `{f, ...}` in `C`,
there exists an object `S`, with a morphism `T X : S ⟶ X` from each `X`,
such that the triangles commute: `T X ≫ f = T Y`, for `f : X ⟶ Y` in the `finset`.
-/
lemma inf_exists :
∃ (S : C) (T : Π {X : C}, X ∈ O → (S ⟶ X)), ∀ {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y},
(⟨X, Y, mX, mY, f⟩ : (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H → T mX ≫ f = T mY :=
begin
classical,
apply finset.induction_on H,
{ obtain ⟨S, f⟩ := inf_objs_exists O,
refine ⟨S, λ X mX, (f mX).some, _⟩,
rintros - - - - - ⟨⟩, },
{ rintros ⟨X, Y, mX, mY, f⟩ H' nmf ⟨S', T', w'⟩,
refine ⟨eq (T' mX ≫ f) (T' mY), λ Z mZ, eq_hom (T' mX ≫ f) (T' mY) ≫ T' mZ, _⟩,
intros X' Y' mX' mY' f' mf',
rw [category.assoc],
by_cases h : X = X' ∧ Y = Y',
{ rcases h with ⟨rfl, rfl⟩,
by_cases hf : f = f',
{ subst hf,
apply eq_condition, },
{ rw @w' _ _ mX mY f' (by simpa [hf ∘ eq.symm] using mf') }, },
{ rw @w' _ _ mX' mY' f' (by finish), }, },
end
/--
An arbitrary choice of object "to the left"
of a finite collection of objects `O` and morphisms `H`,
making all the triangles commute.
-/
noncomputable
def inf : C :=
(inf_exists O H).some
/--
The morphisms from `inf O H`.
-/
noncomputable
def inf_to {X : C} (m : X ∈ O) :
inf O H ⟶ X :=
(inf_exists O H).some_spec.some m
/--
The triangles consisting of a morphism in `H` and the maps from `inf O H` commute.
-/
lemma inf_to_commutes
{X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y}
(mf : (⟨X, Y, mX, mY, f⟩ : Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) ∈ H) :
inf_to O H mX ≫ f = inf_to O H mY :=
(inf_exists O H).some_spec.some_spec mX mY mf
variables {J : Type v} [small_category J] [fin_category J]
/--
If we have `is_cofiltered C`, then for any functor `F : J ⥤ C` with `fin_category J`,
there exists a cone over `F`.
-/
lemma cone_nonempty (F : J ⥤ C) : _root_.nonempty (cone F) :=
begin
classical,
let O := (finset.univ.image F.obj),
let H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) :=
finset.univ.bUnion (λ X : J, finset.univ.bUnion (λ Y : J, finset.univ.image (λ f : X ⟶ Y,
⟨F.obj X, F.obj Y, by simp, by simp, F.map f⟩))),
obtain ⟨Z, f, w⟩ := inf_exists O H,
refine ⟨⟨Z, ⟨λ X, f (by simp), _⟩⟩⟩,
intros j j' g,
dsimp,
simp only [category.id_comp],
symmetry,
apply w,
simp only [finset.mem_univ, finset.mem_bUnion, exists_and_distrib_left,
exists_prop_of_true, finset.mem_image],
exact ⟨j, rfl, j', g, (by simp)⟩,
end
/--
An arbitrary choice of cone over `F : J ⥤ C`, for `fin_category J` and `is_cofiltered C`.
-/
noncomputable def cone (F : J ⥤ C) : cone F :=
(cone_nonempty F).some
variables {D : Type u₁} [category.{v₁} D]
/--
If `C` is cofiltered, and we have a functor `L : C ⥤ D` with a right adjoint,
then `D` is cofiltered.
-/
lemma of_left_adjoint {L : C ⥤ D} {R : D ⥤ C} (h : L ⊣ R) : is_cofiltered D :=
{ cocone_objs := λ X Y,
⟨L.obj (min (R.obj X) (R.obj Y)),
(h.hom_equiv _ X).symm (min_to_left _ _), (h.hom_equiv _ Y).symm (min_to_right _ _), ⟨⟩⟩,
cocone_maps := λ X Y f g,
⟨L.obj (eq (R.map f) (R.map g)), (h.hom_equiv _ _).symm (eq_hom _ _),
by rw [← h.hom_equiv_naturality_right_symm, ← h.hom_equiv_naturality_right_symm,
eq_condition]⟩,
nonempty := is_cofiltered.nonempty.map L.obj }
/-- If `C` is cofiltered, and we have a left adjoint functor `L : C ⥤ D`, then `D` is cofiltered. -/
lemma of_is_left_adjoint (L : C ⥤ D) [is_left_adjoint L] : is_cofiltered D :=
of_left_adjoint (adjunction.of_left_adjoint L)
/-- Being cofiltered is preserved by equivalence of categories. -/
lemma of_equivalence (h : C ≌ D) : is_cofiltered D :=
of_left_adjoint h.to_adjunction
end is_cofiltered
section opposite
open opposite
instance is_cofiltered_op_of_is_filtered [is_filtered C] : is_cofiltered Cᵒᵖ :=
{ cocone_objs := λ X Y, ⟨op (is_filtered.max X.unop Y.unop),
(is_filtered.left_to_max _ _).op, (is_filtered.right_to_max _ _).op, trivial⟩,
cocone_maps := λ X Y f g, ⟨op (is_filtered.coeq f.unop g.unop),
(is_filtered.coeq_hom _ _).op, begin
rw [(show f = f.unop.op, by simp), (show g = g.unop.op, by simp),
← op_comp, ← op_comp],
congr' 1,
exact is_filtered.coeq_condition f.unop g.unop,
end⟩,
nonempty := ⟨op is_filtered.nonempty.some⟩ }
instance is_filtered_op_of_is_cofiltered [is_cofiltered C] : is_filtered Cᵒᵖ :=
{ cocone_objs := λ X Y, ⟨op (is_cofiltered.min X.unop Y.unop),
(is_cofiltered.min_to_left X.unop Y.unop).op,
(is_cofiltered.min_to_right X.unop Y.unop).op, trivial⟩,
cocone_maps := λ X Y f g, ⟨op (is_cofiltered.eq f.unop g.unop),
(is_cofiltered.eq_hom f.unop g.unop).op, begin
rw [(show f = f.unop.op, by simp), (show g = g.unop.op, by simp),
← op_comp, ← op_comp],
congr' 1,
exact is_cofiltered.eq_condition f.unop g.unop,
end⟩,
nonempty := ⟨op is_cofiltered.nonempty.some⟩ }
end opposite
end category_theory
|
1581364f97f7242978ef04de419e8faa8edf7915 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/unitary_group.lean | dac05f32d4cf5502a0fe6418c8190003ada519d7 | [
"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 | 6,201 | lean | /-
Copyright (c) 2021 Shing Tak Lam. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Shing Tak Lam
-/
import linear_algebra.general_linear_group
import linear_algebra.matrix.to_lin
import linear_algebra.matrix.nonsingular_inverse
import algebra.star.unitary
/-!
# The Unitary Group
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines elements of the unitary group `unitary_group n α`, where `α` is a `star_ring`.
This consists of all `n` by `n` matrices with entries in `α` such that the star-transpose is its
inverse. In addition, we define the group structure on `unitary_group n α`, and the embedding into
the general linear group `general_linear_group α (n → α)`.
We also define the orthogonal group `orthogonal_group n β`, where `β` is a `comm_ring`.
## Main Definitions
* `matrix.unitary_group` is the type of matrices where the star-transpose is the inverse
* `matrix.unitary_group.group` is the group structure (under multiplication)
* `matrix.unitary_group.embedding_GL` is the embedding `unitary_group n α → GLₙ(α)`
* `matrix.orthogonal_group` is the type of matrices where the transpose is the inverse
## References
* https://en.wikipedia.org/wiki/Unitary_group
## Tags
matrix group, group, unitary group, orthogonal group
-/
universes u v
namespace matrix
open linear_map
open_locale matrix
section
variables (n : Type u) [decidable_eq n] [fintype n]
variables (α : Type v) [comm_ring α] [star_ring α]
/--
`unitary_group n` is the group of `n` by `n` matrices where the star-transpose is the inverse.
-/
abbreviation unitary_group := unitary (matrix n n α)
end
variables {n : Type u} [decidable_eq n] [fintype n]
variables {α : Type v} [comm_ring α] [star_ring α]
lemma mem_unitary_group_iff {A : matrix n n α} :
A ∈ matrix.unitary_group n α ↔ A * star A = 1 :=
begin
refine ⟨and.right, λ hA, ⟨_, hA⟩⟩,
simpa only [mul_eq_mul, mul_eq_one_comm] using hA
end
lemma mem_unitary_group_iff' {A : matrix n n α} :
A ∈ matrix.unitary_group n α ↔ star A * A = 1 :=
begin
refine ⟨and.left, λ hA, ⟨hA, _⟩⟩,
rwa [mul_eq_mul, mul_eq_one_comm] at hA,
end
lemma det_of_mem_unitary {A : matrix n n α} (hA : A ∈ matrix.unitary_group n α) :
A.det ∈ unitary α :=
begin
split,
{ simpa [star, det_transpose] using congr_arg det hA.1 },
{ simpa [star, det_transpose] using congr_arg det hA.2 },
end
namespace unitary_group
instance coe_matrix : has_coe (unitary_group n α) (matrix n n α) := ⟨subtype.val⟩
instance coe_fun : has_coe_to_fun (unitary_group n α) (λ _, n → n → α) :=
{ coe := λ A, A.val }
/--
`to_lin' A` is matrix multiplication of vectors by `A`, as a linear map.
After the group structure on `unitary_group n` is defined,
we show in `to_linear_equiv` that this gives a linear equivalence.
-/
def to_lin' (A : unitary_group n α) := matrix.to_lin' A
lemma ext_iff (A B : unitary_group n α) : A = B ↔ ∀ i j, A i j = B i j :=
subtype.ext_iff_val.trans ⟨(λ h i j, congr_fun (congr_fun h i) j), matrix.ext⟩
@[ext] lemma ext (A B : unitary_group n α) : (∀ i j, A i j = B i j) → A = B :=
(unitary_group.ext_iff A B).mpr
@[simp]
lemma star_mul_self (A : unitary_group n α) : star A ⬝ A = 1 := A.2.1
section coe_lemmas
variables (A B : unitary_group n α)
@[simp] lemma inv_val : ↑(A⁻¹) = (star A : matrix n n α) := rfl
@[simp] lemma inv_apply : ⇑(A⁻¹) = (star A : matrix n n α) := rfl
@[simp] lemma mul_val : ↑(A * B) = A ⬝ B := rfl
@[simp] lemma mul_apply : ⇑(A * B) = (A ⬝ B) := rfl
@[simp] lemma one_val : ↑(1 : unitary_group n α) = (1 : matrix n n α) := rfl
@[simp] lemma one_apply : ⇑(1 : unitary_group n α) = (1 : matrix n n α) := rfl
@[simp] lemma to_lin'_mul :
to_lin' (A * B) = (to_lin' A).comp (to_lin' B) :=
matrix.to_lin'_mul A B
@[simp] lemma to_lin'_one :
to_lin' (1 : unitary_group n α) = linear_map.id :=
matrix.to_lin'_one
end coe_lemmas
/-- `to_linear_equiv A` is matrix multiplication of vectors by `A`, as a linear equivalence. -/
def to_linear_equiv (A : unitary_group n α) : (n → α) ≃ₗ[α] (n → α) :=
{ inv_fun := to_lin' A⁻¹,
left_inv := λ x, calc
(to_lin' A⁻¹).comp (to_lin' A) x
= (to_lin' (A⁻¹ * A)) x : by rw [←to_lin'_mul]
... = x : by rw [mul_left_inv, to_lin'_one, id_apply],
right_inv := λ x, calc
(to_lin' A).comp (to_lin' A⁻¹) x
= to_lin' (A * A⁻¹) x : by rw [←to_lin'_mul]
... = x : by rw [mul_right_inv, to_lin'_one, id_apply],
..matrix.to_lin' A }
/-- `to_GL` is the map from the unitary group to the general linear group -/
def to_GL (A : unitary_group n α) : general_linear_group α (n → α) :=
general_linear_group.of_linear_equiv (to_linear_equiv A)
lemma coe_to_GL (A : unitary_group n α) :
↑(to_GL A) = to_lin' A :=
rfl
@[simp]
lemma to_GL_one : to_GL (1 : unitary_group n α) = 1 :=
by { ext1 v i, rw [coe_to_GL, to_lin'_one], refl }
@[simp]
lemma to_GL_mul (A B : unitary_group n α) :
to_GL (A * B) = to_GL A * to_GL B :=
by { ext1 v i, rw [coe_to_GL, to_lin'_mul], refl }
/-- `unitary_group.embedding_GL` is the embedding from `unitary_group n α`
to `general_linear_group n α`. -/
def embedding_GL : unitary_group n α →* general_linear_group α (n → α) :=
⟨λ A, to_GL A, by simp, by simp⟩
end unitary_group
section orthogonal_group
variables (n) (β : Type v) [comm_ring β]
local attribute [instance] star_ring_of_comm
/--
`orthogonal_group n` is the group of `n` by `n` matrices where the transpose is the inverse.
-/
abbreviation orthogonal_group := unitary_group n β
lemma mem_orthogonal_group_iff {A : matrix n n β} :
A ∈ matrix.orthogonal_group n β ↔ A * star A = 1 :=
begin
refine ⟨and.right, λ hA, ⟨_, hA⟩⟩,
simpa only [mul_eq_mul, mul_eq_one_comm] using hA
end
lemma mem_orthogonal_group_iff' {A : matrix n n β} :
A ∈ matrix.orthogonal_group n β ↔ star A * A = 1 :=
begin
refine ⟨and.left, λ hA, ⟨hA, _⟩⟩,
rwa [mul_eq_mul, mul_eq_one_comm] at hA,
end
end orthogonal_group
end matrix
|
aaa509723da025db409d2ad4c05010a5c8c4c680 | 9b9a16fa2cb737daee6b2785474678b6fa91d6d4 | /src/data/fin.lean | 62bcef4ae5dd0ebea71e53f675a33a3a98cd5fac | [
"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 | 6,831 | lean | /-
Copyright (c) 2017 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Robert Y. Lewis
More about finite numbers.
-/
import data.nat.basic
open fin nat
/-- `fin 0` is empty -/
def fin_zero_elim {C : Sort*} : fin 0 → C :=
λ x, false.elim $ nat.not_lt_zero x.1 x.2
namespace fin
variables {n m : ℕ} {a b : fin n}
@[simp] protected lemma eta (a : fin n) (h : a.1 < n) : (⟨a.1, h⟩ : fin n) = a :=
by cases a; refl
protected lemma ext_iff (a b : fin n) : a = b ↔ a.val = b.val :=
iff.intro (congr_arg _) fin.eq_of_veq
lemma eq_iff_veq (a b : fin n) : a = b ↔ a.1 = b.1 :=
⟨veq_of_eq, eq_of_veq⟩
instance fin_to_nat (n : ℕ) : has_coe (fin n) nat := ⟨fin.val⟩
@[simp] def mk_val {m n : ℕ} (h : m < n) : (⟨m, h⟩ : fin n).val = m := rfl
instance {n : ℕ} : decidable_linear_order (fin n) :=
decidable_linear_order.lift fin.val (@fin.eq_of_veq _)
lemma zero_le (a : fin (n + 1)) : 0 ≤ a := zero_le a.1
lemma lt_iff_val_lt_val : a < b ↔ a.val < b.val := iff.refl _
lemma le_iff_val_le_val : a ≤ b ↔ a.val ≤ b.val := iff.refl _
@[simp] lemma succ_val (j : fin n) : j.succ.val = j.val.succ :=
by cases j; simp [fin.succ]
protected theorem succ.inj (p : fin.succ a = fin.succ b) : a = b :=
by cases a; cases b; exact eq_of_veq (nat.succ.inj (veq_of_eq p))
@[simp] lemma pred_val (j : fin (n+1)) (h : j ≠ 0) : (j.pred h).val = j.val.pred :=
by cases j; simp [fin.pred]
@[simp] lemma succ_pred : ∀(i : fin (n+1)) (h : i ≠ 0), (i.pred h).succ = i
| ⟨0, h⟩ hi := by contradiction
| ⟨n + 1, h⟩ hi := rfl
@[simp] lemma pred_succ (i : fin n) {h : i.succ ≠ 0} : i.succ.pred h = i :=
by cases i; refl
@[simp] lemma pred_inj :
∀ {a b : fin (n + 1)} {ha : a ≠ 0} {hb : b ≠ 0}, a.pred ha = b.pred hb ↔ a = b
| ⟨0, _⟩ b ha hb := by contradiction
| ⟨i+1, _⟩ ⟨0, _⟩ ha hb := by contradiction
| ⟨i+1, hi⟩ ⟨j+1, hj⟩ ha hb := by simp [fin.eq_iff_veq]
/-- The greatest value of `fin (n+1)` -/
def last (n : ℕ) : fin (n+1) := ⟨_, n.lt_succ_self⟩
/-- `cast_lt i h` embeds `i` into a `fin` where `h` proves it belongs into. -/
def cast_lt (i : fin m) (h : i.1 < n) : fin n := ⟨i.1, h⟩
/-- `cast_le h i` embeds `i` into a larger `fin` type. -/
def cast_le (h : n ≤ m) (a : fin n) : fin m := cast_lt a (lt_of_lt_of_le a.2 h)
/-- `cast eq i` embeds `i` into a equal `fin` type. -/
def cast (eq : n = m): fin n → fin m := cast_le $ le_of_eq eq
/-- `cast_add m i` embedds `i` in `fin (n+m)`. -/
def cast_add (m) : fin n → fin (n + m) := cast_le $ le_add_right n m
/-- `cast_succ i` embedds `i` in `fin (n+1)`. -/
def cast_succ : fin n → fin (n + 1) := cast_add 1
/-- `succ_above p i` embeds into `fin (n + 1)` with a hole around `p`. -/
def succ_above (p : fin (n+1)) (i : fin n) : fin (n+1) :=
if i.1 < p.1 then i.cast_succ else i.succ
/-- `pred_above p i h` embeds `i` into `fin n` by ignoring `p`. -/
def pred_above (p : fin (n+1)) (i : fin (n+1)) (hi : i ≠ p) : fin n :=
if h : i < p
then i.cast_lt (lt_of_lt_of_le h $ nat.le_of_lt_succ p.2)
else i.pred $
have p < i, from lt_of_le_of_ne (le_of_not_gt h) hi.symm,
ne_of_gt (lt_of_le_of_lt (zero_le p) this)
/-- `sub_nat i h` subtracts `m` from `i`, generalizes `fin.pred`. -/
def sub_nat (m) (i : fin (n + m)) (h : i.val ≥ m) : fin n :=
⟨i.val - m, by simp [nat.sub_lt_right_iff_lt_add h, i.is_lt]⟩
/-- `add_nat i h` adds `m` on `i`, generalizes `fin.succ`. -/
def add_nat (m) (i : fin n) : fin (n + m) :=
⟨i.1 + m, add_lt_add_right i.2 _⟩
/-- `nat_add i h` adds `n` on `i` -/
def nat_add (n) {m} (i : fin m) : fin (n + m) :=
⟨n + i.1, add_lt_add_left i.2 _⟩
theorem le_last (i : fin (n+1)) : i ≤ last n :=
le_of_lt_succ i.is_lt
@[simp] lemma cast_succ_val (k : fin n) : k.cast_succ.val = k.val := rfl
@[simp] lemma cast_lt_val (k : fin m) (h : k.1 < n) : (k.cast_lt h).val = k.val := rfl
@[simp] lemma cast_succ_cast_lt (i : fin (n + 1)) (h : i.val < n): cast_succ (cast_lt i h) = i :=
fin.eq_of_veq rfl
@[simp] lemma sub_nat_val (i : fin (n + m)) (h : i.val ≥ m) : (i.sub_nat m h).val = i.val - m :=
rfl
@[simp] lemma add_nat_val (i : fin (n + m)) (h : i.val ≥ m) : (i.add_nat m).val = i.val + m :=
rfl
@[simp] lemma cast_succ_inj {a b : fin n} : a.cast_succ = b.cast_succ ↔ a = b :=
by simp [eq_iff_veq]
theorem succ_above_ne (p : fin (n+1)) (i : fin n) : p.succ_above i ≠ p :=
begin
assume eq,
unfold fin.succ_above at eq,
split_ifs at eq with h;
simpa [lt_irrefl, nat.lt_succ_self, eq.symm] using h
end
@[simp] lemma succ_above_descend : ∀(p i : fin (n+1)) (h : i ≠ p), p.succ_above (p.pred_above i h) = i
| ⟨p, hp⟩ ⟨0, hi⟩ h := fin.eq_of_veq $ by simp [succ_above, pred_above]; split_ifs; simp * at *
| ⟨p, hp⟩ ⟨i+1, hi⟩ h := fin.eq_of_veq
begin
have : i + 1 ≠ p, by rwa [(≠), fin.ext_iff] at h,
unfold succ_above pred_above,
split_ifs with h1 h2; simp at *,
exact (this (le_antisymm h2 (le_of_not_gt h1))).elim
end
@[simp] lemma pred_above_succ_above (p : fin (n+1)) (i : fin n) (h : p.succ_above i ≠ p) :
p.pred_above (p.succ_above i) h = i :=
begin
unfold fin.succ_above,
apply eq_of_veq,
split_ifs with h₀,
{ simp [pred_above, h₀, lt_iff_val_lt_val], },
{ unfold pred_above,
split_ifs with h₁,
{ exfalso,
rw [lt_iff_val_lt_val, succ_val] at h₁,
exact h₀ (lt_trans (nat.lt_succ_self _) h₁) },
{ rw [pred_succ] } }
end
section rec
@[elab_as_eliminator] def succ_rec
{C : ∀ n, fin n → Sort*}
(H0 : ∀ n, C (succ n) 0)
(Hs : ∀ n i, C n i → C (succ n) i.succ) : ∀ {n : ℕ} (i : fin n), C n i
| 0 i := i.elim0
| (succ n) ⟨0, _⟩ := H0 _
| (succ n) ⟨succ i, h⟩ := Hs _ _ (succ_rec ⟨i, lt_of_succ_lt_succ h⟩)
@[elab_as_eliminator] def succ_rec_on {n : ℕ} (i : fin n)
{C : ∀ n, fin n → Sort*}
(H0 : ∀ n, C (succ n) 0)
(Hs : ∀ n i, C n i → C (succ n) i.succ) : C n i :=
i.succ_rec H0 Hs
@[simp] theorem succ_rec_on_zero {C : ∀ n, fin n → Sort*} {H0 Hs} (n) :
@fin.succ_rec_on (succ n) 0 C H0 Hs = H0 n :=
rfl
@[simp] theorem succ_rec_on_succ {C : ∀ n, fin n → Sort*} {H0 Hs} {n} (i : fin n) :
@fin.succ_rec_on (succ n) i.succ C H0 Hs = Hs n i (fin.succ_rec_on i H0 Hs) :=
by cases i; refl
@[elab_as_eliminator] def cases
{C : fin (succ n) → Sort*} (H0 : C 0) (Hs : ∀ i : fin n, C (i.succ)) :
∀ (i : fin (succ n)), C i
| ⟨0, h⟩ := H0
| ⟨succ i, h⟩ := Hs ⟨i, lt_of_succ_lt_succ h⟩
@[simp] theorem cases_zero {n} {C : fin (succ n) → Sort*} {H0 Hs} : @fin.cases n C H0 Hs 0 = H0 :=
rfl
@[simp] theorem cases_succ {n} {C : fin (succ n) → Sort*} {H0 Hs} (i : fin n) :
@fin.cases n C H0 Hs i.succ = Hs i :=
by cases i; refl
end rec
end fin
|
778463ff0508260f5d24f4d6a0b530aabd3126c4 | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /stage0/src/Init/Data/UInt.lean | 22dec3dfc16a8518451ccc29069ba91ab97c2965 | [
"Apache-2.0"
] | permissive | collares/lean4 | 861a9269c4592bce49b71059e232ff0bfe4594cc | 52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee | refs/heads/master | 1,691,419,031,324 | 1,618,678,138,000 | 1,618,678,138,000 | 358,989,750 | 0 | 0 | Apache-2.0 | 1,618,696,333,000 | 1,618,696,333,000 | null | UTF-8 | Lean | false | false | 14,736 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Data.Fin.Basic
import Init.System.Platform
open Nat
@[extern "lean_uint8_of_nat"]
def UInt8.ofNat (n : @& Nat) : UInt8 := ⟨Fin.ofNat n⟩
abbrev Nat.toUInt8 := UInt8.ofNat
@[extern "lean_uint8_to_nat"]
def UInt8.toNat (n : UInt8) : Nat := n.val.val
@[extern c inline "#1 + #2"]
def UInt8.add (a b : UInt8) : UInt8 := ⟨a.val + b.val⟩
@[extern c inline "#1 - #2"]
def UInt8.sub (a b : UInt8) : UInt8 := ⟨a.val - b.val⟩
@[extern c inline "#1 * #2"]
def UInt8.mul (a b : UInt8) : UInt8 := ⟨a.val * b.val⟩
@[extern c inline "#2 == 0 ? 0 : #1 / #2"]
def UInt8.div (a b : UInt8) : UInt8 := ⟨a.val / b.val⟩
@[extern c inline "#2 == 0 ? #1 : #1 % #2"]
def UInt8.mod (a b : UInt8) : UInt8 := ⟨a.val % b.val⟩
@[extern "lean_uint8_modn"]
def UInt8.modn (a : UInt8) (n : @& Nat) : UInt8 := ⟨a.val % n⟩
@[extern c inline "#1 & #2"]
def UInt8.land (a b : UInt8) : UInt8 := ⟨Fin.land a.val b.val⟩
@[extern c inline "#1 | #2"]
def UInt8.lor (a b : UInt8) : UInt8 := ⟨Fin.lor a.val b.val⟩
@[extern c inline "#1 ^ #2"]
def UInt8.xor (a b : UInt8) : UInt8 := ⟨Fin.xor a.val b.val⟩
@[extern c inline "#1 << #2 % 8"]
def UInt8.shiftLeft (a b : UInt8) : UInt8 := ⟨a.val <<< (modn b 8).val⟩
@[extern c inline "#1 >> #2 % 8"]
def UInt8.shiftRight (a b : UInt8) : UInt8 := ⟨a.val >>> (modn b 8).val⟩
def UInt8.lt (a b : UInt8) : Prop := a.val < b.val
def UInt8.le (a b : UInt8) : Prop := a.val ≤ b.val
instance : OfNat UInt8 n := ⟨UInt8.ofNat n⟩
instance : Add UInt8 := ⟨UInt8.add⟩
instance : Sub UInt8 := ⟨UInt8.sub⟩
instance : Mul UInt8 := ⟨UInt8.mul⟩
instance : Mod UInt8 := ⟨UInt8.mod⟩
instance : HMod UInt8 Nat UInt8 := ⟨UInt8.modn⟩
instance : Div UInt8 := ⟨UInt8.div⟩
instance : HasLess UInt8 := ⟨UInt8.lt⟩
instance : HasLessEq UInt8 := ⟨UInt8.le⟩
@[extern c inline "~ #1"]
def UInt8.complement (a:UInt8) : UInt8 := 0-(a+1)
instance : Complement UInt8 := ⟨UInt8.complement⟩
instance : AndOp UInt8 := ⟨UInt8.land⟩
instance : OrOp UInt8 := ⟨UInt8.lor⟩
instance : Xor UInt8 := ⟨UInt8.xor⟩
instance : ShiftLeft UInt8 := ⟨UInt8.shiftLeft⟩
instance : ShiftRight UInt8 := ⟨UInt8.shiftRight⟩
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 < #2"]
def UInt8.decLt (a b : UInt8) : Decidable (a < b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m))
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 <= #2"]
def UInt8.decLe (a b : UInt8) : Decidable (a ≤ b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m))
instance (a b : UInt8) : Decidable (a < b) := UInt8.decLt a b
instance (a b : UInt8) : Decidable (a ≤ b) := UInt8.decLe a b
@[extern "lean_uint16_of_nat"]
def UInt16.ofNat (n : @& Nat) : UInt16 := ⟨Fin.ofNat n⟩
abbrev Nat.toUInt16 := UInt16.ofNat
@[extern "lean_uint16_to_nat"]
def UInt16.toNat (n : UInt16) : Nat := n.val.val
@[extern c inline "#1 + #2"]
def UInt16.add (a b : UInt16) : UInt16 := ⟨a.val + b.val⟩
@[extern c inline "#1 - #2"]
def UInt16.sub (a b : UInt16) : UInt16 := ⟨a.val - b.val⟩
@[extern c inline "#1 * #2"]
def UInt16.mul (a b : UInt16) : UInt16 := ⟨a.val * b.val⟩
@[extern c inline "#2 == 0 ? 0 : #1 / #2"]
def UInt16.div (a b : UInt16) : UInt16 := ⟨a.val / b.val⟩
@[extern c inline "#2 == 0 ? #1 : #1 % #2"]
def UInt16.mod (a b : UInt16) : UInt16 := ⟨a.val % b.val⟩
@[extern "lean_uint16_modn"]
def UInt16.modn (a : UInt16) (n : @& Nat) : UInt16 := ⟨a.val % n⟩
@[extern c inline "#1 & #2"]
def UInt16.land (a b : UInt16) : UInt16 := ⟨Fin.land a.val b.val⟩
@[extern c inline "#1 | #2"]
def UInt16.lor (a b : UInt16) : UInt16 := ⟨Fin.lor a.val b.val⟩
@[extern c inline "#1 ^ #2"]
def UInt16.xor (a b : UInt16) : UInt16 := ⟨Fin.xor a.val b.val⟩
@[extern c inline "#1 << #2 % 16"]
def UInt16.shiftLeft (a b : UInt16) : UInt16 := ⟨a.val <<< (modn b 16).val⟩
@[extern c inline "#1 >> #2 % 16"]
def UInt16.shiftRight (a b : UInt16) : UInt16 := ⟨a.val >>> (modn b 16).val⟩
def UInt16.lt (a b : UInt16) : Prop := a.val < b.val
def UInt16.le (a b : UInt16) : Prop := a.val ≤ b.val
instance : OfNat UInt16 n := ⟨UInt16.ofNat n⟩
instance : Add UInt16 := ⟨UInt16.add⟩
instance : Sub UInt16 := ⟨UInt16.sub⟩
instance : Mul UInt16 := ⟨UInt16.mul⟩
instance : Mod UInt16 := ⟨UInt16.mod⟩
instance : HMod UInt16 Nat UInt16 := ⟨UInt16.modn⟩
instance : Div UInt16 := ⟨UInt16.div⟩
instance : HasLess UInt16 := ⟨UInt16.lt⟩
instance : HasLessEq UInt16 := ⟨UInt16.le⟩
@[extern c inline "~ #1"]
def UInt16.complement (a:UInt16) : UInt16 := 0-(a+1)
instance : Complement UInt16 := ⟨UInt16.complement⟩
instance : AndOp UInt16 := ⟨UInt16.land⟩
instance : OrOp UInt16 := ⟨UInt16.lor⟩
instance : Xor UInt16 := ⟨UInt16.xor⟩
instance : ShiftLeft UInt16 := ⟨UInt16.shiftLeft⟩
instance : ShiftRight UInt16 := ⟨UInt16.shiftRight⟩
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 < #2"]
def UInt16.decLt (a b : UInt16) : Decidable (a < b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m))
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 <= #2"]
def UInt16.decLe (a b : UInt16) : Decidable (a ≤ b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m))
instance (a b : UInt16) : Decidable (a < b) := UInt16.decLt a b
instance (a b : UInt16) : Decidable (a ≤ b) := UInt16.decLe a b
@[extern "lean_uint32_of_nat"]
def UInt32.ofNat (n : @& Nat) : UInt32 := ⟨Fin.ofNat n⟩
@[extern "lean_uint32_of_nat"]
def UInt32.ofNat' (n : Nat) (h : n < UInt32.size) : UInt32 := ⟨⟨n, h⟩⟩
abbrev Nat.toUInt32 := UInt32.ofNat
@[extern c inline "#1 + #2"]
def UInt32.add (a b : UInt32) : UInt32 := ⟨a.val + b.val⟩
@[extern c inline "#1 - #2"]
def UInt32.sub (a b : UInt32) : UInt32 := ⟨a.val - b.val⟩
@[extern c inline "#1 * #2"]
def UInt32.mul (a b : UInt32) : UInt32 := ⟨a.val * b.val⟩
@[extern c inline "#2 == 0 ? 0 : #1 / #2"]
def UInt32.div (a b : UInt32) : UInt32 := ⟨a.val / b.val⟩
@[extern c inline "#2 == 0 ? #1 : #1 % #2"]
def UInt32.mod (a b : UInt32) : UInt32 := ⟨a.val % b.val⟩
@[extern "lean_uint32_modn"]
def UInt32.modn (a : UInt32) (n : @& Nat) : UInt32 := ⟨a.val % n⟩
@[extern c inline "#1 & #2"]
def UInt32.land (a b : UInt32) : UInt32 := ⟨Fin.land a.val b.val⟩
@[extern c inline "#1 | #2"]
def UInt32.lor (a b : UInt32) : UInt32 := ⟨Fin.lor a.val b.val⟩
@[extern c inline "#1 ^ #2"]
def UInt32.xor (a b : UInt32) : UInt32 := ⟨Fin.xor a.val b.val⟩
@[extern c inline "#1 << #2 % 32"]
def UInt32.shiftLeft (a b : UInt32) : UInt32 := ⟨a.val <<< (modn b 32).val⟩
@[extern c inline "#1 >> #2 % 32"]
def UInt32.shiftRight (a b : UInt32) : UInt32 := ⟨a.val >>> (modn b 32).val⟩
@[extern c inline "((uint8_t)#1)"]
def UInt32.toUInt8 (a : UInt32) : UInt8 := a.toNat.toUInt8
@[extern c inline "((uint16_t)#1)"]
def UInt32.toUInt16 (a : UInt32) : UInt16 := a.toNat.toUInt16
@[extern c inline "((uint32_t)#1)"]
def UInt8.toUInt32 (a : UInt8) : UInt32 := a.toNat.toUInt32
instance : OfNat UInt32 n := ⟨UInt32.ofNat n⟩
instance : Add UInt32 := ⟨UInt32.add⟩
instance : Sub UInt32 := ⟨UInt32.sub⟩
instance : Mul UInt32 := ⟨UInt32.mul⟩
instance : Mod UInt32 := ⟨UInt32.mod⟩
instance : HMod UInt32 Nat UInt32 := ⟨UInt32.modn⟩
instance : Div UInt32 := ⟨UInt32.div⟩
@[extern c inline "~ #1"]
def UInt32.complement (a:UInt32) : UInt32 := 0-(a+1)
instance : Complement UInt32 := ⟨UInt32.complement⟩
instance : AndOp UInt32 := ⟨UInt32.land⟩
instance : OrOp UInt32 := ⟨UInt32.lor⟩
instance : Xor UInt32 := ⟨UInt32.xor⟩
instance : ShiftLeft UInt32 := ⟨UInt32.shiftLeft⟩
instance : ShiftRight UInt32 := ⟨UInt32.shiftRight⟩
@[extern "lean_uint64_of_nat"]
def UInt64.ofNat (n : @& Nat) : UInt64 := ⟨Fin.ofNat n⟩
abbrev Nat.toUInt64 := UInt64.ofNat
@[extern "lean_uint64_to_nat"]
def UInt64.toNat (n : UInt64) : Nat := n.val.val
@[extern c inline "#1 + #2"]
def UInt64.add (a b : UInt64) : UInt64 := ⟨a.val + b.val⟩
@[extern c inline "#1 - #2"]
def UInt64.sub (a b : UInt64) : UInt64 := ⟨a.val - b.val⟩
@[extern c inline "#1 * #2"]
def UInt64.mul (a b : UInt64) : UInt64 := ⟨a.val * b.val⟩
@[extern c inline "#2 == 0 ? 0 : #1 / #2"]
def UInt64.div (a b : UInt64) : UInt64 := ⟨a.val / b.val⟩
@[extern c inline "#2 == 0 ? #1 : #1 % #2"]
def UInt64.mod (a b : UInt64) : UInt64 := ⟨a.val % b.val⟩
@[extern "lean_uint64_modn"]
def UInt64.modn (a : UInt64) (n : @& Nat) : UInt64 := ⟨a.val % n⟩
@[extern c inline "#1 & #2"]
def UInt64.land (a b : UInt64) : UInt64 := ⟨Fin.land a.val b.val⟩
@[extern c inline "#1 | #2"]
def UInt64.lor (a b : UInt64) : UInt64 := ⟨Fin.lor a.val b.val⟩
@[extern c inline "#1 ^ #2"]
def UInt64.xor (a b : UInt64) : UInt64 := ⟨Fin.xor a.val b.val⟩
@[extern c inline "#1 << #2 % 64"]
def UInt64.shiftLeft (a b : UInt64) : UInt64 := ⟨a.val <<< (modn b 64).val⟩
@[extern c inline "#1 >> #2 % 64"]
def UInt64.shiftRight (a b : UInt64) : UInt64 := ⟨a.val >>> (modn b 64).val⟩
def UInt64.lt (a b : UInt64) : Prop := a.val < b.val
def UInt64.le (a b : UInt64) : Prop := a.val ≤ b.val
@[extern c inline "((uint8_t)#1)"]
def UInt64.toUInt8 (a : UInt64) : UInt8 := a.toNat.toUInt8
@[extern c inline "((uint16_t)#1)"]
def UInt64.toUInt16 (a : UInt64) : UInt16 := a.toNat.toUInt16
@[extern c inline "((uint32_t)#1)"]
def UInt64.toUInt32 (a : UInt64) : UInt32 := a.toNat.toUInt32
@[extern c inline "((uint64_t)#1)"]
def UInt32.toUInt64 (a : UInt32) : UInt64 := a.toNat.toUInt64
instance : OfNat UInt64 n := ⟨UInt64.ofNat n⟩
instance : Add UInt64 := ⟨UInt64.add⟩
instance : Sub UInt64 := ⟨UInt64.sub⟩
instance : Mul UInt64 := ⟨UInt64.mul⟩
instance : Mod UInt64 := ⟨UInt64.mod⟩
instance : HMod UInt64 Nat UInt64 := ⟨UInt64.modn⟩
instance : Div UInt64 := ⟨UInt64.div⟩
instance : HasLess UInt64 := ⟨UInt64.lt⟩
instance : HasLessEq UInt64 := ⟨UInt64.le⟩
@[extern c inline "~ #1"]
def UInt64.complement (a:UInt64) : UInt64 := 0-(a+1)
instance : Complement UInt64 := ⟨UInt64.complement⟩
instance : AndOp UInt64 := ⟨UInt64.land⟩
instance : OrOp UInt64 := ⟨UInt64.lor⟩
instance : Xor UInt64 := ⟨UInt64.xor⟩
instance : ShiftLeft UInt64 := ⟨UInt64.shiftLeft⟩
instance : ShiftRight UInt64 := ⟨UInt64.shiftRight⟩
@[extern c inline "(uint64_t)#1"]
def Bool.toUInt64 (b : Bool) : UInt64 := if b then 1 else 0
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 < #2"]
def UInt64.decLt (a b : UInt64) : Decidable (a < b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m))
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 <= #2"]
def UInt64.decLe (a b : UInt64) : Decidable (a ≤ b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m))
instance (a b : UInt64) : Decidable (a < b) := UInt64.decLt a b
instance (a b : UInt64) : Decidable (a ≤ b) := UInt64.decLe a b
theorem usizeSzGt0 : USize.size > 0 :=
Nat.posPowOfPos System.Platform.numBits (Nat.zeroLtSucc _)
@[extern "lean_usize_of_nat"]
def USize.ofNat (n : @& Nat) : USize := ⟨Fin.ofNat' n usizeSzGt0⟩
abbrev Nat.toUSize := USize.ofNat
@[extern "lean_usize_to_nat"]
def USize.toNat (n : USize) : Nat := n.val.val
@[extern c inline "#1 + #2"]
def USize.add (a b : USize) : USize := ⟨a.val + b.val⟩
@[extern c inline "#1 - #2"]
def USize.sub (a b : USize) : USize := ⟨a.val - b.val⟩
@[extern c inline "#1 * #2"]
def USize.mul (a b : USize) : USize := ⟨a.val * b.val⟩
@[extern c inline "#2 == 0 ? 0 : #1 / #2"]
def USize.div (a b : USize) : USize := ⟨a.val / b.val⟩
@[extern c inline "#2 == 0 ? #1 : #1 % #2"]
def USize.mod (a b : USize) : USize := ⟨a.val % b.val⟩
@[extern "lean_usize_modn"]
def USize.modn (a : USize) (n : @& Nat) : USize := ⟨a.val % n⟩
@[extern c inline "#1 & #2"]
def USize.land (a b : USize) : USize := ⟨Fin.land a.val b.val⟩
@[extern c inline "#1 | #2"]
def USize.lor (a b : USize) : USize := ⟨Fin.lor a.val b.val⟩
@[extern c inline "#1 ^ #2"]
def USize.xor (a b : USize) : USize := ⟨Fin.xor a.val b.val⟩
@[extern c inline "#1 << #2 % (sizeof(size_t) * 8)"]
def USize.shiftLeft (a b : USize) : USize := ⟨a.val <<< (modn b System.Platform.numBits).val⟩
@[extern c inline "#1 >> #2 % (sizeof(size_t) * 8)"]
def USize.shiftRight (a b : USize) : USize := ⟨a.val >>> (modn b System.Platform.numBits).val⟩
@[extern c inline "#1"]
def UInt32.toUSize (a : UInt32) : USize := a.toNat.toUSize
@[extern c inline "((size_t)#1)"]
def UInt64.toUSize (a : UInt64) : USize := a.toNat.toUSize
@[extern c inline "(uint32_t)#1"]
def USize.toUInt32 (a : USize) : UInt32 := a.toNat.toUInt32
def USize.lt (a b : USize) : Prop := a.val < b.val
def USize.le (a b : USize) : Prop := a.val ≤ b.val
instance : OfNat USize n := ⟨USize.ofNat n⟩
instance : Add USize := ⟨USize.add⟩
instance : Sub USize := ⟨USize.sub⟩
instance : Mul USize := ⟨USize.mul⟩
instance : Mod USize := ⟨USize.mod⟩
instance : HMod USize Nat USize := ⟨USize.modn⟩
instance : Div USize := ⟨USize.div⟩
instance : HasLess USize := ⟨USize.lt⟩
instance : HasLessEq USize := ⟨USize.le⟩
@[extern c inline "~ #1"]
def USize.complement (a:USize) : USize := 0-(a+1)
instance : Complement USize := ⟨USize.complement⟩
instance : AndOp USize := ⟨USize.land⟩
instance : OrOp USize := ⟨USize.lor⟩
instance : Xor USize := ⟨USize.xor⟩
instance : ShiftLeft USize := ⟨USize.shiftLeft⟩
instance : ShiftRight USize := ⟨USize.shiftRight⟩
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 < #2"]
def USize.decLt (a b : USize) : Decidable (a < b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m))
set_option bootstrap.genMatcherCode false in
@[extern c inline "#1 <= #2"]
def USize.decLe (a b : USize) : Decidable (a ≤ b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m))
instance (a b : USize) : Decidable (a < b) := USize.decLt a b
instance (a b : USize) : Decidable (a ≤ b) := USize.decLe a b
theorem USize.modn_lt {m : Nat} : ∀ (u : USize), m > 0 → USize.toNat (u % m) < m
| ⟨u⟩, h => Fin.modn_lt u h
|
b944dd287129a9fdd95cc12370cf9e75c9b7b79c | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/ring_theory/power_series/basic.lean | 9dccb8f29dc3b8e58bfd5dd6e09f5f66a32ff8b3 | [
"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 | 64,452 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Kenny Lau
-/
import data.mv_polynomial
import linear_algebra.std_basis
import ring_theory.ideal.local_ring
import ring_theory.multiplicity
import ring_theory.algebra_tower
import tactic.linarith
import algebra.big_operators.nat_antidiagonal
/-!
# Formal power series
This file defines (multivariate) formal power series
and develops the basic properties of these objects.
A formal power series is to a polynomial like an infinite sum is to a finite sum.
We provide the natural inclusion from polynomials to formal power series.
## Generalities
The file starts with setting up the (semi)ring structure on multivariate power series.
`trunc n φ` truncates a formal power series to the polynomial
that has the same coefficients as `φ`, for all `m ≤ n`, and `0` otherwise.
If the constant coefficient of a formal power series is invertible,
then this formal power series is invertible.
Formal power series over a local ring form a local ring.
## Formal power series in one variable
We prove that if the ring of coefficients is an integral domain,
then formal power series in one variable form an integral domain.
The `order` of a formal power series `φ` is the multiplicity of the variable `X` in `φ`.
If the coefficients form an integral domain, then `order` is a valuation
(`order_mul`, `le_order_add`).
## Implementation notes
In this file we define multivariate formal power series with
variables indexed by `σ` and coefficients in `R` as
`mv_power_series σ R := (σ →₀ ℕ) → R`.
Unfortunately there is not yet enough API to show that they are the completion
of the ring of multivariate polynomials. However, we provide most of the infrastructure
that is needed to do this. Once I-adic completion (topological or algebraic) is available
it should not be hard to fill in the details.
Formal power series in one variable are defined as
`power_series R := mv_power_series unit R`.
This allows us to port a lot of proofs and properties
from the multivariate case to the single variable case.
However, it means that formal power series are indexed by `unit →₀ ℕ`,
which is of course canonically isomorphic to `ℕ`.
We then build some glue to treat formal power series as if they are indexed by `ℕ`.
Occasionally this leads to proofs that are uglier than expected.
-/
noncomputable theory
open_locale classical big_operators
/-- Multivariate formal power series, where `σ` is the index set of the variables
and `R` is the coefficient ring.-/
def mv_power_series (σ : Type*) (R : Type*) := (σ →₀ ℕ) → R
namespace mv_power_series
open finsupp
variables {σ R : Type*}
instance [inhabited R] : inhabited (mv_power_series σ R) := ⟨λ _, default _⟩
instance [has_zero R] : has_zero (mv_power_series σ R) := pi.has_zero
instance [add_monoid R] : add_monoid (mv_power_series σ R) := pi.add_monoid
instance [add_group R] : add_group (mv_power_series σ R) := pi.add_group
instance [add_comm_monoid R] : add_comm_monoid (mv_power_series σ R) := pi.add_comm_monoid
instance [add_comm_group R] : add_comm_group (mv_power_series σ R) := pi.add_comm_group
instance [nontrivial R] : nontrivial (mv_power_series σ R) := function.nontrivial
instance {A} [semiring R] [add_comm_monoid A] [module R A] :
module R (mv_power_series σ A) := pi.module _ _ _
instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [module R A] [module S A]
[has_scalar R S] [is_scalar_tower R S A] :
is_scalar_tower R S (mv_power_series σ A) :=
pi.is_scalar_tower
section semiring
variables (R) [semiring R]
/-- The `n`th monomial with coefficient `a` as multivariate formal power series.-/
def monomial (n : σ →₀ ℕ) : R →ₗ[R] mv_power_series σ R :=
linear_map.std_basis R _ n
/-- The `n`th coefficient of a multivariate formal power series.-/
def coeff (n : σ →₀ ℕ) : (mv_power_series σ R) →ₗ[R] R := linear_map.proj n
variables {R}
/-- Two multivariate formal power series are equal if all their coefficients are equal.-/
@[ext] lemma ext {φ ψ} (h : ∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) :
φ = ψ :=
funext h
/-- Two multivariate formal power series are equal
if and only if all their coefficients are equal.-/
lemma ext_iff {φ ψ : mv_power_series σ R} :
φ = ψ ↔ (∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) :=
function.funext_iff
lemma monomial_def [decidable_eq σ] (n : σ →₀ ℕ) :
monomial R n = linear_map.std_basis R _ n :=
by convert rfl -- unify the `decidable` arguments
lemma coeff_monomial [decidable_eq σ] (m n : σ →₀ ℕ) (a : R) :
coeff R m (monomial R n a) = if m = n then a else 0 :=
by rw [coeff, monomial_def, linear_map.proj_apply, linear_map.std_basis_apply,
function.update_apply, pi.zero_apply]
@[simp] lemma coeff_monomial_same (n : σ →₀ ℕ) (a : R) :
coeff R n (monomial R n a) = a :=
linear_map.std_basis_same R _ n a
lemma coeff_monomial_ne {m n : σ →₀ ℕ} (h : m ≠ n) (a : R) :
coeff R m (monomial R n a) = 0 :=
linear_map.std_basis_ne R _ _ _ h a
lemma eq_of_coeff_monomial_ne_zero {m n : σ →₀ ℕ} {a : R} (h : coeff R m (monomial R n a) ≠ 0) :
m = n :=
by_contra $ λ h', h $ coeff_monomial_ne h' a
@[simp] lemma coeff_comp_monomial (n : σ →₀ ℕ) :
(coeff R n).comp (monomial R n) = linear_map.id :=
linear_map.ext $ coeff_monomial_same n
@[simp] lemma coeff_zero (n : σ →₀ ℕ) : coeff R n (0 : mv_power_series σ R) = 0 := rfl
variables (m n : σ →₀ ℕ) (φ ψ : mv_power_series σ R)
instance : has_one (mv_power_series σ R) := ⟨monomial R (0 : σ →₀ ℕ) 1⟩
lemma coeff_one [decidable_eq σ] :
coeff R n (1 : mv_power_series σ R) = if n = 0 then 1 else 0 :=
coeff_monomial _ _ _
lemma coeff_zero_one : coeff R (0 : σ →₀ ℕ) 1 = 1 :=
coeff_monomial_same 0 1
lemma monomial_zero_one : monomial R (0 : σ →₀ ℕ) 1 = 1 := rfl
instance : has_mul (mv_power_series σ R) :=
⟨λ φ ψ n, ∑ p in finsupp.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ⟩
lemma coeff_mul : coeff R n (φ * ψ) =
∑ p in finsupp.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ := rfl
protected lemma zero_mul : (0 : mv_power_series σ R) * φ = 0 :=
ext $ λ n, by simp [coeff_mul]
protected lemma mul_zero : φ * 0 = 0 :=
ext $ λ n, by simp [coeff_mul]
lemma coeff_monomial_mul (a : R) :
coeff R m (monomial R n a * φ) = if n ≤ m then a * coeff R (m - n) φ else 0 :=
begin
have : ∀ p ∈ antidiagonal m,
coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 (monomial R n a) * coeff R p.2 φ ≠ 0 → p.1 = n :=
λ p _ hp, eq_of_coeff_monomial_ne_zero (left_ne_zero_of_mul hp),
rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_filter_fst_eq,
finset.sum_ite_index],
simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty]
end
lemma coeff_mul_monomial (a : R) :
coeff R m (φ * monomial R n a) = if n ≤ m then coeff R (m - n) φ * a else 0 :=
begin
have : ∀ p ∈ antidiagonal m,
coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 φ * coeff R p.2 (monomial R n a) ≠ 0 → p.2 = n :=
λ p _ hp, eq_of_coeff_monomial_ne_zero (right_ne_zero_of_mul hp),
rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_filter_snd_eq,
finset.sum_ite_index],
simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty]
end
lemma coeff_add_monomial_mul (a : R) :
coeff R (m + n) (monomial R m a * φ) = a * coeff R n φ :=
begin
rw [coeff_monomial_mul, if_pos, add_tsub_cancel_left],
exact le_add_right le_rfl
end
lemma coeff_add_mul_monomial (a : R) :
coeff R (m + n) (φ * monomial R n a) = coeff R m φ * a :=
begin
rw [coeff_mul_monomial, if_pos, add_tsub_cancel_right],
exact le_add_left le_rfl
end
protected lemma one_mul : (1 : mv_power_series σ R) * φ = φ :=
ext $ λ n, by simpa using coeff_add_monomial_mul 0 n φ 1
protected lemma mul_one : φ * 1 = φ :=
ext $ λ n, by simpa using coeff_add_mul_monomial n 0 φ 1
protected lemma mul_add (φ₁ φ₂ φ₃ : mv_power_series σ R) :
φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ :=
ext $ λ n, by simp only [coeff_mul, mul_add, finset.sum_add_distrib, linear_map.map_add]
protected lemma add_mul (φ₁ φ₂ φ₃ : mv_power_series σ R) :
(φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ :=
ext $ λ n, by simp only [coeff_mul, add_mul, finset.sum_add_distrib, linear_map.map_add]
protected lemma mul_assoc (φ₁ φ₂ φ₃ : mv_power_series σ R) :
(φ₁ * φ₂) * φ₃ = φ₁ * (φ₂ * φ₃) :=
begin
ext1 n,
simp only [coeff_mul, finset.sum_mul, finset.mul_sum, finset.sum_sigma'],
refine finset.sum_bij (λ p _, ⟨(p.2.1, p.2.2 + p.1.2), (p.2.2, p.1.2)⟩) _ _ _ _;
simp only [mem_antidiagonal, finset.mem_sigma, heq_iff_eq, prod.mk.inj_iff, and_imp,
exists_prop],
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩, dsimp only, rintro rfl rfl,
simp [add_assoc] },
{ rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩, dsimp only, rintro rfl rfl,
apply mul_assoc },
{ rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩ ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl - rfl rfl - rfl rfl,
refl },
{ rintro ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl,
refine ⟨⟨(i + k, l), (i, k)⟩, _, _⟩; simp [add_assoc] }
end
instance : semiring (mv_power_series σ R) :=
{ mul_one := mv_power_series.mul_one,
one_mul := mv_power_series.one_mul,
mul_assoc := mv_power_series.mul_assoc,
mul_zero := mv_power_series.mul_zero,
zero_mul := mv_power_series.zero_mul,
left_distrib := mv_power_series.mul_add,
right_distrib := mv_power_series.add_mul,
.. mv_power_series.has_one,
.. mv_power_series.has_mul,
.. mv_power_series.add_comm_monoid }
end semiring
instance [comm_semiring R] : comm_semiring (mv_power_series σ R) :=
{ mul_comm := λ φ ψ, ext $ λ n, by simpa only [coeff_mul, mul_comm]
using sum_antidiagonal_swap n (λ a b, coeff R a φ * coeff R b ψ),
.. mv_power_series.semiring }
instance [ring R] : ring (mv_power_series σ R) :=
{ .. mv_power_series.semiring,
.. mv_power_series.add_comm_group }
instance [comm_ring R] : comm_ring (mv_power_series σ R) :=
{ .. mv_power_series.comm_semiring,
.. mv_power_series.add_comm_group }
section semiring
variables [semiring R]
lemma monomial_mul_monomial (m n : σ →₀ ℕ) (a b : R) :
monomial R m a * monomial R n b = monomial R (m + n) (a * b) :=
begin
ext k,
simp only [coeff_mul_monomial, coeff_monomial],
split_ifs with h₁ h₂ h₃ h₃ h₂; try { refl },
{ rw [← h₂, tsub_add_cancel_of_le h₁] at h₃, exact (h₃ rfl).elim },
{ rw [h₃, add_tsub_cancel_right] at h₂, exact (h₂ rfl).elim },
{ exact zero_mul b },
{ rw h₂ at h₁, exact (h₁ $ le_add_left le_rfl).elim }
end
variables (σ) (R)
/-- The constant multivariate formal power series.-/
def C : R →+* mv_power_series σ R :=
{ map_one' := rfl,
map_mul' := λ a b, (monomial_mul_monomial 0 0 a b).symm,
map_zero' := (monomial R (0 : _)).map_zero,
.. monomial R (0 : σ →₀ ℕ) }
variables {σ} {R}
@[simp] lemma monomial_zero_eq_C : ⇑(monomial R (0 : σ →₀ ℕ)) = C σ R := rfl
lemma monomial_zero_eq_C_apply (a : R) : monomial R (0 : σ →₀ ℕ) a = C σ R a := rfl
lemma coeff_C [decidable_eq σ] (n : σ →₀ ℕ) (a : R) :
coeff R n (C σ R a) = if n = 0 then a else 0 :=
coeff_monomial _ _ _
lemma coeff_zero_C (a : R) : coeff R (0 : σ →₀ℕ) (C σ R a) = a :=
coeff_monomial_same 0 a
/-- The variables of the multivariate formal power series ring.-/
def X (s : σ) : mv_power_series σ R := monomial R (single s 1) 1
lemma coeff_X [decidable_eq σ] (n : σ →₀ ℕ) (s : σ) :
coeff R n (X s : mv_power_series σ R) = if n = (single s 1) then 1 else 0 :=
coeff_monomial _ _ _
lemma coeff_index_single_X [decidable_eq σ] (s t : σ) :
coeff R (single t 1) (X s : mv_power_series σ R) = if t = s then 1 else 0 :=
by { simp only [coeff_X, single_left_inj one_ne_zero], split_ifs; refl }
@[simp] lemma coeff_index_single_self_X (s : σ) :
coeff R (single s 1) (X s : mv_power_series σ R) = 1 :=
coeff_monomial_same _ _
lemma coeff_zero_X (s : σ) : coeff R (0 : σ →₀ ℕ) (X s : mv_power_series σ R) = 0 :=
by { rw [coeff_X, if_neg], intro h, exact one_ne_zero (single_eq_zero.mp h.symm) }
lemma X_def (s : σ) : X s = monomial R (single s 1) 1 := rfl
lemma X_pow_eq (s : σ) (n : ℕ) :
(X s : mv_power_series σ R)^n = monomial R (single s n) 1 :=
begin
induction n with n ih,
{ rw [pow_zero, finsupp.single_zero, monomial_zero_one] },
{ rw [pow_succ', ih, nat.succ_eq_add_one, finsupp.single_add, X, monomial_mul_monomial, one_mul] }
end
lemma coeff_X_pow [decidable_eq σ] (m : σ →₀ ℕ) (s : σ) (n : ℕ) :
coeff R m ((X s : mv_power_series σ R)^n) = if m = single s n then 1 else 0 :=
by rw [X_pow_eq s n, coeff_monomial]
@[simp] lemma coeff_mul_C (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) :
coeff R n (φ * C σ R a) = coeff R n φ * a :=
by simpa using coeff_add_mul_monomial n 0 φ a
@[simp] lemma coeff_C_mul (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) :
coeff R n (C σ R a * φ) = a * coeff R n φ :=
by simpa using coeff_add_monomial_mul 0 n φ a
lemma coeff_zero_mul_X (φ : mv_power_series σ R) (s : σ) :
coeff R (0 : σ →₀ ℕ) (φ * X s) = 0 :=
begin
have : ¬single s 1 ≤ 0, from λ h, by simpa using h s,
simp only [X, coeff_mul_monomial, if_neg this]
end
lemma coeff_zero_X_mul (φ : mv_power_series σ R) (s : σ) :
coeff R (0 : σ →₀ ℕ) (X s * φ) = 0 :=
begin
have : ¬single s 1 ≤ 0, from λ h, by simpa using h s,
simp only [X, coeff_monomial_mul, if_neg this]
end
variables (σ) (R)
/-- The constant coefficient of a formal power series.-/
def constant_coeff : (mv_power_series σ R) →+* R :=
{ to_fun := coeff R (0 : σ →₀ ℕ),
map_one' := coeff_zero_one,
map_mul' := λ φ ψ, by simp [coeff_mul, support_single_ne_zero],
map_zero' := linear_map.map_zero _,
.. coeff R (0 : σ →₀ ℕ) }
variables {σ} {R}
@[simp] lemma coeff_zero_eq_constant_coeff :
⇑(coeff R (0 : σ →₀ ℕ)) = constant_coeff σ R := rfl
lemma coeff_zero_eq_constant_coeff_apply (φ : mv_power_series σ R) :
coeff R (0 : σ →₀ ℕ) φ = constant_coeff σ R φ := rfl
@[simp] lemma constant_coeff_C (a : R) : constant_coeff σ R (C σ R a) = a := rfl
@[simp] lemma constant_coeff_comp_C :
(constant_coeff σ R).comp (C σ R) = ring_hom.id R := rfl
@[simp] lemma constant_coeff_zero : constant_coeff σ R 0 = 0 := rfl
@[simp] lemma constant_coeff_one : constant_coeff σ R 1 = 1 := rfl
@[simp] lemma constant_coeff_X (s : σ) : constant_coeff σ R (X s) = 0 := coeff_zero_X s
/-- If a multivariate formal power series is invertible,
then so is its constant coefficient.-/
lemma is_unit_constant_coeff (φ : mv_power_series σ R) (h : is_unit φ) :
is_unit (constant_coeff σ R φ) :=
h.map (constant_coeff σ R).to_monoid_hom
@[simp]
lemma coeff_smul (f : mv_power_series σ R) (n) (a : R) :
coeff _ n (a • f) = a * coeff _ n f :=
rfl
lemma X_inj [nontrivial R] {s t : σ} : (X s : mv_power_series σ R) = X t ↔ s = t :=
⟨begin
intro h, replace h := congr_arg (coeff R (single s 1)) h, rw [coeff_X, if_pos rfl, coeff_X] at h,
split_ifs at h with H,
{ rw finsupp.single_eq_single_iff at H,
cases H, { exact H.1 }, { exfalso, exact one_ne_zero H.1 } },
{ exfalso, exact one_ne_zero h }
end, congr_arg X⟩
end semiring
section map
variables {S T : Type*} [semiring R] [semiring S] [semiring T]
variables (f : R →+* S) (g : S →+* T)
variable (σ)
/-- The map between multivariate formal power series induced by a map on the coefficients.-/
def map : mv_power_series σ R →+* mv_power_series σ S :=
{ to_fun := λ φ n, f $ coeff R n φ,
map_zero' := ext $ λ n, f.map_zero,
map_one' := ext $ λ n, show f ((coeff R n) 1) = (coeff S n) 1,
by { rw [coeff_one, coeff_one], split_ifs; simp [f.map_one, f.map_zero] },
map_add' := λ φ ψ, ext $ λ n,
show f ((coeff R n) (φ + ψ)) = f ((coeff R n) φ) + f ((coeff R n) ψ), by simp,
map_mul' := λ φ ψ, ext $ λ n, show f _ = _,
begin
rw [coeff_mul, f.map_sum, coeff_mul, finset.sum_congr rfl],
rintros ⟨i,j⟩ hij, rw [f.map_mul], refl,
end }
variable {σ}
@[simp] lemma map_id : map σ (ring_hom.id R) = ring_hom.id _ := rfl
lemma map_comp : map σ (g.comp f) = (map σ g).comp (map σ f) := rfl
@[simp] lemma coeff_map (n : σ →₀ ℕ) (φ : mv_power_series σ R) :
coeff S n (map σ f φ) = f (coeff R n φ) := rfl
@[simp] lemma constant_coeff_map (φ : mv_power_series σ R) :
constant_coeff σ S (map σ f φ) = f (constant_coeff σ R φ) := rfl
@[simp] lemma map_monomial (n : σ →₀ ℕ) (a : R) :
map σ f (monomial R n a) = monomial S n (f a) :=
by { ext m, simp [coeff_monomial, apply_ite f] }
@[simp] lemma map_C (a : R) : map σ f (C σ R a) = C σ S (f a) :=
map_monomial _ _ _
@[simp] lemma map_X (s : σ) : map σ f (X s) = X s := by simp [X]
end map
section algebra
variables {A : Type*} [comm_semiring R] [semiring A] [algebra R A]
instance : algebra R (mv_power_series σ A) :=
{ commutes' := λ a φ, by { ext n, simp [algebra.commutes] },
smul_def' := λ a σ, by { ext n, simp [(coeff A n).map_smul_of_tower a, algebra.smul_def] },
to_ring_hom := (mv_power_series.map σ (algebra_map R A)).comp (C σ R),
.. mv_power_series.module }
theorem C_eq_algebra_map : C σ R = (algebra_map R (mv_power_series σ R)) := rfl
theorem algebra_map_apply {r : R} :
algebra_map R (mv_power_series σ A) r = C σ A (algebra_map R A r) :=
begin
change (mv_power_series.map σ (algebra_map R A)).comp (C σ R) r = _,
simp,
end
instance [nonempty σ] [nontrivial R] : nontrivial (subalgebra R (mv_power_series σ R)) :=
⟨⟨⊥, ⊤, begin
rw [ne.def, set_like.ext_iff, not_forall],
inhabit σ,
refine ⟨X (default σ), _⟩,
simp only [algebra.mem_bot, not_exists, set.mem_range, iff_true, algebra.mem_top],
intros x,
rw [ext_iff, not_forall],
refine ⟨finsupp.single (default σ) 1, _⟩,
simp [algebra_map_apply, coeff_C],
end⟩⟩
end algebra
section trunc
variables [comm_semiring R] (n : σ →₀ ℕ)
/-- Auxiliary definition for the truncation function. -/
def trunc_fun (φ : mv_power_series σ R) : mv_polynomial σ R :=
∑ m in Iic_finset n, mv_polynomial.monomial m (coeff R m φ)
lemma coeff_trunc_fun (m : σ →₀ ℕ) (φ : mv_power_series σ R) :
(trunc_fun n φ).coeff m = if m ≤ n then coeff R m φ else 0 :=
by simp [trunc_fun, mv_polynomial.coeff_sum]
variable (R)
/-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/
def trunc : mv_power_series σ R →+ mv_polynomial σ R :=
{ to_fun := trunc_fun n,
map_zero' := by { ext, simp [coeff_trunc_fun] },
map_add' := by { intros, ext, simp [coeff_trunc_fun, ite_add], split_ifs; refl } }
variable {R}
lemma coeff_trunc (m : σ →₀ ℕ) (φ : mv_power_series σ R) :
(trunc R n φ).coeff m = if m ≤ n then coeff R m φ else 0 :=
by simp [trunc, coeff_trunc_fun]
@[simp] lemma trunc_one : trunc R n 1 = 1 :=
mv_polynomial.ext _ _ $ λ m,
begin
rw [coeff_trunc, coeff_one],
split_ifs with H H' H',
{ subst m, simp },
{ symmetry, rw mv_polynomial.coeff_one, exact if_neg (ne.symm H'), },
{ symmetry, rw mv_polynomial.coeff_one, refine if_neg _,
intro H', apply H, subst m, intro s, exact nat.zero_le _ }
end
@[simp] lemma trunc_C (a : R) : trunc R n (C σ R a) = mv_polynomial.C a :=
mv_polynomial.ext _ _ $ λ m,
begin
rw [coeff_trunc, coeff_C, mv_polynomial.coeff_C],
split_ifs with H; refl <|> try {simp * at *},
exfalso, apply H, subst m, intro s, exact nat.zero_le _
end
end trunc
section comm_semiring
variable [comm_semiring R]
lemma X_pow_dvd_iff {s : σ} {n : ℕ} {φ : mv_power_series σ R} :
(X s : mv_power_series σ R)^n ∣ φ ↔ ∀ m : σ →₀ ℕ, m s < n → coeff R m φ = 0 :=
begin
split,
{ rintros ⟨φ, rfl⟩ m h,
rw [coeff_mul, finset.sum_eq_zero],
rintros ⟨i,j⟩ hij, rw [coeff_X_pow, if_neg, zero_mul],
contrapose! h, subst i, rw finsupp.mem_antidiagonal at hij,
rw [← hij, finsupp.add_apply, finsupp.single_eq_same], exact nat.le_add_right n _ },
{ intro h, refine ⟨λ m, coeff R (m + (single s n)) φ, _⟩,
ext m, by_cases H : m - single s n + single s n = m,
{ rw [coeff_mul, finset.sum_eq_single (single s n, m - single s n)],
{ rw [coeff_X_pow, if_pos rfl, one_mul],
simpa using congr_arg (λ (m : σ →₀ ℕ), coeff R m φ) H.symm },
{ rintros ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal at hij,
rw coeff_X_pow, split_ifs with hi,
{ exfalso, apply hne, rw [← hij, ← hi, prod.mk.inj_iff], refine ⟨rfl, _⟩,
ext t, simp only [add_tsub_cancel_left, finsupp.add_apply, finsupp.tsub_apply] },
{ exact zero_mul _ } },
{ intro hni, exfalso, apply hni, rwa [finsupp.mem_antidiagonal, add_comm] } },
{ rw [h, coeff_mul, finset.sum_eq_zero],
{ rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal at hij,
rw coeff_X_pow, split_ifs with hi,
{ exfalso, apply H, rw [← hij, hi], ext,
rw [coe_add, coe_add, pi.add_apply, pi.add_apply, add_tsub_cancel_left, add_comm], },
{ exact zero_mul _ } },
{ classical, contrapose! H, ext t,
by_cases hst : s = t,
{ subst t, simpa using tsub_add_cancel_of_le H },
{ simp [finsupp.single_apply, hst] } } } }
end
lemma X_dvd_iff {s : σ} {φ : mv_power_series σ R} :
(X s : mv_power_series σ R) ∣ φ ↔ ∀ m : σ →₀ ℕ, m s = 0 → coeff R m φ = 0 :=
begin
rw [← pow_one (X s : mv_power_series σ R), X_pow_dvd_iff],
split; intros h m hm,
{ exact h m (hm.symm ▸ zero_lt_one) },
{ exact h m (nat.eq_zero_of_le_zero $ nat.le_of_succ_le_succ hm) }
end
end comm_semiring
section ring
variables [ring R]
/-
The inverse of a multivariate formal power series is defined by
well-founded recursion on the coeffients of the inverse.
-/
/-- Auxiliary definition that unifies
the totalised inverse formal power series `(_)⁻¹` and
the inverse formal power series that depends on
an inverse of the constant coefficient `inv_of_unit`.-/
protected noncomputable def inv.aux (a : R) (φ : mv_power_series σ R) : mv_power_series σ R
| n := if n = 0 then a else
- a * ∑ x in n.antidiagonal,
if h : x.2 < n then coeff R x.1 φ * inv.aux x.2 else 0
using_well_founded
{ rel_tac := λ _ _, `[exact ⟨_, finsupp.lt_wf σ⟩],
dec_tac := tactic.assumption }
lemma coeff_inv_aux [decidable_eq σ] (n : σ →₀ ℕ) (a : R) (φ : mv_power_series σ R) :
coeff R n (inv.aux a φ) = if n = 0 then a else
- a * ∑ x in n.antidiagonal,
if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 :=
show inv.aux a φ n = _,
begin
rw inv.aux,
convert rfl -- unify `decidable` instances
end
/-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/
def inv_of_unit (φ : mv_power_series σ R) (u : units R) : mv_power_series σ R :=
inv.aux (↑u⁻¹) φ
lemma coeff_inv_of_unit [decidable_eq σ] (n : σ →₀ ℕ) (φ : mv_power_series σ R) (u : units R) :
coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else
- ↑u⁻¹ * ∑ x in n.antidiagonal,
if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 :=
coeff_inv_aux n (↑u⁻¹) φ
@[simp] lemma constant_coeff_inv_of_unit (φ : mv_power_series σ R) (u : units R) :
constant_coeff σ R (inv_of_unit φ u) = ↑u⁻¹ :=
by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl]
lemma mul_inv_of_unit (φ : mv_power_series σ R) (u : units R) (h : constant_coeff σ R φ = u) :
φ * inv_of_unit φ u = 1 :=
ext $ λ n, if H : n = 0 then by { rw H, simp [coeff_mul, support_single_ne_zero, h], }
else
begin
have : ((0 : σ →₀ ℕ), n) ∈ n.antidiagonal,
{ rw [finsupp.mem_antidiagonal, zero_add] },
rw [coeff_one, if_neg H, coeff_mul,
← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _),
coeff_zero_eq_constant_coeff_apply, h, coeff_inv_of_unit, if_neg H,
neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, units.mul_inv_cancel_left,
← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _),
finset.insert_erase this, if_neg (not_lt_of_ge $ le_refl _), zero_add, add_comm,
← sub_eq_add_neg, sub_eq_zero, finset.sum_congr rfl],
rintros ⟨i,j⟩ hij, rw [finset.mem_erase, finsupp.mem_antidiagonal] at hij,
cases hij with h₁ h₂,
subst n, rw if_pos,
suffices : (0 : _) + j < i + j, {simpa},
apply add_lt_add_right,
split,
{ intro s, exact nat.zero_le _ },
{ intro H, apply h₁,
suffices : i = 0, {simp [this]},
ext1 s, exact nat.eq_zero_of_le_zero (H s) }
end
end ring
section comm_ring
variable [comm_ring R]
/-- Multivariate formal power series over a local ring form a local ring. -/
instance is_local_ring [local_ring R] : local_ring (mv_power_series σ R) :=
{ is_local := by { intro φ, rcases local_ring.is_local (constant_coeff σ R φ) with ⟨u,h⟩|⟨u,h⟩;
[left, right];
{ refine is_unit_of_mul_eq_one _ _ (mul_inv_of_unit _ u _),
simpa using h.symm } } }
-- TODO(jmc): once adic topology lands, show that this is complete
end comm_ring
section local_ring
variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S)
[is_local_ring_hom f]
-- Thanks to the linter for informing us that this instance does
-- not actually need R and S to be local rings!
/-- The map `A[[X]] → B[[X]]` induced by a local ring hom `A → B` is local -/
instance map.is_local_ring_hom : is_local_ring_hom (map σ f) :=
⟨begin
rintros φ ⟨ψ, h⟩,
replace h := congr_arg (constant_coeff σ S) h,
rw constant_coeff_map at h,
have : is_unit (constant_coeff σ S ↑ψ) := @is_unit_constant_coeff σ S _ (↑ψ) ψ.is_unit,
rw h at this,
rcases is_unit_of_map_unit f _ this with ⟨c, hc⟩,
exact is_unit_of_mul_eq_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c hc.symm)
end⟩
variables [local_ring R] [local_ring S]
instance : local_ring (mv_power_series σ R) :=
{ is_local := local_ring.is_local }
end local_ring
section field
variables {k : Type*} [field k]
/-- The inverse `1/f` of a multivariable power series `f` over a field -/
protected def inv (φ : mv_power_series σ k) : mv_power_series σ k :=
inv.aux (constant_coeff σ k φ)⁻¹ φ
instance : has_inv (mv_power_series σ k) := ⟨mv_power_series.inv⟩
lemma coeff_inv [decidable_eq σ] (n : σ →₀ ℕ) (φ : mv_power_series σ k) :
coeff k n (φ⁻¹) = if n = 0 then (constant_coeff σ k φ)⁻¹ else
- (constant_coeff σ k φ)⁻¹ * ∑ x in n.antidiagonal,
if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 :=
coeff_inv_aux n _ φ
@[simp] lemma constant_coeff_inv (φ : mv_power_series σ k) :
constant_coeff σ k (φ⁻¹) = (constant_coeff σ k φ)⁻¹ :=
by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv, if_pos rfl]
lemma inv_eq_zero {φ : mv_power_series σ k} :
φ⁻¹ = 0 ↔ constant_coeff σ k φ = 0 :=
⟨λ h, by simpa using congr_arg (constant_coeff σ k) h,
λ h, ext $ λ n, by { rw coeff_inv, split_ifs;
simp only [h, mv_power_series.coeff_zero, zero_mul, inv_zero, neg_zero] }⟩
@[simp, priority 1100]
lemma inv_of_unit_eq (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) :
inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl
@[simp]
lemma inv_of_unit_eq' (φ : mv_power_series σ k) (u : units k) (h : constant_coeff σ k φ = u) :
inv_of_unit φ u = φ⁻¹ :=
begin
rw ← inv_of_unit_eq φ (h.symm ▸ u.ne_zero),
congr' 1, rw [units.ext_iff], exact h.symm,
end
@[simp] protected lemma mul_inv (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) :
φ * φ⁻¹ = 1 :=
by rw [← inv_of_unit_eq φ h, mul_inv_of_unit φ (units.mk0 _ h) rfl]
@[simp] protected lemma inv_mul (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) :
φ⁻¹ * φ = 1 :=
by rw [mul_comm, φ.mul_inv h]
protected lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : mv_power_series σ k}
(h : constant_coeff σ k φ₃ ≠ 0) :
φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ :=
⟨λ k, by simp [k, mul_assoc, mv_power_series.inv_mul _ h],
λ k, by simp [← k, mul_assoc, mv_power_series.mul_inv _ h]⟩
protected lemma eq_inv_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) :
φ = ψ⁻¹ ↔ φ * ψ = 1 :=
by rw [← mv_power_series.eq_mul_inv_iff_mul_eq h, one_mul]
protected lemma inv_eq_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) :
ψ⁻¹ = φ ↔ φ * ψ = 1 :=
by rw [eq_comm, mv_power_series.eq_inv_iff_mul_eq_one h]
end field
end mv_power_series
namespace mv_polynomial
open finsupp
variables {σ : Type*} {R : Type*} [comm_semiring R]
/-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/
instance coe_to_mv_power_series : has_coe (mv_polynomial σ R) (mv_power_series σ R) :=
⟨λ φ n, coeff n φ⟩
@[simp, norm_cast] lemma coeff_coe (φ : mv_polynomial σ R) (n : σ →₀ ℕ) :
mv_power_series.coeff R n ↑φ = coeff n φ := rfl
@[simp, norm_cast] lemma coe_monomial (n : σ →₀ ℕ) (a : R) :
(monomial n a : mv_power_series σ R) = mv_power_series.monomial R n a :=
mv_power_series.ext $ λ m,
begin
rw [coeff_coe, coeff_monomial, mv_power_series.coeff_monomial],
split_ifs with h₁ h₂; refl <|> subst m; contradiction
end
@[simp, norm_cast] lemma coe_zero : ((0 : mv_polynomial σ R) : mv_power_series σ R) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : mv_polynomial σ R) : mv_power_series σ R) = 1 :=
coe_monomial _ _
@[simp, norm_cast] lemma coe_add (φ ψ : mv_polynomial σ R) :
((φ + ψ : mv_polynomial σ R) : mv_power_series σ R) = φ + ψ := rfl
@[simp, norm_cast] lemma coe_mul (φ ψ : mv_polynomial σ R) :
((φ * ψ : mv_polynomial σ R) : mv_power_series σ R) = φ * ψ :=
mv_power_series.ext $ λ n,
by simp only [coeff_coe, mv_power_series.coeff_mul, coeff_mul]
@[simp, norm_cast] lemma coe_C (a : R) :
((C a : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.C σ R a :=
coe_monomial _ _
@[simp, norm_cast] lemma coe_X (s : σ) :
((X s : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.X s :=
coe_monomial _ _
/--
The coercion from multivariable polynomials to multivariable power series
as a ring homomorphism.
-/
-- TODO as an algebra homomorphism?
def coe_to_mv_power_series.ring_hom : mv_polynomial σ R →+* mv_power_series σ R :=
{ to_fun := (coe : mv_polynomial σ R → mv_power_series σ R),
map_zero' := coe_zero,
map_one' := coe_one,
map_add' := coe_add,
map_mul' := coe_mul }
end mv_polynomial
/-- Formal power series over the coefficient ring `R`.-/
def power_series (R : Type*) := mv_power_series unit R
namespace power_series
open finsupp (single)
variable {R : Type*}
section
local attribute [reducible] power_series
instance [inhabited R] : inhabited (power_series R) := by apply_instance
instance [add_monoid R] : add_monoid (power_series R) := by apply_instance
instance [add_group R] : add_group (power_series R) := by apply_instance
instance [add_comm_monoid R] : add_comm_monoid (power_series R) := by apply_instance
instance [add_comm_group R] : add_comm_group (power_series R) := by apply_instance
instance [semiring R] : semiring (power_series R) := by apply_instance
instance [comm_semiring R] : comm_semiring (power_series R) := by apply_instance
instance [ring R] : ring (power_series R) := by apply_instance
instance [comm_ring R] : comm_ring (power_series R) := by apply_instance
instance [nontrivial R] : nontrivial (power_series R) := by apply_instance
instance {A} [semiring R] [add_comm_monoid A] [module R A] :
module R (power_series A) := by apply_instance
instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [module R A] [module S A]
[has_scalar R S] [is_scalar_tower R S A] :
is_scalar_tower R S (power_series A) :=
pi.is_scalar_tower
instance {A} [semiring A] [comm_semiring R] [algebra R A] :
algebra R (power_series A) := by apply_instance
end
section semiring
variables (R) [semiring R]
/-- The `n`th coefficient of a formal power series.-/
def coeff (n : ℕ) : power_series R →ₗ[R] R := mv_power_series.coeff R (single () n)
/-- The `n`th monomial with coefficient `a` as formal power series.-/
def monomial (n : ℕ) : R →ₗ[R] power_series R := mv_power_series.monomial R (single () n)
variables {R}
lemma coeff_def {s : unit →₀ ℕ} {n : ℕ} (h : s () = n) :
coeff R n = mv_power_series.coeff R s :=
by erw [coeff, ← h, ← finsupp.unique_single s]
/-- Two formal power series are equal if all their coefficients are equal.-/
@[ext] lemma ext {φ ψ : power_series R} (h : ∀ n, coeff R n φ = coeff R n ψ) :
φ = ψ :=
mv_power_series.ext $ λ n,
by { rw ← coeff_def, { apply h }, refl }
/-- Two formal power series are equal if all their coefficients are equal.-/
lemma ext_iff {φ ψ : power_series R} : φ = ψ ↔ (∀ n, coeff R n φ = coeff R n ψ) :=
⟨λ h n, congr_arg (coeff R n) h, ext⟩
/-- Constructor for formal power series.-/
def mk {R} (f : ℕ → R) : power_series R := λ s, f (s ())
@[simp] lemma coeff_mk (n : ℕ) (f : ℕ → R) : coeff R n (mk f) = f n :=
congr_arg f finsupp.single_eq_same
lemma coeff_monomial (m n : ℕ) (a : R) :
coeff R m (monomial R n a) = if m = n then a else 0 :=
calc coeff R m (monomial R n a) = _ : mv_power_series.coeff_monomial _ _ _
... = if m = n then a else 0 :
by { simp only [finsupp.unique_single_eq_iff], split_ifs; refl }
lemma monomial_eq_mk (n : ℕ) (a : R) :
monomial R n a = mk (λ m, if m = n then a else 0) :=
ext $ λ m, by { rw [coeff_monomial, coeff_mk] }
@[simp] lemma coeff_monomial_same (n : ℕ) (a : R) :
coeff R n (monomial R n a) = a :=
mv_power_series.coeff_monomial_same _ _
@[simp] lemma coeff_comp_monomial (n : ℕ) :
(coeff R n).comp (monomial R n) = linear_map.id :=
linear_map.ext $ coeff_monomial_same n
variable (R)
/--The constant coefficient of a formal power series. -/
def constant_coeff : power_series R →+* R := mv_power_series.constant_coeff unit R
/-- The constant formal power series.-/
def C : R →+* power_series R := mv_power_series.C unit R
variable {R}
/-- The variable of the formal power series ring.-/
def X : power_series R := mv_power_series.X ()
@[simp] lemma coeff_zero_eq_constant_coeff :
⇑(coeff R 0) = constant_coeff R :=
by { rw [coeff, finsupp.single_zero], refl }
lemma coeff_zero_eq_constant_coeff_apply (φ : power_series R) :
coeff R 0 φ = constant_coeff R φ :=
by rw [coeff_zero_eq_constant_coeff]; refl
@[simp] lemma monomial_zero_eq_C : ⇑(monomial R 0) = C R :=
by rw [monomial, finsupp.single_zero, mv_power_series.monomial_zero_eq_C, C]
lemma monomial_zero_eq_C_apply (a : R) : monomial R 0 a = C R a :=
by simp
lemma coeff_C (n : ℕ) (a : R) :
coeff R n (C R a : power_series R) = if n = 0 then a else 0 :=
by rw [← monomial_zero_eq_C_apply, coeff_monomial]
@[simp] lemma coeff_zero_C (a : R) : coeff R 0 (C R a) = a :=
by rw [← monomial_zero_eq_C_apply, coeff_monomial_same 0 a]
lemma X_eq : (X : power_series R) = monomial R 1 1 := rfl
lemma coeff_X (n : ℕ) :
coeff R n (X : power_series R) = if n = 1 then 1 else 0 :=
by rw [X_eq, coeff_monomial]
@[simp] lemma coeff_zero_X : coeff R 0 (X : power_series R) = 0 :=
by rw [coeff, finsupp.single_zero, X, mv_power_series.coeff_zero_X]
@[simp] lemma coeff_one_X : coeff R 1 (X : power_series R) = 1 :=
by rw [coeff_X, if_pos rfl]
lemma X_pow_eq (n : ℕ) : (X : power_series R)^n = monomial R n 1 :=
mv_power_series.X_pow_eq _ n
lemma coeff_X_pow (m n : ℕ) :
coeff R m ((X : power_series R)^n) = if m = n then 1 else 0 :=
by rw [X_pow_eq, coeff_monomial]
@[simp] lemma coeff_X_pow_self (n : ℕ) :
coeff R n ((X : power_series R)^n) = 1 :=
by rw [coeff_X_pow, if_pos rfl]
@[simp] lemma coeff_one (n : ℕ) :
coeff R n (1 : power_series R) = if n = 0 then 1 else 0 :=
coeff_C n 1
lemma coeff_zero_one : coeff R 0 (1 : power_series R) = 1 :=
coeff_zero_C 1
lemma coeff_mul (n : ℕ) (φ ψ : power_series R) :
coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ :=
begin
symmetry,
apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)),
{ rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij,
rw [finsupp.mem_antidiagonal, ← finsupp.single_add, hij], },
{ rintros ⟨i,j⟩ hij, refl },
{ rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl,
simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id },
{ rintros ⟨f,g⟩ hfg,
refine ⟨(f (), g ()), _, _⟩,
{ rw finsupp.mem_antidiagonal at hfg,
rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] },
{ rw prod.mk.inj_iff, dsimp,
exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } }
end
@[simp] lemma coeff_mul_C (n : ℕ) (φ : power_series R) (a : R) :
coeff R n (φ * C R a) = coeff R n φ * a :=
mv_power_series.coeff_mul_C _ φ a
@[simp] lemma coeff_C_mul (n : ℕ) (φ : power_series R) (a : R) :
coeff R n (C R a * φ) = a * coeff R n φ :=
mv_power_series.coeff_C_mul _ φ a
@[simp] lemma coeff_smul (n : ℕ) (φ : power_series R) (a : R) :
coeff R n (a • φ) = a * coeff R n φ :=
rfl
@[simp] lemma coeff_succ_mul_X (n : ℕ) (φ : power_series R) :
coeff R (n+1) (φ * X) = coeff R n φ :=
begin
simp only [coeff, finsupp.single_add],
convert φ.coeff_add_mul_monomial (single () n) (single () 1) _,
rw mul_one
end
@[simp] lemma coeff_succ_X_mul (n : ℕ) (φ : power_series R) :
coeff R (n + 1) (X * φ) = coeff R n φ :=
begin
simp only [coeff, finsupp.single_add, add_comm n 1],
convert φ.coeff_add_monomial_mul (single () 1) (single () n) _,
rw one_mul,
end
@[simp] lemma constant_coeff_C (a : R) : constant_coeff R (C R a) = a := rfl
@[simp] lemma constant_coeff_comp_C :
(constant_coeff R).comp (C R) = ring_hom.id R := rfl
@[simp] lemma constant_coeff_zero : constant_coeff R 0 = 0 := rfl
@[simp] lemma constant_coeff_one : constant_coeff R 1 = 1 := rfl
@[simp] lemma constant_coeff_X : constant_coeff R X = 0 := mv_power_series.coeff_zero_X _
lemma coeff_zero_mul_X (φ : power_series R) : coeff R 0 (φ * X) = 0 := by simp
lemma coeff_zero_X_mul (φ : power_series R) : coeff R 0 (X * φ) = 0 := by simp
/-- If a formal power series is invertible, then so is its constant coefficient.-/
lemma is_unit_constant_coeff (φ : power_series R) (h : is_unit φ) :
is_unit (constant_coeff R φ) :=
mv_power_series.is_unit_constant_coeff φ h
/-- Split off the constant coefficient. -/
lemma eq_shift_mul_X_add_const (φ : power_series R) :
φ = mk (λ p, coeff R (p + 1) φ) * X + C R (constant_coeff R φ) :=
begin
ext (_ | n),
{ simp only [ring_hom.map_add, constant_coeff_C, constant_coeff_X, coeff_zero_eq_constant_coeff,
zero_add, mul_zero, ring_hom.map_mul], },
{ simp only [coeff_succ_mul_X, coeff_mk, linear_map.map_add, coeff_C, n.succ_ne_zero, sub_zero,
if_false, add_zero], }
end
/-- Split off the constant coefficient. -/
lemma eq_X_mul_shift_add_const (φ : power_series R) :
φ = X * mk (λ p, coeff R (p + 1) φ) + C R (constant_coeff R φ) :=
begin
ext (_ | n),
{ simp only [ring_hom.map_add, constant_coeff_C, constant_coeff_X, coeff_zero_eq_constant_coeff,
zero_add, zero_mul, ring_hom.map_mul], },
{ simp only [coeff_succ_X_mul, coeff_mk, linear_map.map_add, coeff_C, n.succ_ne_zero, sub_zero,
if_false, add_zero], }
end
section map
variables {S : Type*} {T : Type*} [semiring S] [semiring T]
variables (f : R →+* S) (g : S →+* T)
/-- The map between formal power series induced by a map on the coefficients.-/
def map : power_series R →+* power_series S :=
mv_power_series.map _ f
@[simp] lemma map_id : (map (ring_hom.id R) :
power_series R → power_series R) = id := rfl
lemma map_comp : map (g.comp f) = (map g).comp (map f) := rfl
@[simp] lemma coeff_map (n : ℕ) (φ : power_series R) :
coeff S n (map f φ) = f (coeff R n φ) := rfl
end map
end semiring
section comm_semiring
variables [comm_semiring R]
lemma X_pow_dvd_iff {n : ℕ} {φ : power_series R} :
(X : power_series R)^n ∣ φ ↔ ∀ m, m < n → coeff R m φ = 0 :=
begin
convert @mv_power_series.X_pow_dvd_iff unit R _ () n φ, apply propext,
classical, split; intros h m hm,
{ rw finsupp.unique_single m, convert h _ hm },
{ apply h, simpa only [finsupp.single_eq_same] using hm }
end
lemma X_dvd_iff {φ : power_series R} :
(X : power_series R) ∣ φ ↔ constant_coeff R φ = 0 :=
begin
rw [← pow_one (X : power_series R), X_pow_dvd_iff, ← coeff_zero_eq_constant_coeff_apply],
split; intro h,
{ exact h 0 zero_lt_one },
{ intros m hm, rwa nat.eq_zero_of_le_zero (nat.le_of_succ_le_succ hm) }
end
open finset nat
/-- The ring homomorphism taking a power series `f(X)` to `f(aX)`. -/
noncomputable def rescale (a : R) : power_series R →+* power_series R :=
{ to_fun := λ f, power_series.mk $ λ n, a^n * (power_series.coeff R n f),
map_zero' := by { ext, simp only [linear_map.map_zero, power_series.coeff_mk, mul_zero], },
map_one' := by { ext1, simp only [mul_boole, power_series.coeff_mk, power_series.coeff_one],
split_ifs, { rw [h, pow_zero], }, refl, },
map_add' := by { intros, ext, exact mul_add _ _ _, },
map_mul' := λ f g, by {
ext,
rw [power_series.coeff_mul, power_series.coeff_mk, power_series.coeff_mul, finset.mul_sum],
apply sum_congr rfl,
simp only [coeff_mk, prod.forall, nat.mem_antidiagonal],
intros b c H,
rw [←H, pow_add, mul_mul_mul_comm] }, }
@[simp] lemma coeff_rescale (f : power_series R) (a : R) (n : ℕ) :
coeff R n (rescale a f) = a^n * coeff R n f := coeff_mk n _
@[simp] lemma rescale_zero : rescale 0 = (C R).comp (constant_coeff R) :=
begin
ext,
simp only [function.comp_app, ring_hom.coe_comp, rescale, ring_hom.coe_mk,
power_series.coeff_mk _ _, coeff_C],
split_ifs,
{ simp only [h, one_mul, coeff_zero_eq_constant_coeff, pow_zero], },
{ rw [zero_pow' n h, zero_mul], },
end
lemma rescale_zero_apply : rescale 0 X = C R (constant_coeff R X) :=
by simp
@[simp] lemma rescale_one : rescale 1 = ring_hom.id (power_series R) :=
by { ext, simp only [ring_hom.id_apply, rescale, one_pow, coeff_mk, one_mul,
ring_hom.coe_mk], }
section trunc
/-- The `n`th truncation of a formal power series to a polynomial -/
def trunc (n : ℕ) (φ : power_series R) : polynomial R :=
∑ m in Ico 0 (n + 1), polynomial.monomial m (coeff R m φ)
lemma coeff_trunc (m) (n) (φ : power_series R) :
(trunc n φ).coeff m = if m ≤ n then coeff R m φ else 0 :=
by simp [trunc, polynomial.coeff_sum, polynomial.coeff_monomial, nat.lt_succ_iff]
@[simp] lemma trunc_zero (n) : trunc n (0 : power_series R) = 0 :=
polynomial.ext $ λ m,
begin
rw [coeff_trunc, linear_map.map_zero, polynomial.coeff_zero],
split_ifs; refl
end
@[simp] lemma trunc_one (n) : trunc n (1 : power_series R) = 1 :=
polynomial.ext $ λ m,
begin
rw [coeff_trunc, coeff_one],
split_ifs with H H' H'; rw [polynomial.coeff_one],
{ subst m, rw [if_pos rfl] },
{ symmetry, exact if_neg (ne.elim (ne.symm H')) },
{ symmetry, refine if_neg _,
intro H', apply H, subst m, exact nat.zero_le _ }
end
@[simp] lemma trunc_C (n) (a : R) : trunc n (C R a) = polynomial.C a :=
polynomial.ext $ λ m,
begin
rw [coeff_trunc, coeff_C, polynomial.coeff_C],
split_ifs with H; refl <|> try {simp * at *}
end
@[simp] lemma trunc_add (n) (φ ψ : power_series R) :
trunc n (φ + ψ) = trunc n φ + trunc n ψ :=
polynomial.ext $ λ m,
begin
simp only [coeff_trunc, add_monoid_hom.map_add, polynomial.coeff_add],
split_ifs with H, {refl}, {rw [zero_add]}
end
end trunc
end comm_semiring
section ring
variables [ring R]
/-- Auxiliary function used for computing inverse of a power series -/
protected def inv.aux : R → power_series R → power_series R :=
mv_power_series.inv.aux
lemma coeff_inv_aux (n : ℕ) (a : R) (φ : power_series R) :
coeff R n (inv.aux a φ) = if n = 0 then a else
- a * ∑ x in finset.nat.antidiagonal n,
if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 :=
begin
rw [coeff, inv.aux, mv_power_series.coeff_inv_aux],
simp only [finsupp.single_eq_zero],
split_ifs, {refl},
congr' 1,
symmetry,
apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)),
{ rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij,
rw [finsupp.mem_antidiagonal, ← finsupp.single_add, hij], },
{ rintros ⟨i,j⟩ hij,
by_cases H : j < n,
{ rw [if_pos H, if_pos], {refl},
split,
{ rintro ⟨⟩, simpa [finsupp.single_eq_same] using le_of_lt H },
{ intro hh, rw lt_iff_not_ge at H, apply H,
simpa [finsupp.single_eq_same] using hh () } },
{ rw [if_neg H, if_neg], rintro ⟨h₁, h₂⟩, apply h₂, rintro ⟨⟩,
simpa [finsupp.single_eq_same] using not_lt.1 H } },
{ rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl,
simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id },
{ rintros ⟨f,g⟩ hfg,
refine ⟨(f (), g ()), _, _⟩,
{ rw finsupp.mem_antidiagonal at hfg,
rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] },
{ rw prod.mk.inj_iff, dsimp,
exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } }
end
/-- A formal power series is invertible if the constant coefficient is invertible.-/
def inv_of_unit (φ : power_series R) (u : units R) : power_series R :=
mv_power_series.inv_of_unit φ u
lemma coeff_inv_of_unit (n : ℕ) (φ : power_series R) (u : units R) :
coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else
- ↑u⁻¹ * ∑ x in finset.nat.antidiagonal n,
if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 :=
coeff_inv_aux n ↑u⁻¹ φ
@[simp] lemma constant_coeff_inv_of_unit (φ : power_series R) (u : units R) :
constant_coeff R (inv_of_unit φ u) = ↑u⁻¹ :=
by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl]
lemma mul_inv_of_unit (φ : power_series R) (u : units R) (h : constant_coeff R φ = u) :
φ * inv_of_unit φ u = 1 :=
mv_power_series.mul_inv_of_unit φ u $ h
/-- Two ways of removing the constant coefficient of a power series are the same. -/
lemma sub_const_eq_shift_mul_X (φ : power_series R) :
φ - C R (constant_coeff R φ) = power_series.mk (λ p, coeff R (p + 1) φ) * X :=
sub_eq_iff_eq_add.mpr (eq_shift_mul_X_add_const φ)
lemma sub_const_eq_X_mul_shift (φ : power_series R) :
φ - C R (constant_coeff R φ) = X * power_series.mk (λ p, coeff R (p + 1) φ) :=
sub_eq_iff_eq_add.mpr (eq_X_mul_shift_add_const φ)
end ring
section comm_ring
variables {A : Type*} [comm_ring A]
@[simp] lemma rescale_neg_one_X : rescale (-1 : A) X = -X :=
begin
ext, simp only [linear_map.map_neg, coeff_rescale, coeff_X],
split_ifs with h; simp [h]
end
/-- The ring homomorphism taking a power series `f(X)` to `f(-X)`. -/
noncomputable def eval_neg_hom : power_series A →+* power_series A :=
rescale (-1 : A)
@[simp] lemma eval_neg_hom_X : eval_neg_hom (X : power_series A) = -X :=
rescale_neg_one_X
end comm_ring
section domain
variables [ring R] [is_domain R]
lemma eq_zero_or_eq_zero_of_mul_eq_zero (φ ψ : power_series R) (h : φ * ψ = 0) :
φ = 0 ∨ ψ = 0 :=
begin
rw or_iff_not_imp_left, intro H,
have ex : ∃ m, coeff R m φ ≠ 0, { contrapose! H, exact ext H },
let m := nat.find ex,
have hm₁ : coeff R m φ ≠ 0 := nat.find_spec ex,
have hm₂ : ∀ k < m, ¬coeff R k φ ≠ 0 := λ k, nat.find_min ex,
ext n, rw (coeff R n).map_zero, apply nat.strong_induction_on n,
clear n, intros n ih,
replace h := congr_arg (coeff R (m + n)) h,
rw [linear_map.map_zero, coeff_mul, finset.sum_eq_single (m,n)] at h,
{ replace h := eq_zero_or_eq_zero_of_mul_eq_zero h,
rw or_iff_not_imp_left at h, exact h hm₁ },
{ rintro ⟨i,j⟩ hij hne,
by_cases hj : j < n, { rw [ih j hj, mul_zero] },
by_cases hi : i < m,
{ specialize hm₂ _ hi, push_neg at hm₂, rw [hm₂, zero_mul] },
rw finset.nat.mem_antidiagonal at hij,
push_neg at hi hj,
suffices : m < i,
{ have : m + n < i + j := add_lt_add_of_lt_of_le this hj,
exfalso, exact ne_of_lt this hij.symm },
contrapose! hne, have : i = m := le_antisymm hne hi, subst i, clear hi hne,
simpa [ne.def, prod.mk.inj_iff] using (add_right_inj m).mp hij },
{ contrapose!, intro h, rw finset.nat.mem_antidiagonal }
end
instance : is_domain (power_series R) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero,
.. power_series.nontrivial, }
end domain
section is_domain
variables [comm_ring R] [is_domain R]
/-- The ideal spanned by the variable in the power series ring
over an integral domain is a prime ideal.-/
lemma span_X_is_prime : (ideal.span ({X} : set (power_series R))).is_prime :=
begin
suffices : ideal.span ({X} : set (power_series R)) = (constant_coeff R).ker,
{ rw this, exact ring_hom.ker_is_prime _ },
apply ideal.ext, intro φ,
rw [ring_hom.mem_ker, ideal.mem_span_singleton, X_dvd_iff]
end
/-- The variable of the power series ring over an integral domain is prime.-/
lemma X_prime : prime (X : power_series R) :=
begin
rw ← ideal.span_singleton_prime,
{ exact span_X_is_prime },
{ intro h, simpa using congr_arg (coeff R 1) h }
end
lemma rescale_injective {a : R} (ha : a ≠ 0) : function.injective (rescale a) :=
begin
intros p q h,
rw power_series.ext_iff at *,
intros n,
specialize h n,
rw [coeff_rescale, coeff_rescale, mul_eq_mul_left_iff] at h,
apply h.resolve_right,
intro h',
exact ha (pow_eq_zero h'),
end
end is_domain
section local_ring
variables {S : Type*} [comm_ring R] [comm_ring S]
(f : R →+* S) [is_local_ring_hom f]
instance map.is_local_ring_hom : is_local_ring_hom (map f) :=
mv_power_series.map.is_local_ring_hom f
variables [local_ring R] [local_ring S]
instance : local_ring (power_series R) :=
mv_power_series.local_ring
end local_ring
section algebra
variables {A : Type*} [comm_semiring R] [semiring A] [algebra R A]
theorem C_eq_algebra_map {r : R} : C R r = (algebra_map R (power_series R)) r := rfl
theorem algebra_map_apply {r : R} :
algebra_map R (power_series A) r = C A (algebra_map R A r) :=
mv_power_series.algebra_map_apply
instance [nontrivial R] : nontrivial (subalgebra R (power_series R)) :=
mv_power_series.subalgebra.nontrivial
end algebra
section field
variables {k : Type*} [field k]
/-- The inverse 1/f of a power series f defined over a field -/
protected def inv : power_series k → power_series k :=
mv_power_series.inv
instance : has_inv (power_series k) := ⟨power_series.inv⟩
lemma inv_eq_inv_aux (φ : power_series k) :
φ⁻¹ = inv.aux (constant_coeff k φ)⁻¹ φ := rfl
lemma coeff_inv (n) (φ : power_series k) :
coeff k n (φ⁻¹) = if n = 0 then (constant_coeff k φ)⁻¹ else
- (constant_coeff k φ)⁻¹ * ∑ x in finset.nat.antidiagonal n,
if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 :=
by rw [inv_eq_inv_aux, coeff_inv_aux n (constant_coeff k φ)⁻¹ φ]
@[simp] lemma constant_coeff_inv (φ : power_series k) :
constant_coeff k (φ⁻¹) = (constant_coeff k φ)⁻¹ :=
mv_power_series.constant_coeff_inv φ
lemma inv_eq_zero {φ : power_series k} :
φ⁻¹ = 0 ↔ constant_coeff k φ = 0 :=
mv_power_series.inv_eq_zero
@[simp, priority 1100] lemma inv_of_unit_eq (φ : power_series k) (h : constant_coeff k φ ≠ 0) :
inv_of_unit φ (units.mk0 _ h) = φ⁻¹ :=
mv_power_series.inv_of_unit_eq _ _
@[simp] lemma inv_of_unit_eq' (φ : power_series k) (u : units k) (h : constant_coeff k φ = u) :
inv_of_unit φ u = φ⁻¹ :=
mv_power_series.inv_of_unit_eq' φ _ h
@[simp] protected lemma mul_inv (φ : power_series k) (h : constant_coeff k φ ≠ 0) :
φ * φ⁻¹ = 1 :=
mv_power_series.mul_inv φ h
@[simp] protected lemma inv_mul (φ : power_series k) (h : constant_coeff k φ ≠ 0) :
φ⁻¹ * φ = 1 :=
mv_power_series.inv_mul φ h
lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : power_series k} (h : constant_coeff k φ₃ ≠ 0) :
φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ :=
mv_power_series.eq_mul_inv_iff_mul_eq h
lemma eq_inv_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) :
φ = ψ⁻¹ ↔ φ * ψ = 1 :=
mv_power_series.eq_inv_iff_mul_eq_one h
lemma inv_eq_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) :
ψ⁻¹ = φ ↔ φ * ψ = 1 :=
mv_power_series.inv_eq_iff_mul_eq_one h
end field
end power_series
namespace power_series
variable {R : Type*}
local attribute [instance, priority 1] classical.prop_decidable
noncomputable theory
section order_basic
open multiplicity
variables [comm_semiring R]
/-- The order of a formal power series `φ` is the greatest `n : enat`
such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/
@[reducible] def order (φ : power_series R) : enat :=
multiplicity X φ
lemma order_finite_of_coeff_ne_zero (φ : power_series R) (h : ∃ n, coeff R n φ ≠ 0) :
(order φ).dom :=
begin
cases h with n h, refine ⟨n, _⟩, dsimp only,
rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩
end
/-- If the order of a formal power series is finite,
then the coefficient indexed by the order is nonzero.-/
lemma coeff_order (φ : power_series R) (h : (order φ).dom) :
coeff R (φ.order.get h) φ ≠ 0 :=
begin
have H := nat.find_spec h, contrapose! H, rw X_pow_dvd_iff,
intros m hm, by_cases Hm : m < nat.find h,
{ have := nat.find_min h Hm, push_neg at this,
rw X_pow_dvd_iff at this, exact this m (lt_add_one m) },
have : m = nat.find h, {linarith}, {rwa this}
end
/-- If the `n`th coefficient of a formal power series is nonzero,
then the order of the power series is less than or equal to `n`.-/
lemma order_le (φ : power_series R) (n : ℕ) (h : coeff R n φ ≠ 0) :
order φ ≤ n :=
begin
have h : ¬ X^(n+1) ∣ φ,
{ rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ },
have : (order φ).dom := ⟨n, h⟩,
rw [← enat.coe_get this, enat.coe_le_coe],
refine nat.find_min' this h
end
/-- The `n`th coefficient of a formal power series is `0` if `n` is strictly
smaller than the order of the power series.-/
lemma coeff_of_lt_order (φ : power_series R) (n : ℕ) (h: ↑n < order φ) :
coeff R n φ = 0 :=
by { contrapose! h, exact order_le _ _ h }
/-- The order of the `0` power series is infinite.-/
@[simp] lemma order_zero : order (0 : power_series R) = ⊤ :=
multiplicity.zero _
/-- The `0` power series is the unique power series with infinite order.-/
@[simp] lemma order_eq_top {φ : power_series R} :
φ.order = ⊤ ↔ φ = 0 :=
begin
split,
{ intro h, ext n, rw [(coeff R n).map_zero, coeff_of_lt_order], simp [h] },
{ rintros rfl, exact order_zero }
end
/-- The order of a formal power series is at least `n` if
the `i`th coefficient is `0` for all `i < n`.-/
lemma nat_le_order (φ : power_series R) (n : ℕ) (h : ∀ i < n, coeff R i φ = 0) :
↑n ≤ order φ :=
begin
by_contra H, rw not_le at H,
have : (order φ).dom := enat.dom_of_le_coe H.le,
rw [← enat.coe_get this, enat.coe_lt_coe] at H,
exact coeff_order _ this (h _ H)
end
/-- The order of a formal power series is at least `n` if
the `i`th coefficient is `0` for all `i < n`.-/
lemma le_order (φ : power_series R) (n : enat) (h : ∀ i : ℕ, ↑i < n → coeff R i φ = 0) :
n ≤ order φ :=
begin
induction n using enat.cases_on,
{ show _ ≤ _, rw [top_le_iff, order_eq_top],
ext i, exact h _ (enat.coe_lt_top i) },
{ apply nat_le_order, simpa only [enat.coe_lt_coe] using h }
end
/-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero,
and the `i`th coefficient is `0` for all `i < n`.-/
lemma order_eq_nat {φ : power_series R} {n : ℕ} :
order φ = n ↔ (coeff R n φ ≠ 0) ∧ (∀ i, i < n → coeff R i φ = 0) :=
begin
simp only [eq_coe_iff, X_pow_dvd_iff], push_neg,
split,
{ rintros ⟨h₁, m, hm₁, hm₂⟩, refine ⟨_, h₁⟩,
suffices : n = m, { rwa this },
suffices : m ≥ n, { linarith },
contrapose! hm₂, exact h₁ _ hm₂ },
{ rintros ⟨h₁, h₂⟩, exact ⟨h₂, n, lt_add_one n, h₁⟩ }
end
/-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero,
and the `i`th coefficient is `0` for all `i < n`.-/
lemma order_eq {φ : power_series R} {n : enat} :
order φ = n ↔ (∀ i:ℕ, ↑i = n → coeff R i φ ≠ 0) ∧ (∀ i:ℕ, ↑i < n → coeff R i φ = 0) :=
begin
induction n using enat.cases_on,
{ rw order_eq_top, split,
{ rintro rfl, split; intros,
{ exfalso, exact enat.coe_ne_top ‹_› ‹_› },
{ exact (coeff _ _).map_zero } },
{ rintro ⟨h₁, h₂⟩, ext i, exact h₂ i (enat.coe_lt_top i) } },
{ simpa [enat.coe_inj] using order_eq_nat }
end
/-- The order of the sum of two formal power series
is at least the minimum of their orders.-/
lemma le_order_add (φ ψ : power_series R) :
min (order φ) (order ψ) ≤ order (φ + ψ) :=
multiplicity.min_le_multiplicity_add
private lemma order_add_of_order_eq.aux (φ ψ : power_series R)
(h : order φ ≠ order ψ) (H : order φ < order ψ) :
order (φ + ψ) ≤ order φ ⊓ order ψ :=
begin
suffices : order (φ + ψ) = order φ,
{ rw [le_inf_iff, this], exact ⟨le_refl _, le_of_lt H⟩ },
{ rw order_eq, split,
{ intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order ψ i (hi.symm ▸ H), add_zero],
exact (order_eq_nat.1 hi.symm).1 },
{ intros i hi,
rw [(coeff _ _).map_add, coeff_of_lt_order φ i hi,
coeff_of_lt_order ψ i (lt_trans hi H), zero_add] } }
end
/-- The order of the sum of two formal power series
is the minimum of their orders if their orders differ.-/
lemma order_add_of_order_eq (φ ψ : power_series R) (h : order φ ≠ order ψ) :
order (φ + ψ) = order φ ⊓ order ψ :=
begin
refine le_antisymm _ (le_order_add _ _),
by_cases H₁ : order φ < order ψ,
{ apply order_add_of_order_eq.aux _ _ h H₁ },
by_cases H₂ : order ψ < order φ,
{ simpa only [add_comm, inf_comm] using order_add_of_order_eq.aux _ _ h.symm H₂ },
exfalso, exact h (le_antisymm (not_lt.1 H₂) (not_lt.1 H₁))
end
/-- The order of the product of two formal power series
is at least the sum of their orders.-/
lemma order_mul_ge (φ ψ : power_series R) :
order φ + order ψ ≤ order (φ * ψ) :=
begin
apply le_order,
intros n hn, rw [coeff_mul, finset.sum_eq_zero],
rintros ⟨i,j⟩ hij,
by_cases hi : ↑i < order φ,
{ rw [coeff_of_lt_order φ i hi, zero_mul] },
by_cases hj : ↑j < order ψ,
{ rw [coeff_of_lt_order ψ j hj, mul_zero] },
rw not_lt at hi hj, rw finset.nat.mem_antidiagonal at hij,
exfalso,
apply ne_of_lt (lt_of_lt_of_le hn $ add_le_add hi hj),
rw [← nat.cast_add, hij]
end
/-- The order of the monomial `a*X^n` is infinite if `a = 0` and `n` otherwise.-/
lemma order_monomial (n : ℕ) (a : R) [decidable (a = 0)] :
order (monomial R n a) = if a = 0 then ⊤ else n :=
begin
split_ifs with h,
{ rw [h, order_eq_top, linear_map.map_zero] },
{ rw [order_eq], split; intros i hi,
{ rw [enat.coe_inj] at hi, rwa [hi, coeff_monomial_same] },
{ rw [enat.coe_lt_coe] at hi, rw [coeff_monomial, if_neg], exact ne_of_lt hi } }
end
/-- The order of the monomial `a*X^n` is `n` if `a ≠ 0`.-/
lemma order_monomial_of_ne_zero (n : ℕ) (a : R) (h : a ≠ 0) :
order (monomial R n a) = n :=
by rw [order_monomial, if_neg h]
/-- If `n` is strictly smaller than the order of `ψ`, then the `n`th coefficient of its product
with any other power series is `0`. -/
lemma coeff_mul_of_lt_order {φ ψ : power_series R} {n : ℕ} (h : ↑n < ψ.order) :
coeff R n (φ * ψ) = 0 :=
begin
suffices : coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, 0,
rw [this, finset.sum_const_zero],
rw [coeff_mul],
apply finset.sum_congr rfl (λ x hx, _),
refine mul_eq_zero_of_right (coeff R x.fst φ) (ψ.coeff_of_lt_order x.snd (lt_of_le_of_lt _ h)),
rw finset.nat.mem_antidiagonal at hx,
norm_cast,
linarith,
end
lemma coeff_mul_one_sub_of_lt_order {R : Type*} [comm_ring R] {φ ψ : power_series R}
(n : ℕ) (h : ↑n < ψ.order) :
coeff R n (φ * (1 - ψ)) = coeff R n φ :=
by simp [coeff_mul_of_lt_order h, mul_sub]
lemma coeff_mul_prod_one_sub_of_lt_order {R ι : Type*} [comm_ring R] (k : ℕ) (s : finset ι)
(φ : power_series R) (f : ι → power_series R) :
(∀ i ∈ s, ↑k < (f i).order) → coeff R k (φ * ∏ i in s, (1 - f i)) = coeff R k φ :=
begin
apply finset.induction_on s,
{ simp },
{ intros a s ha ih t,
simp only [finset.mem_insert, forall_eq_or_imp] at t,
rw [finset.prod_insert ha, ← mul_assoc, mul_right_comm, coeff_mul_one_sub_of_lt_order _ t.1],
exact ih t.2 },
end
end order_basic
section order_zero_ne_one
variables [comm_semiring R] [nontrivial R]
/-- The order of the formal power series `1` is `0`.-/
@[simp] lemma order_one : order (1 : power_series R) = 0 :=
by simpa using order_monomial_of_ne_zero 0 (1:R) one_ne_zero
/-- The order of the formal power series `X` is `1`.-/
@[simp] lemma order_X : order (X : power_series R) = 1 :=
by simpa only [nat.cast_one] using order_monomial_of_ne_zero 1 (1:R) one_ne_zero
/-- The order of the formal power series `X^n` is `n`.-/
@[simp] lemma order_X_pow (n : ℕ) : order ((X : power_series R)^n) = n :=
by { rw [X_pow_eq, order_monomial_of_ne_zero], exact one_ne_zero }
end order_zero_ne_one
section order_is_domain
variables [comm_ring R] [is_domain R]
/-- The order of the product of two formal power series over an integral domain
is the sum of their orders.-/
lemma order_mul (φ ψ : power_series R) :
order (φ * ψ) = order φ + order ψ :=
multiplicity.mul (X_prime)
end order_is_domain
end power_series
namespace polynomial
open finsupp
variables {σ : Type*} {R : Type*} [comm_semiring R]
/-- The natural inclusion from polynomials into formal power series.-/
instance coe_to_power_series : has_coe (polynomial R) (power_series R) :=
⟨λ φ, power_series.mk $ λ n, coeff φ n⟩
@[simp, norm_cast] lemma coeff_coe (φ : polynomial R) (n) :
power_series.coeff R n φ = coeff φ n :=
congr_arg (coeff φ) (finsupp.single_eq_same)
@[simp, norm_cast] lemma coe_monomial (n : ℕ) (a : R) :
(monomial n a : power_series R) = power_series.monomial R n a :=
by { ext, simp [coeff_coe, power_series.coeff_monomial, polynomial.coeff_monomial, eq_comm] }
@[simp, norm_cast] lemma coe_zero : ((0 : polynomial R) : power_series R) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : polynomial R) : power_series R) = 1 :=
begin
have := coe_monomial 0 (1:R),
rwa power_series.monomial_zero_eq_C_apply at this,
end
@[simp, norm_cast] lemma coe_add (φ ψ : polynomial R) :
((φ + ψ : polynomial R) : power_series R) = φ + ψ :=
by { ext, simp }
@[simp, norm_cast] lemma coe_mul (φ ψ : polynomial R) :
((φ * ψ : polynomial R) : power_series R) = φ * ψ :=
power_series.ext $ λ n,
by simp only [coeff_coe, power_series.coeff_mul, coeff_mul]
@[simp, norm_cast] lemma coe_C (a : R) :
((C a : polynomial R) : power_series R) = power_series.C R a :=
begin
have := coe_monomial 0 a,
rwa power_series.monomial_zero_eq_C_apply at this,
end
@[simp, norm_cast] lemma coe_X :
((X : polynomial R) : power_series R) = power_series.X :=
coe_monomial _ _
/--
The coercion from polynomials to power series
as a ring homomorphism.
-/
-- TODO as an algebra homomorphism?
def coe_to_power_series.ring_hom : polynomial R →+* power_series R :=
{ to_fun := (coe : polynomial R → power_series R),
map_zero' := coe_zero,
map_one' := coe_one,
map_add' := coe_add,
map_mul' := coe_mul }
end polynomial
|
0daae761a5ce8a2be44a341aef8294ddbe42624d | 041929c569a4eeeafb4efdddab8a644f6df383c5 | /src/mazes/noneuclidean_maze/level.lean | dcb71c1f8d2e08afac1c3f68da2918594135f140 | [] | no_license | kbuzzard/xena-maze-game | 30ffbe956762dd6603e74efd823d375649e037c3 | 098454dd6acc4c06beccf52b6547bf4cd99cc581 | refs/heads/master | 1,670,840,300,174 | 1,598,554,198,000 | 1,598,554,198,000 | 290,856,036 | 4 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 509 | lean | -- import the definition of the non-euclidean maze
import mazes.noneuclidean_maze.solutions.definition
open maze direction
/-
# Non-euclidean maze.
You are in a maze of twisty passages, all distinct.
You can go north, south east or west.
If you hit the wall there's an error.
When you're at the exit (room `J`), type `out`.
Solver remark : there are 10 rooms.
-/
/- Lemma : no-side-bar
Can you escape from this non-Euclidean maze?
-/
lemma solve : can_escape A :=
begin
s,s,e,e,w,w,out,
end
|
9ee069541267dfbbe3a4868c6932a1650f1b8fd2 | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/linear_algebra/pi_tensor_product.lean | ef13a425aae4233a8ea0dc5cfc7c3b1795270eac | [
"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 | 21,476 | 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, Eric Wieser
-/
import group_theory.congruence
import linear_algebra.multilinear.tensor_product
/-!
# Tensor product of an indexed family of modules over commutative semirings
We define the tensor product of an indexed family `s : ι → Type*` of modules over commutative
semirings. We denote this space by `⨂[R] i, s i` and define it as `free_add_monoid (R × Π i, s i)`
quotiented by the appropriate equivalence relation. The treatment follows very closely that of the
binary tensor product in `linear_algebra/tensor_product.lean`.
## Main definitions
* `pi_tensor_product R s` with `R` a commutative semiring and `s : ι → Type*` is the tensor product
of all the `s i`'s. This is denoted by `⨂[R] i, s i`.
* `tprod R f` with `f : Π i, s i` is the tensor product of the vectors `f i` over all `i : ι`.
This is bundled as a multilinear map from `Π i, s i` to `⨂[R] i, s i`.
* `lift_add_hom` constructs an `add_monoid_hom` from `(⨂[R] i, s i)` to some space `F` from a
function `φ : (R × Π i, s i) → F` with the appropriate properties.
* `lift φ` with `φ : multilinear_map R s E` is the corresponding linear map
`(⨂[R] i, s i) →ₗ[R] E`. This is bundled as a linear equivalence.
* `pi_tensor_product.reindex e` re-indexes the components of `⨂[R] i : ι, M` along `e : ι ≃ ι₂`.
* `pi_tensor_product.tmul_equiv` equivalence between a `tensor_product` of `pi_tensor_product`s and
a single `pi_tensor_product`.
## Notations
* `⨂[R] i, s i` is defined as localized notation in locale `tensor_product`
* `⨂ₜ[R] i, f i` with `f : Π i, f i` is defined globally as the tensor product of all the `f i`'s.
## Implementation notes
* We define it via `free_add_monoid (R × Π i, s i)` with the `R` representing a "hidden" tensor
factor, rather than `free_add_monoid (Π i, s i)` to ensure that, if `ι` is an empty type,
the space is isomorphic to the base ring `R`.
* We have not restricted the index type `ι` to be a `fintype`, as nothing we do here strictly
requires it. However, problems may arise in the case where `ι` is infinite; use at your own
caution.
## TODO
* Define tensor powers, symmetric subspace, etc.
* API for the various ways `ι` can be split into subsets; connect this with the binary
tensor product.
* Include connection with holors.
* Port more of the API from the binary tensor product over to this case.
## Tags
multilinear, tensor, tensor product
-/
open function
section semiring
variables {ι ι₂ ι₃ : Type*} [decidable_eq ι] [decidable_eq ι₂] [decidable_eq ι₃]
variables {R : Type*} [comm_semiring R]
variables {R' : Type*} [comm_semiring R'] [algebra R' R]
variables {s : ι → Type*} [∀ i, add_comm_monoid (s i)] [∀ i, module R (s i)]
variables {M : Type*} [add_comm_monoid M] [module R M]
variables {E : Type*} [add_comm_monoid E] [module R E]
variables {F : Type*} [add_comm_monoid F]
namespace pi_tensor_product
include R
variables (R) (s)
/-- The relation on `free_add_monoid (R × Π i, s i)` that generates a congruence whose quotient is
the tensor product. -/
inductive eqv : free_add_monoid (R × Π i, s i) → free_add_monoid (R × Π i, s i) → Prop
| of_zero : ∀ (r : R) (f : Π i, s i) (i : ι) (hf : f i = 0), eqv (free_add_monoid.of (r, f)) 0
| of_zero_scalar : ∀ (f : Π i, s i), eqv (free_add_monoid.of (0, f)) 0
| of_add : ∀ (r : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i), eqv
(free_add_monoid.of (r, update f i m₁) + free_add_monoid.of (r, update f i m₂))
(free_add_monoid.of (r, update f i (m₁ + m₂)))
| of_add_scalar : ∀ (r r' : R) (f : Π i, s i), eqv
(free_add_monoid.of (r, f) + free_add_monoid.of (r', f))
(free_add_monoid.of (r + r', f))
| of_smul : ∀ (r : R) (f : Π i, s i) (i : ι) (r' : R), eqv
(free_add_monoid.of (r, update f i (r' • (f i))))
(free_add_monoid.of (r' * r, f))
| add_comm : ∀ x y, eqv (x + y) (y + x)
end pi_tensor_product
variables (R) (s)
/-- `pi_tensor_product R s` with `R` a commutative semiring and `s : ι → Type*` is the tensor
product of all the `s i`'s. This is denoted by `⨂[R] i, s i`. -/
def pi_tensor_product : Type* :=
(add_con_gen (pi_tensor_product.eqv R s)).quotient
variables {R}
/- This enables the notation `⨂[R] i : ι, s i` for the pi tensor product, given `s : ι → Type*`. -/
localized "notation `⨂[`:100 R `] ` binders `, ` r:(scoped:67 f, pi_tensor_product R f) := r"
in tensor_product
open_locale tensor_product
namespace pi_tensor_product
section module
instance : add_comm_monoid (⨂[R] i, s i) :=
{ add_comm := λ x y, add_con.induction_on₂ x y $ λ x y, quotient.sound' $
add_con_gen.rel.of _ _ $ eqv.add_comm _ _,
.. (add_con_gen (pi_tensor_product.eqv R s)).add_monoid }
instance : inhabited (⨂[R] i, s i) := ⟨0⟩
variables (R) {s}
/-- `tprod_coeff R r f` with `r : R` and `f : Π i, s i` is the tensor product of the vectors `f i`
over all `i : ι`, multiplied by the coefficient `r`. Note that this is meant as an auxiliary
definition for this file alone, and that one should use `tprod` defined below for most purposes. -/
def tprod_coeff (r : R) (f : Π i, s i) : ⨂[R] i, s i := add_con.mk' _ $ free_add_monoid.of (r, f)
variables {R}
lemma zero_tprod_coeff (f : Π i, s i) : tprod_coeff R 0 f = 0 :=
quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_scalar _
lemma zero_tprod_coeff' (z : R) (f : Π i, s i) (i : ι) (hf: f i = 0) : tprod_coeff R z f = 0 :=
quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero _ _ i hf
lemma add_tprod_coeff (z : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i) :
tprod_coeff R z (update f i m₁) + tprod_coeff R z (update f i m₂) =
tprod_coeff R z (update f i (m₁ + m₂)) :=
quotient.sound' $ add_con_gen.rel.of _ _ (eqv.of_add z f i m₁ m₂)
lemma add_tprod_coeff' (z₁ z₂ : R) (f : Π i, s i) :
tprod_coeff R z₁ f + tprod_coeff R z₂ f = tprod_coeff R (z₁ + z₂) f :=
quotient.sound' $ add_con_gen.rel.of _ _ (eqv.of_add_scalar z₁ z₂ f)
lemma smul_tprod_coeff_aux (z : R) (f : Π i, s i) (i : ι) (r : R) :
tprod_coeff R z (update f i (r • f i)) = tprod_coeff R (r * z) f :=
quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_smul _ _ _ _
lemma smul_tprod_coeff (z : R) (f : Π i, s i) (i : ι) (r : R')
[module R' (s i)] [is_scalar_tower R' R (s i)] :
tprod_coeff R z (update f i (r • f i)) = tprod_coeff R (r • z) f :=
begin
have h₁ : r • z = (r • (1 : R)) * z := by simp,
have h₂ : r • (f i) = (r • (1 : R)) • f i := by simp,
rw [h₁, h₂],
exact smul_tprod_coeff_aux z f i _,
end
/-- Construct an `add_monoid_hom` from `(⨂[R] i, s i)` to some space `F` from a function
`φ : (R × Π i, s i) → F` with the appropriate properties. -/
def lift_add_hom (φ : (R × Π i, s i) → F)
(C0 : ∀ (r : R) (f : Π i, s i) (i : ι) (hf : f i = 0), φ (r, f) = 0)
(C0' : ∀ (f : Π i, s i), φ (0, f) = 0)
(C_add : ∀ (r : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i),
φ (r, update f i m₁) + φ (r, update f i m₂) = φ (r, update f i (m₁ + m₂)))
(C_add_scalar : ∀ (r r' : R) (f : Π i, s i),
φ (r , f) + φ (r', f) = φ (r + r', f))
(C_smul : ∀ (r : R) (f : Π i, s i) (i : ι) (r' : R),
φ (r, update f i (r' • (f i))) = φ (r' * r, f))
: (⨂[R] i, s i) →+ F :=
(add_con_gen (pi_tensor_product.eqv R s)).lift (free_add_monoid.lift φ) $ add_con.add_con_gen_le $
λ x y hxy, match x, y, hxy with
| _, _, (eqv.of_zero r' f i hf) := (add_con.ker_rel _).2 $
by simp [free_add_monoid.lift_eval_of, C0 r' f i hf]
| _, _, (eqv.of_zero_scalar f) := (add_con.ker_rel _).2 $
by simp [free_add_monoid.lift_eval_of, C0']
| _, _, (eqv.of_add z f i m₁ m₂) := (add_con.ker_rel _).2 $
by simp [free_add_monoid.lift_eval_of, C_add]
| _, _, (eqv.of_add_scalar z₁ z₂ f) := (add_con.ker_rel _).2 $
by simp [free_add_monoid.lift_eval_of, C_add_scalar]
| _, _, (eqv.of_smul z f i r') := (add_con.ker_rel _).2 $
by simp [free_add_monoid.lift_eval_of, C_smul]
| _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, add_comm]
end
-- Most of the time we want the instance below this one, which is easier for typeclass resolution
-- to find.
instance has_scalar' : has_scalar R' (⨂[R] i, s i) :=
⟨λ r, lift_add_hom (λ f : R × Π i, s i, tprod_coeff R (r • f.1) f.2)
(λ r' f i hf, by simp_rw [zero_tprod_coeff' _ f i hf])
(λ f, by simp [zero_tprod_coeff])
(λ r' f i m₁ m₂, by simp [add_tprod_coeff])
(λ r' r'' f, by simp [add_tprod_coeff', mul_add])
(λ z f i r', by simp [smul_tprod_coeff])⟩
instance : has_scalar R (⨂[R] i, s i) := pi_tensor_product.has_scalar'
lemma smul_tprod_coeff' (r : R') (z : R) (f : Π i, s i) :
r • (tprod_coeff R z f) = tprod_coeff R (r • z) f := rfl
protected theorem smul_add (r : R') (x y : ⨂[R] i, s i) :
r • (x + y) = r • x + r • y :=
add_monoid_hom.map_add _ _ _
@[elab_as_eliminator]
protected theorem induction_on'
{C : (⨂[R] i, s i) → Prop}
(z : ⨂[R] i, s i)
(C1 : ∀ {r : R} {f : Π i, s i}, C (tprod_coeff R r f))
(Cp : ∀ {x y}, C x → C y → C (x + y)) : C z :=
begin
have C0 : C 0,
{ have h₁ := @C1 0 0,
rwa [zero_tprod_coeff] at h₁ },
refine add_con.induction_on z (λ x, free_add_monoid.rec_on x C0 _),
simp_rw add_con.coe_add,
refine λ f y ih, Cp _ ih,
convert @C1 f.1 f.2,
simp only [prod.mk.eta],
end
-- Most of the time we want the instance below this one, which is easier for typeclass resolution
-- to find.
instance module' : module R' (⨂[R] i, s i) :=
{ smul := (•),
smul_add := λ r x y, pi_tensor_product.smul_add r x y,
mul_smul := λ r r' x,
begin
refine pi_tensor_product.induction_on' x _ _,
{ intros r'' f,
simp [smul_tprod_coeff', smul_smul] },
{ intros x y ihx ihy,
simp [pi_tensor_product.smul_add, ihx, ihy] }
end,
one_smul := λ x, pi_tensor_product.induction_on' x
(λ f, by simp [smul_tprod_coeff' _ _])
(λ z y ihz ihy, by simp_rw [pi_tensor_product.smul_add, ihz, ihy]),
add_smul := λ r r' x,
begin
refine pi_tensor_product.induction_on' x _ _,
{ intros r f,
simp [smul_tprod_coeff' _ _, add_smul, add_tprod_coeff'] },
{ intros x y ihx ihy,
simp [pi_tensor_product.smul_add, ihx, ihy, add_add_add_comm] }
end,
smul_zero := λ r, add_monoid_hom.map_zero _,
zero_smul := λ x,
begin
refine pi_tensor_product.induction_on' x _ _,
{ intros r f,
simp_rw [smul_tprod_coeff' _ _, zero_smul],
exact zero_tprod_coeff _ },
{ intros x y ihx ihy,
rw [pi_tensor_product.smul_add, ihx, ihy, add_zero] },
end }
instance : module R' (⨂[R] i, s i) := pi_tensor_product.module'
variables {R}
variables (R)
/-- The canonical `multilinear_map R s (⨂[R] i, s i)`. -/
def tprod : multilinear_map R s (⨂[R] i, s i) :=
{ to_fun := tprod_coeff R 1,
map_add' := λ f i x y, (add_tprod_coeff (1 : R) f i x y).symm,
map_smul' := λ f i r x,
by simp_rw [smul_tprod_coeff', ←smul_tprod_coeff (1 : R) _ i, update_idem, update_same] }
variables {R}
notation `⨂ₜ[`:100 R`] ` binders `, ` r:(scoped:67 f, tprod R f) := r
@[simp]
lemma tprod_coeff_eq_smul_tprod (z : R) (f : Π i, s i) : tprod_coeff R z f = z • tprod R f :=
begin
have : z = z • (1 : R) := by simp only [mul_one, algebra.id.smul_eq_mul],
conv_lhs { rw this },
rw ←smul_tprod_coeff',
refl,
end
@[elab_as_eliminator]
protected theorem induction_on
{C : (⨂[R] i, s i) → Prop}
(z : ⨂[R] i, s i)
(C1 : ∀ {r : R} {f : Π i, s i}, C (r • (tprod R f)))
(Cp : ∀ {x y}, C x → C y → C (x + y)) : C z :=
begin
simp_rw ←tprod_coeff_eq_smul_tprod at C1,
exact pi_tensor_product.induction_on' z @C1 @Cp,
end
@[ext]
theorem ext {φ₁ φ₂ : (⨂[R] i, s i) →ₗ[R] E}
(H : φ₁.comp_multilinear_map (tprod R) = φ₂.comp_multilinear_map (tprod R)) : φ₁ = φ₂ :=
begin
refine linear_map.ext _,
refine λ z,
(pi_tensor_product.induction_on' z _ (λ x y hx hy, by rw [φ₁.map_add, φ₂.map_add, hx, hy])),
{ intros r f,
rw [tprod_coeff_eq_smul_tprod, φ₁.map_smul, φ₂.map_smul],
apply _root_.congr_arg,
exact multilinear_map.congr_fun H f }
end
end module
section multilinear
open multilinear_map
variables {s}
/-- Auxiliary function to constructing a linear map `(⨂[R] i, s i) → E` given a
`multilinear map R s E` with the property that its composition with the canonical
`multilinear_map R s (⨂[R] i, s i)` is the given multilinear map. -/
def lift_aux (φ : multilinear_map R s E) : (⨂[R] i, s i) →+ E :=
lift_add_hom (λ (p : R × Π i, s i), p.1 • (φ p.2))
(λ z f i hf, by rw [map_coord_zero φ i hf, smul_zero])
(λ f, by rw [zero_smul])
(λ z f i m₁ m₂, by rw [←smul_add, φ.map_add])
(λ z₁ z₂ f, by rw [←add_smul])
(λ z f i r, by simp [φ.map_smul, smul_smul, mul_comm])
lemma lift_aux_tprod (φ : multilinear_map R s E) (f : Π i, s i) : lift_aux φ (tprod R f) = φ f :=
by simp only [lift_aux, lift_add_hom, tprod, multilinear_map.coe_mk, tprod_coeff,
free_add_monoid.lift_eval_of, one_smul, add_con.lift_mk']
lemma lift_aux_tprod_coeff (φ : multilinear_map R s E) (z : R) (f : Π i, s i) :
lift_aux φ (tprod_coeff R z f) = z • φ f :=
by simp [lift_aux, lift_add_hom, tprod_coeff, free_add_monoid.lift_eval_of]
lemma lift_aux.smul {φ : multilinear_map R s E} (r : R) (x : ⨂[R] i, s i) :
lift_aux φ (r • x) = r • lift_aux φ x :=
begin
refine pi_tensor_product.induction_on' x _ _,
{ intros z f,
rw [smul_tprod_coeff' r z f, lift_aux_tprod_coeff, lift_aux_tprod_coeff, smul_assoc] },
{ intros z y ihz ihy,
rw [smul_add, (lift_aux φ).map_add, ihz, ihy, (lift_aux φ).map_add, smul_add] }
end
/-- Constructing a linear map `(⨂[R] i, s i) → E` given a `multilinear_map R s E` with the
property that its composition with the canonical `multilinear_map R s E` is
the given multilinear map `φ`. -/
def lift : (multilinear_map R s E) ≃ₗ[R] ((⨂[R] i, s i) →ₗ[R] E) :=
{ to_fun := λ φ, { map_smul' := lift_aux.smul, .. lift_aux φ },
inv_fun := λ φ', φ'.comp_multilinear_map (tprod R),
left_inv := λ φ, by { ext, simp [lift_aux_tprod, linear_map.comp_multilinear_map] },
right_inv := λ φ, by { ext, simp [lift_aux_tprod] },
map_add' := λ φ₁ φ₂, by { ext, simp [lift_aux_tprod] },
map_smul' := λ r φ₂, by { ext, simp [lift_aux_tprod] } }
variables {φ : multilinear_map R s E}
@[simp] lemma lift.tprod (f : Π i, s i) : lift φ (tprod R f) = φ f := lift_aux_tprod φ f
theorem lift.unique' {φ' : (⨂[R] i, s i) →ₗ[R] E} (H : φ'.comp_multilinear_map (tprod R) = φ) :
φ' = lift φ :=
ext $ H.symm ▸ (lift.symm_apply_apply φ).symm
theorem lift.unique {φ' : (⨂[R] i, s i) →ₗ[R] E} (H : ∀ f, φ' (tprod R f) = φ f) :
φ' = lift φ :=
lift.unique' (multilinear_map.ext H)
@[simp]
theorem lift_symm (φ' : (⨂[R] i, s i) →ₗ[R] E) : lift.symm φ' = φ'.comp_multilinear_map (tprod R) :=
rfl
@[simp]
theorem lift_tprod : lift (tprod R : multilinear_map R s _) = linear_map.id :=
eq.symm $ lift.unique' rfl
section
variables (R M)
/-- Re-index the components of the tensor power by `e`.
For simplicity, this is defined only for homogeneously- (rather than dependently-) typed components.
-/
def reindex (e : ι ≃ ι₂) : ⨂[R] i : ι, M ≃ₗ[R] ⨂[R] i : ι₂, M :=
linear_equiv.of_linear
(((lift.symm ≪≫ₗ
(multilinear_map.dom_dom_congr_linear_equiv M (⨂[R] i : ι₂, M) R R e.symm)) ≪≫ₗ
lift) (linear_map.id))
(((lift.symm ≪≫ₗ
(multilinear_map.dom_dom_congr_linear_equiv M (⨂[R] i : ι, M) R R e)) ≪≫ₗ
lift) (linear_map.id))
(by { ext, simp })
(by { ext, simp })
end
@[simp] lemma reindex_tprod (e : ι ≃ ι₂) (f : Π i, M) :
reindex R M e (tprod R f) = tprod R (λ i, f (e.symm i)) :=
lift.tprod f
@[simp] lemma reindex_comp_tprod (e : ι ≃ ι₂) :
(reindex R M e : ⨂[R] i : ι, M →ₗ[R] ⨂[R] i : ι₂, M).comp_multilinear_map (tprod R) =
(tprod R : multilinear_map R (λ i, M) _).dom_dom_congr e.symm :=
multilinear_map.ext $ reindex_tprod e
@[simp] lemma lift_comp_reindex (e : ι ≃ ι₂) (φ : multilinear_map R (λ _ : ι₂, M) E) :
(lift φ) ∘ₗ ↑(reindex R M e) = lift (φ.dom_dom_congr e.symm) :=
by { ext, simp, }
@[simp]
lemma lift_reindex (e : ι ≃ ι₂) (φ : multilinear_map R (λ _, M) E) (x : ⨂[R] i, M) :
lift φ (reindex R M e x) = lift (φ.dom_dom_congr e.symm) x :=
linear_map.congr_fun (lift_comp_reindex e φ) x
@[simp] lemma reindex_trans (e : ι ≃ ι₂) (e' : ι₂ ≃ ι₃) :
(reindex R M e).trans (reindex R M e') = reindex R M (e.trans e') :=
begin
apply linear_equiv.to_linear_map_injective,
ext f,
simp only [linear_equiv.trans_apply, linear_equiv.coe_coe, reindex_tprod,
linear_map.coe_comp_multilinear_map, function.comp_app, multilinear_map.dom_dom_congr_apply,
reindex_comp_tprod],
congr,
end
@[simp] lemma reindex_symm (e : ι ≃ ι₂) :
(reindex R M e).symm = reindex R M e.symm := rfl
@[simp] lemma reindex_refl : reindex R M (equiv.refl ι) = linear_equiv.refl R _ :=
begin
apply linear_equiv.to_linear_map_injective,
ext1,
rw [reindex_comp_tprod, linear_equiv.refl_to_linear_map, equiv.refl_symm],
refl,
end
/-- The tensor product over an empty set of indices is isomorphic to the base ring -/
def pempty_equiv : ⨂[R] i : pempty, M ≃ₗ[R] R :=
{ to_fun := lift ⟨λ (_ : pempty → M), (1 : R), λ v, pempty.elim, λ v, pempty.elim⟩,
inv_fun := λ r, r • tprod R (λ v, pempty.elim v),
left_inv := λ x, by {
apply x.induction_on,
{ intros r f,
have : f = (λ i, pempty.elim i) := funext (λ i, pempty.elim i),
simp [this], },
{ simp only,
intros x y hx hy,
simp [add_smul, hx, hy] }},
right_inv := λ t, by simp only [mul_one, algebra.id.smul_eq_mul, multilinear_map.coe_mk,
linear_map.map_smul, pi_tensor_product.lift.tprod],
map_add' := linear_map.map_add _,
map_smul' := linear_map.map_smul _, }
section tmul
/-- Collapse a `tensor_product` of `pi_tensor_product`s. -/
private def tmul : (⨂[R] i : ι, M) ⊗[R] (⨂[R] i : ι₂, M) →ₗ[R] ⨂[R] i : ι ⊕ ι₂, M :=
tensor_product.lift
{ to_fun := λ a, pi_tensor_product.lift $ pi_tensor_product.lift
(multilinear_map.curry_sum_equiv R _ _ M _ (tprod R)) a,
map_add' := λ a b, by simp only [linear_equiv.map_add, linear_map.map_add],
map_smul' := λ r a, by simp only [linear_equiv.map_smul, linear_map.map_smul,
ring_hom.id_apply], }
private lemma tmul_apply (a : ι → M) (b : ι₂ → M) :
tmul ((⨂ₜ[R] i, a i) ⊗ₜ[R] (⨂ₜ[R] i, b i)) = ⨂ₜ[R] i, sum.elim a b i :=
begin
erw [tensor_product.lift.tmul, pi_tensor_product.lift.tprod, pi_tensor_product.lift.tprod],
refl
end
/-- Expand `pi_tensor_product` into a `tensor_product` of two factors. -/
private def tmul_symm : ⨂[R] i : ι ⊕ ι₂, M →ₗ[R] (⨂[R] i : ι, M) ⊗[R] (⨂[R] i : ι₂, M) :=
-- by using tactic mode, we avoid the need for a lot of `@`s and `_`s
pi_tensor_product.lift $ by apply multilinear_map.dom_coprod; [exact tprod R, exact tprod R]
private lemma tmul_symm_apply (a : ι ⊕ ι₂ → M) :
tmul_symm (⨂ₜ[R] i, a i) = (⨂ₜ[R] i, a (sum.inl i)) ⊗ₜ[R] (⨂ₜ[R] i, a (sum.inr i)) :=
pi_tensor_product.lift.tprod _
variables (R M)
local attribute [ext] tensor_product.ext
/-- Equivalence between a `tensor_product` of `pi_tensor_product`s and a single
`pi_tensor_product` indexed by a `sum` type.
For simplicity, this is defined only for homogeneously- (rather than dependently-) typed components.
-/
def tmul_equiv : (⨂[R] i : ι, M) ⊗[R] (⨂[R] i : ι₂, M) ≃ₗ[R] ⨂[R] i : ι ⊕ ι₂, M :=
linear_equiv.of_linear tmul tmul_symm
(by { ext x,
show tmul (tmul_symm (tprod R x)) = tprod R x, -- Speed up the call to `simp`.
simp only [tmul_symm_apply, tmul_apply, sum.elim_comp_inl_inr], })
(by { ext x y,
show tmul_symm (tmul (tprod R x ⊗ₜ[R] tprod R y)) = tprod R x ⊗ₜ[R] tprod R y,
simp only [tmul_apply, tmul_symm_apply, sum.elim_inl, sum.elim_inr], })
@[simp] lemma tmul_equiv_apply (a : ι → M) (b : ι₂ → M) :
tmul_equiv R M ((⨂ₜ[R] i, a i) ⊗ₜ[R] (⨂ₜ[R] i, b i)) = ⨂ₜ[R] i, sum.elim a b i :=
tmul_apply a b
@[simp] lemma tmul_equiv_symm_apply (a : ι ⊕ ι₂ → M) :
(tmul_equiv R M).symm (⨂ₜ[R] i, a i) = (⨂ₜ[R] i, a (sum.inl i)) ⊗ₜ[R] (⨂ₜ[R] i, a (sum.inr i)) :=
tmul_symm_apply a
end tmul
end multilinear
end pi_tensor_product
end semiring
section ring
namespace pi_tensor_product
open pi_tensor_product
open_locale tensor_product
variables {ι : Type*} [decidable_eq ι] {R : Type*} [comm_ring R]
variables {s : ι → Type*} [∀ i, add_comm_group (s i)] [∀ i, module R (s i)]
/- Unlike for the binary tensor product, we require `R` to be a `comm_ring` here, otherwise
this is false in the case where `ι` is empty. -/
instance : add_comm_group (⨂[R] i, s i) := module.add_comm_monoid_to_add_comm_group R
end pi_tensor_product
end ring
|
a620ba2e5b3e70c947c58e1b64960e446c26ecd2 | e21db629d2e37a833531fdcb0b37ce4d71825408 | /src/mcl/ts_updates.lean | b2e8aa59493a3b94e0030ed8adaab0bce184145a | [] | no_license | fischerman/GPU-transformation-verifier | 614a28cb4606a05a0eb27e8d4eab999f4f5ea60c | 75a5016f05382738ff93ce5859c4cfa47ccb63c1 | refs/heads/master | 1,586,985,789,300 | 1,579,290,514,000 | 1,579,290,514,000 | 165,031,073 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,530 | lean | import mcl.defs
import mcl.rhl
import mcl.compute_list
open parlang
open parlang.state
open parlang.thread_state
open mcl
open mcl.rhl
inductive op (sig : signature)
| store {t} {dim} (var : string) (idx : vector (expression sig type.int) dim) (h₁ : type_of (sig.val var) = t) (h₂ : ((sig.val var).type).dim = dim) : op
| compute_list (computes : list (memory (parlang_mcl_tlocal sig) → memory (parlang_mcl_tlocal sig))) : op
def ts_updates {sig : signature} : list (op sig) → thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) → thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)
| [] ts := ts
| (op.store var idx h₁ h₂ :: ops) ts := ts_updates ops $ thread_state.tlocal_to_shared var idx h₁ h₂ ts
| (op.compute_list computes :: ops) ts := ts_updates ops $ compute_list computes ts
lemma ts_update_compute_list {sig : signature} (ups : list (op sig)) (computes) : ts_updates (op.compute_list computes :: ups) = ts_updates ups ∘ compute_list computes := by refl
lemma ts_update_split {sig : signature} (up) (ups : list (op sig)) : ts_updates (list.reverse (up :: ups)) = ts_updates [up] ∘ ts_updates (list.reverse ups) := begin
funext ts,
rw list.reverse_cons,
induction (list.reverse ups) generalizing ts,
{
refl,
}, {
simp,
cases hd;
rw ts_updates;
apply ih,
}
end
lemma ts_updates_tlocal {sig : signature} {ts : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} {updates} (m loads stores) :
(ts_updates updates ts).tlocal = (ts_updates updates { tlocal := ts.tlocal, loads := loads, stores := stores, shared := m }).tlocal := begin
sorry,
end
lemma ts_updates_nil {sig : signature} (f : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) → thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)) :
ts_updates [] ∘ f = f := begin
refl,
end
@[simp]
lemma ts_updates_store {sig : signature} {dim} {idx : vector (expression sig type.int) dim} {var t} {h₁ : type_of (sig.val var) = t} {h₂} {updates} (f : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) → thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)) :
ts_updates updates ∘ thread_state.tlocal_to_shared var idx h₁ h₂ ∘ f = ts_updates (op.store var idx h₁ h₂ :: updates) ∘ f := begin
refl,
end
@[simp]
lemma ts_updates_compute {sig : signature} {g} {updates} (f : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) → thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)) :
ts_updates updates ∘ compute g ∘ f = ts_updates (op.compute_list [g] :: updates) ∘ f := begin
refl,
end
@[simp]
lemma ts_updates_merge_computes_list {sig : signature} {updates} {com com' : list (memory (parlang_mcl_tlocal sig) → memory (parlang_mcl_tlocal sig))} :
ts_updates (op.compute_list com :: op.compute_list com' :: updates) = ts_updates (op.compute_list (com ++ com') :: updates) := begin
sorry,
end
@[simp]
lemma compute_list_stores' {sig : signature} {n} {tid : fin n} {ac : vector bool n} {computes}
{s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} :
(vector.nth ((map_active_threads ac (ts_updates [op.compute_list computes]) s).threads) tid).stores = (vector.nth s.threads tid).stores := begin
by_cases h : ac.nth tid = tt,
{
simp [ts_updates, map_active_threads_nth_ac h],
}, {
rw ←map_active_threads_nth_inac h,
}
end
@[simp]
lemma compute_list_loads' {sig : signature} {n} {tid : fin n} {ac : vector bool n} {computes}
{s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} :
(vector.nth ((map_active_threads ac (ts_updates [op.compute_list computes]) s).threads) tid).loads = (vector.nth s.threads tid).loads := begin
by_cases h : ac.nth tid = tt,
{
simp [ts_updates, map_active_threads_nth_ac h],
}, {
rw ←map_active_threads_nth_inac h,
}
end
@[simp]
lemma compute_list_shared' {sig : signature} {n} {tid : fin n} {ac : vector bool n} {computes}
{s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} :
(vector.nth ((map_active_threads ac (ts_updates [op.compute_list computes]) s).threads) tid).shared = (vector.nth s.threads tid).shared := begin
by_cases h : ac.nth tid = tt,
{
simp [ts_updates, map_active_threads_nth_ac h],
}, {
rw ←map_active_threads_nth_inac h,
}
end |
ee3be7495ba9411dd7aef312d117d7a7ba797f29 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Std/System.lean | dc8506a6120ca7ba61bb65e5d2334fc6abffdc8c | [
"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 | 22 | lean | import Std.System.Uri
|
2e9ec3bb61cafb47f9773edde38fb4166deccba6 | e30ff3aabdac29f8ea40ad76887544d0f9be9018 | /ircbot/effects.lean | 2bc09922a2dbf61293b5449ee37cd2de9c7e6ae7 | [] | no_license | forked-from-1kasper/leanbot | bdef0efa3e4d0eb75b06c1707fb4e35086bb57fa | c61c8c7fdad7b05877e0d232719ce23d2999557f | refs/heads/master | 1,651,846,081,986 | 1,646,404,009,000 | 1,646,404,009,000 | 127,132,795 | 12 | 1 | null | 1,605,183,650,000 | 1,522,237,998,000 | Lean | UTF-8 | Lean | false | false | 2,765 | lean | import system.io data.buffer.parser
import ircbot.types ircbot.parsing ircbot.support ircbot.unicode ircbot.datetime
namespace effects
open parser
open parsing types support datetime
structure provider :=
(read : io string)
(write : string → io unit)
(close : io unit)
def string.decode (conf : bot) (buff : char_buffer) :=
match conf.fix.read with
| ff := buffer.to_string buff
| tt := option.get_or_else (unicode.utf8_to_string buff) ""
end
def string.encode (conf : bot) (s : string) :=
match conf.fix.write with
| ff := s
| tt := unicode.string_to_utf8 s
end
def netcat (conf : bot) : io provider := do
proc ← io.proc.spawn
{ cmd := "nc",
args := [conf.info.server, conf.info.port],
stdin := io.process.stdio.piped,
stdout := io.process.stdio.piped },
pure { read := string.decode conf <$> io.fs.get_line proc.stdout,
write := λ s, io.fs.put_str_ln proc.stdin
(string.encode conf s) >> io.fs.flush proc.stdin,
close := io.proc.wait proc >> pure () }
def std (conf : bot) : io provider := do
io.put_str_ln "*** DEBUG ***",
pure { read := io.put_str "> " >> (++ "\n") <$> io.get_line,
write := function.const string (pure ()),
close := pure () }
/-- Return current date. -/
def get_date : io (option date) := do
date_proc ← io.proc.spawn
{ cmd := "date",
args := [date_format],
stdin := io.process.stdio.piped,
stdout := io.process.stdio.piped },
unparsed_date_io ← io.fs.get_line date_proc.stdout,
io.fs.close date_proc.stdout,
io.proc.wait date_proc,
let unparsed := buffer.to_string unparsed_date_io,
sum.cases_on (run_string DateParser unparsed)
(λ _, pure none) (pure ∘ some)
private def wrapped_put (prov : provider)
(s : string) : io unit :=
prov.write s >> io.put_str_ln (sformat! "+ {s}")
private def send (prov : provider) (messages : list irc_text) := do
list.foldl (>>) (pure ()) $ (wrapped_put prov ∘ to_string) <$> messages
private def loop (conf : bot) (prov : provider) : io unit := do
line ← prov.read,
if line.length > 0 then
io.put_str (sformat! "- {line}")
else pure (),
let text : irc_text :=
sum.cases_on (run_string NormalMessage line)
(λ _, irc_text.raw_text line.trim_nl) id,
messages ← list.join <$> sequence (flip bot_function.func text <$> conf.funcs),
send prov messages,
sum.cases_on (run_string Ping line)
(λ _, pure ()) (wrapped_put prov ∘ to_string)
def mk_bot' (conf : bot) (prov : io provider) : io unit := do
inst ← prov, send inst conf.info.on_start,
io.forever (loop conf inst), io.put_str "* OK",
inst.close
/-- Run a bot. -/
def mk_bot (conf : bot) (f : bot → io provider) : io unit :=
mk_bot' conf (f conf)
end effects |
acaab03b48526e43a5a2ca17fd6d19bb102dd11b | f5f7e6fae601a5fe3cac7cc3ed353ed781d62419 | /src/topology/bases.lean | 8d3fc1137d9614418d80c9684ac28071ae968406 | [
"Apache-2.0"
] | permissive | EdAyers/mathlib | 9ecfb2f14bd6caad748b64c9c131befbff0fb4e0 | ca5d4c1f16f9c451cf7170b10105d0051db79e1b | refs/heads/master | 1,626,189,395,845 | 1,555,284,396,000 | 1,555,284,396,000 | 144,004,030 | 0 | 0 | Apache-2.0 | 1,533,727,664,000 | 1,533,727,663,000 | null | UTF-8 | Lean | false | false | 10,483 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
Bases of topologies. Countability axioms.
-/
import topology.order
open set filter lattice classical
namespace topological_space
/- countability axioms
For our applications we are interested that there exists a countable basis, but we do not need the
concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins.
-/
universe u
variables {α : Type u} [t : topological_space α]
include t
/-- A topological basis is one that satisfies the necessary conditions so that
it suffices to take unions of the basis sets to get a topology (without taking
finite intersections as well). -/
def is_topological_basis (s : set (set α)) : Prop :=
(∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂) ∧
(⋃₀ s) = univ ∧
t = generate_from s
lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) :
is_topological_basis ((λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅}) :=
let b' := (λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅} in
⟨assume s₁ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, eq₁⟩ s₂ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, eq₂⟩,
have ie : ⋂₀(t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂, from Inf_union,
eq₁ ▸ eq₂ ▸ assume x h,
⟨_, ⟨t₁ ∪ t₂, ⟨finite_union hft₁ hft₂, union_subset ht₁b ht₂b,
by simpa only [ie] using ne_empty_of_mem h⟩, ie⟩, h, subset.refl _⟩,
eq_univ_iff_forall.2 $ assume a, ⟨univ, ⟨∅, ⟨finite_empty, empty_subset _,
by rw sInter_empty; exact nonempty_iff_univ_ne_empty.1 ⟨a⟩⟩, sInter_empty⟩, mem_univ _⟩,
have generate_from s = generate_from b',
from le_antisymm
(generate_from_le $ assume s hs,
by_cases
(assume : s = ∅, by rw [this]; apply @is_open_empty _ _)
(assume : s ≠ ∅, generate_open.basic _ ⟨{s}, ⟨finite_singleton s, singleton_subset_iff.2 hs,
by rwa [sInter_singleton]⟩, sInter_singleton s⟩))
(generate_from_le $ assume u ⟨t, ⟨hft, htb, ne⟩, eq⟩,
eq ▸ @is_open_sInter _ (generate_from s) _ hft (assume s hs, generate_open.basic _ $ htb hs)),
this ▸ hs⟩
lemma is_topological_basis_of_open_of_nhds {s : set (set α)}
(h_open : ∀ u ∈ s, _root_.is_open u)
(h_nhds : ∀(a:α) (u : set α), a ∈ u → _root_.is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) :
is_topological_basis s :=
⟨assume t₁ ht₁ t₂ ht₂ x ⟨xt₁, xt₂⟩,
h_nhds x (t₁ ∩ t₂) ⟨xt₁, xt₂⟩
(is_open_inter _ _ _ (h_open _ ht₁) (h_open _ ht₂)),
eq_univ_iff_forall.2 $ assume a,
let ⟨u, h₁, h₂, _⟩ := h_nhds a univ trivial (is_open_univ _) in
⟨u, h₁, h₂⟩,
le_antisymm
(assume u hu,
(@is_open_iff_nhds α (generate_from _) _).mpr $ assume a hau,
let ⟨v, hvs, hav, hvu⟩ := h_nhds a u hau hu in
by rw nhds_generate_from; exact infi_le_of_le v (infi_le_of_le ⟨hav, hvs⟩ $ le_principal_iff.2 hvu))
(generate_from_le h_open)⟩
lemma mem_nhds_of_is_topological_basis {a : α} {s : set α} {b : set (set α)}
(hb : is_topological_basis b) : s ∈ nhds a ↔ ∃t∈b, a ∈ t ∧ t ⊆ s :=
begin
change s ∈ (nhds a).sets ↔ ∃t∈b, a ∈ t ∧ t ⊆ s,
rw [hb.2.2, nhds_generate_from, infi_sets_eq'],
{ simp only [mem_bUnion_iff, exists_prop, mem_set_of_eq, and_assoc, and.left_comm], refl },
{ exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩,
have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩,
let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in
⟨u, ⟨hu₂, hu₁⟩, le_principal_iff.2 (subset.trans hu₃ (inter_subset_left _ _)),
le_principal_iff.2 (subset.trans hu₃ (inter_subset_right _ _))⟩ },
{ rcases eq_univ_iff_forall.1 hb.2.1 a with ⟨i, h1, h2⟩,
exact ⟨i, h2, h1⟩ }
end
lemma is_open_of_is_topological_basis {s : set α} {b : set (set α)}
(hb : is_topological_basis b) (hs : s ∈ b) : _root_.is_open s :=
is_open_iff_mem_nhds.2 $ λ a as,
(mem_nhds_of_is_topological_basis hb).2 ⟨s, hs, as, subset.refl _⟩
lemma mem_basis_subset_of_mem_open {b : set (set α)}
(hb : is_topological_basis b) {a:α} {u : set α} (au : a ∈ u)
(ou : _root_.is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u :=
(mem_nhds_of_is_topological_basis hb).1 $ mem_nhds_sets ou au
lemma sUnion_basis_of_is_open {B : set (set α)}
(hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) :
∃ S ⊆ B, u = ⋃₀ S :=
⟨{s ∈ B | s ⊆ u}, λ s h, h.1, set.ext $ λ a,
⟨λ ha, let ⟨b, hb, ab, bu⟩ := mem_basis_subset_of_mem_open hB ha ou in
⟨b, ⟨hb, bu⟩, ab⟩,
λ ⟨b, ⟨hb, bu⟩, ab⟩, bu ab⟩⟩
lemma Union_basis_of_is_open {B : set (set α)}
(hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) :
∃ (β : Type u) (f : β → set α), u = (⋃ i, f i) ∧ ∀ i, f i ∈ B :=
let ⟨S, sb, su⟩ := sUnion_basis_of_is_open hB ou in
⟨S, subtype.val, su.trans set.sUnion_eq_Union, λ ⟨b, h⟩, sb h⟩
variables (α)
/-- A separable space is one with a countable dense subset. -/
class separable_space : Prop :=
(exists_countable_closure_eq_univ : ∃s:set α, countable s ∧ closure s = univ)
/-- A first-countable space is one in which every point has a
countable neighborhood basis. -/
class first_countable_topology : Prop :=
(nhds_generated_countable : ∀a:α, ∃s:set (set α), countable s ∧ nhds a = (⨅t∈s, principal t))
/-- A second-countable space is one with a countable basis. -/
class second_countable_topology : Prop :=
(is_open_generated_countable : ∃b:set (set α), countable b ∧ t = topological_space.generate_from b)
instance second_countable_topology.to_first_countable_topology
[second_countable_topology α] : first_countable_topology α :=
let ⟨b, hb, eq⟩ := second_countable_topology.is_open_generated_countable α in
⟨assume a, ⟨{s | a ∈ s ∧ s ∈ b},
countable_subset (assume x ⟨_, hx⟩, hx) hb, by rw [eq, nhds_generate_from]⟩⟩
lemma second_countable_topology_induced (β)
[t : topological_space β] [second_countable_topology β] (f : α → β) :
@second_countable_topology α (t.induced f) :=
begin
rcases second_countable_topology.is_open_generated_countable β with ⟨b, hb, eq⟩,
refine { is_open_generated_countable := ⟨preimage f '' b, countable_image _ hb, _⟩ },
rw [eq, induced_generate_from_eq]
end
instance subtype.second_countable_topology
(s : set α) [topological_space α] [second_countable_topology α] : second_countable_topology s :=
second_countable_topology_induced s α coe
lemma is_open_generated_countable_inter [second_countable_topology α] :
∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b :=
let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in
let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ s ⊆ b ∧ ⋂₀ s ≠ ∅} in
⟨b',
countable_image _ $ countable_subset
(by simp only [(and_assoc _ _).symm]; exact inter_subset_left _ _)
(countable_set_of_finite_subset hb₁),
assume ⟨s, ⟨_, _, hn⟩, hp⟩, hn hp,
is_topological_basis_of_subbasis hb₂⟩
instance second_countable_topology.to_separable_space
[second_countable_topology α] : separable_space α :=
let ⟨b, hb₁, hb₂, hb₃, hb₄, eq⟩ := is_open_generated_countable_inter α in
have nhds_eq : ∀a, nhds a = (⨅ s : {s : set α // a ∈ s ∧ s ∈ b}, principal s.val),
by intro a; rw [eq, nhds_generate_from, infi_subtype]; refl,
have ∀s∈b, ∃a, a ∈ s, from assume s hs, exists_mem_of_ne_empty $ assume eq, hb₂ $ eq ▸ hs,
have ∃f:∀s∈b, α, ∀s h, f s h ∈ s, by simp only [skolem] at this; exact this,
let ⟨f, hf⟩ := this in
⟨⟨(⋃s∈b, ⋃h:s∈b, {f s h}),
countable_bUnion hb₁ (λ _ _, countable_Union_Prop $ λ _, countable_singleton _),
set.ext $ assume a,
have a ∈ (⋃₀ b), by rw [hb₄]; exact trivial,
let ⟨t, ht₁, ht₂⟩ := this in
have w : {s : set α // a ∈ s ∧ s ∈ b}, from ⟨t, ht₂, ht₁⟩,
suffices (⨅ (x : {s // a ∈ s ∧ s ∈ b}), principal (x.val ∩ ⋃s (h₁ h₂ : s ∈ b), {f s h₂})) ≠ ⊥,
by simpa only [closure_eq_nhds, nhds_eq, infi_inf w, inf_principal, mem_set_of_eq, mem_univ, iff_true],
infi_neq_bot_of_directed ⟨a⟩
(assume ⟨s₁, has₁, hs₁⟩ ⟨s₂, has₂, hs₂⟩,
have a ∈ s₁ ∩ s₂, from ⟨has₁, has₂⟩,
let ⟨s₃, hs₃, has₃, hs⟩ := hb₃ _ hs₁ _ hs₂ _ this in
⟨⟨s₃, has₃, hs₃⟩, begin
simp only [le_principal_iff, mem_principal_sets, (≥)],
simp only [subset_inter_iff] at hs, split;
apply inter_subset_inter_left; simp only [hs]
end⟩)
(assume ⟨s, has, hs⟩,
have s ∩ (⋃ (s : set α) (H h : s ∈ b), {f s h}) ≠ ∅,
from ne_empty_of_mem ⟨hf _ hs, mem_bUnion hs $ mem_Union.mpr ⟨hs, mem_singleton _⟩⟩,
mt principal_eq_bot_iff.1 this) ⟩⟩
variables {α}
lemma is_open_Union_countable [second_countable_topology α]
{ι} (s : ι → set α) (H : ∀ i, _root_.is_open (s i)) :
∃ T : set ι, countable T ∧ (⋃ i ∈ T, s i) = ⋃ i, s i :=
let ⟨B, cB, _, bB⟩ := is_open_generated_countable_inter α in
begin
let B' := {b ∈ B | ∃ i, b ⊆ s i},
choose f hf using λ b:B', b.2.2,
haveI : encodable B' := (countable_subset (sep_subset _ _) cB).to_encodable,
refine ⟨_, countable_range f,
subset.antisymm (bUnion_subset_Union _ _) (sUnion_subset _)⟩,
rintro _ ⟨i, rfl⟩ x xs,
rcases mem_basis_subset_of_mem_open bB xs (H _) with ⟨b, hb, xb, bs⟩,
exact ⟨_, ⟨_, rfl⟩, _, ⟨⟨⟨_, hb, _, bs⟩, rfl⟩, rfl⟩, hf _ (by exact xb)⟩
end
lemma is_open_sUnion_countable [second_countable_topology α]
(S : set (set α)) (H : ∀ s ∈ S, _root_.is_open s) :
∃ T : set (set α), countable T ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S :=
let ⟨T, cT, hT⟩ := is_open_Union_countable (λ s:S, s.1) (λ s, H s.1 s.2) in
⟨subtype.val '' T, countable_image _ cT,
image_subset_iff.2 $ λ ⟨x, xs⟩ xt, xs,
by rwa [sUnion_image, sUnion_eq_Union]⟩
end topological_space
|
79f7213b7ad64141ad73041db1ebc6f4ddb24540 | b3fced0f3ff82d577384fe81653e47df68bb2fa1 | /src/data/equiv/basic.lean | 88201af25e24091c5c027ebea1d0017f01c00842 | [
"Apache-2.0"
] | permissive | ratmice/mathlib | 93b251ef5df08b6fd55074650ff47fdcc41a4c75 | 3a948a6a4cd5968d60e15ed914b1ad2f4423af8d | refs/heads/master | 1,599,240,104,318 | 1,572,981,183,000 | 1,572,981,183,000 | 219,830,178 | 0 | 0 | Apache-2.0 | 1,572,980,897,000 | 1,572,980,896,000 | null | UTF-8 | Lean | false | false | 42,641 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Mario Carneiro
In the standard library we cannot assume the univalence axiom.
We say two types are equivalent if they are isomorphic.
Two equivalent types have the same cardinality.
-/
import tactic.split_ifs logic.function logic.unique data.set.function data.bool data.quot
open function
universes u v w
variables {α : Sort u} {β : Sort v} {γ : Sort w}
/-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/
structure equiv (α : Sort*) (β : Sort*) :=
(to_fun : α → β)
(inv_fun : β → α)
(left_inv : left_inverse inv_fun to_fun)
(right_inv : right_inverse inv_fun to_fun)
infix ` ≃ `:25 := equiv
def function.involutive.to_equiv {f : α → α} (h : involutive f) : α ≃ α :=
⟨f, f, h.left_inverse, h.right_inverse⟩
namespace equiv
/-- `perm α` is the type of bijections from `α` to itself. -/
@[reducible] def perm (α : Sort*) := equiv α α
instance : has_coe_to_fun (α ≃ β) :=
⟨_, to_fun⟩
@[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f :=
rfl
theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : equiv α β}, (e₁ : α → β) = e₂ → e₁ = e₂
| ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h :=
have f₁ = f₂, from h,
have g₁ = g₂, from funext $ assume x,
have f₁ (g₁ x) = f₂ (g₂ x), from (r₁ x).trans (r₂ x).symm,
have f₁ (g₁ x) = f₁ (g₂ x), by { subst f₂, exact this },
show g₁ x = g₂ x, from injective_of_left_inverse l₁ this,
by simp *
@[extensionality] lemma ext (f g : equiv α β) (H : ∀ x, f x = g x) : f = g :=
eq_of_to_fun_eq (funext H)
@[extensionality] lemma perm.ext (σ τ : equiv.perm α) (H : ∀ x, σ x = τ x) : σ = τ :=
equiv.ext _ _ H
@[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩
@[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩
@[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ :=
⟨e₂.to_fun ∘ e₁.to_fun, e₁.inv_fun ∘ e₂.inv_fun,
e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩
protected theorem injective : ∀ f : α ≃ β, injective f
| ⟨f, g, h₁, h₂⟩ := injective_of_left_inverse h₁
protected theorem surjective : ∀ f : α ≃ β, surjective f
| ⟨f, g, h₁, h₂⟩ := surjective_of_has_right_inverse ⟨_, h₂⟩
protected theorem bijective (f : α ≃ β) : bijective f :=
⟨f.injective, f.surjective⟩
protected theorem subsingleton (e : α ≃ β) : ∀ [subsingleton β], subsingleton α
| ⟨H⟩ := ⟨λ a b, e.injective (H _ _)⟩
protected def decidable_eq (e : α ≃ β) [H : decidable_eq β] : decidable_eq α
| a b := decidable_of_iff _ e.injective.eq_iff
lemma nonempty_iff_nonempty : α ≃ β → (nonempty α ↔ nonempty β)
| ⟨f, g, _, _⟩ := nonempty.congr f g
protected def cast {α β : Sort*} (h : α = β) : α ≃ β :=
⟨cast h, cast h.symm, λ x, by { cases h, refl }, λ x, by { cases h, refl }⟩
@[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g :=
rfl
@[simp] theorem refl_apply (x : α) : equiv.refl α x = x := rfl
@[simp] theorem trans_apply (f : α ≃ β) (g : β ≃ γ) (a : α) : (f.trans g) a = g (f a) := rfl
@[simp] theorem apply_symm_apply : ∀ (e : α ≃ β) (x : β), e (e.symm x) = x
| ⟨f₁, g₁, l₁, r₁⟩ x := by { simp [equiv.symm], rw r₁ }
@[simp] theorem symm_apply_apply : ∀ (e : α ≃ β) (x : α), e.symm (e x) = x
| ⟨f₁, g₁, l₁, r₁⟩ x := by { simp [equiv.symm], rw l₁ }
@[simp] lemma symm_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) :
(f.trans g).symm a = f.symm (g.symm a) := rfl
@[simp] theorem apply_eq_iff_eq : ∀ (f : α ≃ β) (x y : α), f x = f y ↔ x = y
| ⟨f₁, g₁, l₁, r₁⟩ x y := (injective_of_left_inverse l₁).eq_iff
@[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl
lemma symm_apply_eq {α β} (e : α ≃ β) {x y} : e.symm x = y ↔ x = e y :=
⟨λ H, by simp [H.symm], λ H, by simp [H]⟩
lemma eq_symm_apply {α β} (e : α ≃ β) {x y} : y = e.symm x ↔ e y = x :=
(eq_comm.trans e.symm_apply_eq).trans eq_comm
@[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := by { cases e, refl }
@[simp] theorem symm_symm_apply (e : α ≃ β) (a : α) : e.symm.symm a = e a := by { cases e, refl }
@[simp] theorem trans_refl (e : α ≃ β) : e.trans (equiv.refl β) = e := by { cases e, refl }
@[simp] theorem refl_symm : (equiv.refl α).symm = equiv.refl α := rfl
@[simp] theorem refl_trans (e : α ≃ β) : (equiv.refl α).trans e = e := by { cases e, refl }
@[simp] theorem symm_trans (e : α ≃ β) : e.symm.trans e = equiv.refl β := ext _ _ (by simp)
@[simp] theorem trans_symm (e : α ≃ β) : e.trans e.symm = equiv.refl α := ext _ _ (by simp)
lemma trans_assoc {δ} (ab : α ≃ β) (bc : β ≃ γ) (cd : γ ≃ δ) :
(ab.trans bc).trans cd = ab.trans (bc.trans cd) :=
equiv.ext _ _ $ assume a, rfl
theorem left_inverse_symm (f : equiv α β) : left_inverse f.symm f := f.left_inv
theorem right_inverse_symm (f : equiv α β) : function.right_inverse f.symm f := f.right_inv
def equiv_congr {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) :=
⟨ λac, (ab.symm.trans ac).trans cd, λbd, ab.trans $ bd.trans $ cd.symm,
assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end,
assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end, ⟩
def perm_congr {α : Type*} {β : Type*} (e : α ≃ β) : perm α ≃ perm β :=
equiv_congr e e
protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s :=
set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv
protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) : t ⊆ e '' s ↔ e.symm '' t ⊆ s :=
by rw [set.image_subset_iff, e.image_eq_preimage]
lemma symm_image_image {α β} (f : equiv α β) (s : set α) : f.symm '' (f '' s) = s :=
by { rw [← set.image_comp], simp }
protected lemma image_compl {α β} (f : equiv α β) (s : set α) :
f '' -s = -(f '' s) :=
set.image_compl_eq f.bijective
/- The group of permutations (self-equivalences) of a type `α` -/
namespace perm
instance perm_group {α : Type u} : group (perm α) :=
begin
refine { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv:= equiv.symm, ..};
intros; apply equiv.ext; try { apply trans_apply },
apply symm_apply_apply
end
@[simp] theorem mul_apply {α : Type u} (f g : perm α) (x) : (f * g) x = f (g x) :=
equiv.trans_apply _ _ _
@[simp] theorem one_apply {α : Type u} (x) : (1 : perm α) x = x := rfl
@[simp] lemma inv_apply_self {α : Type u} (f : perm α) (x) :
f⁻¹ (f x) = x := equiv.symm_apply_apply _ _
@[simp] lemma apply_inv_self {α : Type u} (f : perm α) (x) :
f (f⁻¹ x) = x := equiv.apply_symm_apply _ _
lemma one_def {α : Type u} : (1 : perm α) = equiv.refl α := rfl
lemma mul_def {α : Type u} (f g : perm α) : f * g = g.trans f := rfl
lemma inv_def {α : Type u} (f : perm α) : f⁻¹ = f.symm := rfl
end perm
def equiv_empty (h : α → false) : α ≃ empty :=
⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩
def false_equiv_empty : false ≃ empty :=
equiv_empty _root_.id
def equiv_pempty (h : α → false) : α ≃ pempty :=
⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩
def false_equiv_pempty : false ≃ pempty :=
equiv_pempty _root_.id
def empty_equiv_pempty : empty ≃ pempty :=
equiv_pempty $ empty.rec _
def pempty_equiv_pempty : pempty.{v} ≃ pempty.{w} :=
equiv_pempty pempty.elim
def empty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ empty :=
equiv_empty $ assume a, h ⟨a⟩
def pempty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ pempty :=
equiv_pempty $ assume a, h ⟨a⟩
def prop_equiv_punit {p : Prop} (h : p) : p ≃ punit :=
⟨λ x, (), λ x, h, λ _, rfl, λ ⟨⟩, rfl⟩
def true_equiv_punit : true ≃ punit := prop_equiv_punit trivial
protected def ulift {α : Type u} : ulift α ≃ α :=
⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩
protected def plift : plift α ≃ α :=
⟨plift.down, plift.up, plift.up_down, plift.down_up⟩
@[congr] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(α₁ → β₁) ≃ (α₂ → β₂) :=
{ to_fun := λ f, e₂.to_fun ∘ f ∘ e₁.inv_fun,
inv_fun := λ f, e₂.inv_fun ∘ f ∘ e₁.to_fun,
left_inv := λ f, funext $ λ x, by { dsimp, rw [e₂.left_inv, e₁.left_inv] },
right_inv := λ f, funext $ λ x, by { dsimp, rw [e₂.right_inv, e₁.right_inv] } }
@[simp] lemma arrow_congr_apply {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂)
(f : α₁ → β₁) (x : α₂) :
arrow_congr e₁ e₂ f x = (e₂ $ f $ e₁.symm x) :=
rfl
lemma arrow_congr_comp {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*}
(ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ → β₁) (g : β₁ → γ₁) :
arrow_congr ea ec (g ∘ f) = (arrow_congr eb ec g) ∘ (arrow_congr ea eb f) :=
by { ext, simp only [comp, arrow_congr_apply, eb.symm_apply_apply] }
@[simp] lemma arrow_congr_refl {α β : Sort*} :
arrow_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl
@[simp] lemma arrow_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*}
(e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) :
arrow_congr (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr e₁ e₁').trans (arrow_congr e₂ e₂') :=
rfl
@[simp] lemma arrow_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(arrow_congr e₁ e₂).symm = arrow_congr e₁.symm e₂.symm :=
rfl
def conj (e : α ≃ β) : (α → α) ≃ (β → β) := arrow_congr e e
@[simp] lemma conj_apply (e : α ≃ β) (f : α → α) (x : β) :
e.conj f x = (e $ f $ e.symm x) :=
rfl
@[simp] lemma conj_refl : conj (equiv.refl α) = equiv.refl (α → α) := rfl
@[simp] lemma conj_symm (e : α ≃ β) : e.conj.symm = e.symm.conj := rfl
@[simp] lemma conj_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) :
(e₁.trans e₂).conj = e₁.conj.trans e₂.conj :=
rfl
@[simp] lemma conj_comp (e : α ≃ β) (f₁ f₂ : α → α) :
e.conj (f₁ ∘ f₂) = (e.conj f₁) ∘ (e.conj f₂) :=
by apply arrow_congr_comp
def punit_equiv_punit : punit.{v} ≃ punit.{w} :=
⟨λ _, punit.star, λ _, punit.star, λ u, by { cases u, refl }, λ u, by { cases u, reflexivity }⟩
section
@[simp] def arrow_punit_equiv_punit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} :=
⟨λ f, punit.star, λ u f, punit.star,
λ f, by { funext x, cases f x, refl }, λ u, by { cases u, reflexivity }⟩
@[simp] def punit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α :=
⟨λ f, f punit.star, λ a u, a, λ f, by { funext x, cases x, refl }, λ u, rfl⟩
@[simp] def empty_arrow_equiv_punit (α : Sort*) : (empty → α) ≃ punit.{u} :=
⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by { cases u, refl }⟩
@[simp] def pempty_arrow_equiv_punit (α : Sort*) : (pempty → α) ≃ punit.{u} :=
⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by { cases u, refl }⟩
@[simp] def false_arrow_equiv_punit (α : Sort*) : (false → α) ≃ punit.{u} :=
calc (false → α) ≃ (empty → α) : arrow_congr false_equiv_empty (equiv.refl _)
... ≃ punit : empty_arrow_equiv_punit _
end
@[congr] def prod_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ :β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ :=
⟨λp, (e₁ p.1, e₂ p.2), λp, (e₁.symm p.1, e₂.symm p.2),
λ ⟨a, b⟩, show (e₁.symm (e₁ a), e₂.symm (e₂ b)) = (a, b), by rw [symm_apply_apply, symm_apply_apply],
λ ⟨a, b⟩, show (e₁ (e₁.symm a), e₂ (e₂.symm b)) = (a, b), by rw [apply_symm_apply, apply_symm_apply]⟩
@[simp] theorem prod_congr_apply {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) (b : β₁) :
prod_congr e₁ e₂ (a, b) = (e₁ a, e₂ b) :=
rfl
@[simp] def prod_comm (α β : Sort*) : α × β ≃ β × α :=
⟨λ p, (p.2, p.1), λ p, (p.2, p.1), λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩
@[simp] def prod_assoc (α β γ : Sort*) : (α × β) × γ ≃ α × (β × γ) :=
⟨λ p, ⟨p.1.1, ⟨p.1.2, p.2⟩⟩, λp, ⟨⟨p.1, p.2.1⟩, p.2.2⟩, λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩
@[simp] theorem prod_assoc_apply {α β γ : Sort*} (p : (α × β) × γ) :
prod_assoc α β γ p = ⟨p.1.1, ⟨p.1.2, p.2⟩⟩ := rfl
section
@[simp] def prod_punit (α : Sort*) : α × punit.{u+1} ≃ α :=
⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩
@[simp] theorem prod_punit_apply {α : Sort*} (a : α × punit.{u+1}) : prod_punit α a = a.1 := rfl
@[simp] def punit_prod (α : Sort*) : punit.{u+1} × α ≃ α :=
calc punit × α ≃ α × punit : prod_comm _ _
... ≃ α : prod_punit _
@[simp] theorem punit_prod_apply {α : Sort*} (a : punit.{u+1} × α) : punit_prod α a = a.2 := rfl
@[simp] def prod_empty (α : Sort*) : α × empty ≃ empty :=
equiv_empty (λ ⟨_, e⟩, e.rec _)
@[simp] def empty_prod (α : Sort*) : empty × α ≃ empty :=
equiv_empty (λ ⟨e, _⟩, e.rec _)
@[simp] def prod_pempty (α : Sort*) : α × pempty ≃ pempty :=
equiv_pempty (λ ⟨_, e⟩, e.rec _)
@[simp] def pempty_prod (α : Sort*) : pempty × α ≃ pempty :=
equiv_pempty (λ ⟨e, _⟩, e.rec _)
end
section
open sum
def psum_equiv_sum (α β : Sort*) : psum α β ≃ α ⊕ β :=
⟨λ s, psum.cases_on s inl inr,
λ s, sum.cases_on s psum.inl psum.inr,
λ s, by cases s; refl,
λ s, by cases s; refl⟩
def sum_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → α₁ ⊕ β₁ ≃ α₂ ⊕ β₂
| ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ :=
⟨λ s, match s with inl a₁ := inl (f₁ a₁) | inr b₁ := inr (f₂ b₁) end,
λ s, match s with inl a₂ := inl (g₁ a₂) | inr b₂ := inr (g₂ b₂) end,
λ s, match s with inl a := congr_arg inl (l₁ a) | inr a := congr_arg inr (l₂ a) end,
λ s, match s with inl a := congr_arg inl (r₁ a) | inr a := congr_arg inr (r₂ a) end⟩
@[simp] theorem sum_congr_apply_inl {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) :
sum_congr e₁ e₂ (inl a) = inl (e₁ a) :=
by { cases e₁, cases e₂, refl }
@[simp] theorem sum_congr_apply_inr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (b : β₁) :
sum_congr e₁ e₂ (inr b) = inr (e₂ b) :=
by { cases e₁, cases e₂, refl }
@[simp] lemma sum_congr_symm {α β γ δ : Type u} (e : α ≃ β) (f : γ ≃ δ) (x) :
(equiv.sum_congr e f).symm x = (equiv.sum_congr (e.symm) (f.symm)) x :=
by { cases e, cases f, cases x; refl }
def bool_equiv_punit_sum_punit : bool ≃ punit.{u+1} ⊕ punit.{v+1} :=
⟨λ b, cond b (inr punit.star) (inl punit.star),
λ s, sum.rec_on s (λ_, ff) (λ_, tt),
λ b, by cases b; refl,
λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩
noncomputable def Prop_equiv_bool : Prop ≃ bool :=
⟨λ p, @to_bool p (classical.prop_decidable _),
λ b, b, λ p, by simp, λ b, by simp⟩
@[simp] def sum_comm (α β : Sort*) : α ⊕ β ≃ β ⊕ α :=
⟨λ s, match s with inl a := inr a | inr b := inl b end,
λ s, match s with inl b := inr b | inr a := inl a end,
λ s, by cases s; refl,
λ s, by cases s; refl⟩
@[simp] def sum_assoc (α β γ : Sort*) : (α ⊕ β) ⊕ γ ≃ α ⊕ (β ⊕ γ) :=
⟨λ s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end,
λ s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end,
λ s, by rcases s with ⟨_ | _⟩ | _; refl,
λ s, by rcases s with _ | _ | _; refl⟩
@[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl
@[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl
@[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl
@[simp] def sum_empty (α : Sort*) : α ⊕ empty ≃ α :=
⟨λ s, match s with inl a := a | inr e := empty.rec _ e end,
inl,
λ s, by { rcases s with _ | ⟨⟨⟩⟩, refl },
λ a, rfl⟩
@[simp] def empty_sum (α : Sort*) : empty ⊕ α ≃ α :=
(sum_comm _ _).trans $ sum_empty _
@[simp] def sum_pempty (α : Sort*) : α ⊕ pempty ≃ α :=
⟨λ s, match s with inl a := a | inr e := pempty.rec _ e end,
inl,
λ s, by { rcases s with _ | ⟨⟨⟩⟩, refl },
λ a, rfl⟩
@[simp] def pempty_sum (α : Sort*) : pempty ⊕ α ≃ α :=
(sum_comm _ _).trans $ sum_pempty _
@[simp] def option_equiv_sum_punit (α : Sort*) : option α ≃ α ⊕ punit.{u+1} :=
⟨λ o, match o with none := inr punit.star | some a := inl a end,
λ s, match s with inr _ := none | inl a := some a end,
λ o, by cases o; refl,
λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩
def sum_equiv_sigma_bool (α β : Sort*) : α ⊕ β ≃ (Σ b: bool, cond b α β) :=
⟨λ s, match s with inl a := ⟨tt, a⟩ | inr b := ⟨ff, b⟩ end,
λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end,
λ s, by cases s; refl,
λ s, by rcases s with ⟨_|_, _⟩; refl⟩
def sigma_preimage_equiv {α β : Type*} (f : α → β) :
(Σ y : β, {x // f x = y}) ≃ α :=
⟨λ x, x.2.1, λ x, ⟨f x, x, rfl⟩, λ ⟨y, x, rfl⟩, rfl, λ x, rfl⟩
end
section
def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) :=
⟨λ H a, F a (H a), λ H a, (F a).symm (H a),
λ H, funext $ by simp, λ H, funext $ by simp⟩
def Pi_curry {α} {β : α → Sort*} (γ : Π a, β a → Sort*) : (Π x : sigma β, γ x.1 x.2) ≃ (Π a b, γ a b) :=
{ to_fun := λ f x y, f ⟨x,y⟩,
inv_fun := λ f x, f x.1 x.2,
left_inv := λ f, funext $ λ ⟨x,y⟩, rfl,
right_inv := λ f, funext $ λ x, funext $ λ y, rfl }
end
section
def psigma_equiv_sigma {α} (β : α → Sort*) : psigma β ≃ sigma β :=
⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩
def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : sigma β₁ ≃ sigma β₂ :=
⟨λ ⟨a, b⟩, ⟨a, F a b⟩, λ ⟨a, b⟩, ⟨a, (F a).symm b⟩,
λ ⟨a, b⟩, congr_arg (sigma.mk a) $ symm_apply_apply (F a) b,
λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_symm_apply (F a) b⟩
def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} : ∀ f : α₁ ≃ α₂, (Σ a:α₁, β (f a)) ≃ (Σ a:α₂, β a)
| ⟨f, g, l, r⟩ :=
⟨λ ⟨a, b⟩, ⟨f a, b⟩, λ ⟨a, b⟩, ⟨g a, @@eq.rec β b (r a).symm⟩,
λ ⟨a, b⟩, match g (f a), l a : ∀ a' (h : a' = a),
@sigma.mk _ (β ∘ f) _ (@@eq.rec β b (congr_arg f h.symm)) = ⟨a, b⟩ with
| _, rfl := rfl end,
λ ⟨a, b⟩, match f (g a), _ : ∀ a' (h : a' = a), sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with
| _, rfl := rfl end⟩
def sigma_equiv_prod (α β : Sort*) : (Σ_:α, β) ≃ α × β :=
⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩
def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : ∀ a, β₁ a ≃ β) : sigma β₁ ≃ α × β :=
(sigma_congr_right F).trans (sigma_equiv_prod α β)
end
section
def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ (γ → α) × (γ → β) :=
⟨λ f, (λ c, (f c).1, λ c, (f c).2),
λ p c, (p.1 c, p.2 c),
λ f, funext $ λ c, prod.mk.eta,
λ p, by { cases p, refl }⟩
def arrow_arrow_equiv_prod_arrow (α β γ : Sort*) : (α → β → γ) ≃ (α × β → γ) :=
⟨λ f, λ p, f p.1 p.2,
λ f, λ a b, f (a, b),
λ f, rfl,
λ f, by { funext p, cases p, refl }⟩
open sum
def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ (α → γ) × (β → γ) :=
⟨λ f, (f ∘ inl, f ∘ inr),
λ p s, sum.rec_on s p.1 p.2,
λ f, by { funext s, cases s; refl },
λ p, by { cases p, refl }⟩
def sum_prod_distrib (α β γ : Sort*) : (α ⊕ β) × γ ≃ (α × γ) ⊕ (β × γ) :=
⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end,
λ s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end,
λ p, by rcases p with ⟨_ | _, _⟩; refl,
λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩
@[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) :
sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl
@[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) :
sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl
def prod_sum_distrib (α β γ : Sort*) : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ) :=
calc α × (β ⊕ γ) ≃ (β ⊕ γ) × α : prod_comm _ _
... ≃ (β × α) ⊕ (γ × α) : sum_prod_distrib _ _ _
... ≃ (α × β) ⊕ (α × γ) : sum_congr (prod_comm _ _) (prod_comm _ _)
@[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) :
prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl
@[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) :
prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl
def sigma_prod_distrib {ι : Type*} (α : ι → Type*) (β : Type*) :
((Σ i, α i) × β) ≃ (Σ i, (α i × β)) :=
⟨λ p, ⟨p.1.1, (p.1.2, p.2)⟩,
λ p, (⟨p.1, p.2.1⟩, p.2.2),
λ p, by { rcases p with ⟨⟨_, _⟩, _⟩, refl },
λ p, by { rcases p with ⟨_, ⟨_, _⟩⟩, refl }⟩
def bool_prod_equiv_sum (α : Type u) : bool × α ≃ α ⊕ α :=
calc bool × α ≃ (unit ⊕ unit) × α : prod_congr bool_equiv_punit_sum_punit (equiv.refl _)
... ≃ α × (unit ⊕ unit) : prod_comm _ _
... ≃ (α × unit) ⊕ (α × unit) : prod_sum_distrib _ _ _
... ≃ α ⊕ α : sum_congr (prod_punit _) (prod_punit _)
end
section
open sum nat
def nat_equiv_nat_sum_punit : ℕ ≃ ℕ ⊕ punit.{u+1} :=
⟨λ n, match n with zero := inr punit.star | succ a := inl a end,
λ s, match s with inl n := succ n | inr punit.star := zero end,
λ n, begin cases n, repeat { refl } end,
λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩
@[simp] def nat_sum_punit_equiv_nat : ℕ ⊕ punit.{u+1} ≃ ℕ :=
nat_equiv_nat_sum_punit.symm
def int_equiv_nat_sum_nat : ℤ ≃ ℕ ⊕ ℕ :=
by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl}
end
def list_equiv_of_equiv {α β : Type*} : α ≃ β → list α ≃ list β
| ⟨f, g, l, r⟩ :=
by refine ⟨list.map f, list.map g, λ x, _, λ x, _⟩;
simp [id_of_left_inverse l, id_of_right_inverse r]
def fin_equiv_subtype (n : ℕ) : fin n ≃ {m // m < n} :=
⟨λ x, ⟨x.1, x.2⟩, λ x, ⟨x.1, x.2⟩, λ ⟨a, b⟩, rfl,λ ⟨a, b⟩, rfl⟩
def decidable_eq_of_equiv [decidable_eq β] (e : α ≃ β) : decidable_eq α
| a₁ a₂ := decidable_of_iff (e a₁ = e a₂) e.injective.eq_iff
def inhabited_of_equiv [inhabited β] (e : α ≃ β) : inhabited α :=
⟨e.symm (default _)⟩
def unique_of_equiv (e : α ≃ β) (h : unique β) : unique α :=
unique.of_surjective e.symm.surjective
def unique_congr (e : α ≃ β) : unique α ≃ unique β :=
{ to_fun := e.symm.unique_of_equiv,
inv_fun := e.unique_of_equiv,
left_inv := λ _, subsingleton.elim _ _,
right_inv := λ _, subsingleton.elim _ _ }
section
open subtype
def subtype_congr {p : α → Prop} {q : β → Prop}
(e : α ≃ β) (h : ∀ a, p a ↔ q (e a)) : {a : α // p a} ≃ {b : β // q b} :=
⟨λ x, ⟨e x.1, (h _).1 x.2⟩,
λ y, ⟨e.symm y.1, (h _).2 (by { simp, exact y.2 })⟩,
λ ⟨x, h⟩, subtype.eq' $ by simp,
λ ⟨y, h⟩, subtype.eq' $ by simp⟩
def subtype_congr_right {p q : α → Prop} (e : ∀x, p x ↔ q x) : subtype p ≃ subtype q :=
subtype_congr (equiv.refl _) e
@[simp] lemma subtype_congr_right_mk {p q : α → Prop} (e : ∀x, p x ↔ q x)
{x : α} (h : p x) : subtype_congr_right e ⟨x, h⟩ = ⟨x, (e x).1 h⟩ := rfl
def subtype_equiv_of_subtype' {p : α → Prop} (e : α ≃ β) :
{a : α // p a} ≃ {b : β // p (e.symm b)} :=
subtype_congr e $ by simp
def subtype_congr_prop {α : Type*} {p q : α → Prop} (h : p = q) : subtype p ≃ subtype q :=
subtype_congr (equiv.refl α) (assume a, h ▸ iff.refl _)
def set_congr {α : Type*} {s t : set α} (h : s = t) : s ≃ t :=
subtype_congr_prop h
def subtype_subtype_equiv_subtype_exists {α : Type u} (p : α → Prop) (q : subtype p → Prop) :
subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } :=
⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩,
λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by { cases ha, exact ha_h }⟩,
assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩
def subtype_subtype_equiv_subtype_inter {α : Type u} (p q : α → Prop) :
{x : subtype p // q x.1} ≃ subtype (λ x, p x ∧ q x) :=
(subtype_subtype_equiv_subtype_exists p _).trans $
subtype_congr_right $ λ x, exists_prop
/-- If the outer subtype has more restrictive predicate than the inner one,
then we can drop the latter. -/
def subtype_subtype_equiv_subtype {α : Type u} {p q : α → Prop} (h : ∀ {x}, q x → p x) :
{x : subtype p // q x.1} ≃ subtype q :=
(subtype_subtype_equiv_subtype_inter p _).trans $
subtype_congr_right $
assume x,
⟨and.right, λ h₁, ⟨h h₁, h₁⟩⟩
/-- If a proposition holds for all elements, then the subtype is
equivalent to the original type. -/
def subtype_univ_equiv {α : Type u} {p : α → Prop} (h : ∀ x, p x) :
subtype p ≃ α :=
⟨λ x, x, λ x, ⟨x, h x⟩, λ x, subtype.eq rfl, λ x, rfl⟩
/-- A subtype of a sigma-type is a sigma-type over a subtype. -/
def subtype_sigma_equiv {α : Type u} (p : α → Type v) (q : α → Prop) :
{ y : sigma p // q y.1 } ≃ Σ(x : subtype q), p x.1 :=
⟨λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩,
λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩,
λ ⟨⟨x, h⟩, y⟩, rfl,
λ ⟨⟨x, y⟩, h⟩, rfl⟩
/-- A sigma type over a subtype is equivalent to the sigma set over the original type,
if the fiber is empty outside of the subset -/
def sigma_subtype_equiv_of_subset {α : Type u} (p : α → Type v) (q : α → Prop)
(h : ∀ x, p x → q x) :
(Σ x : subtype q, p x) ≃ Σ x : α, p x :=
(subtype_sigma_equiv p q).symm.trans $ subtype_univ_equiv $ λ x, h x.1 x.2
def sigma_subtype_preimage_equiv {α : Type u} {β : Type v} (f : α → β) (p : β → Prop)
(h : ∀ x, p (f x)) :
(Σ y : subtype p, {x : α // f x = y}) ≃ α :=
calc _ ≃ Σ y : β, {x : α // f x = y} : sigma_subtype_equiv_of_subset _ p (λ y ⟨x, h'⟩, h' ▸ h x)
... ≃ α : sigma_preimage_equiv f
def sigma_subtype_preimage_equiv_subtype {α : Type u} {β : Type v} (f : α → β)
{p : α → Prop} {q : β → Prop} (h : ∀ x, p x ↔ q (f x)) :
(Σ y : subtype q, {x : α // f x = y}) ≃ subtype p :=
calc (Σ y : subtype q, {x : α // f x = y}) ≃
Σ y : subtype q, {x : subtype p // subtype.mk (f x) ((h x).1 x.2) = y} :
begin
apply sigma_congr_right,
assume y,
symmetry,
refine (subtype_subtype_equiv_subtype_exists _ _).trans (subtype_congr_right _),
assume x,
exact ⟨λ ⟨hp, h'⟩, congr_arg subtype.val h', λ h', ⟨(h x).2 (h'.symm ▸ y.2), subtype.eq h'⟩⟩
end
... ≃ subtype p : sigma_preimage_equiv (λ x : subtype p, (⟨f x, (h x).1 x.property⟩ : subtype q))
def pi_equiv_subtype_sigma (ι : Type*) (π : ι → Type*) :
(Πi, π i) ≃ {f : ι → Σi, π i | ∀i, (f i).1 = i } :=
⟨ λf, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, λf i, begin rw ← f.2 i, exact (f.1 i).2 end,
assume f, funext $ assume i, rfl,
assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $
eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩
def subtype_pi_equiv_pi {α : Sort u} {β : α → Sort v} {p : Πa, β a → Prop} :
{f : Πa, β a // ∀a, p a (f a) } ≃ Πa, { b : β a // p a b } :=
⟨λf a, ⟨f.1 a, f.2 a⟩, λf, ⟨λa, (f a).1, λa, (f a).2⟩,
by { rintro ⟨f, h⟩, refl },
by { rintro f, funext a, exact subtype.eq' rfl }⟩
end
section
local attribute [elab_with_expected_type] quot.lift
def quot_equiv_of_quot' {r : α → α → Prop} {s : β → β → Prop} (e : α ≃ β)
(h : ∀ a a', r a a' ↔ s (e a) (e a')) : quot r ≃ quot s :=
⟨quot.lift (λ a, quot.mk _ (e a)) (λ a a' H, quot.sound ((h a a').mp H)),
quot.lift (λ b, quot.mk _ (e.symm b)) (λ b b' H, quot.sound ((h _ _).mpr (by convert H; simp))),
quot.ind $ by simp,
quot.ind $ by simp⟩
def quot_equiv_of_quot {r : α → α → Prop} (e : α ≃ β) :
quot r ≃ quot (λ b b', r (e.symm b) (e.symm b')) :=
quot_equiv_of_quot' e (by simp)
end
namespace set
open set
protected def univ (α) : @univ α ≃ α :=
⟨subtype.val, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩
@[simp] lemma univ_apply {α : Type u} (x : @univ α) :
equiv.set.univ α x = x := rfl
@[simp] lemma univ_symm_apply {α : Type u} (x : α) :
(equiv.set.univ α).symm x = ⟨x, trivial⟩ := rfl
protected def empty (α) : (∅ : set α) ≃ empty :=
equiv_empty $ λ ⟨x, h⟩, not_mem_empty x h
protected def pempty (α) : (∅ : set α) ≃ pempty :=
equiv_pempty $ λ ⟨x, h⟩, not_mem_empty x h
protected def union' {α} {s t : set α}
(p : α → Prop) [decidable_pred p]
(hs : ∀ x ∈ s, p x)
(ht : ∀ x ∈ t, ¬ p x) : (s ∪ t : set α) ≃ s ⊕ t :=
{ to_fun := λ x, if hp : p x.1
then sum.inl ⟨_, x.2.resolve_right (λ xt, ht _ xt hp)⟩
else sum.inr ⟨_, x.2.resolve_left (λ xs, hp (hs _ xs))⟩,
inv_fun := λ o, match o with
| (sum.inl x) := ⟨x.1, or.inl x.2⟩
| (sum.inr x) := ⟨x.1, or.inr x.2⟩
end,
left_inv := λ ⟨x, h'⟩, by by_cases p x; simp [union'._match_1, h]; congr,
right_inv := λ o, begin
rcases o with ⟨x, h⟩ | ⟨x, h⟩;
dsimp [union'._match_1];
[simp [hs _ h], simp [ht _ h]]
end }
protected def union {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) :
(s ∪ t : set α) ≃ s ⊕ t :=
set.union' s (λ _, id) (λ x xt xs, subset_empty_iff.2 H ⟨xs, xt⟩)
lemma union_apply_left {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅)
{a : (s ∪ t : set α)} (ha : ↑a ∈ s) : equiv.set.union H a = sum.inl ⟨a, ha⟩ :=
dif_pos ha
lemma union_apply_right {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅)
{a : (s ∪ t : set α)} (ha : ↑a ∈ t) : equiv.set.union H a = sum.inr ⟨a, ha⟩ :=
dif_neg (show ↑a ∉ s, by finish [set.ext_iff])
protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} :=
⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩,
λ ⟨x, h⟩, by { simp at h, subst x },
λ ⟨⟩, rfl⟩
protected def of_eq {α : Type u} {s t : set α} (h : s = t) : s ≃ t :=
{ to_fun := λ x, ⟨x.1, h ▸ x.2⟩,
inv_fun := λ x, ⟨x.1, h.symm ▸ x.2⟩,
left_inv := λ _, subtype.eq rfl,
right_inv := λ _, subtype.eq rfl }
@[simp] lemma of_eq_apply {α : Type u} {s t : set α} (h : s = t) (a : s) :
equiv.set.of_eq h a = ⟨a, h ▸ a.2⟩ := rfl
@[simp] lemma of_eq_symm_apply {α : Type u} {s t : set α} (h : s = t) (a : t) :
(equiv.set.of_eq h).symm a = ⟨a, h.symm ▸ a.2⟩ := rfl
protected def insert {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) :
(insert a s : set α) ≃ s ⊕ punit.{u+1} :=
calc (insert a s : set α) ≃ ↥(s ∪ {a}) : equiv.set.of_eq (by simp)
... ≃ s ⊕ ({a} : set α) : equiv.set.union (by finish [set.ext_iff])
... ≃ s ⊕ punit.{u+1} : sum_congr (equiv.refl _) (equiv.set.singleton _)
protected def sum_compl {α} (s : set α) [decidable_pred s] : s ⊕ (-s : set α) ≃ α :=
calc s ⊕ (-s : set α) ≃ ↥(s ∪ -s) : (equiv.set.union (by simp [set.ext_iff])).symm
... ≃ @univ α : equiv.set.of_eq (by simp)
... ≃ α : equiv.set.univ _
@[simp] lemma sum_compl_apply_inl {α : Type u} (s : set α) [decidable_pred s] (x : s) :
equiv.set.sum_compl s (sum.inl x) = x := rfl
@[simp] lemma sum_compl_apply_inr {α : Type u} (s : set α) [decidable_pred s] (x : -s) :
equiv.set.sum_compl s (sum.inr x) = x := rfl
lemma sum_compl_symm_apply_of_mem {α : Type u} {s : set α} [decidable_pred s] {x : α}
(hx : x ∈ s) : (equiv.set.sum_compl s).symm x = sum.inl ⟨x, hx⟩ :=
have ↑(⟨x, or.inl hx⟩ : (s ∪ -s : set α)) ∈ s, from hx,
by { rw [equiv.set.sum_compl], simpa using set.union_apply_left _ this }
lemma sum_compl_symm_apply_of_not_mem {α : Type u} {s : set α} [decidable_pred s] {x : α}
(hx : x ∉ s) : (equiv.set.sum_compl s).symm x = sum.inr ⟨x, hx⟩ :=
have ↑(⟨x, or.inr hx⟩ : (s ∪ -s : set α)) ∈ -s, from hx,
by { rw [equiv.set.sum_compl], simpa using set.union_apply_right _ this }
protected def union_sum_inter {α : Type u} (s t : set α) [decidable_pred s] :
(s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ s ⊕ t :=
calc (s ∪ t : set α) ⊕ (s ∩ t : set α)
≃ (s ∪ t \ s : set α) ⊕ (s ∩ t : set α) : by rw [union_diff_self]
... ≃ (s ⊕ (t \ s : set α)) ⊕ (s ∩ t : set α) :
sum_congr (set.union (inter_diff_self _ _)) (equiv.refl _)
... ≃ s ⊕ (t \ s : set α) ⊕ (s ∩ t : set α) : sum_assoc _ _ _
... ≃ s ⊕ (t \ s ∪ s ∩ t : set α) : sum_congr (equiv.refl _) begin
refine (set.union' (∉ s) _ _).symm,
exacts [λ x hx, hx.2, λ x hx, not_not_intro hx.1]
end
... ≃ s ⊕ t : by { rw (_ : t \ s ∪ s ∩ t = t), rw [union_comm, inter_comm, inter_union_diff] }
protected def prod {α β} (s : set α) (t : set β) :
s.prod t ≃ s × t :=
⟨λp, ⟨⟨p.1.1, p.2.1⟩, ⟨p.1.2, p.2.2⟩⟩,
λp, ⟨⟨p.1.1, p.2.1⟩, ⟨p.1.2, p.2.2⟩⟩,
λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, rfl,
λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, rfl⟩
protected noncomputable def image_of_inj_on {α β} (f : α → β) (s : set α) (H : inj_on f s) :
s ≃ (f '' s) :=
⟨λ ⟨x, h⟩, ⟨f x, mem_image_of_mem f h⟩,
λ ⟨y, h⟩, ⟨classical.some h, (classical.some_spec h).1⟩,
λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).1 h
(classical.some_spec (mem_image_of_mem f h)).2),
λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩
protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) :=
equiv.set.image_of_inj_on f s (λ x y hx hy hxy, H hxy)
@[simp] theorem image_apply {α β} (f : α → β) (s : set α) (H : injective f) (a h) :
set.image f s H ⟨a, h⟩ = ⟨f a, mem_image_of_mem _ h⟩ := rfl
protected noncomputable def range {α β} (f : α → β) (H : injective f) :
α ≃ range f :=
{ to_fun := λ x, ⟨f x, mem_range_self _⟩,
inv_fun := λ x, classical.some x.2,
left_inv := λ x, H (classical.some_spec (show f x ∈ range f, from mem_range_self _)),
right_inv := λ x, subtype.eq $ classical.some_spec x.2 }
@[simp] theorem range_apply {α β} (f : α → β) (H : injective f) (a) :
set.range f H a = ⟨f a, set.mem_range_self _⟩ := rfl
protected def congr {α β : Type*} (e : α ≃ β) : set α ≃ set β :=
⟨λ s, e '' s, λ t, e.symm '' t, symm_image_image e, symm_image_image e.symm⟩
protected def sep {α : Type u} (s : set α) (t : α → Prop) :
({ x ∈ s | t x } : set α) ≃ { x : s | t x.1 } :=
(equiv.subtype_subtype_equiv_subtype_inter s t).symm
end set
noncomputable def of_bijective {α β} {f : α → β} (hf : bijective f) : α ≃ β :=
⟨f, λ x, classical.some (hf.2 x), λ x, hf.1 (classical.some_spec (hf.2 (f x))),
λ x, classical.some_spec (hf.2 x)⟩
@[simp] theorem of_bijective_to_fun {α β} {f : α → β} (hf : bijective f) : (of_bijective hf : α → β) = f := rfl
def subtype_quotient_equiv_quotient_subtype (p₁ : α → Prop) [s₁ : setoid α]
[s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧)
(h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) :
{x // p₂ x} ≃ quotient s₂ :=
{ to_fun := λ a, quotient.hrec_on a.1 (λ a h, ⟦⟨a, (hp₂ _).2 h⟩⟧)
(λ a b hab, hfunext (by rw quotient.sound hab)
(λ h₁ h₂ _, heq_of_eq (quotient.sound ((h _ _).2 hab)))) a.2,
inv_fun := λ a, quotient.lift_on a (λ a, (⟨⟦a.1⟧, (hp₂ _).1 a.2⟩ : {x // p₂ x}))
(λ a b hab, subtype.eq' (quotient.sound ((h _ _).1 hab))),
left_inv := λ ⟨a, ha⟩, quotient.induction_on a (λ a ha, rfl) ha,
right_inv := λ a, quotient.induction_on a (λ ⟨a, ha⟩, rfl) }
section swap
variable [decidable_eq α]
open decidable
def swap_core (a b r : α) : α :=
if r = a then b
else if r = b then a
else r
theorem swap_core_self (r a : α) : swap_core a a r = r :=
by { unfold swap_core, split_ifs; cc }
theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r :=
by { unfold swap_core, split_ifs; cc }
theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r :=
by { unfold swap_core, split_ifs; cc }
/-- `swap a b` is the permutation that swaps `a` and `b` and
leaves other values as is. -/
def swap (a b : α) : perm α :=
⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩
theorem swap_self (a : α) : swap a a = equiv.refl _ :=
eq_of_to_fun_eq $ funext $ λ r, swap_core_self r a
theorem swap_comm (a b : α) : swap a b = swap b a :=
eq_of_to_fun_eq $ funext $ λ r, swap_core_comm r _ _
theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x :=
rfl
@[simp] theorem swap_apply_left (a b : α) : swap a b a = b :=
if_pos rfl
@[simp] theorem swap_apply_right (a b : α) : swap a b b = a :=
by { by_cases b = a; simp [swap_apply_def, *] }
theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x :=
by simp [swap_apply_def] {contextual := tt}
@[simp] theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ :=
eq_of_to_fun_eq $ funext $ λ x, swap_core_swap_core _ _ _
theorem swap_comp_apply {a b x : α} (π : perm α) :
π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x :=
by { cases π, refl }
@[simp] lemma swap_inv {α : Type*} [decidable_eq α] (x y : α) :
(swap x y)⁻¹ = swap x y := rfl
@[simp] lemma symm_trans_swap_trans [decidable_eq β] (a b : α)
(e : α ≃ β) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) :=
equiv.ext _ _ (λ x, begin
have : ∀ a, e.symm x = a ↔ x = e a :=
λ a, by { rw @eq_comm _ (e.symm x), split; intros; simp * at * },
simp [swap_apply_def, this],
split_ifs; simp
end)
@[simp] lemma swap_mul_self {α : Type*} [decidable_eq α] (i j : α) : swap i j * swap i j = 1 :=
equiv.swap_swap i j
@[simp] lemma swap_apply_self {α : Type*} [decidable_eq α] (i j a : α) : swap i j (swap i j a) = a :=
by rw [← perm.mul_apply, swap_mul_self, perm.one_apply]
/-- Augment an equivalence with a prescribed mapping `f a = b` -/
def set_value (f : α ≃ β) (a : α) (b : β) : α ≃ β :=
(swap a (f.symm b)).trans f
@[simp] theorem set_value_eq (f : α ≃ β) (a : α) (b : β) : set_value f a b a = b :=
by { dsimp [set_value], simp [swap_apply_left] }
end swap
protected lemma forall_congr {p : α → Prop} {q : β → Prop} (f : α ≃ β)
(h : ∀{x}, p x ↔ q (f x)) : (∀x, p x) ↔ (∀y, q y) :=
begin
split; intros h₂ x,
{ rw [←f.right_inv x], apply h.mp, apply h₂ },
apply h.mpr, apply h₂
end
end equiv
instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton
instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton
instance {α} [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq
instance {α} [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq
def unique_unique_equiv : unique (unique α) ≃ unique α :=
{ to_fun := λ h, h.default,
inv_fun := λ h, { default := h, uniq := λ _, subsingleton.elim _ _ },
left_inv := λ _, subsingleton.elim _ _,
right_inv := λ _, subsingleton.elim _ _ }
def equiv_of_unique_of_unique [unique α] [unique β] : α ≃ β :=
{ to_fun := λ _, default β,
inv_fun := λ _, default α,
left_inv := λ _, subsingleton.elim _ _,
right_inv := λ _, subsingleton.elim _ _ }
def equiv_punit_of_unique [unique α] : α ≃ punit.{v} :=
equiv_of_unique_of_unique
namespace quot
protected def congr {α β} {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β)
(eq : ∀a₁ a₂, ra a₁ a₂ ↔ rb (e a₁) (e a₂)) :
quot ra ≃ quot rb :=
{ to_fun := quot.map e (assume a₁ a₂, (eq a₁ a₂).1),
inv_fun := quot.map e.symm
(assume b₁ b₂ h,
(eq (e.symm b₁) (e.symm b₂)).2
((e.apply_symm_apply b₁).symm ▸ (e.apply_symm_apply b₂).symm ▸ h)),
left_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.symm_apply_apply] },
right_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.apply_symm_apply] } }
/-- Quotients are congruent on equivalences under equality of their relation.
An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/
protected def congr_right {α} {r r' : α → α → Prop} (eq : ∀a₁ a₂, r a₁ a₂ ↔ r' a₁ a₂) :
quot r ≃ quot r' :=
quot.congr (equiv.refl α) eq
end quot
namespace quotient
protected def congr {α β} {ra : setoid α} {rb : setoid β} (e : α ≃ β)
(eq : ∀a₁ a₂, @setoid.r α ra a₁ a₂ ↔ @setoid.r β rb (e a₁) (e a₂)) :
quotient ra ≃ quotient rb :=
quot.congr e eq
protected def congr_right {α} {r r' : setoid α}
(eq : ∀a₁ a₂, @setoid.r α r a₁ a₂ ↔ @setoid.r α r' a₁ a₂) : quotient r ≃ quotient r' :=
quot.congr_right eq
end quotient
|
c36d40563a829d16cb9b737d8d6a4a6713752fc4 | 98beff2e97d91a54bdcee52f922c4e1866a6c9b9 | /src/category/pullbacks.lean | 0523adc233e175192570e5cb0c3f9e6be89ac2fc | [] | no_license | b-mehta/topos | c3fc43fb04ba16bae1965ce5c26c6461172e5bc6 | c9032b11789e36038bc841a1e2b486972421b983 | refs/heads/master | 1,629,609,492,867 | 1,609,907,263,000 | 1,609,907,263,000 | 240,943,034 | 43 | 3 | null | 1,598,210,062,000 | 1,581,877,668,000 | Lean | UTF-8 | Lean | false | false | 21,976 | lean | /-
Copyright (c) 2020 Bhavik Mehta, Edward Ayers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Edward Ayers
-/
import category_theory.limits.shapes
import category_theory.limits.preserves.limits
import category_theory.limits.over
import category_theory.limits.shapes.constructions.over
import tactic
/-!
# Pullbacks
Many, many lemmas to work with pullbacks.
-/
open category_theory category_theory.category category_theory.limits
noncomputable theory
universes u v
variables {C : Type u} [category.{v} C]
variables {J : Type v} [small_category J]
variables {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z}
/-- A supremely useful structure for elementary topos theory. -/
structure has_pullback_top (left : W ⟶ Y) (bottom : Y ⟶ Z) (right : X ⟶ Z) :=
(top : W ⟶ X)
(comm : top ≫ right = left ≫ bottom)
(is_pb : is_limit (pullback_cone.mk _ _ comm))
attribute [reassoc] has_pullback_top.comm
instance subsingleton_hpb (left : W ⟶ Y) (bottom : Y ⟶ Z) (right : X ⟶ Z) [mono right] :
subsingleton (has_pullback_top left bottom right) :=
⟨begin
intros P Q,
cases P,
cases Q,
congr,
rw ← cancel_mono right,
rw P_comm, rw Q_comm
end⟩
def has_pullback_top_of_is_pb {U V W X : C}
{f : U ⟶ V} {g : V ⟶ W} {h : U ⟶ X} {k : X ⟶ W}
{comm : f ≫ g = h ≫ k}
(pb : is_limit (pullback_cone.mk _ _ comm)) :
has_pullback_top h k g :=
{ top := f,
comm := comm,
is_pb := pb }
def is_limit.mk' (t : pullback_cone f g)
(create : Π (s : pullback_cone f g), {l : s.X ⟶ t.X // l ≫ t.fst = s.fst ∧ l ≫ t.snd = s.snd ∧ ∀ {m : s.X ⟶ t.X}, m ≫ t.fst = s.fst → m ≫ t.snd = s.snd → m = l}) :
is_limit t :=
pullback_cone.is_limit_aux' t create
def is_limit.mk'' (t : pullback_cone f g) [mono f]
(create : Π (s : pullback_cone f g), {l : s.X ⟶ t.X // l ≫ t.snd = s.snd ∧ ∀ {m : s.X ⟶ t.X}, m ≫ t.fst = s.fst → m ≫ t.snd = s.snd → m = l}) :
is_limit t :=
is_limit.mk' t $
begin
intro s,
refine ⟨(create s).1, _, (create s).2.1, λ m m₁ m₂, (create s).2.2 m₁ m₂⟩,
rw [← cancel_mono f, assoc, t.condition, s.condition, reassoc_of (create s).2.1]
end
def is_limit.mk''' (t : pullback_cone f g) [mono f] (q : mono t.snd)
(create : Π (s : pullback_cone f g), {l : s.X ⟶ t.X // l ≫ t.snd = s.snd}) :
is_limit t :=
is_limit.mk' t $
begin
intro s,
refine ⟨(create s).1, _, (create s).2, λ m _ m₂, _⟩,
rw [← cancel_mono f, assoc, t.condition, s.condition, reassoc_of (create s).2],
rw [← cancel_mono t.snd, m₂, (create s).2],
end
def construct_type_pb {W X Y Z : Type u} {f : X ⟶ Z} {g : Y ⟶ Z} {h : W ⟶ _} {k} (comm : h ≫ f = k ≫ g) :
(∀ (x : X) (y : Y), f x = g y → {t // h t = x ∧ k t = y ∧ ∀ t', h t' = x → k t' = y → t' = t}) → is_limit (pullback_cone.mk _ _ comm) :=
begin
intro z,
apply is_limit.mk' _ _,
intro s,
refine ⟨λ t, _, _, _, _⟩,
refine (z (s.fst t) (s.snd t) (congr_fun s.condition t)).1,
ext t,
apply (z (s.fst t) (s.snd t) (congr_fun s.condition t)).2.1,
ext t,
apply (z (s.fst t) (s.snd t) (congr_fun s.condition t)).2.2.1,
intros m m₁ m₂,
ext t,
apply (z (s.fst t) (s.snd t) (congr_fun s.condition t)).2.2.2,
apply congr_fun m₁ t,
apply congr_fun m₂ t,
end
def pullback_mono_is_mono (c : pullback_cone f g) [mono f] (t : is_limit c) : mono c.snd :=
⟨λ Z h k eq,
begin
apply t.hom_ext,
apply pullback_cone.equalizer_ext,
rw [← cancel_mono f, assoc, c.condition, reassoc_of eq, assoc, c.condition],
assumption
end⟩
def cone_is_pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_limit (cospan f g)] :
is_limit (pullback_cone.mk _ _ pullback.condition : pullback_cone f g) :=
is_limit.mk' _ $ λ s,
⟨ pullback.lift _ _ s.condition,
pullback.lift_fst _ _ _,
pullback.lift_snd _ _ _,
λ m m₁ m₂, pullback.hom_ext (by simpa using m₁) (by simpa using m₂) ⟩
def is_limit_as_pullback_cone_mk (s : pullback_cone f g) (t : is_limit (pullback_cone.mk s.fst s.snd s.condition)) :
is_limit s :=
{ lift := λ c, t.lift c,
fac' := λ c j,
begin
cases j,
simp [← t.fac c none, ← s.w walking_cospan.hom.inl],
cases j,
exact t.fac c walking_cospan.left,
exact t.fac c walking_cospan.right,
end,
uniq' := λ c m w,
begin
apply t.uniq,
intro j,
rw ← w,
cases j,
simp [← t.fac c none, ← s.w walking_cospan.hom.inl],
cases j; refl,
end }
def has_pullback_top_of_pb [has_limit (cospan f g)] :
has_pullback_top (pullback.snd : pullback f g ⟶ Y) g f :=
{ top := pullback.fst,
comm := pullback.condition,
is_pb := cone_is_pullback f g }
def left_pb_to_both_pb {U V W X Y Z : C}
(f : U ⟶ V) (g : V ⟶ W) (h : U ⟶ X) (k : V ⟶ Y) (l : W ⟶ Z) (m : X ⟶ Y) (n : Y ⟶ Z)
(left_comm : f ≫ k = h ≫ m)
(right_comm : g ≫ l = k ≫ n)
(left_pb : is_limit (pullback_cone.mk f h left_comm))
(right_pb : is_limit (pullback_cone.mk g k right_comm)) :
is_limit (pullback_cone.mk (f ≫ g) h (begin rw [assoc, right_comm, reassoc_of left_comm]end)) :=
is_limit.mk' _ $
begin
intro s,
let t : s.X ⟶ V := right_pb.lift (pullback_cone.mk s.fst (s.snd ≫ m) (by rw [assoc, s.condition])),
have l_comm : t ≫ k = s.snd ≫ m := right_pb.fac _ walking_cospan.right,
let u : s.X ⟶ U := left_pb.lift (pullback_cone.mk _ _ l_comm),
have uf : u ≫ f = t := left_pb.fac _ walking_cospan.left,
have tg : t ≫ g = s.fst := right_pb.fac _ walking_cospan.left,
refine ⟨u, _, left_pb.fac _ walking_cospan.right, _⟩,
{ rw [← tg, ← uf, assoc u f g], refl },
{ intros m' m₁ m₂,
apply left_pb.hom_ext,
apply (pullback_cone.mk f h left_comm).equalizer_ext,
{ apply right_pb.hom_ext,
apply (pullback_cone.mk g k right_comm).equalizer_ext,
{ erw [uf, assoc, tg], exact m₁ },
{ erw [uf, assoc, left_comm, reassoc_of m₂, l_comm] } },
{ erw [left_pb.fac _ walking_cospan.right], exact m₂ } }
end
def both_pb_to_left_pb {U V W X Y Z : C}
(f : U ⟶ V) (g : V ⟶ W) (h : U ⟶ X) (k : V ⟶ Y) (l : W ⟶ Z) (m : X ⟶ Y) (n : Y ⟶ Z)
(left_comm : f ≫ k = h ≫ m)
(right_comm : g ≫ l = k ≫ n)
(right_pb : is_limit (pullback_cone.mk g k right_comm))
(entire_pb : is_limit (pullback_cone.mk (f ≫ g) h (begin rw [assoc, right_comm, reassoc_of left_comm] end))) :
is_limit (pullback_cone.mk f h left_comm) :=
is_limit.mk' _ $
begin
intro s,
let u : s.X ⟶ U := entire_pb.lift (pullback_cone.mk (s.fst ≫ g) s.snd (by rw [assoc, right_comm, s.condition_assoc])),
have uf : u ≫ f = s.fst,
{ apply right_pb.hom_ext,
apply (pullback_cone.mk g k right_comm).equalizer_ext,
{ rw [assoc], exact entire_pb.fac _ walking_cospan.left },
{ erw [assoc, left_comm, ← assoc, entire_pb.fac _ walking_cospan.right, s.condition], refl } },
refine ⟨u, uf, entire_pb.fac _ walking_cospan.right, _⟩,
{ intros m' m₁ m₂,
apply entire_pb.hom_ext,
apply (pullback_cone.mk (f ≫ g) h _).equalizer_ext,
{ erw [reassoc_of uf, reassoc_of m₁] },
{ rwa entire_pb.fac _ walking_cospan.right } }
end
def left_hpb_right_pb_to_both_hpb {U V W X Y Z : C}
(g : V ⟶ W) (h : U ⟶ X) (k : V ⟶ Y) (l : W ⟶ Z) (m : X ⟶ Y) (n : Y ⟶ Z)
(left : has_pullback_top h m k)
(right_comm : g ≫ l = k ≫ n)
(right_pb : is_limit (pullback_cone.mk g k right_comm)) :
has_pullback_top h (m ≫ n) l :=
{ top := left.top ≫ g,
comm := by rw [assoc, right_comm, reassoc_of left.comm],
is_pb := left_pb_to_both_pb left.top g h k l m n left.comm right_comm left.is_pb right_pb }
def right_both_hpb_to_left_hpb {U V W X Y Z : C}
{h : U ⟶ X} {k : V ⟶ Y} (l : W ⟶ Z) {m : X ⟶ Y} (n : Y ⟶ Z)
(both : has_pullback_top h (m ≫ n) l)
(right : has_pullback_top k n l) :
has_pullback_top h m k :=
begin
let t : U ⟶ V := right.is_pb.lift (pullback_cone.mk both.top (h ≫ m) (by rw [assoc, both.comm])),
refine ⟨t, right.is_pb.fac _ walking_cospan.right, _⟩,
apply both_pb_to_left_pb t right.top h k l m n _ _ right.is_pb,
convert both.is_pb,
apply right.is_pb.fac _ walking_cospan.left,
end
def left_right_hpb_to_both_hpb {U V W X Y Z : C}
{h : U ⟶ X} (k : V ⟶ Y) {l : W ⟶ Z} {m : X ⟶ Y} {n : Y ⟶ Z}
(left : has_pullback_top h m k)
(right : has_pullback_top k n l) :
has_pullback_top h (m ≫ n) l :=
{ top := left.top ≫ right.top,
comm := by rw [assoc, right.comm, reassoc_of left.comm],
is_pb := left_pb_to_both_pb left.top right.top h k l m n left.comm right.comm left.is_pb right.is_pb }
def vpaste {U V W X Y Z : C} (f : U ⟶ V) (g : U ⟶ W) (h : V ⟶ X) (k : W ⟶ X) (l : W ⟶ Y) (m : X ⟶ Z) (n : Y ⟶ Z)
(up_comm : f ≫ h = g ≫ k) (down_comm : k ≫ m = l ≫ n)
(down_pb : is_limit (pullback_cone.mk _ _ down_comm))
(up_pb : is_limit (pullback_cone.mk _ _ up_comm)) :
is_limit (pullback_cone.mk f (g ≫ l) (by rw [reassoc_of up_comm, down_comm, assoc]) : pullback_cone (h ≫ m) n):=
is_limit.mk' _ $
begin
intro s,
let c' : pullback_cone m n := pullback_cone.mk (pullback_cone.fst s ≫ h) (pullback_cone.snd s) (by simp [pullback_cone.condition s]),
let t : s.X ⟶ W := down_pb.lift c',
have tl : t ≫ l = pullback_cone.snd s := down_pb.fac c' walking_cospan.right,
have tk : t ≫ k = pullback_cone.fst s ≫ h := down_pb.fac c' walking_cospan.left,
let c'' : pullback_cone h k := pullback_cone.mk (pullback_cone.fst s) t (down_pb.fac c' walking_cospan.left).symm,
let u : s.X ⟶ U := up_pb.lift c'',
have uf : u ≫ f = pullback_cone.fst s := up_pb.fac c'' walking_cospan.left,
have ug : u ≫ g = t := up_pb.fac c'' walking_cospan.right,
refine ⟨u, uf, by erw [reassoc_of ug, tl], _⟩,
intros m' m₁ m₂,
apply up_pb.hom_ext,
apply (pullback_cone.mk f g up_comm).equalizer_ext,
change m' ≫ f = u ≫ f,
erw [m₁, uf],
erw ug,
apply down_pb.hom_ext,
apply (pullback_cone.mk _ _ down_comm).equalizer_ext,
{ change (m' ≫ g) ≫ k = t ≫ k,
slice_lhs 2 3 {rw ← up_comm},
slice_lhs 1 2 {erw m₁},
rw tk },
{ change (m' ≫ g) ≫ l = t ≫ l,
erw [assoc, m₂, tl] }
end
def stretch_hpb_down {U V W X Y Z : C} (g : U ⟶ W) (h : V ⟶ X) (k : W ⟶ X) (l : W ⟶ Y) (m : X ⟶ Z) (n : Y ⟶ Z)
(up : has_pullback_top g k h)
(down_comm : k ≫ m = l ≫ n)
(down_pb : is_limit (pullback_cone.mk _ _ down_comm)) :
has_pullback_top (g ≫ l) n (h ≫ m) :=
{ top := up.top,
comm := by rw [up.comm_assoc, down_comm, assoc],
is_pb := vpaste up.top g h k l m n up.comm down_comm down_pb up.is_pb }
def vpaste' {U V W X Y Z : C} (f : U ⟶ V) (g : U ⟶ W) (h : V ⟶ X) (k : W ⟶ X) (l : W ⟶ Y) (m : X ⟶ Z) (n : Y ⟶ Z)
(up_comm : f ≫ h = g ≫ k) (down_comm : k ≫ m = l ≫ n)
(down_pb : is_limit (pullback_cone.mk _ _ down_comm))
(entire_pb : is_limit (pullback_cone.mk f (g ≫ l) (by rw [reassoc_of up_comm, down_comm, assoc]) : pullback_cone (h ≫ m) n)) :
is_limit (pullback_cone.mk _ _ up_comm) :=
is_limit.mk' _ $
begin
intro s,
let c' : pullback_cone (h ≫ m) n := pullback_cone.mk (pullback_cone.fst s) (pullback_cone.snd s ≫ l) (by simp [pullback_cone.condition_assoc s, down_comm]),
let t : s.X ⟶ U := entire_pb.lift c',
have t₁ : t ≫ f = pullback_cone.fst s := entire_pb.fac c' walking_cospan.left,
have t₂ : t ≫ g ≫ l = pullback_cone.snd s ≫ l := entire_pb.fac c' walking_cospan.right,
have t₃ : t ≫ g = pullback_cone.snd s,
apply down_pb.hom_ext,
apply pullback_cone.equalizer_ext (pullback_cone.mk k l down_comm) _ _,
erw [assoc, ← up_comm, reassoc_of t₁, pullback_cone.condition s], refl,
rwa [assoc],
refine ⟨t, t₁, t₃, _⟩,
intros m' m₁ m₂,
apply entire_pb.hom_ext,
apply pullback_cone.equalizer_ext (pullback_cone.mk f (g ≫ l) _) _ _,
exact m₁.trans t₁.symm,
refine trans _ t₂.symm,
erw [reassoc_of m₂]
end
-- The mono isn't strictly necessary but this version is convenient.
-- XXX: It's to ensure g is unique - the alternate solution is to take g ≫ l as one of the arguments and calculate g
def cut_hpb_up {U V W X Y Z : C} (g : U ⟶ W) (h : V ⟶ X) (k : W ⟶ X) (l : W ⟶ Y) (m : X ⟶ Z) (n : Y ⟶ Z) [mono m]
(all : has_pullback_top (g ≫ l) n (h ≫ m))
(down_comm : k ≫ m = l ≫ n)
(down_pb : is_limit (pullback_cone.mk _ _ down_comm)) :
has_pullback_top g k h :=
{ top := all.top,
comm := by rw [← cancel_mono m, assoc, all.comm, assoc, ← down_comm, assoc],
is_pb := vpaste' _ _ _ _ _ _ _ _ _ down_pb all.is_pb }
def cut_hpb_up' {U V W X Y Z : C} (g : U ⟶ W) (h : V ⟶ X) (k : W ⟶ X) (l : W ⟶ Y) (m : X ⟶ Z) (n : Y ⟶ Z)
(all : has_pullback_top (g ≫ l) n (h ≫ m))
(up_comm : all.top ≫ h = g ≫ k)
(down_comm : k ≫ m = l ≫ n)
(down_pb : is_limit (pullback_cone.mk _ _ down_comm)) :
has_pullback_top g k h :=
{ top := all.top,
comm := up_comm,
is_pb := vpaste' _ _ _ _ _ _ _ _ _ down_pb all.is_pb }
-- Show
-- D × A ⟶ B × A
-- | |
-- v v
-- D ⟶ B
-- is a pullback (needed in over/exponentiable_in_slice)
def pullback_prod (xy : X ⟶ Y) (Z : C) [has_binary_products.{v} C] :
is_limit (pullback_cone.mk limits.prod.fst (limits.prod.map xy (𝟙 Z)) (limits.prod.map_fst _ _).symm) :=
is_limit.mk' _ $
begin
intro s,
refine ⟨prod.lift (pullback_cone.fst s) (pullback_cone.snd s ≫ limits.prod.snd), limit.lift_π _ _, _, _⟩,
{ change limits.prod.lift (pullback_cone.fst s) (pullback_cone.snd s ≫ limits.prod.snd) ≫
limits.prod.map xy (𝟙 Z) = pullback_cone.snd s,
apply prod.hom_ext,
rw [assoc, limits.prod.map_fst, prod.lift_fst_assoc, pullback_cone.condition s],
rw [assoc, limits.prod.map_snd, prod.lift_snd_assoc, comp_id] },
{ intros m m₁ m₂,
apply prod.hom_ext,
simpa using m₁,
erw [prod.lift_snd, ← m₂, assoc, limits.prod.map_snd, comp_id] },
end
def pullback_prod' (xy : X ⟶ Y) (Z : C) [has_binary_products.{v} C] :
is_limit (pullback_cone.mk limits.prod.snd (limits.prod.map (𝟙 Z) xy) (limits.prod.map_snd _ _).symm) :=
is_limit.mk' _ $
begin
intro s,
refine ⟨prod.lift (pullback_cone.snd s ≫ limits.prod.fst) (pullback_cone.fst s), limit.lift_π _ _, _, _⟩,
{ apply prod.hom_ext,
erw [assoc, limits.prod.map_fst, prod.lift_fst_assoc, comp_id],
slice_lhs 2 3 {erw limits.prod.map_snd},
rw [prod.lift_snd_assoc, pullback_cone.condition s] },
{ intros m m₁ m₂,
apply prod.hom_ext,
erw [prod.lift_fst, ← m₂, assoc, limits.prod.map_fst, comp_id],
simpa using m₁ }
end
def pullback_flip {W X Y Z : C} {f : W ⟶ X} {g : W ⟶ Y} {h : X ⟶ Z} {k : Y ⟶ Z} {comm : f ≫ h = g ≫ k} (t : is_limit (pullback_cone.mk _ _ comm.symm)) :
is_limit (pullback_cone.mk _ _ comm) :=
is_limit.mk' _ $ λ s,
begin
refine ⟨(pullback_cone.is_limit.lift' t _ _ s.condition.symm).1,
(pullback_cone.is_limit.lift' t _ _ _).2.2,
(pullback_cone.is_limit.lift' t _ _ _).2.1, λ m m₁ m₂, t.hom_ext _⟩,
apply (pullback_cone.mk g f _).equalizer_ext,
{ rw (pullback_cone.is_limit.lift' t _ _ _).2.1,
exact m₂ },
{ rw (pullback_cone.is_limit.lift' t _ _ _).2.2,
exact m₁ },
end
def pullback_square_iso {W X Y Z : C} (f : W ⟶ X) (g : W ⟶ Y) (h : X ⟶ Z) (k : Y ⟶ Z) [mono h] [is_iso g] (comm : f ≫ h = g ≫ k) :
is_limit (pullback_cone.mk _ _ comm) :=
is_limit.mk''' _ (by dsimp [pullback_cone.mk]; apply_instance) $
λ s, ⟨s.snd ≫ inv g, by erw [assoc, is_iso.inv_hom_id g, comp_id] ⟩
def left_iso_has_pullback_top {W X Y Z : C} (f : W ⟶ X) (g : W ⟶ Y) (h : X ⟶ Z) (k : Y ⟶ Z) [mono h] [is_iso g] (comm : f ≫ h = g ≫ k) :
has_pullback_top g k h :=
{ top := f,
comm := comm,
is_pb := pullback_square_iso f g h k comm }
def pullback_square_iso' {W X Y Z : C} (f : W ⟶ X) (g : W ⟶ Y) (h : X ⟶ Z) (k : Y ⟶ Z) [is_iso f] [mono k] (comm : f ≫ h = g ≫ k) :
is_limit (pullback_cone.mk _ _ comm) :=
is_limit.mk' _ $
begin
intro s,
refine ⟨pullback_cone.fst s ≫ inv f, _, _, _⟩,
erw [assoc, is_iso.inv_hom_id, comp_id],
erw [← cancel_mono k, assoc, ← comm, assoc, is_iso.inv_hom_id_assoc, pullback_cone.condition s],
intros m m₁ m₂,
erw [(as_iso f).eq_comp_inv, m₁]
end
def top_iso_has_pullback_top {W X Y Z : C} (f : W ⟶ X) (g : W ⟶ Y) (h : X ⟶ Z) (k : Y ⟶ Z) [is_iso f] [mono k] (comm : f ≫ h = g ≫ k) :
has_pullback_top g k h :=
{ top := f,
comm := comm,
is_pb := pullback_square_iso' f g h k comm }
lemma mono_of_pullback (X Y : C) (f : X ⟶ Y)
(hl : is_limit (pullback_cone.mk (𝟙 X) (𝟙 X) (by simp) : pullback_cone f f)) : mono f :=
begin
split, intros,
set new_cone : pullback_cone f f := pullback_cone.mk g h w,
exact (hl.fac new_cone walking_cospan.left).symm.trans (hl.fac new_cone walking_cospan.right),
end
def pullback_of_mono {X Y : C} (f : X ⟶ Y) [hf : mono f] :
is_limit (pullback_cone.mk (𝟙 X) (𝟙 X) rfl : pullback_cone f f) :=
pullback_square_iso' _ _ _ _ _
def mono_self_has_pullback_top {X Y : C} (f : X ⟶ Y) [hf : mono f] :
has_pullback_top (𝟙 _) f f :=
{ top := 𝟙 _,
comm := by simp,
is_pb := pullback_of_mono f }
universe u₂
variables {D : Type u₂} [category.{v} D] (F : C ⥤ D)
def cone_cospan_equiv :
cone (cospan (F.map f) (F.map g)) ≌ cone (cospan f g ⋙ F) :=
cones.postcompose_equivalence (iso.symm (diagram_iso_cospan _))
local attribute [tidy] tactic.case_bash
def convert_pb
{W X Y Z : C}
{f : W ⟶ X} {g : X ⟶ Z} {h : W ⟶ Y} {k : Y ⟶ Z} (comm : f ≫ g = h ≫ k) :
(cones.postcompose (diagram_iso_cospan _).hom).obj (F.map_cone (pullback_cone.mk _ _ comm)) ≅
(pullback_cone.mk (F.map f) (F.map h) (by rw [← F.map_comp, comm, F.map_comp]) : pullback_cone (F.map g) (F.map k)) :=
cones.ext (iso.refl _) (by { dsimp [diagram_iso_cospan], tidy })
def thing2
{W X Y Z : C}
{f : W ⟶ X} {g : X ⟶ Z} {h : W ⟶ Y} {k : Y ⟶ Z} (comm : f ≫ g = h ≫ k) :
is_limit (F.map_cone (pullback_cone.mk _ _ comm)) ≅ is_limit (pullback_cone.mk (F.map f) (F.map h) (by rw [← F.map_comp, comm, F.map_comp]) : pullback_cone (F.map g) (F.map k)) :=
{ hom := λ p,
begin
apply is_limit.of_iso_limit _ (convert_pb F comm),
apply is_limit.of_right_adjoint (cones.postcompose_equivalence ((diagram_iso_cospan _).symm)).inverse p,
end,
inv := λ p,
begin
have := is_limit.of_right_adjoint (cones.postcompose_equivalence (diagram_iso_cospan (cospan g k ⋙ F))).inverse p,
apply is_limit.of_iso_limit this _,
refine cones.ext (iso.refl _) _,
dsimp [diagram_iso_cospan],
simp_rw [id_comp],
rintro (_ | _ | _),
{ dsimp, rw [comp_id, F.map_comp] },
{ dsimp, rw [comp_id] },
{ dsimp, rw [comp_id] },
end,
hom_inv_id' := subsingleton.elim _ _,
inv_hom_id' := subsingleton.elim _ _ }
def preserves_pullback_cone
[preserves_limits_of_shape walking_cospan F] {W X Y Z : C}
(f : W ⟶ X) (g : X ⟶ Z) (h : W ⟶ Y) (k : Y ⟶ Z) (comm : f ≫ g = h ≫ k)
(t : is_limit (pullback_cone.mk _ _ comm)) :
is_limit (pullback_cone.mk (F.map f) (F.map h) (by rw [← F.map_comp, comm, F.map_comp]) : pullback_cone (F.map g) (F.map k)) :=
(thing2 F comm).hom (preserves_limit.preserves t)
def reflects_pullback_cone
[reflects_limits_of_shape walking_cospan F] {W X Y Z : C}
{f : W ⟶ X} {g : X ⟶ Z} {h : W ⟶ Y} {k : Y ⟶ Z} (comm : f ≫ g = h ≫ k)
(t : is_limit (pullback_cone.mk (F.map f) (F.map h) (by rw [← F.map_comp, comm, F.map_comp]) : pullback_cone (F.map g) (F.map k))) :
is_limit (pullback_cone.mk _ _ comm) :=
reflects_limit.reflects ((thing2 F comm).inv t)
lemma preserves_mono_of_preserves_pullback
[preserves_limits_of_shape walking_cospan F] (X Y : C) (f : X ⟶ Y) [mono f] :
mono (F.map f) :=
begin
apply mono_of_pullback,
have : 𝟙 (F.obj X) = F.map (𝟙 X),
rw F.map_id,
convert preserves_pullback_cone F (𝟙 _) f (𝟙 _) f rfl (pullback_of_mono f),
end
def preserves_walking_cospan_of_preserves_pb_cone {h : W ⟶ _} {k} (comm : h ≫ f = k ≫ g) (is_lim : is_limit (pullback_cone.mk _ _ comm))
(t : is_limit (pullback_cone.mk (F.map h) (F.map k) (by rw [← F.map_comp, comm, F.map_comp]) : pullback_cone (F.map f) (F.map g))) :
preserves_limit (cospan f g) F :=
begin
apply preserves_limit_of_preserves_limit_cone is_lim,
apply ((thing2 _ _).inv t),
end
def preserves_hpb [preserves_limits_of_shape walking_cospan F] {g : X ⟶ Z} {h : W ⟶ Y} {k : Y ⟶ Z} (t : has_pullback_top h k g) :
has_pullback_top (F.map h) (F.map k) (F.map g) :=
{ top := F.map t.top,
comm := by rw [← F.map_comp, t.comm, F.map_comp],
is_pb := preserves_pullback_cone F _ _ _ _ t.comm t.is_pb }
def fully_faithful_reflects_hpb [reflects_limits_of_shape walking_cospan F] [full F] [faithful F] {g : X ⟶ Z} {h : W ⟶ Y} {k : Y ⟶ Z}
(t : has_pullback_top (F.map h) (F.map k) (F.map g)) :
has_pullback_top h k g :=
{ top := F.preimage t.top,
comm := by { apply F.map_injective, simp [t.comm] },
is_pb :=
begin
refine reflects_pullback_cone F _ _,
convert t.is_pb,
simp,
end }
-- Strictly we don't need the assumption that C has pullbacks but oh well
def over_forget_preserves_hpb [has_pullbacks.{v} C] {B : C} {X Y Z W : over B} (g : X ⟶ Z) (h : Z ⟶ W) (k : Y ⟶ W) (t : has_pullback_top g h k) :
has_pullback_top g.left h.left k.left :=
preserves_hpb (over.forget _) t
def over_forget_reflects_hpb {B : C} {X Y Z W : over B} {g : X ⟶ Z} {h : Z ⟶ W} {k : Y ⟶ W}
(t : has_pullback_top g.left h.left k.left ) :
has_pullback_top g h k :=
{ top :=
begin
apply over.hom_mk t.top _,
simp only [auto_param_eq, ← over.w k, t.comm_assoc, over.w h, over.w g],
end,
comm := by { ext1, exact t.comm },
is_pb :=
begin
apply reflects_pullback_cone (over.forget _),
apply t.is_pb,
refine ⟨λ K, by apply_instance⟩,
end } |
3188df3f146afd99d3cd0c4616a023621ad4b3c8 | 206422fb9edabf63def0ed2aa3f489150fb09ccb | /src/field_theory/minpoly.lean | bf1ab36e41b36c508d38e4b1e663540c37594b36 | [
"Apache-2.0"
] | permissive | hamdysalah1/mathlib | b915f86b2503feeae268de369f1b16932321f097 | 95454452f6b3569bf967d35aab8d852b1ddf8017 | refs/heads/master | 1,677,154,116,545 | 1,611,797,994,000 | 1,611,797,994,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,064 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johan Commelin
-/
import ring_theory.integral_closure
import data.polynomial.field_division
import ring_theory.polynomial.gauss_lemma
/-!
# Minimal polynomials
This file defines the minimal polynomial of an element `x` of an `A`-algebra `B`,
under the assumption that x is integral over `A`.
After stating the defining property we specialize to the setting of field extensions
and derive some well-known properties, amongst which the fact that minimal polynomials
are irreducible, and uniquely determined by their defining property.
-/
open_locale classical
open polynomial set function
variables {A B : Type*}
section min_poly_def
variables (A) [comm_ring A] [ring B] [algebra A B]
/-- Let `B` be an `A`-algebra, and `x` an element of `B` that is integral over `A`
so we have some term `hx : is_integral A x`.
The minimal polynomial `minpoly A x` of `x` is a monic polynomial of smallest degree
that has `x` as its root.
For instance, if `V` is a `K`-vector space for some field `K`, and `f : V →ₗ[K] V` then
the minimal polynomial of `f` is `minpoly f.is_integral`. -/
noncomputable def minpoly (x : B) : polynomial A :=
if hx : is_integral A x then well_founded.min degree_lt_wf _ hx else 0
end min_poly_def
namespace minpoly
section ring
variables [comm_ring A] [ring B] [algebra A B]
variables {x : B}
/--A minimal polynomial is monic.-/
lemma monic (hx : is_integral A x) : monic (minpoly A x) :=
by { delta minpoly, rw dif_pos hx, exact (well_founded.min_mem degree_lt_wf _ hx).1 }
/-- A minimal polynomial is nonzero. -/
lemma ne_zero [nontrivial A] (hx : is_integral A x) : minpoly A x ≠ 0 :=
ne_zero_of_monic (monic hx)
lemma eq_zero (hx : ¬ is_integral A x) : minpoly A x = 0 :=
dif_neg hx
variables (A x)
/--An element is a root of its minimal polynomial.-/
@[simp] lemma aeval : aeval x (minpoly A x) = 0 :=
begin
delta minpoly, split_ifs with hx,
{ exact (well_founded.min_mem degree_lt_wf _ hx).2 },
{ exact aeval_zero _ }
end
lemma mem_range_of_degree_eq_one (hx : (minpoly A x).degree = 1) : x ∈ (algebra_map A B).range :=
begin
have h : is_integral A x,
{ by_contra h,
rw [eq_zero h, degree_zero, ←with_bot.coe_one] at hx,
exact (ne_of_lt (show ⊥ < ↑1, from with_bot.bot_lt_coe 1) hx) },
have key := minpoly.aeval A x,
rw [eq_X_add_C_of_degree_eq_one hx, (minpoly.monic h).leading_coeff, C_1, one_mul, aeval_add,
aeval_C, aeval_X, ←eq_neg_iff_add_eq_zero, ←ring_hom.map_neg] at key,
exact ⟨-(minpoly A x).coeff 0, subring.mem_top (-(minpoly A x).coeff 0), key.symm⟩,
end
/--The defining property of the minimal polynomial of an element x:
it is the monic polynomial with smallest degree that has x as its root.-/
lemma min {p : polynomial A} (pmonic : p.monic) (hp : polynomial.aeval x p = 0) :
degree (minpoly A x) ≤ degree p :=
begin
delta minpoly, split_ifs with hx,
{ exact le_of_not_lt (well_founded.not_lt_min degree_lt_wf _ hx ⟨pmonic, hp⟩) },
{ simp only [degree_zero, bot_le] }
end
-- TODO(Commelin, Brasca): this is a duplicate
/-- If an element `x` is a root of a nonzero monic polynomial `p`,
then the degree of `p` is at least the degree of the minimal polynomial of `x`. -/
lemma degree_le_of_monic
{p : polynomial A} (hmonic : p.monic) (hp : polynomial.aeval x p = 0) :
degree (minpoly A x) ≤ degree p :=
min A x hmonic (by simp [hp])
end ring
section integral_domain
variables [integral_domain A]
section ring
variables [ring B] [algebra A B] [nontrivial B]
variables {x : B}
/-- The degree of a minimal polynomial is positive. -/
lemma degree_pos [nontrivial A] (hx : is_integral A x) : 0 < degree (minpoly A x) :=
begin
apply lt_of_le_of_ne,
{ simpa only [zero_le_degree_iff] using ne_zero hx },
assume deg_eq_zero,
rw eq_comm at deg_eq_zero,
have ndeg_eq_zero : nat_degree (minpoly A x) = 0,
{ simpa using congr_arg nat_degree (eq_C_of_degree_eq_zero deg_eq_zero) },
have eq_one : minpoly A x = 1,
{ rw eq_C_of_degree_eq_zero deg_eq_zero, convert C_1,
simpa only [ndeg_eq_zero.symm] using (monic hx).leading_coeff },
simpa only [eq_one, alg_hom.map_one, one_ne_zero] using aeval A x
end
/-- If `B/A` is an injective ring extension, and `a` is an element of `A`,
then the minimal polynomial of `algebra_map A B a` is `X - C a`. -/
lemma eq_X_sub_C_of_algebra_map_inj [nontrivial A]
(a : A) (hf : function.injective (algebra_map A B)) :
minpoly A (algebra_map A B a) = X - C a :=
begin
have hdegle : (minpoly A (algebra_map A B a)).nat_degree ≤ 1,
{ apply with_bot.coe_le_coe.1,
rw [←degree_eq_nat_degree (ne_zero (@is_integral_algebra_map A B _ _ _ a)),
with_top.coe_one, ←degree_X_sub_C a],
refine min A (algebra_map A B a) (monic_X_sub_C a) _,
simp only [aeval_C, aeval_X, alg_hom.map_sub, sub_self] },
have hdeg : (minpoly A (algebra_map A B a)).degree = 1,
{ apply (degree_eq_iff_nat_degree_eq (ne_zero (@is_integral_algebra_map A B _ _ _ a))).2,
exact (has_le.le.antisymm hdegle (nat.succ_le_of_lt (with_bot.coe_lt_coe.1
(lt_of_lt_of_le (degree_pos (@is_integral_algebra_map A B _ _ _ a)) degree_le_nat_degree)))) },
have hrw := eq_X_add_C_of_degree_eq_one hdeg,
simp only [monic (@is_integral_algebra_map A B _ _ _ a), one_mul,
monic.leading_coeff, ring_hom.map_one] at hrw,
have h0 : (minpoly A (algebra_map A B a)).coeff 0 = -a,
{ have hroot := aeval A (algebra_map A B a),
rw [hrw, add_comm] at hroot,
simp only [aeval_C, aeval_X, aeval_add] at hroot,
replace hroot := eq_neg_of_add_eq_zero hroot,
rw [←ring_hom.map_neg _ a] at hroot,
exact (hf hroot) },
rw hrw,
simp only [h0, ring_hom.map_neg, sub_eq_add_neg],
end
variables (A x)
/-- A minimal polynomial is not a unit. -/
lemma not_is_unit : ¬ is_unit (minpoly A x) :=
begin
by_cases hx : is_integral A x,
{ assume H, exact (ne_of_lt (degree_pos hx)).symm (degree_eq_zero_of_is_unit H) },
{ delta minpoly, rw dif_neg hx, simp only [not_is_unit_zero, not_false_iff] }
end
end ring
section domain
variables [domain B] [algebra A B]
variables {x : B}
/-- If `a` strictly divides the minimal polynomial of `x`, then `x` cannot be a root for `a`. -/
lemma aeval_ne_zero_of_dvd_not_unit_minpoly {a : polynomial A} (hx : is_integral A x)
(hamonic : a.monic) (hdvd : dvd_not_unit a (minpoly A x)) :
polynomial.aeval x a ≠ 0 :=
begin
intro ha,
refine not_lt_of_ge (minpoly.min A x hamonic ha) _,
obtain ⟨hzeroa, b, hb_nunit, prod⟩ := hdvd,
have hbmonic : b.monic,
{ rw monic.def,
have := monic hx,
rwa [monic.def, prod, leading_coeff_mul, monic.def.mp hamonic, one_mul] at this },
have hzerob : b ≠ 0 := hbmonic.ne_zero,
have degbzero : 0 < b.nat_degree,
{ apply nat.pos_of_ne_zero,
intro h,
have h₁ := eq_C_of_nat_degree_eq_zero h,
rw [←h, ←leading_coeff, monic.def.1 hbmonic, C_1] at h₁,
rw h₁ at hb_nunit,
have := is_unit_one,
contradiction },
rw [prod, degree_mul, degree_eq_nat_degree hzeroa, degree_eq_nat_degree hzerob],
exact_mod_cast lt_add_of_pos_right _ degbzero,
end
/--A minimal polynomial is irreducible.-/
lemma irreducible (hx : is_integral A x) : irreducible (minpoly A x) :=
begin
cases irreducible_or_factor (minpoly A x) (not_is_unit A x) with hirr hred,
{ exact hirr },
exfalso,
obtain ⟨a, b, ha_nunit, hb_nunit, hab_eq⟩ := hred,
have coeff_prod : a.leading_coeff * b.leading_coeff = 1,
{ rw [←monic.def.1 (monic hx), ←hab_eq],
simp only [leading_coeff_mul] },
have hamonic : (a * C b.leading_coeff).monic,
{ rw monic.def,
simp only [coeff_prod, leading_coeff_mul, leading_coeff_C] },
have hbmonic : (b * C a.leading_coeff).monic,
{ rw [monic.def, mul_comm],
simp only [coeff_prod, leading_coeff_mul, leading_coeff_C] },
have prod : minpoly A x = (a * C b.leading_coeff) * (b * C a.leading_coeff),
{ symmetry,
calc a * C b.leading_coeff * (b * C a.leading_coeff)
= a * b * (C a.leading_coeff * C b.leading_coeff) : by ring
... = a * b * (C (a.leading_coeff * b.leading_coeff)) : by simp only [ring_hom.map_mul]
... = a * b : by rw [coeff_prod, C_1, mul_one]
... = minpoly A x : hab_eq },
have hzero := aeval A x,
rw [prod, aeval_mul, mul_eq_zero] at hzero,
cases hzero,
{ refine aeval_ne_zero_of_dvd_not_unit_minpoly hx hamonic _ hzero,
exact ⟨hamonic.ne_zero, _, mt is_unit_of_mul_is_unit_left hb_nunit, prod⟩ },
{ refine aeval_ne_zero_of_dvd_not_unit_minpoly hx hbmonic _ hzero,
rw mul_comm at prod,
exact ⟨hbmonic.ne_zero, _, mt is_unit_of_mul_is_unit_left ha_nunit, prod⟩ },
end
end domain
end integral_domain
section field
variables [field A]
section ring
variables [ring B] [algebra A B]
variables {x : B}
variables (A x)
/-- If an element `x` is a root of a nonzero polynomial `p`,
then the degree of `p` is at least the degree of the minimal polynomial of `x`. -/
lemma degree_le_of_ne_zero
{p : polynomial A} (pnz : p ≠ 0) (hp : polynomial.aeval x p = 0) :
degree (minpoly A x) ≤ degree p :=
calc degree (minpoly A x) ≤ degree (p * C (leading_coeff p)⁻¹) :
min A x (monic_mul_leading_coeff_inv pnz) (by simp [hp])
... = degree p : degree_mul_leading_coeff_inv p pnz
/-- The minimal polynomial of an element x is uniquely characterized by its defining property:
if there is another monic polynomial of minimal degree that has x as a root,
then this polynomial is equal to the minimal polynomial of x. -/
lemma unique {p : polynomial A}
(pmonic : p.monic) (hp : polynomial.aeval x p = 0)
(pmin : ∀ q : polynomial A, q.monic → polynomial.aeval x q = 0 → degree p ≤ degree q) :
p = minpoly A x :=
begin
have hx : is_integral A x := ⟨p, pmonic, hp⟩,
symmetry, apply eq_of_sub_eq_zero,
by_contra hnz,
have := degree_le_of_ne_zero A x hnz (by simp [hp]),
contrapose! this,
apply degree_sub_lt _ (ne_zero hx),
{ rw [(monic hx).leading_coeff, pmonic.leading_coeff] },
{ exact le_antisymm (min A x pmonic hp)
(pmin (minpoly A x) (monic hx) (aeval A x)) }
end
/-- If an element x is a root of a polynomial p,
then the minimal polynomial of x divides p. -/
lemma dvd {p : polynomial A} (hp : polynomial.aeval x p = 0) : minpoly A x ∣ p :=
begin
by_cases hp0 : p = 0,
{ simp only [hp0, dvd_zero] },
have hx : is_integral A x,
{ rw ← is_algebraic_iff_is_integral, exact ⟨p, hp0, hp⟩ },
rw ← dvd_iff_mod_by_monic_eq_zero (monic hx),
by_contra hnz,
have := degree_le_of_ne_zero A x hnz _,
{ contrapose! this,
exact degree_mod_by_monic_lt _ (monic hx) (ne_zero hx) },
{ rw ← mod_by_monic_add_div p (monic hx) at hp,
simpa using hp }
end
lemma dvd_map_of_is_scalar_tower (A K : Type*) {R : Type*} [comm_ring A] [field K] [comm_ring R]
[algebra A K] [algebra A R] [algebra K R] [is_scalar_tower A K R] (x : R) :
minpoly K x ∣ (minpoly A x).map (algebra_map A K) :=
by { refine minpoly.dvd K x _, rw [← is_scalar_tower.aeval_apply, minpoly.aeval] }
variables {A x}
theorem unique' [nontrivial B] {p : polynomial A} (hx : is_integral A x)
(hp1 : _root_.irreducible p) (hp2 : polynomial.aeval x p = 0) (hp3 : p.monic) :
p = minpoly A x :=
let ⟨q, hq⟩ := dvd A x hp2 in
eq_of_monic_of_associated hp3 (monic hx) $
mul_one (minpoly A x) ▸ hq.symm ▸ associated_mul_mul (associated.refl _) $
associated_one_iff_is_unit.2 $ (hp1.is_unit_or_is_unit hq).resolve_left $ not_is_unit A x
/-- If `y` is the image of `x` in an extension, their minimal polynomials coincide.
We take `h : y = algebra_map L T x` as an argument because `rw h` typically fails
since `is_integral R y` depends on y.
-/
lemma eq_of_algebra_map_eq {K S T : Type*} [field K] [comm_ring S] [comm_ring T]
[algebra K S] [algebra K T] [algebra S T]
[is_scalar_tower K S T] (hST : function.injective (algebra_map S T))
{x : S} {y : T} (hx : is_integral K x) (h : y = algebra_map S T x) :
minpoly K x = minpoly K y :=
minpoly.unique _ _ (minpoly.monic hx)
(by rw [h, ← is_scalar_tower.algebra_map_aeval, minpoly.aeval, ring_hom.map_zero])
(λ q q_monic root_q, minpoly.min _ _ q_monic
(is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero K S T hST
(h ▸ root_q : polynomial.aeval (algebra_map S T x) q = 0)))
section gcd_domain
/-- For GCD domains, the minimal polynomial over the ring is the same as the minimal polynomial
over the fraction field. -/
lemma gcd_domain_eq_field_fractions {A K R : Type*} [integral_domain A]
[gcd_monoid A] [field K] [integral_domain R] (f : fraction_map A K) [algebra f.codomain R]
[algebra A R] [is_scalar_tower A f.codomain R] {x : R} (hx : is_integral A x) :
minpoly f.codomain x = (minpoly A x).map (localization_map.to_ring_hom f) :=
begin
refine (unique' (@is_integral_of_is_scalar_tower A f.codomain R _ _ _ _ _ _ _ x hx) _ _ _).symm,
{ exact (polynomial.is_primitive.irreducible_iff_irreducible_map_fraction_map f
(polynomial.monic.is_primitive (monic hx))).1 (irreducible hx) },
{ have htower := is_scalar_tower.aeval_apply A f.codomain R x (minpoly A x),
simp only [localization_map.algebra_map_eq, aeval] at htower,
exact htower.symm },
{ exact monic_map _ (monic hx) }
end
/-- The minimal polynomial over `ℤ` is the same as the minimal polynomial over `ℚ`. -/
--TODO use `gcd_domain_eq_field_fractions` directly when localizations are defined
-- in terms of algebras instead of `ring_hom`s
lemma over_int_eq_over_rat {A : Type*} [integral_domain A] {x : A} [hℚA : algebra ℚ A]
(hx : is_integral ℤ x) :
minpoly ℚ x = map (int.cast_ring_hom ℚ) (minpoly ℤ x) :=
begin
refine (unique' (@is_integral_of_is_scalar_tower ℤ ℚ A _ _ _ _ _ _ _ x hx) _ _ _).symm,
{ exact (is_primitive.int.irreducible_iff_irreducible_map_cast
(polynomial.monic.is_primitive (monic hx))).1 (irreducible hx) },
{ have htower := is_scalar_tower.aeval_apply ℤ ℚ A x (minpoly ℤ x),
simp only [localization_map.algebra_map_eq, aeval] at htower,
exact htower.symm },
{ exact monic_map _ (monic hx) }
end
/-- For GCD domains, the minimal polynomial divides any primitive polynomial that has the integral
element as root. -/
lemma gcd_domain_dvd {A K R : Type*}
[integral_domain A] [gcd_monoid A] [field K] [integral_domain R]
(f : fraction_map A K) [algebra f.codomain R] [algebra A R] [is_scalar_tower A f.codomain R]
{x : R} (hx : is_integral A x)
{P : polynomial A} (hprim : is_primitive P) (hroot : polynomial.aeval x P = 0) :
minpoly A x ∣ P :=
begin
apply (is_primitive.dvd_iff_fraction_map_dvd_fraction_map f
(monic.is_primitive (monic hx)) hprim ).2,
rw [← gcd_domain_eq_field_fractions f hx],
refine dvd _ _ _,
rwa [← localization_map.algebra_map_eq, ← is_scalar_tower.aeval_apply]
end
/-- The minimal polynomial over `ℤ` divides any primitive polynomial that has the integral element
as root. -/
-- TODO use `gcd_domain_dvd` directly when localizations are defined in terms of algebras
-- instead of `ring_hom`s
lemma integer_dvd {A : Type*} [integral_domain A] [algebra ℚ A] {x : A} (hx : is_integral ℤ x)
{P : polynomial ℤ} (hprim : is_primitive P) (hroot : polynomial.aeval x P = 0) :
minpoly ℤ x ∣ P :=
begin
apply (is_primitive.int.dvd_iff_map_cast_dvd_map_cast _ _
(monic.is_primitive (monic hx)) hprim ).2,
rw [← over_int_eq_over_rat hx],
refine dvd _ _ _,
rwa [(int.cast_ring_hom ℚ).ext_int (algebra_map ℤ ℚ), ← is_scalar_tower.aeval_apply]
end
end gcd_domain
variables (B) [nontrivial B]
/-- If `B/K` is a nontrivial algebra over a field, and `x` is an element of `K`,
then the minimal polynomial of `algebra_map K B x` is `X - C x`. -/
lemma eq_X_sub_C (a : A) : minpoly A (algebra_map A B a) = X - C a :=
eq_X_sub_C_of_algebra_map_inj a (algebra_map A B).injective
lemma eq_X_sub_C' (a : A) : minpoly A a = X - C a := eq_X_sub_C A a
variables (A)
/-- The minimal polynomial of `0` is `X`. -/
@[simp] lemma zero : minpoly A (0:B) = X :=
by simpa only [add_zero, C_0, sub_eq_add_neg, neg_zero, ring_hom.map_zero]
using eq_X_sub_C B (0:A)
/-- The minimal polynomial of `1` is `X - 1`. -/
@[simp] lemma one : minpoly A (1:B) = X - 1 :=
by simpa only [ring_hom.map_one, C_1, sub_eq_add_neg] using eq_X_sub_C B (1:A)
end ring
section domain
variables [domain B] [algebra A B]
variables {x : B}
/-- A minimal polynomial is prime. -/
lemma prime (hx : is_integral A x) : prime (minpoly A x) :=
begin
refine ⟨ne_zero hx, not_is_unit A x, _⟩,
rintros p q ⟨d, h⟩,
have : polynomial.aeval x (p*q) = 0 := by simp [h, aeval A x],
replace : polynomial.aeval x p = 0 ∨ polynomial.aeval x q = 0 := by simpa,
exact or.imp (dvd A x) (dvd A x) this
end
/-- If `L/K` is a field extension and an element `y` of `K` is a root of the minimal polynomial
of an element `x ∈ L`, then `y` maps to `x` under the field embedding. -/
lemma root {x : B} (hx : is_integral A x) {y : A} (h : is_root (minpoly A x) y) :
algebra_map A B y = x :=
have key : minpoly A x = X - C y :=
eq_of_monic_of_associated (monic hx) (monic_X_sub_C y) (associated_of_dvd_dvd
(dvd_symm_of_irreducible (irreducible_X_sub_C y) (irreducible hx) (dvd_iff_is_root.2 h))
(dvd_iff_is_root.2 h)),
by { have := aeval A x, rwa [key, alg_hom.map_sub, aeval_X, aeval_C, sub_eq_zero, eq_comm] at this }
/--The constant coefficient of the minimal polynomial of `x` is `0` if and only if `x = 0`. -/
@[simp] lemma coeff_zero_eq_zero (hx : is_integral A x) : coeff (minpoly A x) 0 = 0 ↔ x = 0 :=
begin
split,
{ intro h,
have zero_root := zero_is_root_of_coeff_zero_eq_zero h,
rw ← root hx zero_root,
exact ring_hom.map_zero _ },
{ rintro rfl, simp }
end
/--The minimal polynomial of a nonzero element has nonzero constant coefficient. -/
lemma coeff_zero_ne_zero (hx : is_integral A x) (h : x ≠ 0) : coeff (minpoly A x) 0 ≠ 0 :=
by { contrapose! h, simpa only [hx, coeff_zero_eq_zero] using h }
end domain
end field
end minpoly
|
3c329ef70f8a7b9dc4d9526f4a371d3e315a9e7e | 618003631150032a5676f229d13a079ac875ff77 | /src/data/seq/computation.lean | 27d78b513e8317edb0558c6e1a8fbfe781e948d6 | [
"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 | 37,569 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Coinductive formalization of unbounded computations.
-/
import data.stream
import tactic.basic
universes u v w
/-
coinductive computation (α : Type u) : Type u
| return : α → computation α
| think : computation α → computation α
-/
/-- `computation α` is the type of unbounded computations returning `α`.
An element of `computation α` is an infinite sequence of `option α` such
that if `f n = some a` for some `n` then it is constantly `some a` after that. -/
def computation (α : Type u) : Type u :=
{ f : stream (option α) // ∀ {n a}, f n = some a → f (n+1) = some a }
namespace computation
variables {α : Type u} {β : Type v} {γ : Type w}
-- constructors
/-- `return a` is the computation that immediately terminates with result `a`. -/
def return (a : α) : computation α := ⟨stream.const (some a), λn a', id⟩
instance : has_coe_t α (computation α) := ⟨return⟩ -- note [use has_coe_t]
/-- `think c` is the computation that delays for one "tick" and then performs
computation `c`. -/
def think (c : computation α) : computation α :=
⟨none :: c.1, λn a h, by {cases n with n, contradiction, exact c.2 h}⟩
/-- `thinkN c n` is the computation that delays for `n` ticks and then performs
computation `c`. -/
def thinkN (c : computation α) : ℕ → computation α
| 0 := c
| (n+1) := think (thinkN n)
-- check for immediate result
/-- `head c` is the first step of computation, either `some a` if `c = return a`
or `none` if `c = think c'`. -/
def head (c : computation α) : option α := c.1.head
-- one step of computation
/-- `tail c` is the remainder of computation, either `c` if `c = return a`
or `c'` if `c = think c'`. -/
def tail (c : computation α) : computation α :=
⟨c.1.tail, λ n a, let t := c.2 in t⟩
/-- `empty α` is the computation that never returns, an infinite sequence of
`think`s. -/
def empty (α) : computation α := ⟨stream.const none, λn a', id⟩
instance : inhabited (computation α) := ⟨empty _⟩
/-- `run_for c n` evaluates `c` for `n` steps and returns the result, or `none`
if it did not terminate after `n` steps. -/
def run_for : computation α → ℕ → option α := subtype.val
/-- `destruct c` is the destructor for `computation α` as a coinductive type.
It returns `inl a` if `c = return a` and `inr c'` if `c = think c'`. -/
def destruct (c : computation α) : α ⊕ computation α :=
match c.1 0 with
| none := sum.inr (tail c)
| some a := sum.inl a
end
/-- `run c` is an unsound meta function that runs `c` to completion, possibly
resulting in an infinite loop in the VM. -/
meta def run : computation α → α | c :=
match destruct c with
| sum.inl a := a
| sum.inr ca := run ca
end
theorem destruct_eq_ret {s : computation α} {a : α} :
destruct s = sum.inl a → s = return a :=
begin
dsimp [destruct],
induction f0 : s.1 0; intro h,
{ contradiction },
{ apply subtype.eq, funext n,
induction n with n IH,
{ injection h with h', rwa h' at f0 },
{ exact s.2 IH } }
end
theorem destruct_eq_think {s : computation α} {s'} :
destruct s = sum.inr s' → s = think s' :=
begin
dsimp [destruct],
induction f0 : s.1 0 with a'; intro h,
{ injection h with h', rw ←h',
cases s with f al,
apply subtype.eq, dsimp [think, tail],
rw ←f0, exact (stream.eta f).symm },
{ contradiction }
end
@[simp] theorem destruct_ret (a : α) : destruct (return a) = sum.inl a := rfl
@[simp] theorem destruct_think : ∀ s : computation α, destruct (think s) = sum.inr s
| ⟨f, al⟩ := rfl
@[simp] theorem destruct_empty : destruct (empty α) = sum.inr (empty α) := rfl
@[simp] theorem head_ret (a : α) : head (return a) = some a := rfl
@[simp] theorem head_think (s : computation α) : head (think s) = none := rfl
@[simp] theorem head_empty : head (empty α) = none := rfl
@[simp] theorem tail_ret (a : α) : tail (return a) = return a := rfl
@[simp] theorem tail_think (s : computation α) : tail (think s) = s :=
by cases s with f al; apply subtype.eq; dsimp [tail, think]; rw [stream.tail_cons]
@[simp] theorem tail_empty : tail (empty α) = empty α := rfl
theorem think_empty : empty α = think (empty α) :=
destruct_eq_think destruct_empty
def cases_on {C : computation α → Sort v} (s : computation α)
(h1 : ∀ a, C (return a)) (h2 : ∀ s, C (think s)) : C s := begin
induction H : destruct s with v v,
{ rw destruct_eq_ret H, apply h1 },
{ cases v with a s', rw destruct_eq_think H, apply h2 }
end
def corec.F (f : β → α ⊕ β) : α ⊕ β → option α × (α ⊕ β)
| (sum.inl a) := (some a, sum.inl a)
| (sum.inr b) := (match f b with
| sum.inl a := some a
| sum.inr b' := none
end, f b)
/-- `corec f b` is the corecursor for `computation α` as a coinductive type.
If `f b = inl a` then `corec f b = return a`, and if `f b = inl b'` then
`corec f b = think (corec f b')`. -/
def corec (f : β → α ⊕ β) (b : β) : computation α :=
begin
refine ⟨stream.corec' (corec.F f) (sum.inr b), λn a' h, _⟩,
rw stream.corec'_eq,
change stream.corec' (corec.F f) (corec.F f (sum.inr b)).2 n = some a',
revert h, generalize : sum.inr b = o, revert o,
induction n with n IH; intro o,
{ change (corec.F f o).1 = some a' → (corec.F f (corec.F f o).2).1 = some a',
cases o with a b; intro h, { exact h },
dsimp [corec.F] at h, dsimp [corec.F],
cases f b with a b', { exact h },
{ contradiction } },
{ rw [stream.corec'_eq (corec.F f) (corec.F f o).2,
stream.corec'_eq (corec.F f) o],
exact IH (corec.F f o).2 }
end
/-- left map of `⊕` -/
def lmap (f : α → β) : α ⊕ γ → β ⊕ γ
| (sum.inl a) := sum.inl (f a)
| (sum.inr b) := sum.inr b
/-- right map of `⊕` -/
def rmap (f : β → γ) : α ⊕ β → α ⊕ γ
| (sum.inl a) := sum.inl a
| (sum.inr b) := sum.inr (f b)
attribute [simp] lmap rmap
@[simp] lemma corec_eq (f : β → α ⊕ β) (b : β) :
destruct (corec f b) = rmap (corec f) (f b) :=
begin
dsimp [corec, destruct],
change stream.corec' (corec.F f) (sum.inr b) 0 with corec.F._match_1 (f b),
induction h : f b with a b', { refl },
dsimp [corec.F, destruct],
apply congr_arg, apply subtype.eq,
dsimp [corec, tail],
rw [stream.corec'_eq, stream.tail_cons],
dsimp [corec.F], rw h
end
section bisim
variable (R : computation α → computation α → Prop)
local infix ~ := R
def bisim_o : α ⊕ computation α → α ⊕ computation α → Prop
| (sum.inl a) (sum.inl a') := a = a'
| (sum.inr s) (sum.inr s') := R s s'
| _ _ := false
attribute [simp] bisim_o
def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → bisim_o R (destruct s₁) (destruct s₂)
-- If two computations are bisimilar, then they are equal
theorem eq_of_bisim (bisim : is_bisimulation R) {s₁ s₂} (r : s₁ ~ s₂) : s₁ = s₂ :=
begin
apply subtype.eq,
apply stream.eq_of_bisim (λx y, ∃ s s' : computation α, s.1 = x ∧ s'.1 = y ∧ R s s'),
dsimp [stream.is_bisimulation],
intros t₁ t₂ e,
exact match t₁, t₂, e with ._, ._, ⟨s, s', rfl, rfl, r⟩ :=
suffices head s = head s' ∧ R (tail s) (tail s'), from
and.imp id (λr, ⟨tail s, tail s',
by cases s; refl, by cases s'; refl, r⟩) this,
begin
have := bisim r, revert r this,
apply cases_on s _ _; intros; apply cases_on s' _ _; intros; intros r this,
{ constructor, dsimp at this, rw this, assumption },
{ rw [destruct_ret, destruct_think] at this,
exact false.elim this },
{ rw [destruct_ret, destruct_think] at this,
exact false.elim this },
{ simp at this, simp [*] }
end
end,
exact ⟨s₁, s₂, rfl, rfl, r⟩
end
end bisim
-- It's more of a stretch to use ∈ for this relation, but it
-- asserts that the computation limits to the given value.
protected def mem (a : α) (s : computation α) := some a ∈ s.1
instance : has_mem α (computation α) := ⟨computation.mem⟩
theorem le_stable (s : computation α) {a m n} (h : m ≤ n) :
s.1 m = some a → s.1 n = some a :=
by {cases s with f al, induction h with n h IH, exacts [id, λ h2, al (IH h2)]}
theorem mem_unique :
relator.left_unique ((∈) : α → computation α → Prop) :=
λa s b ⟨m, ha⟩ ⟨n, hb⟩, by injection
(le_stable s (le_max_left m n) ha.symm).symm.trans
(le_stable s (le_max_right m n) hb.symm)
/-- `terminates s` asserts that the computation `s` eventually terminates with some value. -/
@[class] def terminates (s : computation α) : Prop := ∃ a, a ∈ s
theorem terminates_of_mem {s : computation α} {a : α} : a ∈ s → terminates s :=
exists.intro a
theorem terminates_def (s : computation α) : terminates s ↔ ∃ n, (s.1 n).is_some :=
⟨λ⟨a, n, h⟩, ⟨n, by {dsimp [stream.nth] at h, rw ←h, exact rfl}⟩,
λ⟨n, h⟩, ⟨option.get h, n, (option.eq_some_of_is_some h).symm⟩⟩
theorem ret_mem (a : α) : a ∈ return a :=
exists.intro 0 rfl
theorem eq_of_ret_mem {a a' : α} (h : a' ∈ return a) : a' = a :=
mem_unique h (ret_mem _)
instance ret_terminates (a : α) : terminates (return a) :=
terminates_of_mem (ret_mem _)
theorem think_mem {s : computation α} {a} : a ∈ s → a ∈ think s
| ⟨n, h⟩ := ⟨n+1, h⟩
instance think_terminates (s : computation α) :
∀ [terminates s], terminates (think s)
| ⟨a, n, h⟩ := ⟨a, n+1, h⟩
theorem of_think_mem {s : computation α} {a} : a ∈ think s → a ∈ s
| ⟨n, h⟩ := by {cases n with n', contradiction, exact ⟨n', h⟩}
theorem of_think_terminates {s : computation α} :
terminates (think s) → terminates s
| ⟨a, h⟩ := ⟨a, of_think_mem h⟩
theorem not_mem_empty (a : α) : a ∉ empty α :=
λ ⟨n, h⟩, by clear _fun_match; contradiction
theorem not_terminates_empty : ¬ terminates (empty α) :=
λ ⟨a, h⟩, not_mem_empty a h
theorem eq_empty_of_not_terminates {s} (H : ¬ terminates s) : s = empty α :=
begin
apply subtype.eq, funext n,
induction h : s.val n, {refl},
refine absurd _ H, exact ⟨_, _, h.symm⟩
end
theorem thinkN_mem {s : computation α} {a} : ∀ n, a ∈ thinkN s n ↔ a ∈ s
| 0 := iff.rfl
| (n+1) := iff.trans ⟨of_think_mem, think_mem⟩ (thinkN_mem n)
instance thinkN_terminates (s : computation α) :
∀ [terminates s] n, terminates (thinkN s n)
| ⟨a, h⟩ n := ⟨a, (thinkN_mem n).2 h⟩
theorem of_thinkN_terminates (s : computation α) (n) :
terminates (thinkN s n) → terminates s
| ⟨a, h⟩ := ⟨a, (thinkN_mem _).1 h⟩
/-- `promises s a`, or `s ~> a`, asserts that although the computation `s`
may not terminate, if it does, then the result is `a`. -/
def promises (s : computation α) (a : α) : Prop := ∀ ⦃a'⦄, a' ∈ s → a = a'
infix ` ~> `:50 := promises
theorem mem_promises {s : computation α} {a : α} : a ∈ s → s ~> a :=
λ h a', mem_unique h
theorem empty_promises (a : α) : empty α ~> a :=
λ a' h, absurd h (not_mem_empty _)
section get
variables (s : computation α) [h : terminates s]
include s h
/-- `length s` gets the number of steps of a terminating computation -/
def length : ℕ := nat.find ((terminates_def _).1 h)
/-- `get s` returns the result of a terminating computation -/
def get : α := option.get (nat.find_spec $ (terminates_def _).1 h)
theorem get_mem : get s ∈ s :=
exists.intro (length s) (option.eq_some_of_is_some _).symm
theorem get_eq_of_mem {a} : a ∈ s → get s = a :=
mem_unique (get_mem _)
theorem mem_of_get_eq {a} : get s = a → a ∈ s :=
by intro h; rw ←h; apply get_mem
@[simp] theorem get_think : get (think s) = get s :=
get_eq_of_mem _ $ let ⟨n, h⟩ := get_mem s in ⟨n+1, h⟩
@[simp] theorem get_thinkN (n) : get (thinkN s n) = get s :=
get_eq_of_mem _ $ (thinkN_mem _).2 (get_mem _)
theorem get_promises : s ~> get s := λ a, get_eq_of_mem _
theorem mem_of_promises {a} (p : s ~> a) : a ∈ s :=
by unfreezeI; cases h with a' h; rw p h; exact h
theorem get_eq_of_promises {a} : s ~> a → get s = a :=
get_eq_of_mem _ ∘ mem_of_promises _
end get
/-- `results s a n` completely characterizes a terminating computation:
it asserts that `s` terminates after exactly `n` steps, with result `a`. -/
def results (s : computation α) (a : α) (n : ℕ) :=
∃ (h : a ∈ s), @length _ s (terminates_of_mem h) = n
theorem results_of_terminates (s : computation α) [T : terminates s] :
results s (get s) (length s) :=
⟨get_mem _, rfl⟩
theorem results_of_terminates' (s : computation α) [T : terminates s] {a} (h : a ∈ s) :
results s a (length s) :=
by rw ←get_eq_of_mem _ h; apply results_of_terminates
theorem results.mem {s : computation α} {a n} : results s a n → a ∈ s
| ⟨m, _⟩ := m
theorem results.terminates {s : computation α} {a n} (h : results s a n) : terminates s :=
terminates_of_mem h.mem
theorem results.length {s : computation α} {a n} [T : terminates s] :
results s a n → length s = n
| ⟨_, h⟩ := h
theorem results.val_unique {s : computation α} {a b m n}
(h1 : results s a m) (h2 : results s b n) : a = b :=
mem_unique h1.mem h2.mem
theorem results.len_unique {s : computation α} {a b m n}
(h1 : results s a m) (h2 : results s b n) : m = n :=
by haveI := h1.terminates; haveI := h2.terminates; rw [←h1.length, h2.length]
theorem exists_results_of_mem {s : computation α} {a} (h : a ∈ s) : ∃ n, results s a n :=
by haveI := terminates_of_mem h; exact ⟨_, results_of_terminates' s h⟩
@[simp] theorem get_ret (a : α) : get (return a) = a :=
get_eq_of_mem _ ⟨0, rfl⟩
@[simp] theorem length_ret (a : α) : length (return a) = 0 :=
let h := computation.ret_terminates a in
nat.eq_zero_of_le_zero $ nat.find_min' ((terminates_def (return a)).1 h) rfl
theorem results_ret (a : α) : results (return a) a 0 :=
⟨_, length_ret _⟩
@[simp] theorem length_think (s : computation α) [h : terminates s] :
length (think s) = length s + 1 :=
begin
apply le_antisymm,
{ exact nat.find_min' _ (nat.find_spec ((terminates_def _).1 h)) },
{ have : (option.is_some ((think s).val (length (think s))) : Prop) :=
nat.find_spec ((terminates_def _).1 s.think_terminates),
cases length (think s) with n,
{ contradiction },
{ apply nat.succ_le_succ, apply nat.find_min', apply this } }
end
theorem results_think {s : computation α} {a n}
(h : results s a n) : results (think s) a (n + 1) :=
by haveI := h.terminates; exact ⟨think_mem h.mem, by rw [length_think, h.length]⟩
theorem of_results_think {s : computation α} {a n}
(h : results (think s) a n) : ∃ m, results s a m ∧ n = m + 1 :=
begin
haveI := of_think_terminates h.terminates,
have := results_of_terminates' _ (of_think_mem h.mem),
exact ⟨_, this, results.len_unique h (results_think this)⟩,
end
@[simp] theorem results_think_iff {s : computation α} {a n} :
results (think s) a (n + 1) ↔ results s a n :=
⟨λ h, let ⟨n', r, e⟩ := of_results_think h in by injection e with h'; rwa h',
results_think⟩
theorem results_thinkN {s : computation α} {a m} :
∀ n, results s a m → results (thinkN s n) a (m + n)
| 0 h := h
| (n+1) h := results_think (results_thinkN n h)
theorem results_thinkN_ret (a : α) (n) : results (thinkN (return a) n) a n :=
by have := results_thinkN n (results_ret a); rwa nat.zero_add at this
@[simp] theorem length_thinkN (s : computation α) [h : terminates s] (n) :
length (thinkN s n) = length s + n :=
(results_thinkN n (results_of_terminates _)).length
theorem eq_thinkN {s : computation α} {a n} (h : results s a n) :
s = thinkN (return a) n :=
begin
revert s,
induction n with n IH; intro s;
apply cases_on s (λ a', _) (λ s, _); intro h,
{ rw ←eq_of_ret_mem h.mem, refl },
{ cases of_results_think h with n h, cases h, contradiction },
{ have := h.len_unique (results_ret _), contradiction },
{ rw IH (results_think_iff.1 h), refl }
end
theorem eq_thinkN' (s : computation α) [h : terminates s] :
s = thinkN (return (get s)) (length s) :=
eq_thinkN (results_of_terminates _)
def mem_rec_on {C : computation α → Sort v} {a s} (M : a ∈ s)
(h1 : C (return a)) (h2 : ∀ s, C s → C (think s)) : C s :=
begin
haveI T := terminates_of_mem M,
rw [eq_thinkN' s, get_eq_of_mem s M],
generalize : length s = n,
induction n with n IH, exacts [h1, h2 _ IH]
end
def terminates_rec_on {C : computation α → Sort v} (s) [terminates s]
(h1 : ∀ a, C (return a)) (h2 : ∀ s, C s → C (think s)) : C s :=
mem_rec_on (get_mem s) (h1 _) h2
/-- Map a function on the result of a computation. -/
def map (f : α → β) : computation α → computation β
| ⟨s, al⟩ := ⟨s.map (λo, option.cases_on o none (some ∘ f)),
λn b, begin
dsimp [stream.map, stream.nth],
induction e : s n with a; intro h,
{ contradiction }, { rw [al e, ←h] }
end⟩
def bind.G : β ⊕ computation β → β ⊕ computation α ⊕ computation β
| (sum.inl b) := sum.inl b
| (sum.inr cb') := sum.inr $ sum.inr cb'
def bind.F (f : α → computation β) :
computation α ⊕ computation β → β ⊕ computation α ⊕ computation β
| (sum.inl ca) :=
match destruct ca with
| sum.inl a := bind.G $ destruct (f a)
| sum.inr ca' := sum.inr $ sum.inl ca'
end
| (sum.inr cb) := bind.G $ destruct cb
/-- Compose two computations into a monadic `bind` operation. -/
def bind (c : computation α) (f : α → computation β) : computation β :=
corec (bind.F f) (sum.inl c)
instance : has_bind computation := ⟨@bind⟩
theorem has_bind_eq_bind {β} (c : computation α) (f : α → computation β) :
c >>= f = bind c f := rfl
/-- Flatten a computation of computations into a single computation. -/
def join (c : computation (computation α)) : computation α := c >>= id
@[simp] theorem map_ret (f : α → β) (a) : map f (return a) = return (f a) := rfl
@[simp] theorem map_think (f : α → β) : ∀ s, map f (think s) = think (map f s)
| ⟨s, al⟩ := by apply subtype.eq; dsimp [think, map]; rw stream.map_cons
@[simp] theorem destruct_map (f : α → β) (s) : destruct (map f s) = lmap f (rmap (map f) (destruct s)) :=
by apply s.cases_on; intro; simp
@[simp] theorem map_id : ∀ (s : computation α), map id s = s
| ⟨f, al⟩ := begin
apply subtype.eq; simp [map, function.comp],
have e : (@option.rec α (λ_, option α) none some) = id,
{ funext x, cases x; refl },
simp [e, stream.map_id]
end
theorem map_comp (f : α → β) (g : β → γ) :
∀ (s : computation α), map (g ∘ f) s = map g (map f s)
| ⟨s, al⟩ := begin
apply subtype.eq; dsimp [map],
rw stream.map_map,
apply congr_arg (λ f : _ → option γ, stream.map f s),
funext x, cases x with x; refl
end
@[simp] theorem ret_bind (a) (f : α → computation β) :
bind (return a) f = f a :=
begin
apply eq_of_bisim (λc₁ c₂,
c₁ = bind (return a) f ∧ c₂ = f a ∨
c₁ = corec (bind.F f) (sum.inr c₂)),
{ intros c₁ c₂ h,
exact match c₁, c₂, h with
| ._, ._, or.inl ⟨rfl, rfl⟩ := begin
simp [bind, bind.F],
cases destruct (f a) with b cb; simp [bind.G]
end
| ._, c, or.inr rfl := begin
simp [bind.F],
cases destruct c with b cb; simp [bind.G]
end end },
{ simp }
end
@[simp] theorem think_bind (c) (f : α → computation β) :
bind (think c) f = think (bind c f) :=
destruct_eq_think $ by simp [bind, bind.F]
@[simp] theorem bind_ret (f : α → β) (s) : bind s (return ∘ f) = map f s :=
begin
apply eq_of_bisim (λc₁ c₂, c₁ = c₂ ∨
∃ s, c₁ = bind s (return ∘ f) ∧ c₂ = map f s),
{ intros c₁ c₂ h,
exact match c₁, c₂, h with
| _, _, or.inl (eq.refl c) := begin cases destruct c with b cb; simp end
| _, _, or.inr ⟨s, rfl, rfl⟩ := begin
apply cases_on s; intros s; simp,
exact or.inr ⟨s, rfl, rfl⟩
end end },
{ exact or.inr ⟨s, rfl, rfl⟩ }
end
@[simp] theorem bind_ret' (s : computation α) : bind s return = s :=
by rw bind_ret; change (λ x : α, x) with @id α; rw map_id
@[simp] theorem bind_assoc (s : computation α) (f : α → computation β) (g : β → computation γ) :
bind (bind s f) g = bind s (λ (x : α), bind (f x) g) :=
begin
apply eq_of_bisim (λc₁ c₂, c₁ = c₂ ∨
∃ s, c₁ = bind (bind s f) g ∧ c₂ = bind s (λ (x : α), bind (f x) g)),
{ intros c₁ c₂ h,
exact match c₁, c₂, h with
| _, _, or.inl (eq.refl c) := by cases destruct c with b cb; simp
| ._, ._, or.inr ⟨s, rfl, rfl⟩ := begin
apply cases_on s; intros s; simp,
{ generalize : f s = fs,
apply cases_on fs; intros t; simp,
{ cases destruct (g t) with b cb; simp } },
{ exact or.inr ⟨s, rfl, rfl⟩ }
end end },
{ exact or.inr ⟨s, rfl, rfl⟩ }
end
theorem results_bind {s : computation α} {f : α → computation β} {a b m n}
(h1 : results s a m) (h2 : results (f a) b n) : results (bind s f) b (n + m) :=
begin
have := h1.mem, revert m,
apply mem_rec_on this _ (λ s IH, _); intros m h1,
{ rw [ret_bind], rw h1.len_unique (results_ret _), exact h2 },
{ rw [think_bind], cases of_results_think h1 with m' h, cases h with h1 e,
rw e, exact results_think (IH h1) }
end
theorem mem_bind {s : computation α} {f : α → computation β} {a b}
(h1 : a ∈ s) (h2 : b ∈ f a) : b ∈ bind s f :=
let ⟨m, h1⟩ := exists_results_of_mem h1,
⟨n, h2⟩ := exists_results_of_mem h2 in (results_bind h1 h2).mem
instance terminates_bind (s : computation α) (f : α → computation β)
[terminates s] [terminates (f (get s))] :
terminates (bind s f) :=
terminates_of_mem (mem_bind (get_mem s) (get_mem (f (get s))))
@[simp] theorem get_bind (s : computation α) (f : α → computation β)
[terminates s] [terminates (f (get s))] :
get (bind s f) = get (f (get s)) :=
get_eq_of_mem _ (mem_bind (get_mem s) (get_mem (f (get s))))
@[simp] theorem length_bind (s : computation α) (f : α → computation β)
[T1 : terminates s] [T2 : terminates (f (get s))] :
length (bind s f) = length (f (get s)) + length s :=
(results_of_terminates _).len_unique $
results_bind (results_of_terminates _) (results_of_terminates _)
theorem of_results_bind {s : computation α} {f : α → computation β} {b k} :
results (bind s f) b k →
∃ a m n, results s a m ∧ results (f a) b n ∧ k = n + m :=
begin
induction k with n IH generalizing s;
apply cases_on s (λ a, _) (λ s', _); intro e,
{ simp [thinkN] at e, refine ⟨a, _, _, results_ret _, e, rfl⟩ },
{ have := congr_arg head (eq_thinkN e), contradiction },
{ simp at e, refine ⟨a, _, n+1, results_ret _, e, rfl⟩ },
{ simp at e, exact let ⟨a, m, n', h1, h2, e'⟩ := IH e in
by rw e'; exact ⟨a, m.succ, n', results_think h1, h2, rfl⟩ }
end
theorem exists_of_mem_bind {s : computation α} {f : α → computation β} {b}
(h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a :=
let ⟨k, h⟩ := exists_results_of_mem h,
⟨a, m, n, h1, h2, e⟩ := of_results_bind h in ⟨a, h1.mem, h2.mem⟩
theorem bind_promises {s : computation α} {f : α → computation β} {a b}
(h1 : s ~> a) (h2 : f a ~> b) : bind s f ~> b :=
λ b' bB, begin
rcases exists_of_mem_bind bB with ⟨a', a's, ba'⟩,
rw ←h1 a's at ba', exact h2 ba'
end
instance : monad computation :=
{ map := @map,
pure := @return,
bind := @bind }
instance : is_lawful_monad computation :=
{ id_map := @map_id,
bind_pure_comp_eq_map := @bind_ret,
pure_bind := @ret_bind,
bind_assoc := @bind_assoc }
theorem has_map_eq_map {β} (f : α → β) (c : computation α) : f <$> c = map f c := rfl
@[simp] theorem return_def (a) : (_root_.return a : computation α) = return a := rfl
@[simp] theorem map_ret' {α β} : ∀ (f : α → β) (a), f <$> return a = return (f a) := map_ret
@[simp] theorem map_think' {α β} : ∀ (f : α → β) s, f <$> think s = think (f <$> s) := map_think
theorem mem_map (f : α → β) {a} {s : computation α} (m : a ∈ s) : f a ∈ map f s :=
by rw ←bind_ret; apply mem_bind m; apply ret_mem
theorem exists_of_mem_map {f : α → β} {b : β} {s : computation α} (h : b ∈ map f s) :
∃ a, a ∈ s ∧ f a = b :=
by rw ←bind_ret at h; exact
let ⟨a, as, fb⟩ := exists_of_mem_bind h in ⟨a, as, mem_unique (ret_mem _) fb⟩
instance terminates_map (f : α → β) (s : computation α) [terminates s] : terminates (map f s) :=
by rw ←bind_ret; apply_instance
theorem terminates_map_iff (f : α → β) (s : computation α) :
terminates (map f s) ↔ terminates s :=
⟨λ⟨a, h⟩, let ⟨b, h1, _⟩ := exists_of_mem_map h in ⟨_, h1⟩, @computation.terminates_map _ _ _ _⟩
-- Parallel computation
/-- `c₁ <|> c₂` calculates `c₁` and `c₂` simultaneously, returning
the first one that gives a result. -/
def orelse (c₁ c₂ : computation α) : computation α :=
@computation.corec α (computation α × computation α)
(λ⟨c₁, c₂⟩, match destruct c₁ with
| sum.inl a := sum.inl a
| sum.inr c₁' := match destruct c₂ with
| sum.inl a := sum.inl a
| sum.inr c₂' := sum.inr (c₁', c₂')
end
end) (c₁, c₂)
instance : alternative computation :=
{ orelse := @orelse, failure := @empty, ..computation.monad }
@[simp] theorem ret_orelse (a : α) (c₂ : computation α) :
(return a <|> c₂) = return a :=
destruct_eq_ret $ by unfold has_orelse.orelse; simp [orelse]
@[simp] theorem orelse_ret (c₁ : computation α) (a : α) :
(think c₁ <|> return a) = return a :=
destruct_eq_ret $ by unfold has_orelse.orelse; simp [orelse]
@[simp] theorem orelse_think (c₁ c₂ : computation α) :
(think c₁ <|> think c₂) = think (c₁ <|> c₂) :=
destruct_eq_think $ by unfold has_orelse.orelse; simp [orelse]
@[simp] theorem empty_orelse (c) : (empty α <|> c) = c :=
begin
apply eq_of_bisim (λc₁ c₂, (empty α <|> c₂) = c₁) _ rfl,
intros s' s h, rw ←h,
apply cases_on s; intros s; rw think_empty; simp,
rw ←think_empty,
end
@[simp] theorem orelse_empty (c : computation α) : (c <|> empty α) = c :=
begin
apply eq_of_bisim (λc₁ c₂, (c₂ <|> empty α) = c₁) _ rfl,
intros s' s h, rw ←h,
apply cases_on s; intros s; rw think_empty; simp,
rw←think_empty,
end
/-- `c₁ ~ c₂` asserts that `c₁` and `c₂` either both terminate with the same result,
or both loop forever. -/
def equiv (c₁ c₂ : computation α) : Prop := ∀ a, a ∈ c₁ ↔ a ∈ c₂
infix ~ := equiv
@[refl] theorem equiv.refl (s : computation α) : s ~ s := λ_, iff.rfl
@[symm] theorem equiv.symm {s t : computation α} : s ~ t → t ~ s :=
λh a, (h a).symm
@[trans] theorem equiv.trans {s t u : computation α} : s ~ t → t ~ u → s ~ u :=
λh1 h2 a, (h1 a).trans (h2 a)
theorem equiv.equivalence : equivalence (@equiv α) :=
⟨@equiv.refl _, @equiv.symm _, @equiv.trans _⟩
theorem equiv_of_mem {s t : computation α} {a} (h1 : a ∈ s) (h2 : a ∈ t) : s ~ t :=
λa', ⟨λma, by rw mem_unique ma h1; exact h2,
λma, by rw mem_unique ma h2; exact h1⟩
theorem terminates_congr {c₁ c₂ : computation α}
(h : c₁ ~ c₂) : terminates c₁ ↔ terminates c₂ :=
exists_congr h
theorem promises_congr {c₁ c₂ : computation α}
(h : c₁ ~ c₂) (a) : c₁ ~> a ↔ c₂ ~> a :=
forall_congr (λa', imp_congr (h a') iff.rfl)
theorem get_equiv {c₁ c₂ : computation α} (h : c₁ ~ c₂)
[terminates c₁] [terminates c₂] : get c₁ = get c₂ :=
get_eq_of_mem _ $ (h _).2 $ get_mem _
theorem think_equiv (s : computation α) : think s ~ s :=
λ a, ⟨of_think_mem, think_mem⟩
theorem thinkN_equiv (s : computation α) (n) : thinkN s n ~ s :=
λ a, thinkN_mem n
theorem bind_congr {s1 s2 : computation α} {f1 f2 : α → computation β}
(h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 :=
λ b, ⟨λh, let ⟨a, ha, hb⟩ := exists_of_mem_bind h in
mem_bind ((h1 a).1 ha) ((h2 a b).1 hb),
λh, let ⟨a, ha, hb⟩ := exists_of_mem_bind h in
mem_bind ((h1 a).2 ha) ((h2 a b).2 hb)⟩
theorem equiv_ret_of_mem {s : computation α} {a} (h : a ∈ s) : s ~ return a :=
equiv_of_mem h (ret_mem _)
/-- `lift_rel R ca cb` is a generalization of `equiv` to relations other than
equality. It asserts that if `ca` terminates with `a`, then `cb` terminates with
some `b` such that `R a b`, and if `cb` terminates with `b` then `ca` terminates
with some `a` such that `R a b`. -/
def lift_rel (R : α → β → Prop) (ca : computation α) (cb : computation β) : Prop :=
(∀ {a}, a ∈ ca → ∃ {b}, b ∈ cb ∧ R a b) ∧
∀ {b}, b ∈ cb → ∃ {a}, a ∈ ca ∧ R a b
theorem lift_rel.swap (R : α → β → Prop) (ca : computation α) (cb : computation β) :
lift_rel (function.swap R) cb ca ↔ lift_rel R ca cb :=
and_comm _ _
theorem lift_eq_iff_equiv (c₁ c₂ : computation α) : lift_rel (=) c₁ c₂ ↔ c₁ ~ c₂ :=
⟨λ⟨h1, h2⟩ a,
⟨λ a1, let ⟨b, b2, ab⟩ := h1 a1 in by rwa ab,
λ a2, let ⟨b, b1, ab⟩ := h2 a2 in by rwa ←ab⟩,
λe, ⟨λ a a1, ⟨a, (e _).1 a1, rfl⟩, λ a a2, ⟨a, (e _).2 a2, rfl⟩⟩⟩
theorem lift_rel.refl (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) :=
λ s, ⟨λ a as, ⟨a, as, H a⟩, λ b bs, ⟨b, bs, H b⟩⟩
theorem lift_rel.symm (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) :=
λ s1 s2 ⟨l, r⟩,
⟨λ a a2, let ⟨b, b1, ab⟩ := r a2 in ⟨b, b1, H ab⟩,
λ a a1, let ⟨b, b2, ab⟩ := l a1 in ⟨b, b2, H ab⟩⟩
theorem lift_rel.trans (R : α → α → Prop) (H : transitive R) : transitive (lift_rel R) :=
λ s1 s2 s3 ⟨l1, r1⟩ ⟨l2, r2⟩,
⟨λ a a1, let ⟨b, b2, ab⟩ := l1 a1, ⟨c, c3, bc⟩ := l2 b2 in ⟨c, c3, H ab bc⟩,
λ c c3, let ⟨b, b2, bc⟩ := r2 c3, ⟨a, a1, ab⟩ := r1 b2 in ⟨a, a1, H ab bc⟩⟩
theorem lift_rel.equiv (R : α → α → Prop) : equivalence R → equivalence (lift_rel R)
| ⟨refl, symm, trans⟩ :=
⟨lift_rel.refl R refl, lift_rel.symm R symm, lift_rel.trans R trans⟩
theorem lift_rel.imp {R S : α → β → Prop} (H : ∀ {a b}, R a b → S a b) (s t) :
lift_rel R s t → lift_rel S s t | ⟨l, r⟩ :=
⟨λ a as, let ⟨b, bt, ab⟩ := l as in ⟨b, bt, H ab⟩,
λ b bt, let ⟨a, as, ab⟩ := r bt in ⟨a, as, H ab⟩⟩
theorem terminates_of_lift_rel {R : α → β → Prop} {s t} :
lift_rel R s t → (terminates s ↔ terminates t) | ⟨l, r⟩ :=
⟨λ ⟨a, as⟩, let ⟨b, bt, ab⟩ := l as in ⟨b, bt⟩,
λ ⟨b, bt⟩, let ⟨a, as, ab⟩ := r bt in ⟨a, as⟩⟩
theorem rel_of_lift_rel {R : α → β → Prop} {ca cb} :
lift_rel R ca cb → ∀ {a b}, a ∈ ca → b ∈ cb → R a b
| ⟨l, r⟩ a b ma mb :=
let ⟨b', mb', ab'⟩ := l ma in by rw mem_unique mb mb'; exact ab'
theorem lift_rel_of_mem {R : α → β → Prop} {a b ca cb}
(ma : a ∈ ca) (mb : b ∈ cb) (ab : R a b) : lift_rel R ca cb :=
⟨λ a' ma', by rw mem_unique ma' ma; exact ⟨b, mb, ab⟩,
λ b' mb', by rw mem_unique mb' mb; exact ⟨a, ma, ab⟩⟩
theorem exists_of_lift_rel_left {R : α → β → Prop} {ca cb}
(H : lift_rel R ca cb) {a} (h : a ∈ ca) : ∃ {b}, b ∈ cb ∧ R a b :=
H.left h
theorem exists_of_lift_rel_right {R : α → β → Prop} {ca cb}
(H : lift_rel R ca cb) {b} (h : b ∈ cb) : ∃ {a}, a ∈ ca ∧ R a b :=
H.right h
theorem lift_rel_def {R : α → β → Prop} {ca cb} : lift_rel R ca cb ↔
(terminates ca ↔ terminates cb) ∧ ∀ {a b}, a ∈ ca → b ∈ cb → R a b :=
⟨λh, ⟨terminates_of_lift_rel h, λ a b ma mb,
let ⟨b', mb', ab⟩ := h.left ma in by rwa mem_unique mb mb'⟩,
λ⟨l, r⟩,
⟨λ a ma, let ⟨b, mb⟩ := l.1 ⟨_, ma⟩ in ⟨b, mb, r ma mb⟩,
λ b mb, let ⟨a, ma⟩ := l.2 ⟨_, mb⟩ in ⟨a, ma, r ma mb⟩⟩⟩
theorem lift_rel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop)
{s1 : computation α} {s2 : computation β}
{f1 : α → computation γ} {f2 : β → computation δ}
(h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → lift_rel S (f1 a) (f2 b))
: lift_rel S (bind s1 f1) (bind s2 f2) :=
let ⟨l1, r1⟩ := h1 in
⟨λ c cB,
let ⟨a, a1, c₁⟩ := exists_of_mem_bind cB,
⟨b, b2, ab⟩ := l1 a1,
⟨l2, r2⟩ := h2 ab,
⟨d, d2, cd⟩ := l2 c₁ in
⟨_, mem_bind b2 d2, cd⟩,
λ d dB,
let ⟨b, b1, d1⟩ := exists_of_mem_bind dB,
⟨a, a2, ab⟩ := r1 b1,
⟨l2, r2⟩ := h2 ab,
⟨c, c₂, cd⟩ := r2 d1 in
⟨_, mem_bind a2 c₂, cd⟩⟩
@[simp] theorem lift_rel_return_left (R : α → β → Prop) (a : α) (cb : computation β) :
lift_rel R (return a) cb ↔ ∃ {b}, b ∈ cb ∧ R a b :=
⟨λ⟨l, r⟩, l (ret_mem _),
λ⟨b, mb, ab⟩,
⟨λ a' ma', by rw eq_of_ret_mem ma'; exact ⟨b, mb, ab⟩,
λ b' mb', ⟨_, ret_mem _, by rw mem_unique mb' mb; exact ab⟩⟩⟩
@[simp] theorem lift_rel_return_right (R : α → β → Prop) (ca : computation α) (b : β) :
lift_rel R ca (return b) ↔ ∃ {a}, a ∈ ca ∧ R a b :=
by rw [lift_rel.swap, lift_rel_return_left]
@[simp] theorem lift_rel_return (R : α → β → Prop) (a : α) (b : β) :
lift_rel R (return a) (return b) ↔ R a b :=
by rw [lift_rel_return_left]; exact
⟨λ⟨b', mb', ab'⟩, by rwa eq_of_ret_mem mb' at ab',
λab, ⟨_, ret_mem _, ab⟩⟩
@[simp] theorem lift_rel_think_left (R : α → β → Prop) (ca : computation α) (cb : computation β) :
lift_rel R (think ca) cb ↔ lift_rel R ca cb :=
and_congr (forall_congr $ λb, imp_congr ⟨of_think_mem, think_mem⟩ iff.rfl)
(forall_congr $ λb, imp_congr iff.rfl $
exists_congr $ λ b, and_congr ⟨of_think_mem, think_mem⟩ iff.rfl)
@[simp] theorem lift_rel_think_right (R : α → β → Prop) (ca : computation α) (cb : computation β) :
lift_rel R ca (think cb) ↔ lift_rel R ca cb :=
by rw [←lift_rel.swap R, ←lift_rel.swap R]; apply lift_rel_think_left
theorem lift_rel_mem_cases {R : α → β → Prop} {ca cb}
(Ha : ∀ a ∈ ca, lift_rel R ca cb)
(Hb : ∀ b ∈ cb, lift_rel R ca cb) : lift_rel R ca cb :=
⟨λ a ma, (Ha _ ma).left ma, λ b mb, (Hb _ mb).right mb⟩
theorem lift_rel_congr {R : α → β → Prop} {ca ca' : computation α} {cb cb' : computation β}
(ha : ca ~ ca') (hb : cb ~ cb') : lift_rel R ca cb ↔ lift_rel R ca' cb' :=
and_congr
(forall_congr $ λ a, imp_congr (ha _) $ exists_congr $ λ b, and_congr (hb _) iff.rfl)
(forall_congr $ λ b, imp_congr (hb _) $ exists_congr $ λ a, and_congr (ha _) iff.rfl)
theorem lift_rel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop)
{s1 : computation α} {s2 : computation β}
{f1 : α → γ} {f2 : β → δ}
(h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b))
: lift_rel S (map f1 s1) (map f2 s2) :=
by rw [←bind_ret, ←bind_ret]; apply lift_rel_bind _ _ h1; simp; exact @h2
theorem map_congr (R : α → α → Prop) (S : β → β → Prop)
{s1 s2 : computation α} {f : α → β}
(h1 : s1 ~ s2) : map f s1 ~ map f s2 :=
by rw [←lift_eq_iff_equiv];
exact lift_rel_map eq _ ((lift_eq_iff_equiv _ _).2 h1) (λ a b, congr_arg _)
def lift_rel_aux (R : α → β → Prop)
(C : computation α → computation β → Prop) :
α ⊕ computation α → β ⊕ computation β → Prop
| (sum.inl a) (sum.inl b) := R a b
| (sum.inl a) (sum.inr cb) := ∃ {b}, b ∈ cb ∧ R a b
| (sum.inr ca) (sum.inl b) := ∃ {a}, a ∈ ca ∧ R a b
| (sum.inr ca) (sum.inr cb) := C ca cb
attribute [simp] lift_rel_aux
@[simp] lemma lift_rel_aux.ret_left (R : α → β → Prop)
(C : computation α → computation β → Prop) (a cb) :
lift_rel_aux R C (sum.inl a) (destruct cb) ↔ ∃ {b}, b ∈ cb ∧ R a b :=
begin
apply cb.cases_on (λ b, _) (λ cb, _),
{ exact ⟨λ h, ⟨_, ret_mem _, h⟩, λ ⟨b', mb, h⟩,
by rw [mem_unique (ret_mem _) mb]; exact h⟩ },
{ rw [destruct_think],
exact ⟨λ ⟨b, h, r⟩, ⟨b, think_mem h, r⟩,
λ ⟨b, h, r⟩, ⟨b, of_think_mem h, r⟩⟩ }
end
theorem lift_rel_aux.swap (R : α → β → Prop) (C) (a b) :
lift_rel_aux (function.swap R) (function.swap C) b a = lift_rel_aux R C a b :=
by cases a with a ca; cases b with b cb; simp only [lift_rel_aux]
@[simp] lemma lift_rel_aux.ret_right (R : α → β → Prop)
(C : computation α → computation β → Prop) (b ca) :
lift_rel_aux R C (destruct ca) (sum.inl b) ↔ ∃ {a}, a ∈ ca ∧ R a b :=
by rw [←lift_rel_aux.swap, lift_rel_aux.ret_left]
theorem lift_rel_rec.lem {R : α → β → Prop} (C : computation α → computation β → Prop)
(H : ∀ {ca cb}, C ca cb → lift_rel_aux R C (destruct ca) (destruct cb))
(ca cb) (Hc : C ca cb) (a) (ha : a ∈ ca) : lift_rel R ca cb :=
begin
revert cb, refine mem_rec_on ha _ (λ ca' IH, _);
intros cb Hc; have h := H Hc,
{ simp at h, simp [h] },
{ have h := H Hc, simp, revert h, apply cb.cases_on (λ b, _) (λ cb', _);
intro h; simp at h; simp [h], exact IH _ h }
end
theorem lift_rel_rec {R : α → β → Prop} (C : computation α → computation β → Prop)
(H : ∀ {ca cb}, C ca cb → lift_rel_aux R C (destruct ca) (destruct cb))
(ca cb) (Hc : C ca cb) : lift_rel R ca cb :=
lift_rel_mem_cases (lift_rel_rec.lem C @H ca cb Hc) (λ b hb,
(lift_rel.swap _ _ _).2 $
lift_rel_rec.lem (function.swap C)
(λ cb ca h, cast (lift_rel_aux.swap _ _ _ _).symm $ H h)
cb ca Hc b hb)
end computation
|
0cdd094eec7e7e4d74266a5c6c4cfc53f08f7edd | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/chain.lean | b457fb43efaea7055c150ab75f09e7c8bf17a9c4 | [] | 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 | 894 | 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
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.ext
import Mathlib.PostPort
universes l
namespace Mathlib
namespace tactic
/-
This file defines a `chain` tactic, which takes a list of tactics, and exhaustively tries to apply them
to the goals, until no tactic succeeds on any goal.
Along the way, it generates auxiliary declarations, in order to speed up elaboration time
of the resulting (sometimes long!) proofs.
This tactic is used by the `tidy` tactic.
-/
-- α is the return type of our tactics. When `chain` is called by `tidy`, this is string,
-- describing what that tactic did as an interactive tactic.
def tactic_script (α : Type) :=
_nest_1_1.tactic.tactic_script
|
ead40ec679f50ddda479d40482c312931a7e1215 | ff5230333a701471f46c57e8c115a073ebaaa448 | /tests/lean/run/monad_error_problem.lean | 7221c1c25a22cc52faac57f7202d2da97aa5fd52 | [
"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 | 635 | lean | namespace issue
universes u v w
class monad_error (ε : out_param $ Type u) (m : Type w → Type v) :=
[monad_m : monad m]
(fail : Π {α : Type w}, ε → m α)
set_option pp.all true
def unreachable {α} {m} [monad_error string m] : m α :=
monad_error.fail m "unreachable"
#check @unreachable
end issue
namespace original_issue
universes u v
class monad_error (ε : out_param $ Type u) (m : Type u → Type v) :=
[monad_m : monad m]
(fail : Π {α : Type u}, ε → m α)
set_option pp.all true
def unreachable {α} {m} [monad_error string m] : m α :=
monad_error.fail m "unreachable"
#check @unreachable
end original_issue
|
dc3c91d8e03618f53fac01d2e14f1c782097e5d7 | 737dc4b96c97368cb66b925eeea3ab633ec3d702 | /stage0/src/Init/SimpLemmas.lean | b5ce6742cf4c3392d8ee0f1220f444385461b6bf | [
"Apache-2.0"
] | permissive | Bioye97/lean4 | 1ace34638efd9913dc5991443777b01a08983289 | bc3900cbb9adda83eed7e6affeaade7cfd07716d | refs/heads/master | 1,690,589,820,211 | 1,631,051,000,000 | 1,631,067,598,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,473 | 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
notation, basic datatypes and type classes
-/
prelude
import Init.Core
@[simp] theorem eq_self (a : α) : (a = a) = True :=
propext <| Iff.intro (fun _ => trivial) (fun _ => rfl)
theorem of_eq_true (h : p = True) : p :=
h ▸ trivial
theorem eq_true (h : p) : p = True :=
propext <| Iff.intro (fun _ => trivial) (fun _ => h)
theorem eq_false (h : ¬ p) : p = False :=
propext <| Iff.intro (fun h' => absurd h' h) (fun h' => False.elim h')
theorem eq_false' (h : p → False) : p = False :=
propext <| Iff.intro (fun h' => absurd h' h) (fun h' => False.elim h')
theorem eq_true_of_decide {p : Prop} {s : Decidable p} (h : decide p = true) : p = True :=
propext <| Iff.intro (fun h => trivial) (fun _ => of_decide_eq_true h)
theorem eq_false_of_decide {p : Prop} {s : Decidable p} (h : decide p = false) : p = False :=
propext <| Iff.intro (fun h' => absurd h' (of_decide_eq_false h)) (fun h => False.elim h)
theorem implies_congr {p₁ p₂ : Sort u} {q₁ q₂ : Sort v} (h₁ : p₁ = p₂) (h₂ : q₁ = q₂) : (p₁ → q₁) = (p₂ → q₂) :=
h₁ ▸ h₂ ▸ rfl
theorem implies_congr_ctx {p₁ p₂ q₁ q₂ : Prop} (h₁ : p₁ = p₂) (h₂ : p₂ → q₁ = q₂) : (p₁ → q₁) = (p₂ → q₂) :=
propext <| Iff.intro
(fun h hp₂ =>
have : p₁ := h₁ ▸ hp₂
have : q₁ := h this
h₂ hp₂ ▸ this)
(fun h hp₁ =>
have hp₂ : p₂ := h₁ ▸ hp₁
have : q₂ := h hp₂
h₂ hp₂ ▸ this)
theorem forall_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a = q a)) : (∀ a, p a) = (∀ a, q a) :=
have : p = q := funext h
this ▸ rfl
@[congr]
theorem ite_congr {x y u v : α} {s : Decidable b} [Decidable c] (h₁ : b = c) (h₂ : c → x = u) (h₃ : ¬ c → y = v) : ite b x y = ite c u v := by
cases Decidable.em c with
| inl h => rw [if_pos h]; subst b; rw[if_pos h]; exact h₂ h
| inr h => rw [if_neg h]; subst b; rw[if_neg h]; exact h₃ h
theorem Eq.mpr_prop {p q : Prop} (h₁ : p = q) (h₂ : q) : p :=
h₁ ▸ h₂
theorem Eq.mpr_not {p q : Prop} (h₁ : p = q) (h₂ : ¬q) : ¬p :=
h₁ ▸ h₂
@[congr]
theorem dite_congr {s : Decidable b} [Decidable c]
{x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α}
(h₁ : b = c)
(h₂ : (h : c) → x (Eq.mpr_prop h₁ h) = u h)
(h₃ : (h : ¬c) → y (Eq.mpr_not h₁ h) = v h)
: dite b x y = dite c u v := by
cases Decidable.em c with
| inl h => rw [dif_pos h]; subst b; rw [dif_pos h]; exact h₂ h
| inr h => rw [dif_neg h]; subst b; rw [dif_neg h]; exact h₃ h
@[simp] theorem ne_eq (a b : α) : (a ≠ b) = Not (a = b) := rfl
@[simp] theorem ite_true (a b : α) : (if True then a else b) = a := rfl
@[simp] theorem ite_false (a b : α) : (if False then a else b) = b := rfl
@[simp] theorem dite_true {α : Sort u} {t : True → α} {e : ¬ True → α} : (dite True t e) = t True.intro := rfl
@[simp] theorem dite_false {α : Sort u} {t : False → α} {e : ¬ False → α} : (dite False t e) = e not_false := rfl
@[simp] theorem and_self (p : Prop) : (p ∧ p) = p := propext <| Iff.intro (fun h => h.1) (fun h => ⟨h, h⟩)
@[simp] theorem and_true (p : Prop) : (p ∧ True) = p := propext <| Iff.intro (fun h => h.1) (fun h => ⟨h, trivial⟩)
@[simp] theorem true_and (p : Prop) : (True ∧ p) = p := propext <| Iff.intro (fun h => h.2) (fun h => ⟨trivial, h⟩)
@[simp] theorem and_false (p : Prop) : (p ∧ False) = False := propext <| Iff.intro (fun h => h.2) (fun h => False.elim h)
@[simp] theorem false_and (p : Prop) : (False ∧ p) = False := propext <| Iff.intro (fun h => h.1) (fun h => False.elim h)
@[simp] theorem or_self (p : Prop) : (p ∨ p) = p := propext <| Iff.intro (fun | Or.inl h => h | Or.inr h => h) (fun h => Or.inl h)
@[simp] theorem or_true (p : Prop) : (p ∨ True) = True := propext <| Iff.intro (fun h => trivial) (fun h => Or.inr trivial)
@[simp] theorem true_or (p : Prop) : (True ∨ p) = True := propext <| Iff.intro (fun h => trivial) (fun h => Or.inl trivial)
@[simp] theorem or_false (p : Prop) : (p ∨ False) = p := propext <| Iff.intro (fun | Or.inl h => h | Or.inr h => False.elim h) (fun h => Or.inl h)
@[simp] theorem false_or (p : Prop) : (False ∨ p) = p := propext <| Iff.intro (fun | Or.inr h => h | Or.inl h => False.elim h) (fun h => Or.inr h)
@[simp] theorem iff_self (p : Prop) : (p ↔ p) = True := propext <| Iff.intro (fun h => trivial) (fun _ => Iff.intro id id)
@[simp] theorem iff_true (p : Prop) : (p ↔ True) = p := propext <| Iff.intro (fun h => h.mpr trivial) (fun h => Iff.intro (fun _ => trivial) (fun _ => h))
@[simp] theorem true_iff (p : Prop) : (True ↔ p) = p := propext <| Iff.intro (fun h => h.mp trivial) (fun h => Iff.intro (fun _ => h) (fun _ => trivial))
@[simp] theorem iff_false (p : Prop) : (p ↔ False) = ¬p := propext <| Iff.intro (fun h hp => h.mp hp) (fun h => Iff.intro h False.elim)
@[simp] theorem false_iff (p : Prop) : (False ↔ p) = ¬p := propext <| Iff.intro (fun h hp => h.mpr hp) (fun h => Iff.intro False.elim h)
@[simp] theorem false_implies (p : Prop) : (False → p) = True := propext <| Iff.intro (fun _ => trivial) (by intros; trivial)
@[simp] theorem implies_true (p : Prop) : (p → True) = True := propext <| Iff.intro (fun _ => trivial) (by intros; trivial)
@[simp] theorem true_implies (p : Prop) : (True → p) = p := propext <| Iff.intro (fun h => h trivial) (by intros; trivial)
@[simp] theorem Bool.or_false (b : Bool) : (b || false) = b := by cases b <;> rfl
@[simp] theorem Bool.or_true (b : Bool) : (b || true) = true := by cases b <;> rfl
@[simp] theorem Bool.false_or (b : Bool) : (false || b) = b := by cases b <;> rfl
@[simp] theorem Bool.true_or (b : Bool) : (true || b) = true := by cases b <;> rfl
@[simp] theorem Bool.or_self (b : Bool) : (b || b) = b := by cases b <;> rfl
@[simp] theorem Bool.and_false (b : Bool) : (b && false) = false := by cases b <;> rfl
@[simp] theorem Bool.and_true (b : Bool) : (b && true) = b := by cases b <;> rfl
@[simp] theorem Bool.false_and (b : Bool) : (false && b) = false := by cases b <;> rfl
@[simp] theorem Bool.true_and (b : Bool) : (true && b) = b := by cases b <;> rfl
@[simp] theorem Bool.and_self (b : Bool) : (b && b) = b := by cases b <;> rfl
|
2d6ec64f9552af4b74042c37a4dc5a9f285e08f5 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tmp/eqns/prototype.lean | 292df1046714ca6880677f128f0afbe0c6a66a80 | [
"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 | 6,011 | lean | prelude
import Init.Lean.Meta.Tactic.Cases
namespace Lean
namespace Meta
namespace DepElim
inductive Pattern
| inaccessible (ref : Syntax) (e : Expr)
| var (ref : Syntax) (fvarId : FVarId)
| ctor (ref : Syntax) (ctorName : Name) (fields : List Pattern)
| val (ref : Syntax) (e : Expr)
| arrayLit (ref : Syntax) (xs : List Pattern)
namespace Pattern
instance : Inhabited Pattern := ⟨Pattern.arrayLit Syntax.missing []⟩
partial def toMessageData : Pattern → MessageData
| inaccessible _ e => ".(" ++ e ++ ")"
| var _ fvarId => mkFVar fvarId
| ctor _ ctorName [] => ctorName
| ctor _ ctorName pats => "(" ++ ctorName ++ pats.foldl (fun (msg : MessageData) pat => msg ++ " " ++ toMessageData pat) Format.nil ++ ")"
| val _ e => "val!(" ++ e ++ ")"
| arrayLit _ pats => "#[" ++ MessageData.joinSep (pats.map toMessageData) ", " ++ "]"
end Pattern
structure AltLHS :=
(fvarDecls : List LocalDecl) -- Free variables used in the patterns.
(patterns : List Pattern) -- We use `List Pattern` since we have nary match-expressions.
namespace AltLHS
instance : Inhabited AltLHS := ⟨⟨[], []⟩⟩
partial def toMessageData (alt : AltLHS) : MetaM MessageData := do
lctx ← getLCtx;
localInsts ← getLocalInstances;
let lctx := alt.fvarDecls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) lctx;
withLocalContext lctx localInsts $ do
let msg : MessageData := "⟦" ++ MessageData.joinSep (alt.patterns.map Pattern.toMessageData) ", " ++ "⟧";
addContext msg
end AltLHS
structure MinorsRange :=
(firstMinorPos : Nat)
(numMinors : Nat)
abbrev AltToMinorsMap := PersistentHashMap Nat MinorsRange
structure ElimResult :=
(numMinors : Nat) -- It is the number of alternatives (Reason: support for overlapping equations)
(numEqs : Nat) -- It is the number of minors (Reason: users may want equations that hold definitionally)
(elim : Expr) -- The eliminator. It is not just `Expr.const elimName` because the type of the major premises may contain free variables.
(altMap : AltToMinorsMap) -- each alternative may be "expanded" into multiple minor premise
private def checkNumPatterns (majors : List Expr) (lhss : List AltLHS) : MetaM Unit :=
let num := majors.length;
when (lhss.any (fun lhs => lhs.patterns.length != num)) $
throw $ Exception.other "incorrect number of patterns"
def mkElim (elimName : Name) (majors : List Expr) (lhss : List AltLHS) : MetaM ElimResult := do
checkNumPatterns majors lhss;
pure { numMinors := 0, numEqs := 0, elim := arbitrary _, altMap := {} } -- TODO
end DepElim
end Meta
end Lean
open Lean
open Lean.Meta
open Lean.Meta.DepElim
/- Infrastructure for testing -/
def printAltLHS (alts : List AltLHS) : MetaM Unit := do
msgs ← alts.mapM AltLHS.toMessageData;
trace! `Meta.debug (Format.line ++ (MessageData.joinSep msgs Format.line))
universes u v
def inaccessible {α : Sort u} (a : α) : α := a
def val {α : Sort u} (a : α) : α := a
/- Convert expression using auxiliary hints `inaccessible` and `val` into a pattern -/
partial def mkPattern : Expr → MetaM Pattern
| e =>
if e.isAppOfArity `val 2 then
pure $ Pattern.val Syntax.missing e.appArg!
else if e.isAppOfArity `inaccessible 2 then
pure $ Pattern.inaccessible Syntax.missing e.appArg!
else if e.isFVar then
pure $ Pattern.var Syntax.missing e.fvarId!
else match e.arrayLit? with
| some es => do
pats ← es.mapM mkPattern;
pure $ Pattern.arrayLit Syntax.missing pats
| none => do
cval? ← constructorApp? e;
match cval? with
| none => throw $ Exception.other "unexpected pattern"
| some cval => do
let args := e.getAppArgs;
let fields := args.extract cval.nparams args.size;
pats ← fields.toList.mapM mkPattern;
pure $ Pattern.ctor Syntax.missing cval.name pats
partial def decodePats : Expr → MetaM (List Pattern)
| e =>
match e.app2? `Pat with
| some (_, pat) => do pat ← mkPattern pat; pure [pat]
| none =>
match e.prod? with
| none => throw $ Exception.other "unexpected pattern"
| some (pat, pats) => do
pat ← decodePats pat;
pats ← decodePats pats;
pure (pat ++ pats)
partial def decodeAltLHS (e : Expr) : MetaM AltLHS :=
forallTelescopeReducing e $ fun args body => do
decls ← args.toList.mapM (fun arg => getLocalDecl arg.fvarId!);
pats ← decodePats body;
pure { fvarDecls := decls, patterns := pats }
partial def decodeAltLHSs : Expr → MetaM (List AltLHS)
| e =>
match e.app2? `LHS with
| some (_, lhs) => do lhs ← decodeAltLHS lhs; pure [lhs]
| none =>
match e.prod? with
| none => throw $ Exception.other "unexpected LHS"
| some (lhs, lhss) => do
lhs ← decodeAltLHSs lhs;
lhss ← decodeAltLHSs lhss;
pure (lhs ++ lhss)
def mkDepElimFrom (declName : Name) (numPats : Nat) : MetaM (List Expr × List AltLHS) := do
cinfo ← getConstInfo declName;
forallTelescopeReducing cinfo.type $ fun args body =>
if args.size < numPats then
throw $ Exception.other "insufficient number of parameters"
else do
let xs := (args.extract (args.size - numPats) args.size).toList;
alts ← decodeAltLHSs body;
pure (xs, alts)
inductive Pat {α : Sort u} (a : α) : Type u
| mk {} : Pat
inductive LHS {α : Sort u} (a : α) : Type u
| mk {} : LHS
instance LHS.inhabited {α} (a : α) : Inhabited (LHS a) := ⟨LHS.mk⟩
def ex1 (α : Type u) (β : Type v) (n : Nat) (x : List α) (y : List β) :
LHS (Pat ([] : List α) × Pat ([] : List α))
× LHS (forall (a : α) (b : α), Pat [a] × Pat [b])
× LHS (forall (a₁ a₂ : α) (as : List α) (b₁ b₂ : β) (bs : List β), Pat (a₁::a₂::as) × Pat (b₁::b₂::bs))
× LHS (forall (as : List α) (bs : List β), Pat as × Pat bs)
:= arbitrary _
set_option trace.Meta.debug true
def tst1 : MetaM Unit := do
(majors, alts) ← mkDepElimFrom `ex1 2;
printAltLHS alts;
mkElim `test majors alts;
pure ()
#eval tst1
|
cd73d25721900e948e5337971a9d36a5ac9c439e | be30445afb85fcb2041b437059d21f9a84dff894 | /graphmodel.hlean | 1122ec8f533da64e893793c582ba3fd27559a6ea | [
"Apache-2.0"
] | permissive | EgbertRijke/GraphModel | 784efde97299c4f3cb1760369e8a260e02caafd5 | 2a473880764093dd151554a913292ed465e80e62 | refs/heads/master | 1,609,477,731,119 | 1,476,299,056,000 | 1,476,299,056,000 | 58,213,801 | 6 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,930 | hlean | /-
Title: The graph model of type theory.
Author: Egbert Rijke
Copyright: Apache 2.0
Year: 2016
This document is part of the GraphModel project, see
https://github.com/EgbertRijke/GraphModel.git
for the licence.
-/
import types move_to_main
open sigma sigma.ops eq pi is_equiv
-- We fix a universe, because lean makes a mess when we allow it to assign
-- universes freely, and I don't know how to deal with that otherwise.
universe u
/-
We formalize basic aspects of the graph model of type theory. In particular, we
formalize
- The basic structure of type dependence. So we have graphs, families of graphs
and their terms. We have weakening and substitution and identity.
- We define Pi-types, Id-types and W-types in the graph model
On the naming convention.
- Everything in the graph model of type theory is in the namespace `graph`.
- Most structures will have a part about points, and a part about edges.
In their structures, they will be referred to by `pts` and `edg`. For example,
a graph is a context in the graph model, so its structure is called `graph.ctx`.
A graph consists of a type
`graph.ctx.pts`
and a type family
`graph.ctx.edg : graph.ctx.pts -> graph.ctx.pts -> Type`.
-/
namespace graph
----------------------------------------------------------------------------------------------------
--= CONTEXTS =--
namespace ctx
-- We define the ingredients of a context in the graph model
definition ty_pts : Type := Type.{u}
definition ty_edg : ty_pts → Type := λ V, V → V → Type.{u}
end ctx
-- introduction of contexts
structure ctx : Type :=
( pts : ctx.ty_pts )
( edg : ctx.ty_edg pts)
namespace ctx
-- equality of contexts
definition eq {Δ Γ : ctx} :
Π (p : ctx.pts Δ = ctx.pts Γ), (ctx.edg Δ) =[p] ctx.edg Γ → Δ = Γ :=
begin
induction Δ with Δ.pts Δ.edg,
induction Γ with Γ.pts Γ.edg,
esimp,
intro p q,
induction q,
reflexivity
end
end ctx
----------------------------------------------------------------------------------------------------
--= FAMILIES =--
namespace fam
variable (Γ : ctx)
include Γ
definition ty_pts : Type := ctx.pts Γ → Type.{u}
definition ty_edg : ty_pts Γ → Type :=
λ V, Π ⦃i j : ctx.pts Γ⦄, ctx.edg Γ i j → V i → V j → Type.{u}
end fam
-- introduction of families
structure fam (Γ : ctx) : Type :=
( pts : fam.ty_pts Γ)
( edg : fam.ty_edg Γ pts)
namespace fam
-- equality of families
definition eq {Γ : ctx} (A B : fam Γ) :
Π ( p : fam.pts A = fam.pts B), fam.edg A =[p] fam.edg B → A = B :=
begin
induction A with A.pts A.edg,
induction B with B.pts B.edg,
esimp,
intro p q,
induction q,
reflexivity
end
end fam
----------------------------------------------------------------------------------------------------
--= TERMS =--
namespace tm
-- We define the basic ingredients of terms in the graph model
variables {Γ : ctx} (A : fam Γ)
include A
definition ty_pts : Type :=
Π (i : ctx.pts Γ), fam.pts A i
definition ty_edg : ty_pts A → Type :=
λ pt, Π ⦃i j : ctx.pts Γ⦄ (e : ctx.edg Γ i j), fam.edg A e (pt i) (pt j)
end tm
-- introduction of terms
structure tm {Γ : ctx} (A : fam Γ) : Type :=
( pts : tm.ty_pts A)
( edg : tm.ty_edg A pts)
namespace tm
-- equality of terms
definition eq {Γ : ctx} {A : fam Γ} {t1 t2 : tm A} :
Π ( p : tm.pts t1 = tm.pts t2 ), (tm.edg t1) =[p] tm.edg t2 → t1 = t2 :=
begin
induction t1 with t1.pts t1.edg,
induction t2 with t2.pts t2.edg,
esimp,
intro p q,
induction q,
reflexivity
end
end tm
----------------------------------------------------------------------------------------------------
--= CONTEXT EXTENSION =--
namespace ext
-- We define the basic ingredients of context extension
variables (Γ : ctx) (A : fam Γ)
structure pts : Type :=
( in_ctx : ctx.pts Γ)
( in_fam : @fam.pts Γ A in_ctx)
structure edg (a b : pts Γ A) : Type :=
( in_ctx : ctx.edg Γ (pts.in_ctx a) (pts.in_ctx b))
( in_fam : fam.edg A in_ctx (pts.in_fam a) (pts.in_fam b))
end ext
-- introduction of context extension
definition ext (Γ : ctx) (A : fam Γ) : ctx :=
ctx.mk (ext.pts Γ A) (ext.edg Γ A)
----------------------------------------------------------------------------------------------------
--= WEAKENING =--
namespace wk
-- This namespace contains the ingredients of weakening.
variables {Γ : ctx} (A B : fam Γ)
definition pts : ctx.pts (ext Γ A) → Type :=
λ p, fam.pts B (ext.pts.in_ctx p)
definition edg : Π ⦃p q : ctx.pts (ext Γ A)⦄,
ctx.edg (ext Γ A) p q → pts A B p → pts A B q → Type :=
λ p q e, fam.edg B (ext.edg.in_ctx e)
end wk
definition wk {Γ : ctx} (A B : fam Γ) : fam (ext Γ A) :=
fam.mk (wk.pts A B) (wk.edg A B)
notation `⟨` A `⟩` B := wk A B
----------------------------------------------------------------------------------------------------
--= SUBSTITUTION =--
namespace subst
-- This namespace contains the ingredients for substitution
variables {Γ : ctx} {A : fam Γ}
definition pts (t : tm A) (P : fam (ext Γ A)) : ctx.pts Γ → Type.{u} :=
λ i, fam.pts P (ext.pts.mk _ (tm.pts t i))
definition edg (t : tm A) (P : fam (ext Γ A)) : Π ⦃i j : ctx.pts Γ⦄, ctx.edg Γ i j → pts t P i → pts t P j → Type :=
λ i j e, fam.edg P (ext.edg.mk _ (tm.edg t e))
end subst
definition subst {Γ : ctx} {A : fam Γ} (t : tm A) (P : fam (ext Γ A)) : fam Γ :=
fam.mk _ (subst.edg t P)
notation P `[` t `]` := subst t P
----------------------------------------------------------------------------------------------------
--= IDENTITY TERMS =--
definition idtm {Γ : ctx} (A : fam Γ) : tm (⟨A⟩ A) :=
begin
fapply tm.mk,
intro p,
exact ext.pts.in_fam p,
intro p q s,
induction p with i x,
induction q with j y,
exact ext.edg.in_fam s
end
----------------------------------------------------------------------------------------------------
--= DEPENDENT FUNCTION TYPES =--
/-
In the following we implement dependent function types in the graph model.
- We introduce `prd A P` for any family `P` over `ext Γ A`
- We define lambda-abstract and evaluation
- We show that lambda-abstraction and evaluation are mutual inverses, and hence that the types
tm P and tm (prd A P) are equivalent. The fact that
evl (abstr f) = f
for any f : tm P, is an implementation of the beta-conversion rule. The fact that
abstr (evl g) = g
for any g : prd A P is an implementation of the eta-conversion rule. Of course, these results
rely on function extensionality in the ambient type theory.
-/
namespace prd
-- This namespace contains the ingredients for dependent function graphs
variables {Γ : ctx} (A : fam Γ) (P : fam (ext Γ A))
include A P
definition pts : ctx.pts Γ → Type :=
λ i, Π (x : fam.pts A i), fam.pts P (ext.pts.mk i x)
definition edg : Π {i j : ctx.pts Γ}, ctx.edg Γ i j → pts A P i → pts A P j → Type.{u} :=
λ i j e f g, Π {x : fam.pts A i} {y : fam.pts A j} (s : fam.edg A e x y), fam.edg P (ext.edg.mk e s) (f x) (g y)
end prd
-- introduce dependent function types
definition prd {Γ : ctx} (A : fam Γ) (P : fam (ext Γ A)) : fam Γ :=
fam.mk _ (@prd.edg _ A P)
-- lambda-abstraction for dependent function types
definition abstr [unfold 4] {Γ : ctx} {A : fam Γ} {P : fam (ext Γ A)} : tm P → tm (prd A P) :=
begin
intro f,
fapply tm.mk,
intro i x,
exact tm.pts f (ext.pts.mk i x),
intro i j e x y s,
exact tm.edg f (ext.edg.mk e s)
end
-- evaluation
definition evl [unfold 4] {Γ : ctx} {A : fam Γ} {P : fam (ext Γ A)} : tm (prd A P) → tm P :=
begin
intro g,
fapply tm.mk,
intro p,
induction p with i x,
exact tm.pts g i x,
intro p q s,
induction p with i x,
induction q with j y,
induction s with e s,
exact tm.edg g e x y s
end
namespace beta
variables {Γ : ctx} {A : fam Γ} (P : fam (ext Γ A))
include P
definition pts [unfold 4] (f : tm P) : tm.pts (evl (abstr f)) = tm.pts f :=
begin
induction f with f.pts f.edg, esimp,
apply eq_of_homotopy,
intro p, induction p with i x,
reflexivity
end
definition edg (f : tm P) : tm.edg (evl (abstr f)) =[beta.pts P f] tm.edg f :=
begin
induction f with f.pts f.edg,
apply pi_pathover_constant,
intro p, induction p with i x,
apply pi_pathover_constant,
intro q, induction q with j y,
apply pi_pathover_constant,
intro t, induction t with e s,
esimp at e, esimp at s, esimp,
apply pathover_of_tr_eq,
apply tr_eq_of_homotopy
end
end beta
definition beta {Γ : ctx} {A : fam Γ} {P : fam (ext Γ A)} (f : tm P) : evl (abstr f) = f :=
tm.eq (beta.pts P f) (beta.edg P f)
namespace eta
variables {Γ : ctx} {A : fam Γ} (P : fam (ext Γ A))
include P
definition pts [unfold 4] (g : tm (prd A P)) : tm.pts (abstr (evl g)) = tm.pts g :=
eq_of_homotopy2 (λ i x, refl (tm.pts g i x))
local attribute homotopy2.rec_on [recursor]
definition tr_eq_of_homotopy2 (g : tm (prd A P)) (g0' : Π (i : ctx.pts Γ) (x : fam.pts A i), fam.pts P (ext.pts.mk i x))
(H : tm.pts g ~2 g0')
{i j : ctx.pts Γ} (e : ctx.edg Γ i j) {x : fam.pts A i} {y : fam.pts A j} (s : fam.edg A e x y) :
((eq_of_homotopy2 H) ▸ (tm.edg g)) i j e x y s = (H i x) ▸ ( (H j y) ▸ (tm.edg g e x y s)) :=
begin
induction H with q,
induction q,
krewrite eq_of_homotopy2_id
end
definition edg (g : tm (prd A P)) : tm.edg (abstr (evl g)) =[eta.pts P g] tm.edg g :=
begin
apply pathover_of_tr_eq,
apply eq_of_homotopy2,
intros i j,
apply eq_of_homotopy,
intro e,
apply eq_of_homotopy2,
intros x y,
apply eq_of_homotopy,
intro s,
esimp,
krewrite tr_eq_of_homotopy2,
end
end eta
definition eta {Γ : ctx} {A : fam Γ} {P : fam (ext Γ A)} (g : tm (prd A P)) : abstr (evl g) = g :=
tm.eq _ (eta.edg P g)
definition is_equiv_abstr {Γ : ctx} {A : fam Γ} (P : fam (ext Γ A)) : is_equiv (@abstr Γ A P) :=
begin
fapply adjointify,
exact evl,
exact eta,
exact beta,
end
----------------------------------------------------------------------------------------------------
--= GRAPH HOMOMORPHISMS =--
/-
Introduction of graph homomorphisms. A graph homomorphism from Δ to Γ is the same thing as
a term of the weakened graph ⟨Δ⟩Γ.
-/
structure hom (Δ Γ : ctx) : Type :=
( pts : ctx.pts Δ → ctx.pts Γ)
( edg : Π (i j : ctx.pts Δ), ctx.edg Δ i j → ctx.edg Γ (pts i) (pts j))
-- introduction of the slice over Γ
structure slice (Γ : ctx) : Type :=
( domain : graph.ctx)
( mor : graph.hom domain Γ)
namespace proj₁
-- We define the basic ingredients of the projections
definition pts (Γ : ctx) (A : fam Γ) : ctx.pts (ext Γ A) → ctx.pts Γ :=
ext.pts.in_ctx
definition edg (Γ : ctx) (A : fam Γ) (a b : ctx.pts (ext Γ A)) :
ctx.edg (ext Γ A) a b → ctx.edg Γ (pts Γ A a) (pts Γ A b) :=
ext.edg.in_ctx
end proj₁
definition proj₁ (Γ : ctx) (A : fam Γ) : hom (ext Γ A) Γ :=
hom.mk _ (proj₁.edg Γ A)
definition slice_from_fam (Γ : ctx) : fam Γ → slice Γ :=
λ A, slice.mk _ (proj₁ Γ A)
----------------------------------------------------------------------------------------------------
--= UNIT GRAPH =--
namespace unit
inductive pts : Type.{u} :=
| pt0
inductive edg : pts → pts → Type.{u} :=
| pt1 : edg pts.pt0 pts.pt0
end unit
definition unit : ctx :=
ctx.mk unit.pts unit.edg
-- definition star : tm unit :=
-- tm.mk unit.pts.pt0 unit.edg.pt1
namespace unit
-- definition ind (P : fam unit) : tm P
end unit
----------------------------------------------------------------------------------------------------
--= DEPENDENT PAIR TYPES =--
namespace ism
variables {Γ : ctx} (A : fam Γ) (P : fam (ext Γ A))
-- If the `inductive` environment would be slightly more permissive, I would have
-- liked to write `fam.ty_pts Γ` rather than `ctx.pts Γ → Type`. The reason is that,
-- according to the abstraction principle, I should not be required to write out
-- that type explicitly over and over again; once should suffice.
inductive pts : ctx.pts Γ → Type :=
| pair : Π ⦃i : ctx.pts Γ⦄ (x : fam.pts A i), fam.pts P (ext.pts.mk i x) → pts i
-- Similarly, here I would have liked to write `fam.ty_edg Γ (pts A P)`. Note that
-- currently a lot more work goes into writing down the correct expression, with no
-- verification process behind it to verify that the expression I wrote matches my
-- intention.
inductive edg : Π ⦃i j : ctx.pts Γ⦄, (ctx.edg Γ i j) → (pts A P i) → (pts A P j) → Type :=
| pair : Π ⦃i j : ctx.pts Γ⦄ (e : ctx.edg Γ i j)
(x : fam.pts A i) (u : fam.pts P (ext.pts.mk i x))
(y : fam.pts A j) (v : fam.pts P (ext.pts.mk j y)),
edg e (pts.pair x u) (pts.pair y v)
end ism
definition ism {Γ : ctx} (A : fam Γ) (P : fam (ext Γ A)) : fam Γ :=
fam.mk _ (ism.edg A P)
definition ipair {Γ : ctx} (A : fam Γ) (P : fam (ext Γ A)) : tm (⟨P⟩(⟨A⟩ (ism A P))) :=
begin
fapply tm.mk,
intros p,
induction p with p u,
induction p with i x,
exact ism.pts.pair x u,
esimp,
intros p q s,
induction p with p u,
induction p with i x,
induction q with q v,
induction q with j y,
induction s with s t,
induction s with e s,
esimp,
fapply ism.edg.pair,
end
--tm.mk _ (ism.edg.pair A P)
namespace dsm
variables {Γ : ctx} (A : fam Γ) (P : fam (ext Γ A))
include A P
definition pts : fam.ty_pts Γ :=
λ i, Σ (x : fam.pts A i), fam.pts P (ext.pts.mk i x)
definition edg : fam.ty_edg Γ (pts A P) :=
λ i j e p q, Σ (s : fam.edg A e (pr1 p) (pr1 q)), fam.edg P (ext.edg.mk e s) (pr2 p) (pr2 q)
end dsm
----------------------------------------------------------------------------------------------------
--= IDENTITY TYPES =--
----------------------------------------------------------------------------------------------------
--= W-TYPES =--
end graph
|
1ff359b0b4c36016d3535aa3152f1abab40f5867 | dd4e652c749fea9ac77e404005cb3470e5f75469 | /src/LDLT.lean | 9b0b74016bf731fae7825955cdac50b7bd7d08db | [] | no_license | skbaek/cvx | e32822ad5943541539966a37dee162b0a5495f55 | c50c790c9116f9fac8dfe742903a62bdd7292c15 | refs/heads/master | 1,623,803,010,339 | 1,618,058,958,000 | 1,618,058,958,000 | 176,293,135 | 3 | 2 | null | null | null | null | UTF-8 | Lean | false | false | 1,121 | lean | import .array2
variables {k m n : nat}
meta def write_col (A_jj' : rat) (j : nat) (v : array j rat) (h1 : j < n) :
nat → array₂ n n rat → array₂ n n rat | k A :=
if h2 : n ≤ k then A else
let j' : fin n := ⟨j, h1⟩ in
let k' : fin n := ⟨k, lt_of_not_ge' h2⟩ in
let A_kj : rat := A.read k' j' in
let w : array j rat := (array.read A k').take j (le_of_lt h1) in
let r : rat := (A_kj - array.dot_prod w v) / A_jj' in
let A' : array₂ n n rat := A.write k' j' r in
write_col (k+1) A'
meta def LDLT : nat → array₂ n n rat → array₂ n n rat | j A :=
if h1 : n ≤ j then A else
let h2 : j < n := lt_of_not_ge' h1 in
let j' : fin n := ⟨j, h2⟩ in
let v : array j rat := (mk_array j 0).foreach
(λ i _,
let i' : fin n := ⟨i.val, lt_trans i.is_lt h2⟩ in
(A.read j' i') * (A.read i' i')) in
let w : array j rat := ((array.read A j').take j (le_of_lt h2)) in
let A_jj : rat := A.read j' j' in
let A_jj' : rat := A_jj - (array.dot_prod w v) in
let A' : array₂ n n rat := A.write j' j' A_jj' in
let A'' : array₂ n n rat := write_col A_jj' j v h2 (j+1) A' in
LDLT (j+1) A''
|
1ec12341e5fcfc1e886a40637ba0b7d0306555d2 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Data/Array/Basic.lean | 55781c07367f6582368cec7093e466c712243dfd | [
"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 | 24,951 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Data.Nat.Basic
import Init.Data.Fin.Basic
import Init.Data.UInt
import Init.Data.Repr
import Init.Data.ToString
import Init.Control.Id
import Init.Util
universes u v w
/-
The Compiler has special support for arrays.
They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array
-/
structure Array (α : Type u) :=
(sz : Nat)
(data : Fin sz → α)
attribute [extern "lean_array_mk"] Array.mk
attribute [extern "lean_array_data"] Array.data
attribute [extern "lean_array_sz"] Array.sz
@[reducible, extern "lean_array_get_size"]
def Array.size {α : Type u} (a : @& Array α) : Nat :=
a.sz
namespace Array
variables {α : Type u}
/- The parameter `c` is the initial capacity -/
@[extern "lean_mk_empty_array_with_capacity"]
def mkEmpty (c : @& Nat) : Array α :=
{ sz := 0,
data := fun ⟨x, h⟩ => absurd h (Nat.notLtZero x) }
@[extern "lean_array_push"]
def push (a : Array α) (v : α) : Array α :=
{ sz := Nat.succ a.sz,
data := fun ⟨j, h₁⟩ =>
if h₂ : j = a.sz then v
else a.data ⟨j, Nat.ltOfLeOfNe (Nat.leOfLtSucc h₁) h₂⟩ }
@[extern "lean_mk_array"]
def mkArray {α : Type u} (n : Nat) (v : α) : Array α :=
{ sz := n,
data := fun _ => v}
theorem szMkArrayEq {α : Type u} (n : Nat) (v : α) : (mkArray n v).sz = n :=
rfl
def empty : Array α :=
mkEmpty 0
instance : HasEmptyc (Array α) :=
⟨Array.empty⟩
instance : Inhabited (Array α) :=
⟨Array.empty⟩
def isEmpty (a : Array α) : Bool :=
a.size = 0
def singleton (v : α) : Array α :=
mkArray 1 v
@[extern "lean_array_fget"]
def get (a : @& Array α) (i : @& Fin a.size) : α :=
a.data i
/- Low-level version of `fget` which is as fast as a C array read.
`Fin` values are represented as tag pointers in the Lean runtime. Thus,
`fget` may be slightly slower than `uget`. -/
@[extern "lean_array_uget"]
def uget (a : @& Array α) (i : USize) (h : i.toNat < a.size) : α :=
a.get ⟨i.toNat, h⟩
/- "Comfortable" version of `fget`. It performs a bound check at runtime. -/
@[extern "lean_array_get"]
def get! [Inhabited α] (a : @& Array α) (i : @& Nat) : α :=
if h : i < a.size then a.get ⟨i, h⟩ else arbitrary α
def back [Inhabited α] (a : Array α) : α :=
a.get! (a.size - 1)
def get? (a : Array α) (i : Nat) : Option α :=
if h : i < a.size then some (a.get ⟨i, h⟩) else none
def getD (a : Array α) (i : Nat) (v₀ : α) : α :=
if h : i < a.size then a.get ⟨i, h⟩ else v₀
def getOp [Inhabited α] (self : Array α) (idx : Nat) : α :=
self.get! idx
-- auxiliary declaration used in the equation compiler when pattern matching array literals.
abbrev getLit {α : Type u} {n : Nat} (a : Array α) (i : Nat) (h₁ : a.size = n) (h₂ : i < n) : α :=
a.get ⟨i, h₁.symm ▸ h₂⟩
@[extern "lean_array_fset"]
def set (a : Array α) (i : @& Fin a.size) (v : α) : Array α :=
{ sz := a.sz,
data := fun j => if h : i = j then v else a.data j }
theorem szFSetEq (a : Array α) (i : Fin a.size) (v : α) : (set a i v).size = a.size :=
rfl
theorem szPushEq (a : Array α) (v : α) : (push a v).size = a.size + 1 :=
rfl
/- Low-level version of `fset` which is as fast as a C array fset.
`Fin` values are represented as tag pointers in the Lean runtime. Thus,
`fset` may be slightly slower than `uset`. -/
@[extern "lean_array_uset"]
def uset (a : Array α) (i : USize) (v : α) (h : i.toNat < a.size) : Array α :=
a.set ⟨i.toNat, h⟩ v
/- "Comfortable" version of `fset`. It performs a bound check at runtime. -/
@[extern "lean_array_set"]
def set! (a : Array α) (i : @& Nat) (v : α) : Array α :=
if h : i < a.size then a.set ⟨i, h⟩ v else panic! "index out of bounds"
@[extern "lean_array_fswap"]
def swap (a : Array α) (i j : @& Fin a.size) : Array α :=
let v₁ := a.get i;
let v₂ := a.get j;
let a := a.set i v₂;
a.set j v₁
@[extern "lean_array_swap"]
def swap! (a : Array α) (i j : @& Nat) : Array α :=
if h₁ : i < a.size then
if h₂ : j < a.size then swap a ⟨i, h₁⟩ ⟨j, h₂⟩
else panic! "index out of bounds"
else panic! "index out of bounds"
@[inline] def swapAt {α : Type} (a : Array α) (i : Fin a.size) (v : α) : α × Array α :=
let e := a.get i;
let a := a.set i v;
(e, a)
-- TODO: delete as soon as we can define local instances
@[neverExtract] private def swapAtPanic! [Inhabited α] (i : Nat) : α × Array α :=
panic! ("index " ++ toString i ++ " out of bounds")
@[inline] def swapAt! {α : Type} (a : Array α) (i : Nat) (v : α) : α × Array α :=
if h : i < a.size then swapAt a ⟨i, h⟩ v else @swapAtPanic! _ ⟨v⟩ i
@[extern "lean_array_pop"]
def pop (a : Array α) : Array α :=
{ sz := Nat.pred a.size,
data := fun ⟨j, h⟩ => a.get ⟨j, Nat.ltOfLtOfLe h (Nat.predLe _)⟩ }
-- TODO(Leo): justify termination using wf-rec
partial def shrink : Array α → Nat → Array α
| a, n => if n ≥ a.size then a else shrink a.pop n
section
variables {m : Type v → Type w} [Monad m]
variables {β : Type v} {σ : Type u}
-- TODO(Leo): justify termination using wf-rec
@[specialize] partial def iterateMAux (a : Array α) (f : ∀ (i : Fin a.size), α → β → m β) : Nat → β → m β
| i, b =>
if h : i < a.size then
let idx : Fin a.size := ⟨i, h⟩;
f idx (a.get idx) b >>= iterateMAux (i+1)
else pure b
@[inline] def iterateM (a : Array α) (b : β) (f : ∀ (i : Fin a.size), α → β → m β) : m β :=
iterateMAux a f 0 b
@[inline] def foldlM (f : β → α → m β) (init : β) (a : Array α) : m β :=
iterateM a init (fun _ b a => f a b)
@[inline] def foldlFromM (f : β → α → m β) (init : β) (a : Array α) (beginIdx : Nat := 0) : m β :=
iterateMAux a (fun _ b a => f a b) beginIdx init
-- TODO(Leo): justify termination using wf-rec
@[specialize] partial def iterateM₂Aux (a₁ : Array α) (a₂ : Array σ) (f : ∀ (i : Fin a₁.size), α → σ → β → m β) : Nat → β → m β
| i, b =>
if h₁ : i < a₁.size then
let idx₁ : Fin a₁.size := ⟨i, h₁⟩;
if h₂ : i < a₂.size then
let idx₂ : Fin a₂.size := ⟨i, h₂⟩;
f idx₁ (a₁.get idx₁) (a₂.get idx₂) b >>= iterateM₂Aux (i+1)
else pure b
else pure b
@[inline] def iterateM₂ (a₁ : Array α) (a₂ : Array σ) (b : β) (f : ∀ (i : Fin a₁.size), α → σ → β → m β) : m β :=
iterateM₂Aux a₁ a₂ f 0 b
@[inline] def foldlM₂ (f : β → α → σ → m β) (b : β) (a₁ : Array α) (a₂ : Array σ): m β :=
iterateM₂ a₁ a₂ b (fun _ a₁ a₂ b => f b a₁ a₂)
@[specialize] partial def findSomeMAux (a : Array α) (f : α → m (Option β)) : Nat → m (Option β)
| i =>
if h : i < a.size then
let idx : Fin a.size := ⟨i, h⟩;
do r ← f (a.get idx);
match r with
| some v => pure r
| none => findSomeMAux (i+1)
else pure none
@[inline] def findSomeM? (a : Array α) (f : α → m (Option β)) : m (Option β) :=
findSomeMAux a f 0
@[specialize] partial def findSomeRevMAux (a : Array α) (f : α → m (Option β)) : ∀ (idx : Nat), idx ≤ a.size → m (Option β)
| i, h =>
if hLt : 0 < i then
have i - 1 < i from Nat.subLt hLt (Nat.zeroLtSucc 0);
have i - 1 < a.size from Nat.ltOfLtOfLe this h;
let idx : Fin a.size := ⟨i - 1, this⟩;
do
r ← f (a.get idx);
match r with
| some v => pure r
| none =>
have i - 1 ≤ a.size from Nat.leOfLt this;
findSomeRevMAux (i-1) this
else pure none
@[inline] def findSomeRevM? (a : Array α) (f : α → m (Option β)) : m (Option β) :=
findSomeRevMAux a f a.size (Nat.leRefl _)
end
-- TODO(Leo): justify termination using wf-rec
@[specialize] partial def findMAux {α : Type} {m : Type → Type} [Monad m] (a : Array α) (p : α → m Bool) : Nat → m (Option α)
| i =>
if h : i < a.size then do
let v := a.get ⟨i, h⟩;
condM (p v) (pure (some v)) (findMAux (i+1))
else pure none
@[inline] def findM? {α : Type} {m : Type → Type} [Monad m] (a : Array α) (p : α → m Bool) : m (Option α) :=
findMAux a p 0
@[inline] def find? {α : Type} (a : Array α) (p : α → Bool) : Option α :=
Id.run $ a.findM? p
@[specialize] partial def findRevMAux {α : Type} {m : Type → Type} [Monad m] (a : Array α) (p : α → m Bool) : ∀ (idx : Nat), idx ≤ a.size → m (Option α)
| i, h =>
if hLt : 0 < i then
have i - 1 < i from Nat.subLt hLt (Nat.zeroLtSucc 0);
have i - 1 < a.size from Nat.ltOfLtOfLe this h;
let v := a.get ⟨i - 1, this⟩;
do {
condM (p v) (pure (some v)) $
have i - 1 ≤ a.size from Nat.leOfLt this;
findRevMAux (i-1) this
}
else pure none
@[inline] def findRevM? {α : Type} {m : Type → Type} [Monad m] (a : Array α) (p : α → m Bool) : m (Option α) :=
findRevMAux a p a.size (Nat.leRefl _)
@[inline] def findRev? {α : Type} (a : Array α) (p : α → Bool) : Option α :=
Id.run $ a.findRevM? p
section
variables {β : Type w} {σ : Type u}
@[inline] def iterate (a : Array α) (b : β) (f : ∀ (i : Fin a.size), α → β → β) : β :=
Id.run $ iterateMAux a f 0 b
@[inline] def iterateFrom (a : Array α) (b : β) (i : Nat) (f : ∀ (i : Fin a.size), α → β → β) : β :=
Id.run $ iterateMAux a f i b
@[inline] def foldl (f : β → α → β) (init : β) (a : Array α) : β :=
iterate a init (fun _ a b => f b a)
@[inline] def foldlFrom (f : β → α → β) (init : β) (a : Array α) (beginIdx : Nat := 0) : β :=
Id.run $ foldlFromM f init a beginIdx
@[inline] def iterate₂ (a₁ : Array α) (a₂ : Array σ) (b : β) (f : ∀ (i : Fin a₁.size), α → σ → β → β) : β :=
Id.run $ iterateM₂Aux a₁ a₂ f 0 b
@[inline] def foldl₂ (f : β → α → σ → β) (b : β) (a₁ : Array α) (a₂ : Array σ) : β :=
iterate₂ a₁ a₂ b (fun _ a₁ a₂ b => f b a₁ a₂)
@[inline] def findSome? (a : Array α) (f : α → Option β) : Option β :=
Id.run $ findSomeMAux a f 0
@[inline] def findSome! [Inhabited β] (a : Array α) (f : α → Option β) : β :=
match findSome? a f with
| some b => b
| none => panic! "failed to find element"
@[inline] def findSomeRev? (a : Array α) (f : α → Option β) : Option β :=
Id.run $ findSomeRevMAux a f a.size (Nat.leRefl _)
@[inline] def findSomeRev! [Inhabited β] (a : Array α) (f : α → Option β) : β :=
match findSomeRev? a f with
| some b => b
| none => panic! "failed to find element"
@[specialize] partial def findIdxMAux {m : Type → Type u} [Monad m] (a : Array α) (p : α → m Bool) : Nat → m (Option Nat)
| i =>
if h : i < a.size then
condM (p (a.get ⟨i, h⟩)) (pure (some i)) (findIdxMAux (i+1))
else
pure none
@[inline] def findIdxM? {m : Type → Type u} [Monad m] (a : Array α) (p : α → m Bool) : m (Option Nat) :=
findIdxMAux a p 0
@[specialize] partial def findIdxAux (a : Array α) (p : α → Bool) : Nat → Option Nat
| i =>
if h : i < a.size then
if p (a.get ⟨i, h⟩) then some i else findIdxAux (i+1)
else
none
@[inline] def findIdx? (a : Array α) (p : α → Bool) : Option Nat :=
findIdxAux a p 0
@[inline] def findIdx! (a : Array α) (p : α → Bool) : Nat :=
match findIdxAux a p 0 with
| some i => i
| none => panic! "failed to find element"
def getIdx? [HasBeq α] (a : Array α) (v : α) : Option Nat :=
a.findIdx? $ fun a => a == v
end
section
variables {m : Type → Type w} [Monad m]
@[specialize] partial def anyRangeMAux (a : Array α) (endIdx : Nat) (hlt : endIdx ≤ a.size) (p : α → m Bool) : Nat → m Bool
| i =>
if h : i < endIdx then
let idx : Fin a.size := ⟨i, Nat.ltOfLtOfLe h hlt⟩;
do b ← p (a.get idx);
match b with
| true => pure true
| false => anyRangeMAux (i+1)
else pure false
@[inline] def anyM (a : Array α) (p : α → m Bool) : m Bool :=
anyRangeMAux a a.size (Nat.leRefl _) p 0
@[inline] def allM (a : Array α) (p : α → m Bool) : m Bool := do
b ← anyM a (fun v => do b ← p v; pure (!b)); pure (!b)
@[inline] def anyRangeM (a : Array α) (beginIdx endIdx : Nat) (p : α → m Bool) : m Bool :=
if h : endIdx ≤ a.size then
anyRangeMAux a endIdx h p beginIdx
else
anyRangeMAux a a.size (Nat.leRefl _) p beginIdx
@[inline] def allRangeM (a : Array α) (beginIdx endIdx : Nat) (p : α → m Bool) : m Bool := do
b ← anyRangeM a beginIdx endIdx (fun v => do b ← p v; pure b); pure (!b)
end
@[inline] def any (a : Array α) (p : α → Bool) : Bool :=
Id.run $ anyM a p
@[inline] def anyRange (a : Array α) (beginIdx endIdx : Nat) (p : α → Bool) : Bool :=
Id.run $ anyRangeM a beginIdx endIdx p
@[inline] def anyFrom (a : Array α) (beginIdx : Nat) (p : α → Bool) : Bool :=
Id.run $ anyRangeM a beginIdx a.size p
@[inline] def all (a : Array α) (p : α → Bool) : Bool :=
!any a (fun v => !p v)
@[inline] def allRange (a : Array α) (beginIdx endIdx : Nat) (p : α → Bool) : Bool :=
!anyRange a beginIdx endIdx (fun v => !p v)
section
variables {m : Type v → Type w} [Monad m]
variable {β : Type v}
@[specialize] private def iterateRevMAux (a : Array α) (f : ∀ (i : Fin a.size), α → β → m β) : ∀ (i : Nat), i ≤ a.size → β → m β
| 0, h, b => pure b
| j+1, h, b => do
let i : Fin a.size := ⟨j, h⟩;
b ← f i (a.get i) b;
iterateRevMAux j (Nat.leOfLt h) b
@[inline] def iterateRevM (a : Array α) (b : β) (f : ∀ (i : Fin a.size), α → β → m β) : m β :=
iterateRevMAux a f a.size (Nat.leRefl _) b
@[inline] def foldrM (f : α → β → m β) (init : β) (a : Array α) : m β :=
iterateRevM a init (fun _ => f)
@[specialize] private def foldrRangeMAux (a : Array α) (f : α → β → m β) (beginIdx : Nat) : ∀ (i : Nat), i ≤ a.size → β → m β
| 0, h, b => pure b
| j+1, h, b => do
let i : Fin a.size := ⟨j, h⟩;
b ← f (a.get i) b;
if j == beginIdx then pure b else foldrRangeMAux j (Nat.leOfLt h) b
@[inline] def foldrRangeM (beginIdx endIdx : Nat) (f : α → β → m β) (ini : β) (a : Array α) : m β :=
if h : endIdx ≤ a.size then
foldrRangeMAux a f beginIdx endIdx h ini
else
foldrRangeMAux a f beginIdx a.size (Nat.leRefl _) ini
@[specialize] partial def foldlStepMAux (step : Nat) (a : Array α) (f : β → α → m β) : Nat → β → m β
| i, b =>
if h : i < a.size then do
let curr := a.get ⟨i, h⟩;
b ← f b curr;
foldlStepMAux (i+step) b
else
pure b
@[inline] def foldlStepM (f : β → α → m β) (init : β) (step : Nat) (a : Array α) : m β :=
foldlStepMAux step a f 0 init
end
@[inline] def iterateRev {β} (a : Array α) (b : β) (f : ∀ (i : Fin a.size), α → β → β) : β :=
Id.run $ iterateRevM a b f
@[inline] def foldr {β} (f : α → β → β) (init : β) (a : Array α) : β :=
Id.run $ foldrM f init a
@[inline] def foldrRange {β} (beginIdx endIdx : Nat) (f : α → β → β) (init : β) (a : Array α) : β :=
Id.run $ foldrRangeM beginIdx endIdx f init a
@[inline] def foldlStep {β} (f : β → α → β) (init : β) (step : Nat) (a : Array α) : β :=
Id.run $ foldlStepM f init step a
@[inline] def getEvenElems (a : Array α) : Array α :=
a.foldlStep (fun r a => Array.push r a) empty 2
def toList (a : Array α) : List α :=
a.foldr List.cons []
instance [HasRepr α] : HasRepr (Array α) :=
⟨fun a => "#" ++ repr a.toList⟩
instance [HasToString α] : HasToString (Array α) :=
⟨fun a => "#" ++ toString a.toList⟩
section
variables {m : Type u → Type w} [Monad m]
variable {β : Type u}
@[specialize] unsafe partial def umapMAux (f : Nat → α → m β) : Nat → Array (PNonScalar.{u}) → m (Array (PNonScalar.{u}))
| i, a =>
if h : i < a.size then
let idx : Fin a.size := ⟨i, h⟩;
let v : PNonScalar := a.get idx;
let a := a.set idx (arbitrary _);
do newV ← f i (unsafeCast v); umapMAux (i+1) (a.set idx (unsafeCast newV))
else
pure a
@[inline] unsafe partial def umapM (f : α → m β) (as : Array α) : m (Array β) :=
@unsafeCast (m (Array PNonScalar.{u})) (m (Array β)) $ umapMAux (fun i a => f a) 0 (unsafeCast as)
@[inline] unsafe partial def umapIdxM (f : Nat → α → m β) (as : Array α) : m (Array β) :=
@unsafeCast (m (Array PNonScalar.{u})) (m (Array β)) $ umapMAux f 0 (unsafeCast as)
@[implementedBy Array.umapM] def mapM (f : α → m β) (as : Array α) : m (Array β) :=
as.foldlM (fun bs a => do b ← f a; pure (bs.push b)) (mkEmpty as.size)
@[implementedBy Array.umapIdxM] def mapIdxM (f : Nat → α → m β) (as : Array α) : m (Array β) :=
as.iterateM (mkEmpty as.size) (fun i a bs => do b ← f i.val a; pure (bs.push b))
end
section
variables {m : Type u → Type v} [Monad m]
variable {β : Type u}
@[inline] def modifyM [Inhabited α] (a : Array α) (i : Nat) (f : α → m α) : m (Array α) :=
if h : i < a.size then do
let idx : Fin a.size := ⟨i, h⟩;
let v := a.get idx;
let a := a.set idx (arbitrary α);
v ← f v;
pure $ (a.set idx v)
else
pure a
end
section
variable {β : Type u}
@[inline] def modify [Inhabited α] (a : Array α) (i : Nat) (f : α → α) : Array α :=
Id.run $ a.modifyM i f
@[inline] def modifyOp [Inhabited α] (self : Array α) (idx : Nat) (f : α → α) : Array α :=
self.modify idx f
@[inline] def mapIdx (f : Nat → α → β) (a : Array α) : Array β :=
Id.run $ mapIdxM f a
@[inline] def map (f : α → β) (as : Array α) : Array β :=
Id.run $ mapM f as
end
section
variables {m : Type u → Type v} [Monad m]
variable {β : Type u}
@[specialize]
partial def forMAux {α : Type w} {β : Type u} (f : α → m β) (a : Array α) : Nat → m PUnit
| i =>
if h : i < a.size then
let idx : Fin a.size := ⟨i, h⟩;
let v : α := a.get idx;
do f v; forMAux (i+1)
else
pure ⟨⟩
@[inline] def forM {α : Type w} {β : Type u} (f : α → m β) (a : Array α) : m PUnit :=
a.forMAux f 0
@[specialize]
partial def forRevMAux {α : Type w} {β : Type u} (f : α → m β) (a : Array α) : forall (i : Nat), i ≤ a.size → m PUnit
| i, h =>
if hLt : 0 < i then
have i - 1 < i from Nat.subLt hLt (Nat.zeroLtSucc 0);
have i - 1 < a.size from Nat.ltOfLtOfLe this h;
let v : α := a.get ⟨i-1, this⟩;
have i - 1 ≤ a.size from Nat.leOfLt this;
do f v; forRevMAux (i-1) this
else
pure ⟨⟩
@[inline] def forRevM {α : Type w} {β : Type u} (f : α → m β) (a : Array α) : m PUnit :=
a.forRevMAux f a.size (Nat.leRefl _)
end
-- TODO(Leo): justify termination using wf-rec
partial def extractAux (a : Array α) : Nat → ∀ (e : Nat), e ≤ a.size → Array α → Array α
| i, e, hle, r =>
if hlt : i < e then
let idx : Fin a.size := ⟨i, Nat.ltOfLtOfLe hlt hle⟩;
extractAux (i+1) e hle (r.push (a.get idx))
else r
def extract (a : Array α) (b e : Nat) : Array α :=
let r : Array α := mkEmpty (e - b);
if h : e ≤ a.size then extractAux a b e h r
else r
protected def append (a : Array α) (b : Array α) : Array α :=
b.foldl (fun a v => a.push v) a
instance : HasAppend (Array α) := ⟨Array.append⟩
-- TODO(Leo): justify termination using wf-rec
@[specialize] partial def isEqvAux (a b : Array α) (hsz : a.size = b.size) (p : α → α → Bool) : Nat → Bool
| i =>
if h : i < a.size then
let aidx : Fin a.size := ⟨i, h⟩;
let bidx : Fin b.size := ⟨i, hsz ▸ h⟩;
match p (a.get aidx) (b.get bidx) with
| true => isEqvAux (i+1)
| false => false
else
true
@[inline] def isEqv (a b : Array α) (p : α → α → Bool) : Bool :=
if h : a.size = b.size then
isEqvAux a b h p 0
else
false
instance [HasBeq α] : HasBeq (Array α) :=
⟨fun a b => isEqv a b HasBeq.beq⟩
-- TODO(Leo): justify termination using wf-rec, and use `swap`
partial def reverseAux : Array α → Nat → Array α
| a, i =>
let n := a.size;
if i < n / 2 then
reverseAux (a.swap! i (n - i - 1)) (i+1)
else
a
def reverse (a : Array α) : Array α :=
reverseAux a 0
-- TODO(Leo): justify termination using wf-rec
@[specialize] partial def filterAux (p : α → Bool) : Array α → Nat → Nat → Array α
| a, i, j =>
if h₁ : i < a.size then
if p (a.get ⟨i, h₁⟩) then
if h₂ : j < i then
filterAux (a.swap ⟨i, h₁⟩ ⟨j, Nat.ltTrans h₂ h₁⟩) (i+1) (j+1)
else
filterAux a (i+1) (j+1)
else
filterAux a (i+1) j
else
a.shrink j
@[inline] def filter (p : α → Bool) (as : Array α) : Array α :=
filterAux p as 0 0
@[specialize] partial def filterMAux {m : Type → Type} [Monad m] {α : Type} (p : α → m Bool) : Array α → Nat → Nat → m (Array α)
| a, i, j =>
if h₁ : i < a.size then
condM (p (a.get ⟨i, h₁⟩))
(if h₂ : j < i then
filterMAux (a.swap ⟨i, h₁⟩ ⟨j, Nat.ltTrans h₂ h₁⟩) (i+1) (j+1)
else
filterMAux a (i+1) (j+1))
(filterMAux a (i+1) j)
else
pure $ a.shrink j
@[inline] def filterM {m : Type → Type} [Monad m] {α : Type} (p : α → m Bool) (as : Array α) : m (Array α) :=
filterMAux p as 0 0
partial def indexOfAux {α} [HasBeq α] (a : Array α) (v : α) : Nat → Option (Fin a.size)
| i =>
if h : i < a.size then
let idx : Fin a.size := ⟨i, h⟩;
if a.get idx == v then some idx
else indexOfAux (i+1)
else none
def indexOf {α} [HasBeq α] (a : Array α) (v : α) : Option (Fin a.size) :=
indexOfAux a v 0
partial def eraseIdxAux {α} : Nat → Array α → Array α
| i, a =>
if h : i < a.size then
let idx : Fin a.size := ⟨i, h⟩;
let idx1 : Fin a.size := ⟨i - 1, Nat.ltOfLeOfLt (Nat.predLe i) h⟩;
eraseIdxAux (i+1) (a.swap idx idx1)
else
a.pop
def feraseIdx {α} (a : Array α) (i : Fin a.size) : Array α :=
eraseIdxAux (i.val + 1) a
def eraseIdx {α} (a : Array α) (i : Nat) : Array α :=
if i < a.size then eraseIdxAux (i+1) a else a
theorem szFSwapEq (a : Array α) (i j : Fin a.size) : (a.swap i j).size = a.size :=
rfl
theorem szPopEq (a : Array α) : a.pop.size = a.size - 1 :=
rfl
section
/- Instance for justifying `partial` declaration.
We should be able to delete it as soon as we restore support for well-founded recursion. -/
instance eraseIdxSzAuxInstance (a : Array α) : Inhabited { r : Array α // r.size = a.size - 1 } :=
⟨⟨a.pop, szPopEq a⟩⟩
partial def eraseIdxSzAux {α} (a : Array α) : ∀ (i : Nat) (r : Array α), r.size = a.size → { r : Array α // r.size = a.size - 1 }
| i, r, heq =>
if h : i < r.size then
let idx : Fin r.size := ⟨i, h⟩;
let idx1 : Fin r.size := ⟨i - 1, Nat.ltOfLeOfLt (Nat.predLe i) h⟩;
eraseIdxSzAux (i+1) (r.swap idx idx1) ((szFSwapEq r idx idx1).trans heq)
else
⟨r.pop, (szPopEq r).trans (heq ▸ rfl)⟩
end
def eraseIdx' {α} (a : Array α) (i : Fin a.size) : { r : Array α // r.size = a.size - 1 } :=
eraseIdxSzAux a (i.val + 1) a rfl
def contains [HasBeq α] (as : Array α) (a : α) : Bool :=
as.any $ fun b => a == b
def elem [HasBeq α] (a : α) (as : Array α) : Bool :=
as.contains a
partial def insertAtAux {α} (i : Nat) : Array α → Nat → Array α
| as, j =>
if i == j then as
else
let as := as.swap! (j-1) j;
insertAtAux as (j-1)
/--
Insert element `a` at position `i`.
Pre: `i < as.size` -/
def insertAt {α} (as : Array α) (i : Nat) (a : α) : Array α :=
if i > as.size then panic! "invalid index"
else
let as := as.push a;
as.insertAtAux i as.size
theorem ext {α : Type u} (a b : Array α) : a.size = b.size → (∀ (i : Nat) (hi₁ : i < a.size) (hi₂ : i < b.size) , a.get ⟨i, hi₁⟩ = b.get ⟨i, hi₂⟩) → a = b :=
match a, b with
| ⟨sz₁, f₁⟩, ⟨sz₂, f₂⟩ =>
show sz₁ = sz₂ → (∀ (i : Nat) (hi₁ : i < sz₁) (hi₂ : i < sz₂) , f₁ ⟨i, hi₁⟩ = f₂ ⟨i, hi₂⟩) → Array.mk sz₁ f₁ = Array.mk sz₂ f₂ from
fun h₁ h₂ =>
match sz₁, sz₂, f₁, f₂, h₁, h₂ with
| sz, _, f₁, f₂, rfl, h₂ =>
have f₁ = f₂ from funext $ fun ⟨i, hi₁⟩ => h₂ i hi₁ hi₁;
congrArg _ this
theorem extLit {α : Type u} {n : Nat}
(a b : Array α)
(hsz₁ : a.size = n) (hsz₂ : b.size = n)
(h : ∀ (i : Nat) (hi : i < n), a.getLit i hsz₁ hi = b.getLit i hsz₂ hi) : a = b :=
Array.ext a b (hsz₁.trans hsz₂.symm) $ fun i hi₁ hi₂ => h i (hsz₁ ▸ hi₁)
end Array
export Array (mkArray)
@[inlineIfReduce] def List.toArrayAux {α : Type u} : List α → Array α → Array α
| [], r => r
| a::as, r => List.toArrayAux as (r.push a)
@[inlineIfReduce] def List.redLength {α : Type u} : List α → Nat
| [] => 0
| _::as => as.redLength + 1
@[inline] def List.toArray {α : Type u} (as : List α) : Array α :=
as.toArrayAux (Array.mkEmpty as.redLength)
|
58c21bbf353641d63a18c3d06a2e8e2aa187e2e3 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/algebra/direct_sum/internal.lean | ab0e4e73c852abc06d4ab967cbc44f33359221a1 | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,719 | lean | /-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser, Kevin Buzzard, Jujian Zhang
-/
import algebra.direct_sum.algebra
/-!
# Internally graded rings and algebras
This module provides `gsemiring` and `gcomm_semiring` instances for a collection of subobjects `A`
when a `set_like.graded_monoid` instance is available:
* on `add_submonoid R`s: `add_submonoid.gsemiring`, `add_submonoid.gcomm_semiring`.
* on `add_subgroup R`s: `add_subgroup.gsemiring`, `add_subgroup.gcomm_semiring`.
* on `submodule S R`s: `submodule.gsemiring`, `submodule.gcomm_semiring`.
With these instances in place, it provides the bundled canonical maps out of a direct sum of
subobjects into their carrier type:
* `direct_sum.add_submonoid_coe_ring_hom` (a `ring_hom` version of `direct_sum.add_submonoid_coe`)
* `direct_sum.add_subgroup_coe_ring_hom` (a `ring_hom` version of `direct_sum.add_subgroup_coe`)
* `direct_sum.submodule_coe_alg_hom` (an `alg_hom` version of `direct_sum.submodule_coe`)
Strictly the definitions in this file are not sufficient to fully define an "internal" direct sum;
to represent this case, `(h : direct_sum.submodule_is_internal A) [set_like.graded_monoid A]` is
needed. In the future there will likely be a data-carrying, constructive, typeclass version of
`direct_sum.submodule_is_internal` for providing an explicit decomposition function.
When `complete_lattice.independent (set.range A)` (a weaker condition than
`direct_sum.submodule_is_internal A`), these provide a grading of `⨆ i, A i`, and the
mapping `⨁ i, A i →+ ⨆ i, A i` can be obtained as
`direct_sum.to_monoid (λ i, add_submonoid.inclusion $ le_supr A i)`.
## tags
internally graded ring
-/
open_locale direct_sum
variables {ι : Type*} {S R : Type*} [decidable_eq ι]
/-! #### From `add_submonoid`s -/
namespace add_submonoid
/-- Build a `gsemiring` instance for a collection of `add_submonoid`s. -/
instance gsemiring [add_monoid ι] [semiring R]
(A : ι → add_submonoid R) [set_like.graded_monoid A] :
direct_sum.gsemiring (λ i, A i) :=
{ mul_zero := λ i j _, subtype.ext (mul_zero _),
zero_mul := λ i j _, subtype.ext (zero_mul _),
mul_add := λ i j _ _ _, subtype.ext (mul_add _ _ _),
add_mul := λ i j _ _ _, subtype.ext (add_mul _ _ _),
..set_like.gmonoid A }
/-- Build a `gcomm_semiring` instance for a collection of `add_submonoid`s. -/
instance gcomm_semiring [add_comm_monoid ι] [comm_semiring R]
(A : ι → add_submonoid R) [set_like.graded_monoid A] :
direct_sum.gcomm_semiring (λ i, A i) :=
{ ..set_like.gcomm_monoid A,
..add_submonoid.gsemiring A, }
end add_submonoid
/-- The canonical ring isomorphism between `⨁ i, A i` and `R`-/
def direct_sum.submonoid_coe_ring_hom [add_monoid ι] [semiring R]
(A : ι → add_submonoid R) [h : set_like.graded_monoid A] : (⨁ i, A i) →+* R :=
direct_sum.to_semiring (λ i, (A i).subtype) rfl (λ _ _ _ _, rfl)
/-- The canonical ring isomorphism between `⨁ i, A i` and `R`-/
@[simp] lemma direct_sum.submonoid_coe_ring_hom_of [add_monoid ι] [semiring R]
(A : ι → add_submonoid R) [h : set_like.graded_monoid A] (i : ι) (x : A i) :
direct_sum.submonoid_coe_ring_hom A (direct_sum.of (λ i, A i) i x) = x :=
direct_sum.to_semiring_of _ _ _ _ _
/-! #### From `add_subgroup`s -/
namespace add_subgroup
/-- Build a `gsemiring` instance for a collection of `add_subgroup`s. -/
instance gsemiring [add_monoid ι] [ring R]
(A : ι → add_subgroup R) [h : set_like.graded_monoid A] :
direct_sum.gsemiring (λ i, A i) :=
have i' : set_like.graded_monoid (λ i, (A i).to_add_submonoid) := {..h},
by exactI add_submonoid.gsemiring (λ i, (A i).to_add_submonoid)
/-- Build a `gcomm_semiring` instance for a collection of `add_subgroup`s. -/
instance gcomm_semiring [add_comm_group ι] [comm_ring R]
(A : ι → add_subgroup R) [h : set_like.graded_monoid A] :
direct_sum.gsemiring (λ i, A i) :=
have i' : set_like.graded_monoid (λ i, (A i).to_add_submonoid) := {..h},
by exactI add_submonoid.gsemiring (λ i, (A i).to_add_submonoid)
end add_subgroup
/-- The canonical ring isomorphism between `⨁ i, A i` and `R`. -/
def direct_sum.subgroup_coe_ring_hom [add_monoid ι] [ring R]
(A : ι → add_subgroup R) [set_like.graded_monoid A] : (⨁ i, A i) →+* R :=
direct_sum.to_semiring (λ i, (A i).subtype) rfl (λ _ _ _ _, rfl)
@[simp] lemma direct_sum.subgroup_coe_ring_hom_of [add_monoid ι] [ring R]
(A : ι → add_subgroup R) [set_like.graded_monoid A] (i : ι) (x : A i) :
direct_sum.subgroup_coe_ring_hom A (direct_sum.of (λ i, A i) i x) = x :=
direct_sum.to_semiring_of _ _ _ _ _
/-! #### From `submodules`s -/
namespace submodule
/-- Build a `gsemiring` instance for a collection of `submodule`s. -/
instance gsemiring [add_monoid ι]
[comm_semiring S] [semiring R] [algebra S R]
(A : ι → submodule S R) [h : set_like.graded_monoid A] :
direct_sum.gsemiring (λ i, A i) :=
have i' : set_like.graded_monoid (λ i, (A i).to_add_submonoid) := {..h},
by exactI add_submonoid.gsemiring (λ i, (A i).to_add_submonoid)
/-- Build a `gsemiring` instance for a collection of `submodule`s. -/
instance gcomm_semiring [add_comm_monoid ι]
[comm_semiring S] [comm_semiring R] [algebra S R]
(A : ι → submodule S R) [h : set_like.graded_monoid A] :
direct_sum.gcomm_semiring (λ i, A i) :=
have i' : set_like.graded_monoid (λ i, (A i).to_add_submonoid) := {..h},
by exactI add_submonoid.gcomm_semiring (λ i, (A i).to_add_submonoid)
/-- Build a `galgebra` instance for a collection of `submodule`s. -/
instance galgebra [add_monoid ι]
[comm_semiring S] [semiring R] [algebra S R]
(A : ι → submodule S R) [h : set_like.graded_monoid A] :
direct_sum.galgebra S (λ i, A i) :=
{ to_fun := begin
refine ((algebra.linear_map S R).cod_restrict (A 0) $ λ r, _).to_add_monoid_hom,
exact submodule.one_le.mpr set_like.has_graded_one.one_mem (submodule.algebra_map_mem _),
end,
map_one := subtype.ext $ by exact (algebra_map S R).map_one,
map_mul := λ x y, sigma.subtype_ext (add_zero 0).symm $ (algebra_map S R).map_mul _ _,
commutes := λ r ⟨i, xi⟩,
sigma.subtype_ext ((zero_add i).trans (add_zero i).symm) $ algebra.commutes _ _,
smul_def := λ r ⟨i, xi⟩, sigma.subtype_ext (zero_add i).symm $ algebra.smul_def _ _ }
@[simp] lemma set_like.coe_galgebra_to_fun [add_monoid ι]
[comm_semiring S] [semiring R] [algebra S R]
(A : ι → submodule S R) [h : set_like.graded_monoid A] (s : S) :
↑(@direct_sum.galgebra.to_fun _ S (λ i, A i) _ _ _ _ _ _ _ s) = (algebra_map S R s : R) := rfl
/-- A direct sum of powers of a submodule of an algebra has a multiplicative structure. -/
instance nat_power_graded_monoid
[comm_semiring S] [semiring R] [algebra S R] (p : submodule S R) :
set_like.graded_monoid (λ i : ℕ, p ^ i) :=
{ one_mem := by { rw [←one_le, pow_zero], exact le_rfl },
mul_mem := λ i j p q hp hq, by { rw pow_add, exact submodule.mul_mem_mul hp hq } }
end submodule
/-- The canonical algebra isomorphism between `⨁ i, A i` and `R`. -/
def direct_sum.submodule_coe_alg_hom [add_monoid ι]
[comm_semiring S] [semiring R] [algebra S R]
(A : ι → submodule S R) [h : set_like.graded_monoid A] : (⨁ i, A i) →ₐ[S] R :=
direct_sum.to_algebra S _ (λ i, (A i).subtype) rfl (λ _ _ _ _, rfl) (λ _, rfl)
@[simp] lemma direct_sum.submodule_coe_alg_hom_of [add_monoid ι]
[comm_semiring S] [semiring R] [algebra S R]
(A : ι → submodule S R) [h : set_like.graded_monoid A] (i : ι) (x : A i) :
direct_sum.submodule_coe_alg_hom A (direct_sum.of (λ i, A i) i x) = x :=
direct_sum.to_semiring_of _ rfl (λ _ _ _ _, rfl) _ _
|
d3bbc6598e5f8cab45f19d38cea96ddb240dd60b | 957a80ea22c5abb4f4670b250d55534d9db99108 | /tests/lean/run/io_fs.lean | 62631ff1c2f489c20e652ccebaf0d92f3541cbd0 | [
"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 | 495 | lean | import system.io
open io
variable [io.interface]
def mk_test_file : io unit :=
do h ← mk_file_handle "io_fs.txt" io.mode.write,
fs.put_str_ln h "hello world",
fs.put_str_ln h "hello world again",
fs.close h
def read_test_file : io string :=
do b ← fs.read_file "io_fs.txt",
return b^.to_string
#eval do
mk_test_file,
c ← read_test_file,
put_str c,
if c = "hello world\nhello world again\n" then return ()
else io.fail "file content does not match expected result"
|
a9dbfc6c40ef1ff7676d0db6cd092c7d94fa4fda | f20db13587f4dd28a4b1fbd31953afd491691fa0 | /library/init/data/char/basic.lean | 5226cc1918ea69c071539064f0081d1b49ec01de | [
"Apache-2.0"
] | permissive | AHartNtkn/lean | 9a971edfc6857c63edcbf96bea6841b9a84cf916 | 0d83a74b26541421fc1aa33044c35b03759710ed | refs/heads/master | 1,620,592,591,236 | 1,516,749,881,000 | 1,516,749,881,000 | 118,697,288 | 1 | 0 | null | 1,516,759,470,000 | 1,516,759,470,000 | null | UTF-8 | Lean | false | false | 2,002 | 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.nat.basic
open nat
@[reducible] def is_valid_char (n : nat) : Prop :=
n < 0xd800 ∨ (0xdfff < n ∧ n < 0x110000)
lemma is_valid_char_range_1 (n : nat) (h : n < 0xd800) : is_valid_char n :=
or.inl h
lemma is_valid_char_range_2 (n : nat) (h₁ : 0xdfff < n) (h₂ : n < 0x110000) : is_valid_char n :=
or.inr ⟨h₁, h₂⟩
/-- The `char` type represents an unicode scalar value.
See http://www.unicode.org/glossary/#unicode_scalar_value). -/
structure char :=
(val : nat) (valid : is_valid_char val)
instance : has_sizeof char :=
⟨λ c, c.val⟩
namespace char
protected def lt (a b : char) : Prop := a.val < b.val
protected def le (a b : char) : Prop := a.val ≤ b.val
instance : has_lt char := ⟨char.lt⟩
instance : has_le char := ⟨char.le⟩
instance decidable_lt (a b : char) : decidable (a < b) :=
nat.decidable_lt _ _
instance decidable_le (a b : char) : decidable (a ≤ b) :=
nat.decidable_le _ _
/- We cannot use tactic dec_trivial here because the tactic framework has not been defined yet. -/
lemma zero_lt_d800 : 0 < 0xd800 :=
zero_lt_succ _
@[pattern] def of_nat (n : nat) : char :=
if h : is_valid_char n then {val := n, valid := h} else {val := 0, valid := or.inl zero_lt_d800}
def to_nat (c : char) : nat :=
c.val
lemma eq_of_veq : ∀ {c d : char}, c.val = d.val → c = d
| ⟨v, h⟩ ⟨_, _⟩ rfl := rfl
lemma veq_of_eq : ∀ {c d : char}, c = d → c.val = d.val
| _ _ rfl := rfl
lemma ne_of_vne {c d : char} (h : c.val ≠ d.val) : c ≠ d :=
λ h', absurd (veq_of_eq h') h
lemma vne_of_ne {c d : char} (h : c ≠ d) : c.val ≠ d.val :=
λ h', absurd (eq_of_veq h') h
end char
instance : decidable_eq char :=
λ i j, decidable_of_decidable_of_iff
(nat.decidable_eq i.val j.val) ⟨char.eq_of_veq, char.veq_of_eq⟩
instance : inhabited char :=
⟨'A'⟩
|
8936930e7fb62b5c9ded45eb1553f783b8677b6a | 1b8f093752ba748c5ca0083afef2959aaa7dace5 | /src/category_theory/filtered.lean | aab6321236bdfd8f58727db2c1681093e9fad97f | [] | no_license | khoek/lean-category-theory | 7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386 | 63dcb598e9270a3e8b56d1769eb4f825a177cd95 | refs/heads/master | 1,585,251,725,759 | 1,539,344,445,000 | 1,539,344,445,000 | 145,281,070 | 0 | 0 | null | 1,534,662,376,000 | 1,534,662,376,000 | null | UTF-8 | Lean | false | false | 894 | lean | import category_theory.limits.shape
import order.filter
open category_theory.limits
namespace category_theory
universes u₁ v₁
variables α : Type u₁
class directed [preorder α] :=
(bound (x₁ x₂ : α) : α)
(i₁ (x₁ x₂ : α) : x₁ ≤ bound x₁ x₂)
(i₂ (x₁ x₂ : α) : x₂ ≤ bound x₁ x₂)
variables (C : Type u₁) [𝒞 : category.{u₁ v₁} C]
include 𝒞
class filtered :=
(default : C)
(obj_bound (X Y : C) : cospan X Y)
(hom_bound {X Y : C} (f g : X ⟶ Y) : cofork f g)
instance [inhabited α] [preorder α] [directed α] : filtered.{u₁ u₁} α :=
{ default := default α,
obj_bound := λ x y, { X := directed.bound x y, ι₁ := ⟨ ⟨ directed.i₁ x y ⟩ ⟩, ι₂ := ⟨ ⟨ directed.i₂ x y ⟩ ⟩ },
hom_bound := λ _ y f g, { X := y, π := 𝟙 y, w := begin cases f, cases f, cases g, cases g, simp end } }
end category_theory |
95b2a142f1cb829a6f72ed31424b0b0b8de96ce0 | e8d53a7b78545d183a23dd7bd921bc7ff312989f | /types/sigma.hlean | f27e6ca7ee2d4ec562edaf0ad31419da5398d476 | [] | no_license | Sumit0730/Impredicative | 857007626592440a27cf4440aa9a226d0ede7f3e | a75cb9989a684133d31d4889a746ee4fa7b66cea | refs/heads/master | 1,631,994,804,745 | 1,531,980,761,000 | 1,531,980,761,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 23,529 | hlean | /-
Copyright (c) 2014-15 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Partially ported from Coq HoTT
Theorems about sigma-types (dependent sums)
-/
import types.prod
open eq sigma sigma.ops equiv is_equiv function is_trunc sum unit
namespace sigma
variables {A A' : Type} {B : A → Type} {B' : A' → Type} {C : Πa, B a → Type}
{D : Πa b, C a b → Type}
{a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {u v w : Σa, B a}
definition destruct := @sigma.cases_on
/- Paths in a sigma-type -/
protected definition eta [unfold 3] : Π (u : Σa, B a), ⟨u.1 , u.2⟩ = u
| eta ⟨u₁, u₂⟩ := idp
definition eta2 : Π (u : Σa b, C a b), ⟨u.1, u.2.1, u.2.2⟩ = u
| eta2 ⟨u₁, u₂, u₃⟩ := idp
definition eta3 : Π (u : Σa b c, D a b c), ⟨u.1, u.2.1, u.2.2.1, u.2.2.2⟩ = u
| eta3 ⟨u₁, u₂, u₃, u₄⟩ := idp
definition dpair_eq_dpair [unfold 8] (p : a = a') (q : b =[p] b') : ⟨a, b⟩ = ⟨a', b'⟩ :=
apd011 sigma.mk p q
definition sigma_eq [unfold 5 6] (p : u.1 = v.1) (q : u.2 =[p] v.2) : u = v :=
by induction u; induction v; exact (dpair_eq_dpair p q)
definition sigma_eq_right [unfold 6] (q : b₁ = b₂) : ⟨a, b₁⟩ = ⟨a, b₂⟩ :=
ap (dpair a) q
definition eq_pr1 [unfold 5] (p : u = v) : u.1 = v.1 :=
ap pr1 p
postfix `..1`:(max+1) := eq_pr1
definition eq_pr2 [unfold 5] (p : u = v) : u.2 =[p..1] v.2 :=
by induction p; exact idpo
postfix `..2`:(max+1) := eq_pr2
definition dpair_sigma_eq (p : u.1 = v.1) (q : u.2 =[p] v.2)
: ⟨(sigma_eq p q)..1, (sigma_eq p q)..2⟩ = ⟨p, q⟩ :=
by induction u; induction v;esimp at *;induction q;esimp
definition sigma_eq_pr1 (p : u.1 = v.1) (q : u.2 =[p] v.2) : (sigma_eq p q)..1 = p :=
(dpair_sigma_eq p q)..1
definition sigma_eq_pr2 (p : u.1 = v.1) (q : u.2 =[p] v.2)
: (sigma_eq p q)..2 =[sigma_eq_pr1 p q] q :=
(dpair_sigma_eq p q)..2
definition sigma_eq_eta (p : u = v) : sigma_eq (p..1) (p..2) = p :=
by induction p; induction u; reflexivity
definition eq2_pr1 {p q : u = v} (r : p = q) : p..1 = q..1 :=
ap eq_pr1 r
definition eq2_pr2 {p q : u = v} (r : p = q) : p..2 =[eq2_pr1 r] q..2 :=
!pathover_ap (apd eq_pr2 r)
definition tr_pr1_sigma_eq {B' : A → Type} (p : u.1 = v.1) (q : u.2 =[p] v.2)
: transport (λx, B' x.1) (sigma_eq p q) = transport B' p :=
by induction u; induction v; esimp at *;induction q; reflexivity
protected definition ap_pr1 (p : u = v) : ap (λx : sigma B, x.1) p = p..1 := idp
/- the uncurried version of sigma_eq. We will prove that this is an equivalence -/
definition sigma_eq_unc [unfold 5] : Π (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2), u = v
| sigma_eq_unc ⟨pq₁, pq₂⟩ := sigma_eq pq₁ pq₂
definition dpair_sigma_eq_unc : Π (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2),
⟨(sigma_eq_unc pq)..1, (sigma_eq_unc pq)..2⟩ = pq
| dpair_sigma_eq_unc ⟨pq₁, pq₂⟩ := dpair_sigma_eq pq₁ pq₂
definition sigma_eq_pr1_unc (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2)
: (sigma_eq_unc pq)..1 = pq.1 :=
(dpair_sigma_eq_unc pq)..1
definition sigma_eq_pr2_unc (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2) :
(sigma_eq_unc pq)..2 =[sigma_eq_pr1_unc pq] pq.2 :=
(dpair_sigma_eq_unc pq)..2
definition sigma_eq_eta_unc (p : u = v) : sigma_eq_unc ⟨p..1, p..2⟩ = p :=
sigma_eq_eta p
definition tr_sigma_eq_pr1_unc {B' : A → Type}
(pq : Σ(p : u.1 = v.1), u.2 =[p] v.2)
: transport (λx, B' x.1) (@sigma_eq_unc A B u v pq) = transport B' pq.1 :=
destruct pq tr_pr1_sigma_eq
definition is_equiv_sigma_eq [instance] [constructor] (u v : Σa, B a)
: is_equiv (@sigma_eq_unc A B u v) :=
adjointify sigma_eq_unc
(λp, ⟨p..1, p..2⟩)
sigma_eq_eta_unc
dpair_sigma_eq_unc
definition sigma_eq_equiv [constructor] (u v : Σa, B a)
: (u = v) ≃ (Σ(p : u.1 = v.1), u.2 =[p] v.2) :=
(equiv.mk sigma_eq_unc _)⁻¹ᵉ
definition dpair_eq_dpair_con (p1 : a = a' ) (q1 : b =[p1] b' )
(p2 : a' = a'') (q2 : b' =[p2] b'') :
dpair_eq_dpair (p1 ⬝ p2) (q1 ⬝o q2) = dpair_eq_dpair p1 q1 ⬝ dpair_eq_dpair p2 q2 :=
by induction q1; induction q2; reflexivity
definition sigma_eq_con (p1 : u.1 = v.1) (q1 : u.2 =[p1] v.2)
(p2 : v.1 = w.1) (q2 : v.2 =[p2] w.2) :
sigma_eq (p1 ⬝ p2) (q1 ⬝o q2) = sigma_eq p1 q1 ⬝ sigma_eq p2 q2 :=
by induction u; induction v; induction w; apply dpair_eq_dpair_con
local attribute dpair_eq_dpair [reducible]
definition dpair_eq_dpair_con_idp (p : a = a') (q : b =[p] b') :
dpair_eq_dpair p q = dpair_eq_dpair p !pathover_tr ⬝
dpair_eq_dpair idp (pathover_idp_of_eq (tr_eq_of_pathover q)) :=
by induction q; reflexivity
/- eq_pr1 commutes with the groupoid structure. -/
definition eq_pr1_idp (u : Σa, B a) : (refl u) ..1 = refl (u.1) := idp
definition eq_pr1_con (p : u = v) (q : v = w) : (p ⬝ q) ..1 = (p..1) ⬝ (q..1) := !ap_con
definition eq_pr1_inv (p : u = v) : p⁻¹ ..1 = (p..1)⁻¹ := !ap_inv
/- Applying dpair to one argument is the same as dpair_eq_dpair with reflexivity in the first place. -/
definition ap_dpair (q : b₁ = b₂) :
ap (sigma.mk a) q = dpair_eq_dpair idp (pathover_idp_of_eq q) :=
by induction q; reflexivity
/- Dependent transport is the same as transport along a sigma_eq. -/
definition transportD_eq_transport (p : a = a') (c : C a b) :
p ▸D c = transport (λu, C (u.1) (u.2)) (dpair_eq_dpair p !pathover_tr) c :=
by induction p; reflexivity
definition sigma_eq_eq_sigma_eq {p1 q1 : a = a'} {p2 : b =[p1] b'} {q2 : b =[q1] b'}
(r : p1 = q1) (s : p2 =[r] q2) : sigma_eq p1 p2 = sigma_eq q1 q2 :=
by induction s; reflexivity
/- A path between paths in a total space is commonly shown component wise. -/
definition sigma_eq2 {p q : u = v} (r : p..1 = q..1) (s : p..2 =[r] q..2)
: p = q :=
begin
induction p, induction u with u1 u2,
transitivity sigma_eq q..1 q..2,
apply sigma_eq_eq_sigma_eq r s,
apply sigma_eq_eta,
end
definition sigma_eq2_unc {p q : u = v} (rs : Σ(r : p..1 = q..1), p..2 =[r] q..2) : p = q :=
destruct rs sigma_eq2
definition ap_dpair_eq_dpair (f : Πa, B a → A') (p : a = a') (q : b =[p] b')
: ap (sigma.rec f) (dpair_eq_dpair p q) = apd011 f p q :=
by induction q; reflexivity
/- Transport -/
/- The concrete description of transport in sigmas (and also pis) is rather trickier than in the other types. In particular, these cannot be described just in terms of transport in simpler types; they require also the dependent transport [transportD].
In particular, this indicates why `transport` alone cannot be fully defined by induction on the structure of types, although Id-elim/transportD can be (cf. Observational Type Theory). A more thorough set of lemmas, along the lines of the present ones but dealing with Id-elim rather than just transport, might be nice to have eventually? -/
definition sigma_transport (p : a = a') (bc : Σ(b : B a), C a b)
: p ▸ bc = ⟨p ▸ bc.1, p ▸D bc.2⟩ :=
by induction p; induction bc; reflexivity
/- The special case when the second variable doesn't depend on the first is simpler. -/
definition sigma_transport_nondep {B : Type} {C : A → B → Type} (p : a = a')
(bc : Σ(b : B), C a b) : p ▸ bc = ⟨bc.1, p ▸ bc.2⟩ :=
by induction p; induction bc; reflexivity
/- Or if the second variable contains a first component that doesn't depend on the first. -/
definition sigma_transport2_nondep {C : A → Type} {D : Π a:A, B a → C a → Type} (p : a = a')
(bcd : Σ(b : B a) (c : C a), D a b c) : p ▸ bcd = ⟨p ▸ bcd.1, p ▸ bcd.2.1, p ▸D2 bcd.2.2⟩ :=
begin
induction p, induction bcd with b cd, induction cd, reflexivity
end
/- Pathovers -/
definition etao (p : a = a') (bc : Σ(b : B a), C a b)
: bc =[p] ⟨p ▸ bc.1, p ▸D bc.2⟩ :=
by induction p; induction bc; apply idpo
-- TODO: interchange sigma_pathover and sigma_pathover'
definition sigma_pathover (p : a = a') (u : Σ(b : B a), C a b) (v : Σ(b : B a'), C a' b)
(r : u.1 =[p] v.1) (s : u.2 =[apd011 C p r] v.2) : u =[p] v :=
begin
induction u, induction v, esimp at *, induction r,
esimp [apd011] at s, induction s using idp_rec_on, apply idpo
end
definition sigma_pathover' (p : a = a') (u : Σ(b : B a), C a b) (v : Σ(b : B a'), C a' b)
(r : u.1 =[p] v.1) (s : pathover (λx, C x.1 x.2) u.2 (sigma_eq p r) v.2) : u =[p] v :=
begin
induction u, induction v, esimp at *, induction r,
induction s using idp_rec_on, apply idpo
end
definition sigma_pathover_nondep {B : Type} {C : A → B → Type} (p : a = a')
(u : Σ(b : B), C a b) (v : Σ(b : B), C a' b)
(r : u.1 = v.1) (s : pathover (λx, C (prod.pr1 x) (prod.pr2 x)) u.2 (prod.prod_eq p r) v.2) : u =[p] v :=
begin
induction p, induction u, induction v, esimp at *, induction r,
induction s using idp_rec_on, apply idpo
end
definition pathover_pr1 [unfold 9] {A : Type} {B : A → Type} {C : Πa, B a → Type}
{a a' : A} {p : a = a'} {x : Σb, C a b} {x' : Σb', C a' b'}
(q : x =[p] x') : x.1 =[p] x'.1 :=
begin induction q, constructor end
/-
definition sigma_pathover_equiv_of_is_prop {A : Type} {B : A → Type} (C : Πa, B a → Type)
{a a' : A} (p : a = a') (x : Σb, C a b) (x' : Σb', C a' b')
[Πa b, is_prop (C a b)] : x =[p] x' ≃ x.1 =[p] x'.1 :=
begin
fapply equiv.MK,
{ exact pathover_pr1 },
{ intro q, induction x with b c, induction x' with b' c', esimp at q, induction q,
apply pathover_idp_of_eq, exact sigma_eq idp !is_prop.elimo },
{ intro q, induction x with b c, induction x' with b' c', esimp at q, induction q,
have c = c', from !is_prop.elim, induction this,
rewrite [▸*, is_prop_elimo_self (C a) c] },
{ intro q, induction q, induction x with b c, rewrite [▸*, is_prop_elimo_self (C a) c] }
end
-/
/-
TODO:
* define the projections from the type u =[p] v
* show that the uncurried version of sigma_pathover is an equivalence
-/
/- Squares in a sigma type are characterized in cubical.squareover (to avoid circular imports) -/
/- Functorial action -/
variables (f : A → A') (g : Πa, B a → B' (f a))
definition sigma_functor [unfold 7] (u : Σa, B a) : Σa', B' a' :=
⟨f u.1, g u.1 u.2⟩
definition total [reducible] [unfold 5] {B' : A → Type} (g : Πa, B a → B' a) : (Σa, B a) → (Σa, B' a) :=
sigma_functor id g
/- Equivalences -/
definition is_equiv_sigma_functor [constructor] [H1 : is_equiv f] [H2 : Π a, is_equiv (g a)]
: is_equiv (sigma_functor f g) :=
adjointify (sigma_functor f g)
(sigma_functor f⁻¹ (λ(a' : A') (b' : B' a'),
((g (f⁻¹ a'))⁻¹ (transport B' (right_inv f a')⁻¹ b'))))
abstract begin
intro u', induction u' with a' b',
apply sigma_eq (right_inv f a'),
rewrite [▸*,right_inv (g (f⁻¹ a')),▸*],
apply tr_pathover
end end
abstract begin
intro u,
induction u with a b,
apply (sigma_eq (left_inv f a)),
apply pathover_of_tr_eq,
rewrite [▸*,adj f,-(fn_tr_eq_tr_fn (left_inv f a) (λ a, (g a)⁻¹)),
▸*,tr_compose B' f,tr_inv_tr,left_inv]
end end
definition sigma_equiv_sigma_of_is_equiv [constructor]
[H1 : is_equiv f] [H2 : Π a, is_equiv (g a)] : (Σa, B a) ≃ (Σa', B' a') :=
equiv.mk (sigma_functor f g) !is_equiv_sigma_functor
definition sigma_equiv_sigma [constructor] (Hf : A ≃ A') (Hg : Π a, B a ≃ B' (to_fun Hf a)) :
(Σa, B a) ≃ (Σa', B' a') :=
sigma_equiv_sigma_of_is_equiv (to_fun Hf) (λ a, to_fun (Hg a))
definition sigma_equiv_sigma_right [constructor] {B' : A → Type} (Hg : Π a, B a ≃ B' a)
: (Σa, B a) ≃ Σa, B' a :=
sigma_equiv_sigma equiv.rfl Hg
definition sigma_equiv_sigma_left [constructor] (Hf : A ≃ A') :
(Σa, B a) ≃ (Σa', B (to_inv Hf a')) :=
sigma_equiv_sigma Hf (λ a, equiv_ap B !right_inv⁻¹)
definition sigma_equiv_sigma_left' [constructor] (Hf : A' ≃ A) : (Σa, B (Hf a)) ≃ (Σa', B a') :=
sigma_equiv_sigma Hf (λa, erfl)
definition ap_sigma_functor_eq_dpair (p : a = a') (q : b =[p] b') :
ap (sigma_functor f g) (sigma_eq p q) = sigma_eq (ap f p) (pathover.rec_on q idpo) :=
by induction q; reflexivity
definition sigma_ua {A B : Type} (C : A ≃ B → Type) :
(Σ(p : A = B), C (equiv_of_eq p)) ≃ Σ(e : A ≃ B), C e :=
sigma_equiv_sigma_left' !eq_equiv_equiv
-- definition ap_sigma_functor_eq (p : u.1 = v.1) (q : u.2 =[p] v.2)
-- : ap (sigma_functor f g) (sigma_eq p q) =
-- sigma_eq (ap f p)
-- ((tr_compose B' f p (g u.1 u.2))⁻¹ ⬝ (fn_tr_eq_tr_fn p g u.2)⁻¹ ⬝ ap (g v.1) q) :=
-- by induction u; induction v; apply ap_sigma_functor_eq_dpair
/- definition 3.11.9(i): Summing up a contractible family of types does nothing. -/
definition is_equiv_pr1 [instance] [constructor] (B : A → Type) [H : Π a, is_contr (B a)]
: is_equiv (@pr1 A B) :=
adjointify pr1
(λa, ⟨a, !center⟩)
(λa, idp)
(λu, sigma_eq idp (pathover_idp_of_eq !center_eq))
definition sigma_equiv_of_is_contr_right [constructor] [H : Π a, is_contr (B a)]
: (Σa, B a) ≃ A :=
equiv.mk pr1 _
/- definition 3.11.9(ii): Dually, summing up over a contractible type does nothing. -/
definition sigma_equiv_of_is_contr_left [constructor] (B : A → Type) [H : is_contr A]
: (Σa, B a) ≃ B (center A) :=
equiv.MK
(λu, (center_eq u.1)⁻¹ ▸ u.2)
(λb, ⟨!center, b⟩)
abstract (λb, ap (λx, x ▸ b) !prop_eq_of_is_contr) end
abstract (λu, sigma_eq !center_eq !tr_pathover) end
/- Associativity -/
--this proof is harder than in Coq because we don't have eta definitionally for sigma
definition sigma_assoc_equiv [constructor] (C : (Σa, B a) → Type)
: (Σa b, C ⟨a, b⟩) ≃ (Σu, C u) :=
equiv.mk _ (adjointify
(λav, ⟨⟨av.1, av.2.1⟩, av.2.2⟩)
(λuc, ⟨uc.1.1, uc.1.2, !sigma.eta⁻¹ ▸ uc.2⟩)
abstract begin intro uc, induction uc with u c, induction u, reflexivity end end
abstract begin intro av, induction av with a v, induction v, reflexivity end end)
open prod prod.ops
definition assoc_equiv_prod [constructor] (C : (A × A') → Type) : (Σa a', C (a,a')) ≃ (Σu, C u) :=
equiv.mk _ (adjointify
(λav, ⟨(av.1, av.2.1), av.2.2⟩)
(λuc, ⟨pr₁ (uc.1), pr₂ (uc.1), !prod.eta⁻¹ ▸ uc.2⟩)
abstract proof (λuc, destruct uc (λu, prod.destruct u (λa b c, idp))) qed end
abstract proof (λav, destruct av (λa v, destruct v (λb c, idp))) qed end)
/- Symmetry -/
definition comm_equiv_unc (C : A × A' → Type) : (Σa a', C (a, a')) ≃ (Σa' a, C (a, a')) :=
calc
(Σa a', C (a, a')) ≃ Σu, C u : assoc_equiv_prod
... ≃ Σv, C (flip v) : sigma_equiv_sigma !prod_comm_equiv
(λu, prod.destruct u (λa a', equiv.rfl))
... ≃ Σa' a, C (a, a') : assoc_equiv_prod
definition sigma_comm_equiv [constructor] (C : A → A' → Type)
: (Σa a', C a a') ≃ (Σa' a, C a a') :=
comm_equiv_unc (λu, C (prod.pr1 u) (prod.pr2 u))
definition equiv_prod [constructor] (A B : Type) : (Σ(a : A), B) ≃ A × B :=
equiv.mk _ (adjointify
(λs, (s.1, s.2))
(λp, ⟨pr₁ p, pr₂ p⟩)
proof (λp, prod.destruct p (λa b, idp)) qed
proof (λs, destruct s (λa b, idp)) qed)
definition comm_equiv_nondep (A B : Type) : (Σ(a : A), B) ≃ Σ(b : B), A :=
calc
(Σ(a : A), B) ≃ A × B : equiv_prod
... ≃ B × A : prod_comm_equiv
... ≃ Σ(b : B), A : equiv_prod
definition sigma_assoc_comm_equiv {A : Type} (B C : A → Type)
: (Σ(v : Σa, B a), C v.1) ≃ (Σ(u : Σa, C a), B u.1) :=
calc (Σ(v : Σa, B a), C v.1)
≃ (Σa (b : B a), C a) : sigma_assoc_equiv
... ≃ (Σa (c : C a), B a) : sigma_equiv_sigma_right (λa, !comm_equiv_nondep)
... ≃ (Σ(u : Σa, C a), B u.1) : sigma_assoc_equiv
/- Interaction with other type constructors -/
definition sigma_empty_left [constructor] (B : empty → Type) : (Σx, B x) ≃ empty :=
begin
fapply equiv.MK,
{ intro v, induction v, contradiction},
{ intro x, contradiction},
{ intro x, contradiction},
{ intro v, induction v, contradiction},
end
definition sigma_empty_right [constructor] (A : Type) : (Σ(a : A), empty) ≃ empty :=
begin
fapply equiv.MK,
{ intro v, induction v, contradiction},
{ intro x, contradiction},
{ intro x, contradiction},
{ intro v, induction v, contradiction},
end
definition sigma_unit_left [constructor] (B : unit → Type) : (Σx, B x) ≃ B star :=
!sigma_equiv_of_is_contr_left
definition sigma_unit_right [constructor] (A : Type) : (Σ(a : A), unit) ≃ A :=
!sigma_equiv_of_is_contr_right
definition sigma_sum_left [constructor] (B : A + A' → Type)
: (Σp, B p) ≃ (Σa, B (inl a)) + (Σa, B (inr a)) :=
begin
fapply equiv.MK,
{ intro v,
induction v with p b,
induction p,
{ apply inl, constructor, assumption },
{ apply inr, constructor, assumption }},
{ intro p, induction p with v v: induction v; constructor; assumption},
{ intro p, induction p with v v: induction v; reflexivity},
{ intro v, induction v with p b, induction p: reflexivity},
end
definition sigma_sum_right [constructor] (B C : A → Type)
: (Σa, B a + C a) ≃ (Σa, B a) + (Σa, C a) :=
begin
fapply equiv.MK,
{ intro v,
induction v with a p,
induction p,
{ apply inl, constructor, assumption},
{ apply inr, constructor, assumption}},
{ intro p,
induction p with v v,
{ induction v, constructor, apply inl, assumption },
{ induction v, constructor, apply inr, assumption }},
{ intro p, induction p with v v: induction v; reflexivity},
{ intro v, induction v with a p, induction p: reflexivity},
end
definition sigma_sigma_eq_right {A : Type} (a : A) (P : Π(b : A), a = b → Type)
: (Σ(b : A) (p : a = b), P b p) ≃ P a idp :=
calc
(Σ(b : A) (p : a = b), P b p) ≃ (Σ(v : Σ(b : A), a = b), P v.1 v.2) : sigma_assoc_equiv
... ≃ P a idp : !sigma_equiv_of_is_contr_left
definition sigma_sigma_eq_left {A : Type} (a : A) (P : Π(b : A), b = a → Type)
: (Σ(b : A) (p : b = a), P b p) ≃ P a idp :=
calc
(Σ(b : A) (p : b = a), P b p) ≃ (Σ(v : Σ(b : A), b = a), P v.1 v.2) : sigma_assoc_equiv
... ≃ P a idp : !sigma_equiv_of_is_contr_left
/- ** Universal mapping properties -/
/- *** The positive universal property. -/
section
definition is_equiv_sigma_rec [instance] (C : (Σa, B a) → Type)
: is_equiv (sigma.rec : (Πa b, C ⟨a, b⟩) → Πab, C ab) :=
adjointify _ (λ g a b, g ⟨a, b⟩)
(λ g, proof eq_of_homotopy (λu, destruct u (λa b, idp)) qed)
(λ f, refl f)
definition equiv_sigma_rec (C : (Σa, B a) → Type)
: (Π(a : A) (b: B a), C ⟨a, b⟩) ≃ (Πxy, C xy) :=
equiv.mk sigma.rec _
/- *** The negative universal property. -/
protected definition coind_unc (fg : Σ(f : Πa, B a), Πa, C a (f a)) (a : A)
: Σ(b : B a), C a b :=
⟨fg.1 a, fg.2 a⟩
protected definition coind (f : Π a, B a) (g : Π a, C a (f a)) (a : A) : Σ(b : B a), C a b :=
sigma.coind_unc ⟨f, g⟩ a
--is the instance below dangerous?
--in Coq this can be done without function extensionality
definition is_equiv_coind [instance] (C : Πa, B a → Type)
: is_equiv (@sigma.coind_unc _ _ C) :=
adjointify _ (λ h, ⟨λa, (h a).1, λa, (h a).2⟩)
(λ h, proof eq_of_homotopy (λu, !sigma.eta) qed)
(λfg, destruct fg (λ(f : Π (a : A), B a) (g : Π (x : A), C x (f x)), proof idp qed))
definition sigma_pi_equiv_pi_sigma : (Σ(f : Πa, B a), Πa, C a (f a)) ≃ (Πa, Σb, C a b) :=
equiv.mk sigma.coind_unc _
end
/- Subtypes (sigma types whose second components are props) -/
definition subtype [reducible] {A : Type} (P : A → Type) [H : Πa, is_prop (P a)] :=
Σ(a : A), P a
notation [parsing_only] `{` binder `|` r:(scoped:1 P, subtype P) `}` := r
/- To prove equality in a subtype, we only need equality of the first component. -/
definition subtype_eq [unfold_full] [H : Πa, is_prop (B a)] {u v : {a | B a}} :
u.1 = v.1 → u = v :=
sigma_eq_unc ∘ inv pr1
definition is_equiv_subtype_eq [constructor] [H : Πa, is_prop (B a)] (u v : {a | B a})
: is_equiv (subtype_eq : u.1 = v.1 → u = v) :=
!is_equiv_compose
local attribute is_equiv_subtype_eq [instance]
definition equiv_subtype [constructor] [H : Πa, is_prop (B a)] (u v : {a | B a}) :
(u.1 = v.1) ≃ (u = v) :=
equiv.mk !subtype_eq _
definition subtype_eq_equiv [constructor] [H : Πa, is_prop (B a)] (u v : {a | B a}) :
(u = v) ≃ (u.1 = v.1) :=
(equiv_subtype u v)⁻¹ᵉ
definition subtype_eq_inv {A : Type} {B : A → Type} [H : Πa, is_prop (B a)] (u v : Σa, B a)
: u = v → u.1 = v.1 :=
subtype_eq⁻¹ᶠ
local attribute subtype_eq_inv [reducible]
definition is_equiv_subtype_eq_inv {A : Type} {B : A → Type} [H : Πa, is_prop (B a)]
(u v : Σa, B a) : is_equiv (subtype_eq_inv u v) :=
_
/- truncatedness -/
theorem is_trunc_sigma (B : A → Type) (n : trunc_index)
[HA : is_trunc n A] [HB : Πa, is_trunc n (B a)] : is_trunc n (Σa, B a) :=
begin
revert A B HA HB,
induction n with n IH,
{ intro A B HA HB, fapply is_trunc_equiv_closed_rev, apply sigma_equiv_of_is_contr_left},
{ intro A B HA HB, apply is_trunc_succ_intro, intro u v,
apply is_trunc_equiv_closed_rev,
apply sigma_eq_equiv,
exact IH _ _ _ _}
end
theorem is_trunc_subtype (B : A → Prop) (n : trunc_index)
[HA : is_trunc (n.+1) A] : is_trunc (n.+1) (Σa, B a) :=
@(is_trunc_sigma B (n.+1)) _ (λa, !is_trunc_succ_of_is_prop)
/- if the total space is a mere proposition, you can equate two points in the base type by
finding points in their fibers -/
definition eq_base_of_is_prop_sigma {A : Type} (B : A → Type) (H : is_prop (Σa, B a)) {a a' : A}
(b : B a) (b' : B a') : a = a' :=
(is_prop.elim ⟨a, b⟩ ⟨a', b'⟩)..1
end sigma
attribute sigma.is_trunc_sigma [instance] [priority 1490]
attribute sigma.is_trunc_subtype [instance] [priority 1200]
namespace sigma
/- pointed sigma type -/
open pointed
definition pointed_sigma [instance] [constructor] {A : Type} (P : A → Type) [G : pointed A]
[H : pointed (P pt)] : pointed (Σx, P x) :=
pointed.mk ⟨pt,pt⟩
definition psigma [constructor] {A : Type*} (P : A → Type*) : Type* :=
pointed.mk' (Σa, P a)
notation `Σ*` binders `, ` r:(scoped P, psigma P) := r
definition ppr1 [constructor] {A : Type*} {B : A → Type*} : (Σ*(x : A), B x) →* A :=
pmap.mk pr1 idp
definition ppr2 [unfold_full] {A : Type*} {B : A → Type*} (v : (Σ*(x : A), B x)) : B (ppr1 v) :=
pr2 v
definition ptsigma [constructor] {n : ℕ₋₂} {A : n-Type*} (P : A → n-Type*) : n-Type* :=
ptrunctype.mk' n (Σa, P a)
end sigma
|
5f6afd8f1191ee7e713922b63fe001233f6ad8fe | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /tests/lean/run/vars_anywhere.lean | b7dd0179bed1f337c56fc34bdeb2f26181d289f6 | [
"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 | 138 | lean | variable {A : Type}
definition id (a : A) := a
check @id
inductive list :=
| nil : list
| cons : A → list → list
check @list.cons
|
ba059cdb1e8c874f8aa1f41085b16085060cbfe8 | bb31430994044506fa42fd667e2d556327e18dfe | /src/analysis/complex/locally_uniform_limit.lean | 549d05693862d2d082a7b4142bcaa0132d1bfeab | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 8,826 | lean | /-
Copyright (c) 2022 Vincent Beffara. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Vincent Beffara
-/
import analysis.complex.removable_singularity
import analysis.calculus.uniform_limits_deriv
/-!
# Locally uniform limits of holomorphic functions
This file gathers some results about locally uniform limits of holomorphic functions on an open
subset of the complex plane.
## Main results
* `tendsto_locally_uniformly_on.differentiable_on`: A locally uniform limit of holomorphic functions
is holomorphic.
* `tendsto_locally_uniformly_on.deriv`: Locally uniform convergence implies locally uniform
convergence of the derivatives to the derivative of the limit.
-/
open set metric measure_theory filter complex interval_integral
open_locale real topological_space
variables {E ι : Type*} [normed_add_comm_group E] [normed_space ℂ E] [complete_space E]
{U K : set ℂ} {z : ℂ} {M r δ : ℝ} {φ : filter ι} {F : ι → ℂ → E} {f g : ℂ → E}
namespace complex
section cderiv
/-- A circle integral which coincides with `deriv f z` whenever one can apply the Cauchy formula for
the derivative. It is useful in the proof that locally uniform limits of holomorphic functions are
holomorphic, because it depends continuously on `f` for the uniform topology. -/
noncomputable def cderiv (r : ℝ) (f : ℂ → E) (z : ℂ) : E :=
(2 * π * I : ℂ)⁻¹ • ∮ w in C(z, r), ((w - z) ^ 2)⁻¹ • f w
lemma cderiv_eq_deriv (hU : is_open U) (hf : differentiable_on ℂ f U) (hr : 0 < r)
(hzr : closed_ball z r ⊆ U) :
cderiv r f z = deriv f z :=
two_pi_I_inv_smul_circle_integral_sub_sq_inv_smul_of_differentiable hU hzr hf (mem_ball_self hr)
lemma norm_cderiv_le (hr : 0 < r) (hf : ∀ w ∈ sphere z r, ‖f w‖ ≤ M) :
‖cderiv r f z‖ ≤ M / r :=
begin
have hM : 0 ≤ M,
{ obtain ⟨w, hw⟩ : (sphere z r).nonempty := normed_space.sphere_nonempty.mpr hr.le,
exact (norm_nonneg _).trans (hf w hw) },
have h1 : ∀ w ∈ sphere z r, ‖((w - z) ^ 2)⁻¹ • f w‖ ≤ M / r ^ 2,
{ intros w hw,
simp only [mem_sphere_iff_norm, norm_eq_abs] at hw,
simp only [norm_smul, inv_mul_eq_div, hw, norm_eq_abs, map_inv₀, complex.abs_pow],
exact div_le_div hM (hf w hw) (sq_pos_of_pos hr) le_rfl },
have h2 := circle_integral.norm_integral_le_of_norm_le_const hr.le h1,
simp only [cderiv, norm_smul],
refine (mul_le_mul le_rfl h2 (norm_nonneg _) (norm_nonneg _)).trans (le_of_eq _),
field_simp [_root_.abs_of_nonneg real.pi_pos.le, real.pi_pos.ne.symm, hr.ne.symm],
ring
end
lemma cderiv_sub (hr : 0 < r) (hf : continuous_on f (sphere z r))
(hg : continuous_on g (sphere z r)) :
cderiv r (f - g) z = cderiv r f z - cderiv r g z :=
begin
have h1 : continuous_on (λ (w : ℂ), ((w - z) ^ 2)⁻¹) (sphere z r),
{ refine ((continuous_id'.sub continuous_const).pow 2).continuous_on.inv₀ (λ w hw h, hr.ne _),
rwa [mem_sphere_iff_norm, sq_eq_zero_iff.mp h, norm_zero] at hw },
simp_rw [cderiv, ← smul_sub],
congr' 1,
simpa only [pi.sub_apply, smul_sub] using circle_integral.integral_sub
((h1.smul hf).circle_integrable hr.le) ((h1.smul hg).circle_integrable hr.le)
end
lemma norm_cderiv_lt (hr : 0 < r) (hfM : ∀ w ∈ sphere z r, ‖f w‖ < M)
(hf : continuous_on f (sphere z r)) :
‖cderiv r f z‖ < M / r :=
begin
obtain ⟨L, hL1, hL2⟩ : ∃ L < M, ∀ w ∈ sphere z r, ‖f w‖ ≤ L,
{ have e1 : (sphere z r).nonempty := normed_space.sphere_nonempty.mpr hr.le,
have e2 : continuous_on (λ w, ‖f w‖) (sphere z r),
from continuous_norm.comp_continuous_on hf,
obtain ⟨x, hx, hx'⟩ := (is_compact_sphere z r).exists_forall_ge e1 e2,
exact ⟨‖f x‖, hfM x hx, hx'⟩ },
exact (norm_cderiv_le hr hL2).trans_lt ((div_lt_div_right hr).mpr hL1)
end
lemma norm_cderiv_sub_lt (hr : 0 < r) (hfg : ∀ w ∈ sphere z r, ‖f w - g w‖ < M)
(hf : continuous_on f (sphere z r)) (hg : continuous_on g (sphere z r)) :
‖cderiv r f z - cderiv r g z‖ < M / r :=
cderiv_sub hr hf hg ▸ norm_cderiv_lt hr hfg (hf.sub hg)
lemma tendsto_uniformly_on.cderiv (hF : tendsto_uniformly_on F f φ (cthickening δ K)) (hδ : 0 < δ)
(hFn : ∀ᶠ n in φ, continuous_on (F n) (cthickening δ K)) :
tendsto_uniformly_on (cderiv δ ∘ F) (cderiv δ f) φ K :=
begin
by_cases φ = ⊥,
{ simp only [h, tendsto_uniformly_on, eventually_bot, implies_true_iff]},
haveI : φ.ne_bot := ne_bot_iff.2 h,
have e1 : continuous_on f (cthickening δ K) := tendsto_uniformly_on.continuous_on hF hFn,
rw [tendsto_uniformly_on_iff] at hF ⊢,
rintro ε hε,
filter_upwards [hF (ε * δ) (mul_pos hε hδ), hFn] with n h h' z hz,
simp_rw [dist_eq_norm] at h ⊢,
have e2 : ∀ w ∈ sphere z δ, ‖f w - F n w‖ < ε * δ,
from λ w hw1, h w (closed_ball_subset_cthickening hz δ (sphere_subset_closed_ball hw1)),
have e3 := sphere_subset_closed_ball.trans (closed_ball_subset_cthickening hz δ),
have hf : continuous_on f (sphere z δ),
from e1.mono (sphere_subset_closed_ball.trans (closed_ball_subset_cthickening hz δ)),
simpa only [mul_div_cancel _ hδ.ne.symm] using norm_cderiv_sub_lt hδ e2 hf (h'.mono e3)
end
end cderiv
section weierstrass
lemma tendsto_uniformly_on_deriv_of_cthickening_subset (hf : tendsto_locally_uniformly_on F f φ U)
(hF : ∀ᶠ n in φ, differentiable_on ℂ (F n) U) {δ : ℝ} (hδ: 0 < δ) (hK : is_compact K)
(hU : is_open U) (hKU : cthickening δ K ⊆ U) :
tendsto_uniformly_on (deriv ∘ F) (cderiv δ f) φ K :=
begin
have h1 : ∀ᶠ n in φ, continuous_on (F n) (cthickening δ K),
by filter_upwards [hF] with n h using h.continuous_on.mono hKU,
have h2 : is_compact (cthickening δ K),
from is_compact_of_is_closed_bounded is_closed_cthickening hK.bounded.cthickening,
have h3 : tendsto_uniformly_on F f φ (cthickening δ K),
from (tendsto_locally_uniformly_on_iff_forall_is_compact hU).mp hf (cthickening δ K) hKU h2,
apply (h3.cderiv hδ h1).congr,
filter_upwards [hF] with n h z hz,
exact cderiv_eq_deriv hU h hδ ((closed_ball_subset_cthickening hz δ).trans hKU)
end
lemma exists_cthickening_tendsto_uniformly_on (hf : tendsto_locally_uniformly_on F f φ U)
(hF : ∀ᶠ n in φ, differentiable_on ℂ (F n) U) (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) :
∃ δ > 0, cthickening δ K ⊆ U ∧ tendsto_uniformly_on (deriv ∘ F) (cderiv δ f) φ K :=
begin
obtain ⟨δ, hδ, hKδ⟩ := hK.exists_cthickening_subset_open hU hKU,
exact ⟨δ, hδ, hKδ, tendsto_uniformly_on_deriv_of_cthickening_subset hf hF hδ hK hU hKδ⟩
end
/-- A locally uniform limit of holomorphic functions on an open domain of the complex plane is
holomorphic (the derivatives converge locally uniformly to that of the limit, which is proved
as `tendsto_locally_uniformly_on.deriv`). -/
theorem _root_.tendsto_locally_uniformly_on.differentiable_on [φ.ne_bot]
(hf : tendsto_locally_uniformly_on F f φ U) (hF : ∀ᶠ n in φ, differentiable_on ℂ (F n) U)
(hU : is_open U) :
differentiable_on ℂ f U :=
begin
rintro x hx,
obtain ⟨K, ⟨hKx, hK⟩, hKU⟩ := (compact_basis_nhds x).mem_iff.mp (hU.mem_nhds hx),
obtain ⟨δ, hδ, -, h1⟩ := exists_cthickening_tendsto_uniformly_on hf hF hK hU hKU,
have h2 : interior K ⊆ U := interior_subset.trans hKU,
have h3 : ∀ᶠ n in φ, differentiable_on ℂ (F n) (interior K),
filter_upwards [hF] with n h using h.mono h2,
have h4 : tendsto_locally_uniformly_on F f φ (interior K) := hf.mono h2,
have h5 : tendsto_locally_uniformly_on (deriv ∘ F) (cderiv δ f) φ (interior K),
from h1.tendsto_locally_uniformly_on.mono interior_subset,
have h6 : ∀ x ∈ interior K, has_deriv_at f (cderiv δ f x) x,
from λ x h, has_deriv_at_of_tendsto_locally_uniformly_on'
is_open_interior h5 h3 (λ _, h4.tendsto_at) h,
have h7 : differentiable_on ℂ f (interior K),
from λ x hx, (h6 x hx).differentiable_at.differentiable_within_at,
exact (h7.differentiable_at (interior_mem_nhds.mpr hKx)).differentiable_within_at
end
lemma _root_.tendsto_locally_uniformly_on.deriv (hf : tendsto_locally_uniformly_on F f φ U)
(hF : ∀ᶠ n in φ, differentiable_on ℂ (F n) U) (hU : is_open U) :
tendsto_locally_uniformly_on (deriv ∘ F) (deriv f) φ U :=
begin
rw [tendsto_locally_uniformly_on_iff_forall_is_compact hU],
by_cases φ = ⊥,
{ simp only [h, tendsto_uniformly_on, eventually_bot, implies_true_iff] },
haveI : φ.ne_bot := ne_bot_iff.2 h,
rintro K hKU hK,
obtain ⟨δ, hδ, hK4, h⟩ := exists_cthickening_tendsto_uniformly_on hf hF hK hU hKU,
refine h.congr_right (λ z hz, cderiv_eq_deriv hU (hf.differentiable_on hF hU) hδ _),
exact (closed_ball_subset_cthickening hz δ).trans hK4,
end
end weierstrass
end complex
|
d49390659b98758664a58036572212b73fbbe230 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/linear/basic.lean | 59a42152c08448f0807b78b79db835cb294de6d9 | [
"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 | 6,202 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.preadditive.basic
import algebra.module.linear_map
import algebra.invertible
import algebra.algebra.basic
/-!
# Linear categories
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
An `R`-linear category is a category in which `X ⟶ Y` is an `R`-module in such a way that
composition of morphisms is `R`-linear in both variables.
Note that sometimes in the literature a "linear category" is further required to be abelian.
## Implementation
Corresponding to the fact that we need to have an `add_comm_group X` structure in place
to talk about a `module R X` structure,
we need `preadditive C` as a prerequisite typeclass for `linear R C`.
This makes for longer signatures than would be ideal.
## Future work
It would be nice to have a usable framework of enriched categories in which this just became
a category enriched in `Module R`.
-/
universes w v u
open category_theory.limits
open linear_map
namespace category_theory
/-- A category is called `R`-linear if `P ⟶ Q` is an `R`-module such that composition is
`R`-linear in both variables. -/
class linear (R : Type w) [semiring R] (C : Type u) [category.{v} C] [preadditive C] :=
(hom_module : Π X Y : C, module R (X ⟶ Y) . tactic.apply_instance)
(smul_comp' : ∀ (X Y Z : C) (r : R) (f : X ⟶ Y) (g : Y ⟶ Z),
(r • f) ≫ g = r • (f ≫ g) . obviously)
(comp_smul' : ∀ (X Y Z : C) (f : X ⟶ Y) (r : R) (g : Y ⟶ Z),
f ≫ (r • g) = r • (f ≫ g) . obviously)
attribute [instance] linear.hom_module
restate_axiom linear.smul_comp'
restate_axiom linear.comp_smul'
attribute [simp,reassoc] linear.smul_comp
attribute [reassoc, simp] linear.comp_smul -- (the linter doesn't like `simp` on the `_assoc` lemma)
end category_theory
open category_theory
namespace category_theory.linear
variables {C : Type u} [category.{v} C] [preadditive C]
instance preadditive_nat_linear : linear ℕ C :=
{ smul_comp' := λ X Y Z r f g, (preadditive.right_comp X g).map_nsmul f r,
comp_smul' := λ X Y Z f r g, (preadditive.left_comp Z f).map_nsmul g r, }
instance preadditive_int_linear : linear ℤ C :=
{ smul_comp' := λ X Y Z r f g, (preadditive.right_comp X g).map_zsmul f r,
comp_smul' := λ X Y Z f r g, (preadditive.left_comp Z f).map_zsmul g r, }
section End
variables {R : Type w}
instance [semiring R] [linear R C] (X : C) : module R (End X) :=
by { dsimp [End], apply_instance, }
instance [comm_semiring R] [linear R C] (X : C) : algebra R (End X) :=
algebra.of_module (λ r f g, comp_smul _ _ _ _ _ _) (λ r f g, smul_comp _ _ _ _ _ _)
end End
section
variables {R : Type w} [semiring R] [linear R C]
section induced_category
universes u'
variables {C} {D : Type u'} (F : D → C)
instance induced_category : linear.{w v} R (induced_category C F) :=
{ hom_module := λ X Y, @linear.hom_module R _ C _ _ _ (F X) (F Y),
smul_comp' := λ P Q R f f' g, smul_comp' _ _ _ _ _ _,
comp_smul' := λ P Q R f g g', comp_smul' _ _ _ _ _ _, }
end induced_category
instance full_subcategory (Z : C → Prop) : linear.{w v} R (full_subcategory Z) :=
{ hom_module := λ X Y, @linear.hom_module R _ C _ _ _ X.obj Y.obj,
smul_comp' := λ P Q R f f' g, smul_comp' _ _ _ _ _ _,
comp_smul' := λ P Q R f g g', comp_smul' _ _ _ _ _ _, }
variables (R)
/-- Composition by a fixed left argument as an `R`-linear map. -/
@[simps]
def left_comp {X Y : C} (Z : C) (f : X ⟶ Y) : (Y ⟶ Z) →ₗ[R] (X ⟶ Z) :=
{ to_fun := λ g, f ≫ g,
map_add' := by simp,
map_smul' := by simp, }
/-- Composition by a fixed right argument as an `R`-linear map. -/
@[simps]
def right_comp (X : C) {Y Z : C} (g : Y ⟶ Z) : (X ⟶ Y) →ₗ[R] (X ⟶ Z) :=
{ to_fun := λ f, f ≫ g,
map_add' := by simp,
map_smul' := by simp, }
instance {X Y : C} (f : X ⟶ Y) [epi f] (r : R) [invertible r] : epi (r • f) :=
⟨λ R g g' H, begin
rw [smul_comp, smul_comp, ←comp_smul, ←comp_smul, cancel_epi] at H,
simpa [smul_smul] using congr_arg (λ f, ⅟r • f) H,
end⟩
instance {X Y : C} (f : X ⟶ Y) [mono f] (r : R) [invertible r] : mono (r • f) :=
⟨λ R g g' H, begin
rw [comp_smul, comp_smul, ←smul_comp, ←smul_comp, cancel_mono] at H,
simpa [smul_smul] using congr_arg (λ f, ⅟r • f) H,
end⟩
/-- Given isomorphic objects `X ≅ Y, W ≅ Z` in a `k`-linear category, we have a `k`-linear
isomorphism between `Hom(X, W)` and `Hom(Y, Z).` -/
def hom_congr (k : Type*) {C : Type*} [category C] [semiring k]
[preadditive C] [linear k C] {X Y W Z : C} (f₁ : X ≅ Y) (f₂ : W ≅ Z) :
(X ⟶ W) ≃ₗ[k] (Y ⟶ Z) :=
{ inv_fun := (left_comp k W f₁.hom).comp (right_comp k Y f₂.symm.hom),
left_inv := λ x, by simp only [iso.symm_hom, linear_map.to_fun_eq_coe, linear_map.coe_comp,
function.comp_app, left_comp_apply, right_comp_apply, category.assoc, iso.hom_inv_id,
category.comp_id, iso.hom_inv_id_assoc],
right_inv := λ x, by simp only [iso.symm_hom, linear_map.coe_comp, function.comp_app,
right_comp_apply, left_comp_apply, linear_map.to_fun_eq_coe, iso.inv_hom_id_assoc,
category.assoc, iso.inv_hom_id, category.comp_id],
..(right_comp k Y f₂.hom).comp (left_comp k W f₁.symm.hom) }
lemma hom_congr_apply (k : Type*) {C : Type*} [category C] [semiring k]
[preadditive C] [linear k C] {X Y W Z : C} (f₁ : X ≅ Y) (f₂ : W ≅ Z) (f : X ⟶ W) :
hom_congr k f₁ f₂ f = (f₁.inv ≫ f) ≫ f₂.hom := rfl
lemma hom_congr_symm_apply (k : Type*) {C : Type*} [category C] [semiring k]
[preadditive C] [linear k C] {X Y W Z : C} (f₁ : X ≅ Y) (f₂ : W ≅ Z) (f : Y ⟶ Z) :
(hom_congr k f₁ f₂).symm f = f₁.hom ≫ f ≫ f₂.inv := rfl
end
section
variables {S : Type w} [comm_semiring S] [linear S C]
/-- Composition as a bilinear map. -/
@[simps]
def comp (X Y Z : C) : (X ⟶ Y) →ₗ[S] ((Y ⟶ Z) →ₗ[S] (X ⟶ Z)) :=
{ to_fun := λ f, left_comp S Z f,
map_add' := by { intros, ext, simp, },
map_smul' := by { intros, ext, simp, }, }
end
end category_theory.linear
|
3ffa448e38339a6ee60deab8181b6e4417ae4680 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/exactErrorPos.lean | acbc74db057fcb754102f36d3bc9a9f8b386e867 | [
"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 | 923 | lean | set_option pp.rawOnError true
theorem ex1 (f : Nat → Nat) (x : Nat) (h1 : (x : Nat) → x > 0 → f x = x) (h2 : x > 0) : f x = x := by
exact h1 _ _
theorem ex2 (f : Nat → Nat) (x : Nat) (h1 : (x : Nat) → x > 0 → f x = x) (h2 : x > 0) : f x = x := by
refine h1 _ _
theorem ex3 (f : Nat → Nat) (x : Nat) (h1 : (x : Nat) → x > 0 → f x = x) (h2 : x > 0) : f x = x := by
first | exact h1 _ _ | apply h1
assumption
theorem ex4 (f : Nat → Nat) (x : Nat) (h1 : (x : Nat) → x > 0 → f x = x) (h2 : x > 0) : f x = x := by
first | refine h1 _ _ | apply h1
assumption
theorem ex5 (f g : Nat → Nat) (x : Nat) (h1 : (x : Nat) → x > 0 → f x = x) (h2 : x > 0) (h3 : g x = x) : f x = x := by
first | apply h3 | apply h1
assumption
theorem ex6 (f : Nat → Nat) (x : Nat) (h1 : (x : Nat) → x > 0 → f x = x) (h2 : x > 0) : f x = x := by
first | refine h1 _ _ | refine h1 _ _
assumption
|
9469f029090ab5faf911762c57ac11b5da578c9b | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/t13.lean | a4bbef515430116ccf79c10e51db5a8b6fbd30d9 | [
"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 | 318 | lean | variable A : Type.{1}
variable f : A → A → A
variable g : A → A → A
precedence `+` : 65
infixl + := f
infixl + := g
variable a : A
variable b : A
print raw a+b -- + is overloaded
check fun (h : A → A → A)
(infixl + := h), -- Like local declarations, local notation "shadows" global one.
a+b |
fe4394525e710bac0290be169b2d823d3286065c | aa5a655c05e5359a70646b7154e7cac59f0b4132 | /stage0/src/Init/Data/Range.lean | 6eaf97ad994de6ebffb21d1b3fcf5e7079bac483 | [
"Apache-2.0"
] | permissive | lambdaxymox/lean4 | ae943c960a42247e06eff25c35338268d07454cb | 278d47c77270664ef29715faab467feac8a0f446 | refs/heads/master | 1,677,891,867,340 | 1,612,500,005,000 | 1,612,500,005,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,527 | 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
-/
prelude
import Init.Meta
namespace Std
-- We put `Range` in `Init` because we want the notation `[i:j]` without importing `Std`
-- We don't put `Range` in the top-level namespace to avoid collisions with user defined types
structure Range where
start : Nat := 0
stop : Nat
step : Nat := 1
namespace Range
universes u v
@[inline] protected def forIn {β : Type u} {m : Type u → Type v} [Monad m] (range : Range) (init : β) (f : Nat → β → m (ForInStep β)) : m β :=
let rec @[specialize] loop (i : Nat) (j : Nat) (b : β) : m β := do
if j ≥ range.stop then
pure b
else match i with
| 0 => pure b
| i+1 => match ← f j b with
| ForInStep.done b => pure b
| ForInStep.yield b => loop i (j + range.step) b
loop range.stop range.start init
instance : ForIn m Range Nat where
forIn := Range.forIn
syntax:max "[" ":" term "]" : term
syntax:max "[" term ":" term "]" : term
syntax:max "[" ":" term ":" term "]" : term
syntax:max "[" term ":" term ":" term "]" : term
macro_rules
| `([ : $stop]) => `({ stop := $stop : Range })
| `([ $start : $stop ]) => `({ start := $start, stop := $stop : Range })
| `([ $start : $stop : $step ]) => `({ start := $start, stop := $stop, step := $step : Range })
| `([ : $stop : $step ]) => `({ stop := $stop, step := $step : Range })
end Range
end Std
|
670d0d7d24653302970d7b13d54fe5ff900d96fc | 6afa22d5eee6e9a56b6a2f1210eca8f7a1067466 | /tests/lean/widget/widget3.lean | 8423666d3b3f306bd2d9b2f5b898db30b4181e9e | [
"Apache-2.0"
] | permissive | giordano/lean | 72a1fabfeb2f1ccfd38673e2719a719cd6ffbb40 | 56f8877f1efa22215aca0b82f1c0ce2ff975b9c3 | refs/heads/master | 1,663,091,511,168 | 1,590,688,082,000 | 1,590,688,082,000 | 268,183,678 | 0 | 0 | Apache-2.0 | 1,590,885,425,000 | 1,590,885,424,000 | null | UTF-8 | Lean | false | false | 558 | lean |
open widget
meta def asdf_c (message : list string) : component nat empty :=
widget.component.mk
unit
(list nat)
(λ p s, p :: ([] <| s))
(λ p ls x, (ls,none))
(λ p ss, [h "div" [] [html.of_string $ to_string p ++ to_string message ++ to_string ss], button "asdf" ()])
(λ p1 p2, ff)
meta def qwerty_c : component tactic_state string :=
widget.component.mk
unit
nat
(λ p s,(0) <| s)
(λ p ls ⟨⟩, ⟨ls + 1, none⟩)
(λ p s, [to_string s, button "+" (), html.of_component s (asdf_c [" *** "])])
(λ x y, ff)
#html qwerty_c
|
e1d6715a86507ca7c359d10aff32bf560d796893 | 97c8e5d8aca4afeebb5b335f26a492c53680efc8 | /ground_zero/cubical/example.lean | 82550ef492bddbdb9bb3fe42baf5321ea6b390be | [] | no_license | jfrancese/lean | cf32f0d8d5520b6f0e9d3987deb95841c553c53c | 06e7efaecce4093d97fb5ecc75479df2ef1dbbdb | refs/heads/master | 1,587,915,151,351 | 1,551,012,140,000 | 1,551,012,140,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,381 | lean | import ground_zero.cubical
open ground_zero.cubical
/-
This example on Lean.
https://tonpa.guru/stream/2017/2017-10-31%20Доказательство%20коммутативности%20в%20кубике.txt
-/
namespace ground_zero.cubical.cubicaltt
def add (m : ℕ) : ℕ → ℕ
| 0 := m
| (n + 1) := nat.succ (add n)
def add_zero : Π (a : ℕ), add nat.zero a ⇝ a
| 0 := <i> nat.zero
| (a + 1) := <i> nat.succ (add_zero a # i)
def add_succ (a : ℕ) : Π (b : ℕ), add (nat.succ a) b ⇝ nat.succ (add a b)
| 0 := <i> nat.succ a
| (b + 1) := <i> nat.succ (add_succ b # i)
def add_zero_inv : Π (a : ℕ), a ⇝ add a nat.zero :=
Path.refl
def add_comm (a : ℕ) : Π (b : ℕ), add a b ⇝ add b a
| 0 := <i> (add_zero a) # −i
| (b + 1) := Path.kan
(<i> nat.succ (add_comm b # i))
(<j> nat.succ (add a b))
(<j> add_succ b a # −j)
def add_assoc (a b : ℕ) : Π (c : ℕ), add a (add b c) ⇝ add (add a b) c
| 0 := <i> add a b
| (c + 1) := <i> nat.succ (add_assoc c # i)
def add_comm₃ {a b c : ℕ} : add a (add b c) ⇝ add c (add b a) :=
let r : add a (add b c) ⇝ add a (add c b) :=
<i> add a (add_comm b c # i) in
Path.kan (add_comm a (add c b))
(<j> r # −j) (<j> add_assoc c b a # −j)
example (n m : ℕ) (h : n ⇝ m) : nat.succ n ⇝ nat.succ m :=
<i> nat.succ (h # i)
end ground_zero.cubical.cubicaltt |
1257a99dca97eb120da4899399fdf87ad4b73cb6 | 3f7026ea8bef0825ca0339a275c03b911baef64d | /src/algebra/ordered_ring.lean | be4463b50edfc4f8179b7bfdbeb0048be0883674 | [
"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 | 20,148 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import tactic.split_ifs order.basic algebra.order algebra.ordered_group algebra.ring data.nat.cast
universe u
variable {α : Type u}
-- TODO: this is necessary additionally to mul_nonneg otherwise the simplifier can not match
lemma zero_le_mul [ordered_semiring α] {a b : α} : 0 ≤ a → 0 ≤ b → 0 ≤ a * b :=
mul_nonneg
section linear_ordered_semiring
variable [linear_ordered_semiring α]
@[simp] lemma mul_le_mul_left {a b c : α} (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b :=
⟨λ h', le_of_mul_le_mul_left h' h, λ h', mul_le_mul_of_nonneg_left h' (le_of_lt h)⟩
@[simp] lemma mul_le_mul_right {a b c : α} (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b :=
⟨λ h', le_of_mul_le_mul_right h' h, λ h', mul_le_mul_of_nonneg_right h' (le_of_lt h)⟩
@[simp] lemma mul_lt_mul_left {a b c : α} (h : 0 < c) : c * a < c * b ↔ a < b :=
⟨lt_imp_lt_of_le_imp_le $ λ h', mul_le_mul_of_nonneg_left h' (le_of_lt h),
λ h', mul_lt_mul_of_pos_left h' h⟩
@[simp] lemma mul_lt_mul_right {a b c : α} (h : 0 < c) : a * c < b * c ↔ a < b :=
⟨lt_imp_lt_of_le_imp_le $ λ h', mul_le_mul_of_nonneg_right h' (le_of_lt h),
λ h', mul_lt_mul_of_pos_right h' h⟩
lemma mul_lt_mul'' {a b c d : α} (h1 : a < c) (h2 : b < d) (h3 : 0 ≤ a) (h4 : 0 ≤ b) :
a * b < c * d :=
(lt_or_eq_of_le h4).elim
(λ b0, mul_lt_mul h1 (le_of_lt h2) b0 (le_trans h3 (le_of_lt h1)))
(λ b0, by rw [← b0, mul_zero]; exact
mul_pos (lt_of_le_of_lt h3 h1) (lt_of_le_of_lt h4 h2))
lemma le_mul_iff_one_le_left {a b : α} (hb : b > 0) : b ≤ a * b ↔ 1 ≤ a :=
suffices 1 * b ≤ a * b ↔ 1 ≤ a, by rwa one_mul at this,
mul_le_mul_right hb
lemma lt_mul_iff_one_lt_left {a b : α} (hb : b > 0) : b < a * b ↔ 1 < a :=
suffices 1 * b < a * b ↔ 1 < a, by rwa one_mul at this,
mul_lt_mul_right hb
lemma le_mul_iff_one_le_right {a b : α} (hb : b > 0) : b ≤ b * a ↔ 1 ≤ a :=
suffices b * 1 ≤ b * a ↔ 1 ≤ a, by rwa mul_one at this,
mul_le_mul_left hb
lemma lt_mul_iff_one_lt_right {a b : α} (hb : b > 0) : b < b * a ↔ 1 < a :=
suffices b * 1 < b * a ↔ 1 < a, by rwa mul_one at this,
mul_lt_mul_left hb
lemma lt_mul_of_gt_one_right' {a b : α} (hb : b > 0) : a > 1 → b < b * a :=
(lt_mul_iff_one_lt_right hb).2
lemma le_mul_of_ge_one_right' {a b : α} (hb : b ≥ 0) (h : a ≥ 1) : b ≤ b * a :=
suffices b * 1 ≤ b * a, by rwa mul_one at this,
mul_le_mul_of_nonneg_left h hb
lemma le_mul_of_ge_one_left' {a b : α} (hb : b ≥ 0) (h : a ≥ 1) : b ≤ a * b :=
suffices 1 * b ≤ a * b, by rwa one_mul at this,
mul_le_mul_of_nonneg_right h hb
theorem mul_nonneg_iff_right_nonneg_of_pos {a b : α} (h : 0 < a) : 0 ≤ b * a ↔ 0 ≤ b :=
⟨assume : 0 ≤ b * a, nonneg_of_mul_nonneg_right this h, assume : 0 ≤ b, mul_nonneg this $ le_of_lt h⟩
lemma bit1_pos {a : α} (h : 0 ≤ a) : 0 < bit1 a :=
lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one
lemma bit1_pos' {a : α} (h : 0 < a) : 0 < bit1 a :=
bit1_pos (le_of_lt h)
lemma lt_add_one (a : α) : a < a + 1 :=
lt_add_of_le_of_pos (le_refl _) zero_lt_one
lemma one_lt_two : 1 < (2 : α) := lt_add_one _
lemma one_lt_mul {a b : α} (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b :=
(one_mul (1 : α)) ▸ mul_lt_mul' ha hb zero_le_one (lt_of_lt_of_le zero_lt_one ha)
lemma mul_le_one {a b : α} (ha : a ≤ 1) (hb' : 0 ≤ b) (hb : b ≤ 1) : a * b ≤ 1 :=
begin rw ← one_mul (1 : α), apply mul_le_mul; {assumption <|> apply zero_le_one} end
lemma one_lt_mul_of_le_of_lt {a b : α} (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b :=
calc 1 = 1 * 1 : by rw one_mul
... < a * b : mul_lt_mul' ha hb zero_le_one (lt_of_lt_of_le zero_lt_one ha)
lemma one_lt_mul_of_lt_of_le {a b : α} (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b :=
calc 1 = 1 * 1 : by rw one_mul
... < a * b : mul_lt_mul ha hb zero_lt_one (le_trans zero_le_one (le_of_lt ha))
lemma mul_le_of_le_one_right {a b : α} (ha : 0 ≤ a) (hb1 : b ≤ 1) : a * b ≤ a :=
calc a * b ≤ a * 1 : mul_le_mul_of_nonneg_left hb1 ha
... = a : mul_one a
lemma mul_le_of_le_one_left {a b : α} (hb : 0 ≤ b) (ha1 : a ≤ 1) : a * b ≤ b :=
calc a * b ≤ 1 * b : mul_le_mul ha1 (le_refl b) hb zero_le_one
... = b : one_mul b
lemma mul_lt_one_of_nonneg_of_lt_one_left {a b : α}
(ha0 : 0 ≤ a) (ha : a < 1) (hb : b ≤ 1) : a * b < 1 :=
calc a * b ≤ a : mul_le_of_le_one_right ha0 hb
... < 1 : ha
lemma mul_lt_one_of_nonneg_of_lt_one_right {a b : α}
(ha : a ≤ 1) (hb0 : 0 ≤ b) (hb : b < 1) : a * b < 1 :=
calc a * b ≤ b : mul_le_of_le_one_left hb0 ha
... < 1 : hb
lemma mul_le_iff_le_one_left {a b : α} (hb : b > 0) : a * b ≤ b ↔ a ≤ 1 :=
⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).2 (not_lt_of_ge h)),
λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).1 (not_lt_of_ge h)) ⟩
lemma mul_lt_iff_lt_one_left {a b : α} (hb : b > 0) : a * b < b ↔ a < 1 :=
⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).2 (not_le_of_gt h)),
λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).1 (not_le_of_gt h)) ⟩
lemma mul_le_iff_le_one_right {a b : α} (hb : b > 0) : b * a ≤ b ↔ a ≤ 1 :=
⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).2 (not_lt_of_ge h)),
λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).1 (not_lt_of_ge h)) ⟩
lemma mul_lt_iff_lt_one_right {a b : α} (hb : b > 0) : b * a < b ↔ a < 1 :=
⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).2 (not_le_of_gt h)),
λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).1 (not_le_of_gt h)) ⟩
lemma nonpos_of_mul_nonneg_left {a b : α} (h : 0 ≤ a * b) (hb : b < 0) : a ≤ 0 :=
le_of_not_gt (λ ha, absurd h (not_le_of_gt (mul_neg_of_pos_of_neg ha hb)))
lemma nonpos_of_mul_nonneg_right {a b : α} (h : 0 ≤ a * b) (ha : a < 0) : b ≤ 0 :=
le_of_not_gt (λ hb, absurd h (not_le_of_gt (mul_neg_of_neg_of_pos ha hb)))
lemma neg_of_mul_pos_left {a b : α} (h : 0 < a * b) (hb : b ≤ 0) : a < 0 :=
lt_of_not_ge (λ ha, absurd h (not_lt_of_ge (mul_nonpos_of_nonneg_of_nonpos ha hb)))
lemma neg_of_mul_pos_right {a b : α} (h : 0 < a * b) (ha : a ≤ 0) : b < 0 :=
lt_of_not_ge (λ hb, absurd h (not_lt_of_ge (mul_nonpos_of_nonpos_of_nonneg ha hb)))
end linear_ordered_semiring
section decidable_linear_ordered_semiring
variable [decidable_linear_ordered_semiring α]
@[simp] lemma decidable.mul_le_mul_left {a b c : α} (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b :=
decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_left h
@[simp] lemma decidable.mul_le_mul_right {a b c : α} (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b :=
decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_right h
end decidable_linear_ordered_semiring
instance linear_ordered_semiring.to_no_top_order {α : Type*} [linear_ordered_semiring α] :
no_top_order α :=
⟨assume a, ⟨a + 1, lt_add_of_pos_right _ zero_lt_one⟩⟩
instance linear_ordered_semiring.to_no_bot_order {α : Type*} [linear_ordered_ring α] :
no_bot_order α :=
⟨assume a, ⟨a - 1, sub_lt_iff_lt_add.mpr $ lt_add_of_pos_right _ zero_lt_one⟩⟩
instance to_domain [s : linear_ordered_ring α] : domain α :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_ring.eq_zero_or_eq_zero_of_mul_eq_zero α s,
..s }
section linear_ordered_ring
variable [linear_ordered_ring α]
@[simp] lemma mul_le_mul_left_of_neg {a b c : α} (h : c < 0) : c * a ≤ c * b ↔ b ≤ a :=
⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_left h' h,
λ h', mul_le_mul_of_nonpos_left h' (le_of_lt h)⟩
@[simp] lemma mul_le_mul_right_of_neg {a b c : α} (h : c < 0) : a * c ≤ b * c ↔ b ≤ a :=
⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_right h' h,
λ h', mul_le_mul_of_nonpos_right h' (le_of_lt h)⟩
@[simp] lemma mul_lt_mul_left_of_neg {a b c : α} (h : c < 0) : c * a < c * b ↔ b < a :=
lt_iff_lt_of_le_iff_le (mul_le_mul_left_of_neg h)
@[simp] lemma mul_lt_mul_right_of_neg {a b c : α} (h : c < 0) : a * c < b * c ↔ b < a :=
lt_iff_lt_of_le_iff_le (mul_le_mul_right_of_neg h)
lemma sub_one_lt (a : α) : a - 1 < a :=
sub_lt_iff_lt_add.2 (lt_add_one a)
lemma mul_self_pos {a : α} (ha : a ≠ 0) : 0 < a * a :=
by rcases lt_trichotomy a 0 with h|h|h;
[exact mul_pos_of_neg_of_neg h h, exact (ha h).elim, exact mul_pos h h]
lemma mul_self_le_mul_self_of_le_of_neg_le {x y : α} (h₁ : x ≤ y) (h₂ : -x ≤ y) : x * x ≤ y * y :=
begin
cases le_total 0 x,
{ exact mul_self_le_mul_self h h₁ },
{ rw ← neg_mul_neg, exact mul_self_le_mul_self (neg_nonneg_of_nonpos h) h₂ }
end
lemma nonneg_of_mul_nonpos_left {a b : α} (h : a * b ≤ 0) (hb : b < 0) : 0 ≤ a :=
le_of_not_gt (λ ha, absurd h (not_le_of_gt (mul_pos_of_neg_of_neg ha hb)))
lemma nonneg_of_mul_nonpos_right {a b : α} (h : a * b ≤ 0) (ha : a < 0) : 0 ≤ b :=
le_of_not_gt (λ hb, absurd h (not_le_of_gt (mul_pos_of_neg_of_neg ha hb)))
lemma pos_of_mul_neg_left {a b : α} (h : a * b < 0) (hb : b ≤ 0) : 0 < a :=
lt_of_not_ge (λ ha, absurd h (not_lt_of_ge (mul_nonneg_of_nonpos_of_nonpos ha hb)))
lemma pos_of_mul_neg_right {a b : α} (h : a * b < 0) (ha : a ≤ 0) : 0 < b :=
lt_of_not_ge (λ hb, absurd h (not_lt_of_ge (mul_nonneg_of_nonpos_of_nonpos ha hb)))
/- The sum of two squares is zero iff both elements are zero. -/
lemma mul_self_add_mul_self_eq_zero {x y : α} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 :=
begin
split; intro h, swap, { rcases h with ⟨rfl, rfl⟩, simp },
have : y * y ≤ 0, { rw [← h], apply le_add_of_nonneg_left (mul_self_nonneg x) },
have : y * y = 0 := le_antisymm this (mul_self_nonneg y),
have hx : x = 0, { rwa [this, add_zero, mul_self_eq_zero] at h },
rw mul_self_eq_zero at this, split; assumption
end
end linear_ordered_ring
set_option old_structure_cmd true
/-- Extend `nonneg_comm_group` to support ordered rings
specified by their nonnegative elements -/
class nonneg_ring (α : Type*)
extends ring α, zero_ne_one_class α, nonneg_comm_group α :=
(mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b))
(mul_pos : ∀ {a b}, pos a → pos b → pos (a * b))
/-- Extend `nonneg_comm_group` to support linearly ordered rings
specified by their nonnegative elements -/
class linear_nonneg_ring (α : Type*) extends domain α, nonneg_comm_group α :=
(mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b))
(nonneg_total : ∀ a, nonneg a ∨ nonneg (-a))
namespace nonneg_ring
open nonneg_comm_group
variable [s : nonneg_ring α]
instance to_ordered_ring : ordered_ring α :=
{ le := (≤),
lt := (<),
lt_iff_le_not_le := @lt_iff_le_not_le _ _,
le_refl := @le_refl _ _,
le_trans := @le_trans _ _,
le_antisymm := @le_antisymm _ _,
add_lt_add_left := @add_lt_add_left _ _,
add_le_add_left := @add_le_add_left _ _,
mul_nonneg := λ a b, by simp [nonneg_def.symm]; exact mul_nonneg,
mul_pos := λ a b, by simp [pos_def.symm]; exact mul_pos,
..s }
def nonneg_ring.to_linear_nonneg_ring
(nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a))
: linear_nonneg_ring α :=
{ nonneg_total := nonneg_total,
eq_zero_or_eq_zero_of_mul_eq_zero :=
suffices ∀ {a} b : α, nonneg a → a * b = 0 → a = 0 ∨ b = 0,
from λ a b, (nonneg_total a).elim (this b)
(λ na, by simpa using this b na),
suffices ∀ {a b : α}, nonneg a → nonneg b → a * b = 0 → a = 0 ∨ b = 0,
from λ a b na, (nonneg_total b).elim (this na)
(λ nb, by simpa using this na nb),
λ a b na nb z, classical.by_cases
(λ nna : nonneg (-a), or.inl (nonneg_antisymm na nna))
(λ pa, classical.by_cases
(λ nnb : nonneg (-b), or.inr (nonneg_antisymm nb nnb))
(λ pb, absurd z $ ne_of_gt $ pos_def.1 $ mul_pos
((pos_iff _ _).2 ⟨na, pa⟩)
((pos_iff _ _).2 ⟨nb, pb⟩))),
..s }
end nonneg_ring
namespace linear_nonneg_ring
open nonneg_comm_group
variable [s : linear_nonneg_ring α]
instance to_nonneg_ring : nonneg_ring α :=
{ mul_pos := λ a b pa pb,
let ⟨a1, a2⟩ := (pos_iff α a).1 pa,
⟨b1, b2⟩ := (pos_iff α b).1 pb in
have ab : nonneg (a * b), from mul_nonneg a1 b1,
(pos_iff α _).2 ⟨ab, λ hn,
have a * b = 0, from nonneg_antisymm ab hn,
(eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).elim
(ne_of_gt (pos_def.1 pa))
(ne_of_gt (pos_def.1 pb))⟩,
..s }
instance to_linear_order : linear_order α :=
{ le := (≤),
lt := (<),
lt_iff_le_not_le := @lt_iff_le_not_le _ _,
le_refl := @le_refl _ _,
le_trans := @le_trans _ _,
le_antisymm := @le_antisymm _ _,
le_total := nonneg_total_iff.1 nonneg_total,
..s }
instance to_linear_ordered_ring : linear_ordered_ring α :=
{ le := (≤),
lt := (<),
lt_iff_le_not_le := @lt_iff_le_not_le _ _,
le_refl := @le_refl _ _,
le_trans := @le_trans _ _,
le_antisymm := @le_antisymm _ _,
le_total := @le_total _ _,
add_lt_add_left := @add_lt_add_left _ _,
add_le_add_left := @add_le_add_left _ _,
mul_nonneg := by simp [nonneg_def.symm]; exact @mul_nonneg _ _,
mul_pos := by simp [pos_def.symm]; exact @nonneg_ring.mul_pos _ _,
zero_lt_one := lt_of_not_ge $ λ (h : nonneg (0 - 1)), begin
rw [zero_sub] at h,
have := mul_nonneg h h, simp at this,
exact zero_ne_one _ (nonneg_antisymm this h).symm
end, ..s }
instance to_decidable_linear_ordered_comm_ring
[decidable_pred (@nonneg α _)]
[comm : @is_commutative α (*)]
: decidable_linear_ordered_comm_ring α :=
{ decidable_le := by apply_instance,
decidable_eq := by apply_instance,
decidable_lt := by apply_instance,
mul_comm := is_commutative.comm (*),
..@linear_nonneg_ring.to_linear_ordered_ring _ s }
end linear_nonneg_ring
class canonically_ordered_comm_semiring (α : Type*) extends
canonically_ordered_monoid α, comm_semiring α, zero_ne_one_class α :=
(mul_eq_zero_iff (a b : α) : a * b = 0 ↔ a = 0 ∨ b = 0)
namespace canonically_ordered_semiring
open canonically_ordered_monoid
lemma mul_le_mul [canonically_ordered_comm_semiring α] {a b c d : α} (hab : a ≤ b) (hcd : c ≤ d) :
a * c ≤ b * d :=
begin
rcases (le_iff_exists_add _ _).1 hab with ⟨b, rfl⟩,
rcases (le_iff_exists_add _ _).1 hcd with ⟨d, rfl⟩,
suffices : a * c ≤ a * c + (a * d + b * c + b * d), by simpa [mul_add, add_mul],
exact (le_iff_exists_add _ _).2 ⟨_, rfl⟩
end
end canonically_ordered_semiring
instance : canonically_ordered_comm_semiring ℕ :=
{ le_iff_exists_add := assume a b,
⟨assume h, let ⟨c, hc⟩ := nat.le.dest h in ⟨c, hc.symm⟩,
assume ⟨c, hc⟩, hc.symm ▸ nat.le_add_right _ _⟩,
zero_ne_one := ne_of_lt zero_lt_one,
mul_eq_zero_iff := assume a b,
iff.intro nat.eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}),
bot := 0,
bot_le := nat.zero_le,
.. (infer_instance : ordered_comm_monoid ℕ),
.. (infer_instance : linear_ordered_semiring ℕ),
.. (infer_instance : comm_semiring ℕ) }
namespace with_top
variables [canonically_ordered_comm_semiring α] [decidable_eq α]
instance : mul_zero_class (with_top α) :=
{ zero := 0,
mul := λm n, if m = 0 ∨ n = 0 then 0 else m.bind (λa, n.bind $ λb, ↑(a * b)),
zero_mul := assume a, if_pos $ or.inl rfl,
mul_zero := assume a, if_pos $ or.inr rfl }
instance : has_one (with_top α) := ⟨↑(1:α)⟩
lemma mul_def {a b : with_top α} :
a * b = if a = 0 ∨ b = 0 then 0 else a.bind (λa, b.bind $ λb, ↑(a * b)) := rfl
@[simp] theorem top_ne_zero [partial_order α] : ⊤ ≠ (0 : with_top α) .
@[simp] theorem zero_ne_top [partial_order α] : (0 : with_top α) ≠ ⊤ .
@[simp] theorem coe_eq_zero [partial_order α] {a : α} : (a : with_top α) = 0 ↔ a = 0 :=
iff.intro
(assume h, match a, h with _, rfl := rfl end)
(assume h, h.symm ▸ rfl)
@[simp] theorem zero_eq_coe [partial_order α] {a : α} : 0 = (a : with_top α) ↔ a = 0 :=
by rw [eq_comm, coe_eq_zero]
@[simp] theorem coe_zero [partial_order α] : ↑(0 : α) = (0 : with_top α) := rfl
@[simp] lemma mul_top {a : with_top α} (h : a ≠ 0) : a * ⊤ = ⊤ :=
by cases a; simp [mul_def, h]; refl
@[simp] lemma top_mul {a : with_top α} (h : a ≠ 0) : ⊤ * a = ⊤ :=
by cases a; simp [mul_def, h]; refl
@[simp] lemma top_mul_top : (⊤ * ⊤ : with_top α) = ⊤ :=
top_mul top_ne_zero
lemma coe_mul {a b : α} : (↑(a * b) : with_top α) = a * b :=
decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha,
decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb,
by simp [*, mul_def]; refl
lemma mul_coe {b : α} (hb : b ≠ 0) : ∀{a : with_top α}, a * b = a.bind (λa:α, ↑(a * b))
| none := show (if (⊤:with_top α) = 0 ∨ (b:with_top α) = 0 then 0 else ⊤ : with_top α) = ⊤,
by simp [hb]
| (some a) := show ↑a * ↑b = ↑(a * b), from coe_mul.symm
private lemma comm (a b : with_top α) : a * b = b * a :=
begin
by_cases ha : a = 0, { simp [ha] },
by_cases hb : b = 0, { simp [hb] },
simp [ha, hb, mul_def, option.bind_comm a b, mul_comm]
end
@[simp] lemma mul_eq_top_iff {a b : with_top α} : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) :=
begin
have H : ∀x:α, (¬x = 0) ↔ (⊤ : with_top α) * ↑x = ⊤ :=
λx, ⟨λhx, by simp [top_mul, hx], λhx f, by simpa [f] using hx⟩,
cases a; cases b; simp [none_eq_top, top_mul, coe_ne_top, some_eq_coe, coe_mul.symm],
{ rw [H b] },
{ rw [H a, comm] }
end
private lemma distrib' (a b c : with_top α) : (a + b) * c = a * c + b * c :=
begin
cases c,
{ show (a + b) * ⊤ = a * ⊤ + b * ⊤,
by_cases ha : a = 0; simp [ha] },
{ show (a + b) * c = a * c + b * c,
by_cases hc : c = 0, { simp [hc] },
simp [mul_coe hc], cases a; cases b,
repeat { refl <|> exact congr_arg some (add_mul _ _ _) } }
end
private lemma mul_eq_zero (a b : with_top α) : a * b = 0 ↔ a = 0 ∨ b = 0 :=
by cases a; cases b; dsimp [mul_def]; split_ifs;
simp [*, none_eq_top, some_eq_coe, canonically_ordered_comm_semiring.mul_eq_zero_iff] at *
private lemma assoc (a b c : with_top α) : (a * b) * c = a * (b * c) :=
begin
cases a,
{ by_cases hb : b = 0; by_cases hc : c = 0;
simp [*, none_eq_top, mul_eq_zero b c] },
cases b,
{ by_cases ha : a = 0; by_cases hc : c = 0;
simp [*, none_eq_top, some_eq_coe, mul_eq_zero ↑a c] },
cases c,
{ by_cases ha : a = 0; by_cases hb : b = 0;
simp [*, none_eq_top, some_eq_coe, mul_eq_zero ↑a ↑b] },
simp [some_eq_coe, coe_mul.symm, mul_assoc]
end
private lemma one_mul' : ∀a : with_top α, 1 * a = a
| none := show ((1:α) : with_top α) * ⊤ = ⊤, by simp [-with_bot.coe_one]
| (some a) := show ((1:α) : with_top α) * a = a, by simp [coe_mul.symm, -with_bot.coe_one]
instance [canonically_ordered_comm_semiring α] [decidable_eq α] :
canonically_ordered_comm_semiring (with_top α) :=
{ one := (1 : α),
right_distrib := distrib',
left_distrib := assume a b c, by rw [comm, distrib', comm b, comm c]; refl,
mul_assoc := assoc,
mul_comm := comm,
mul_eq_zero_iff := mul_eq_zero,
one_mul := one_mul',
mul_one := assume a, by rw [comm, one_mul'],
zero_ne_one := assume h, @zero_ne_one α _ $ option.some.inj h,
.. with_top.add_comm_monoid, .. with_top.mul_zero_class, .. with_top.canonically_ordered_monoid }
@[simp] lemma coe_nat : ∀(n : nat), ((n : α) : with_top α) = n
| 0 := rfl
| (n+1) := have (((1 : nat) : α) : with_top α) = ((1 : nat) : with_top α) := rfl,
by rw [nat.cast_add, coe_add, nat.cast_add, coe_nat n, this]
@[simp] lemma nat_ne_top (n : nat) : (n : with_top α ) ≠ ⊤ :=
by rw [←coe_nat n]; apply coe_ne_top
@[simp] lemma top_ne_nat (n : nat) : (⊤ : with_top α) ≠ n :=
by rw [←coe_nat n]; apply top_ne_coe
@[elab_as_eliminator]
lemma nat_induction {P : with_top ℕ → Prop} (a : with_top ℕ)
(h0 : P 0) (hsuc : ∀n:ℕ, P n → P n.succ) (htop : (∀n : ℕ, P n) → P ⊤) : P a :=
begin
have A : ∀n:ℕ, P n,
{ assume n,
induction n with n IH,
{ exact h0 },
{ exact hsuc n IH } },
cases a,
{ exact htop A },
{ exact A a }
end
end with_top
|
9d5c5d51f0714b9c46e792f67fcea5cc46c95036 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/data/lazy_list/basic.lean | bfbe67391208c1ee2f9a0788cdea27f93166ce55 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 7,772 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
Traversable instance for lazy_lists.
-/
import control.traversable.equiv
import control.traversable.instances
import data.lazy_list
/-!
## Definitions on lazy lists
This file contains various definitions and proofs on lazy lists.
TODO: move the `lazy_list.lean` file from core to mathlib.
-/
universes u
namespace thunk
/-- Creates a thunk with a (non-lazy) constant value. -/
def mk {α} (x : α) : thunk α := λ _, x
instance {α : Type u} [decidable_eq α] : decidable_eq (thunk α) | a b :=
have a = b ↔ a () = b (), from ⟨by cc, by intro; ext x; cases x; assumption⟩,
by rw this; apply_instance
end thunk
namespace lazy_list
open function
/-- Isomorphism between strict and lazy lists. -/
def list_equiv_lazy_list (α : Type*) : list α ≃ lazy_list α :=
{ to_fun := lazy_list.of_list,
inv_fun := lazy_list.to_list,
right_inv := by { intro, induction x, refl, simp! [*],
ext, cases x, refl },
left_inv := by { intro, induction x, refl, simp! [*] } }
instance {α : Type u} : inhabited (lazy_list α) := ⟨nil⟩
instance {α : Type u} [decidable_eq α] : decidable_eq (lazy_list α)
| nil nil := is_true rfl
| (cons x xs) (cons y ys) :=
if h : x = y then
match decidable_eq (xs ()) (ys ()) with
| is_false h2 := is_false (by intro; cc)
| is_true h2 :=
have xs = ys, by ext u; cases u; assumption,
is_true (by cc)
end
else
is_false (by intro; cc)
| nil (cons _ _) := is_false (by cc)
| (cons _ _) nil := is_false (by cc)
/-- Traversal of lazy lists using an applicative effect. -/
protected def traverse {m : Type u → Type u} [applicative m] {α β : Type u}
(f : α → m β) : lazy_list α → m (lazy_list β)
| lazy_list.nil := pure lazy_list.nil
| (lazy_list.cons x xs) := lazy_list.cons <$> f x <*> (thunk.mk <$> traverse (xs ()))
instance : traversable lazy_list :=
{ map := @lazy_list.traverse id _,
traverse := @lazy_list.traverse }
instance : is_lawful_traversable lazy_list :=
begin
apply equiv.is_lawful_traversable' list_equiv_lazy_list;
intros ; resetI; ext,
{ induction x, refl,
simp! [equiv.map,functor.map] at *,
simp [*], refl, },
{ induction x, refl,
simp! [equiv.map,functor.map_const] at *,
simp [*], refl, },
{ induction x,
{ simp! [traversable.traverse,equiv.traverse] with functor_norm, refl },
simp! [equiv.map,functor.map_const,traversable.traverse] at *, rw x_ih,
dsimp [list_equiv_lazy_list,equiv.traverse,to_list,traversable.traverse,list.traverse],
simp! with functor_norm, refl },
end
/-- `init xs`, if `xs` non-empty, drops the last element of the list.
Otherwise, return the empty list. -/
def init {α} : lazy_list α → lazy_list α
| lazy_list.nil := lazy_list.nil
| (lazy_list.cons x xs) :=
let xs' := xs () in
match xs' with
| lazy_list.nil := lazy_list.nil
| (lazy_list.cons _ _) := lazy_list.cons x (init xs')
end
/-- Return the first object contained in the list that satisfies
predicate `p` -/
def find {α} (p : α → Prop) [decidable_pred p] : lazy_list α → option α
| nil := none
| (cons h t) := if p h then some h else find (t ())
/-- `interleave xs ys` creates a list where elements of `xs` and `ys` alternate. -/
def interleave {α} : lazy_list α → lazy_list α → lazy_list α
| lazy_list.nil xs := xs
| a@(lazy_list.cons x xs) lazy_list.nil := a
| (lazy_list.cons x xs) (lazy_list.cons y ys) :=
lazy_list.cons x (lazy_list.cons y (interleave (xs ()) (ys ())))
/-- `interleave_all (xs::ys::zs::xss)` creates a list where elements of `xs`, `ys`
and `zs` and the rest alternate. Every other element of the resulting list is taken from
`xs`, every fourth is taken from `ys`, every eighth is taken from `zs` and so on. -/
def interleave_all {α} : list (lazy_list α) → lazy_list α
| [] := lazy_list.nil
| (x :: xs) := interleave x (interleave_all xs)
/-- Monadic bind operation for `lazy_list`. -/
protected def bind {α β} : lazy_list α → (α → lazy_list β) → lazy_list β
| lazy_list.nil _ := lazy_list.nil
| (lazy_list.cons x xs) f := lazy_list.append (f x) (bind (xs ()) f)
/-- Reverse the order of a `lazy_list`.
It is done by converting to a `list` first because reversal involves evaluating all
the list and if the list is all evaluated, `list` is a better representation for
it than a series of thunks. -/
def reverse {α} (xs : lazy_list α) : lazy_list α :=
of_list xs.to_list.reverse
instance : monad lazy_list :=
{ pure := @lazy_list.singleton,
bind := @lazy_list.bind }
lemma append_nil {α} (xs : lazy_list α) : xs.append lazy_list.nil = xs :=
begin
induction xs, refl,
simp [lazy_list.append, xs_ih],
ext, congr,
end
lemma append_assoc {α} (xs ys zs : lazy_list α) : (xs.append ys).append zs = xs.append (ys.append zs) :=
by induction xs; simp [append, *]
lemma append_bind {α β} (xs : lazy_list α) (ys : thunk (lazy_list α)) (f : α → lazy_list β) :
(@lazy_list.append _ xs ys).bind f = (xs.bind f).append ((ys ()).bind f) :=
by induction xs; simp [lazy_list.bind, append, *, append_assoc, append, lazy_list.bind]
instance : is_lawful_monad lazy_list :=
{ pure_bind := by { intros, apply append_nil },
bind_assoc := by { intros, dsimp [(>>=)], induction x; simp [lazy_list.bind, append_bind, *], },
id_map :=
begin
intros,
simp [(<$>)],
induction x; simp [lazy_list.bind, *, singleton, append],
ext ⟨ ⟩, refl,
end }
/-- Try applying function `f` to every element of a `lazy_list` and
return the result of the first attempt that succeeds. -/
def mfirst {m} [alternative m] {α β} (f : α → m β) : lazy_list α → m β
| nil := failure
| (cons x xs) :=
f x <|> mfirst (xs ())
/-- Membership in lazy lists -/
protected def mem {α} (x : α) : lazy_list α → Prop
| lazy_list.nil := false
| (lazy_list.cons y ys) := x = y ∨ mem (ys ())
instance {α} : has_mem α (lazy_list α) :=
⟨ lazy_list.mem ⟩
instance mem.decidable {α} [decidable_eq α] (x : α) : Π xs : lazy_list α, decidable (x ∈ xs)
| lazy_list.nil := decidable.false
| (lazy_list.cons y ys) :=
if h : x = y
then decidable.is_true (or.inl h)
else decidable_of_decidable_of_iff (mem.decidable (ys ())) (by simp [*, (∈), lazy_list.mem])
@[simp]
lemma mem_nil {α} (x : α) : x ∈ @lazy_list.nil α ↔ false := iff.rfl
@[simp]
lemma mem_cons {α} (x y : α) (ys : thunk (lazy_list α)) : x ∈ @lazy_list.cons α y ys ↔ x = y ∨ x ∈ ys () := iff.rfl
theorem forall_mem_cons {α} {p : α → Prop} {a : α} {l : thunk (lazy_list α)} :
(∀ x ∈ @lazy_list.cons _ a l, p x) ↔ p a ∧ ∀ x ∈ l (), p x :=
by simp only [has_mem.mem, lazy_list.mem, or_imp_distrib, forall_and_distrib, forall_eq]
/-! ### map for partial functions -/
/-- Partial map. If `f : Π a, p a → β` is a partial function defined on
`a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l`
but is defined only when all members of `l` satisfy `p`, using the proof
to apply `f`. -/
@[simp] def pmap {α β} {p : α → Prop} (f : Π a, p a → β) : Π l : lazy_list α, (∀ a ∈ l, p a) → lazy_list β
| lazy_list.nil H := lazy_list.nil
| (lazy_list.cons x xs) H := lazy_list.cons (f x (forall_mem_cons.1 H).1) (pmap (xs ()) (forall_mem_cons.1 H).2)
/-- "Attach" the proof that the elements of `l` are in `l` to produce a new `lazy_list`
with the same elements but in the type `{x // x ∈ l}`. -/
def attach {α} (l : lazy_list α) : lazy_list {x // x ∈ l} := pmap subtype.mk l (λ a, id)
instance {α} [has_repr α] : has_repr (lazy_list α) :=
⟨ λ xs, repr xs.to_list ⟩
end lazy_list
|
dd673308112907d1c534cc7a86fac4b1e6a1cc7a | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /src/Lean/Elab/Util.lean | 6414a8e12d49cbf11a08a2a1f98dd9606bbce907 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 10,129 | 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.Parser.Command
import Lean.KeyedDeclsAttribute
import Lean.Elab.Exception
namespace Lean
def Syntax.prettyPrint (stx : Syntax) : Format :=
match stx.unsetTrailing.reprint with -- TODO use syntax pretty printer
| some str => format str.toFormat
| none => format stx
def MacroScopesView.format (view : MacroScopesView) (mainModule : Name) : Format :=
Std.format <|
if view.scopes.isEmpty then
view.name
else if view.mainModule == mainModule then
view.scopes.foldl Name.mkNum (view.name ++ view.imported)
else
view.scopes.foldl Name.mkNum (view.name ++ view.imported ++ view.mainModule)
namespace Elab
def expandOptNamedPrio (stx : Syntax) : MacroM Nat :=
if stx.isNone then
return eval_prio default
else match stx[0] with
| `(Parser.Command.namedPrio| (priority := $prio)) => evalPrio prio
| _ => Macro.throwUnsupported
structure MacroStackElem where
before : Syntax
after : Syntax
abbrev MacroStack := List MacroStackElem
/-- If `ref` does not have position information, then try to use macroStack -/
def getBetterRef (ref : Syntax) (macroStack : MacroStack) : Syntax :=
match ref.getPos? with
| some _ => ref
| none =>
match macroStack.find? (·.before.getPos? != none) with
| some elem => elem.before
| none => ref
register_builtin_option pp.macroStack : Bool := {
defValue := false
group := "pp"
descr := "dispaly macro expansion stack"
}
def addMacroStack {m} [Monad m] [MonadOptions m] (msgData : MessageData) (macroStack : MacroStack) : m MessageData := do
if !pp.macroStack.get (← getOptions) then pure msgData else
match macroStack with
| [] => pure msgData
| stack@(top::_) =>
let msgData := msgData ++ Format.line ++ "with resulting expansion" ++ indentD top.after
pure $ stack.foldl
(fun (msgData : MessageData) (elem : MacroStackElem) =>
msgData ++ Format.line ++ "while expanding" ++ indentD elem.before)
msgData
def checkSyntaxNodeKind [Monad m] [MonadEnv m] [MonadError m] (k : Name) : m Name := do
if Parser.isValidSyntaxNodeKind (← getEnv) k then pure k
else throwError "failed"
def checkSyntaxNodeKindAtNamespaces [Monad m] [MonadEnv m] [MonadError m] (k : Name) : Name → m Name
| n@(.str p _) => checkSyntaxNodeKind (n ++ k) <|> checkSyntaxNodeKindAtNamespaces k p
| .anonymous => checkSyntaxNodeKind k
| _ => throwError "failed"
def checkSyntaxNodeKindAtCurrentNamespaces (k : Name) : AttrM Name := do
let ctx ← read
checkSyntaxNodeKindAtNamespaces k ctx.currNamespace
def syntaxNodeKindOfAttrParam (defaultParserNamespace : Name) (stx : Syntax) : AttrM SyntaxNodeKind := do
let k ← Attribute.Builtin.getId stx
checkSyntaxNodeKindAtCurrentNamespaces k
<|>
checkSyntaxNodeKind (defaultParserNamespace ++ k)
<|>
throwError "invalid syntax node kind '{k}'"
private unsafe def evalSyntaxConstantUnsafe (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax :=
env.evalConstCheck Syntax opts `Lean.Syntax constName
@[implementedBy evalSyntaxConstantUnsafe]
opaque evalSyntaxConstant (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax := throw ""
unsafe def mkElabAttribute (γ) (attrDeclName attrBuiltinName attrName : Name) (parserNamespace : Name) (typeName : Name) (kind : String)
: IO (KeyedDeclsAttribute γ) :=
KeyedDeclsAttribute.init {
builtinName := attrBuiltinName
name := attrName
descr := kind ++ " elaborator"
valueTypeName := typeName
evalKey := fun _ stx => do
let kind ← syntaxNodeKindOfAttrParam parserNamespace stx
/- Recall that a `SyntaxNodeKind` is often the name of the parser, but this is not always true, and we must check it. -/
if (← getEnv).contains kind && (← getInfoState).enabled then
pushInfoLeaf <| Info.ofTermInfo {
elaborator := .anonymous
lctx := {}
expr := mkConst kind
stx := stx[1]
expectedType? := none
}
return kind
onAdded := fun builtin declName => do
if builtin then
if let some doc ← findDocString? (← getEnv) declName (includeBuiltin := false) then
declareBuiltin (declName ++ `docString) (mkAppN (mkConst ``addBuiltinDocString) #[toExpr declName, toExpr doc])
if let some declRanges ← findDeclarationRanges? declName then
declareBuiltin (declName ++ `declRange) (mkAppN (mkConst ``addBuiltinDeclarationRanges) #[toExpr declName, toExpr declRanges])
} attrDeclName
unsafe def mkMacroAttributeUnsafe : IO (KeyedDeclsAttribute Macro) :=
mkElabAttribute Macro `Lean.Elab.macroAttribute `builtinMacro `macro Name.anonymous `Lean.Macro "macro"
@[implementedBy mkMacroAttributeUnsafe]
opaque mkMacroAttribute : IO (KeyedDeclsAttribute Macro)
builtin_initialize macroAttribute : KeyedDeclsAttribute Macro ← mkMacroAttribute
/--
Try to expand macro at syntax tree root and return macro declaration name and new syntax if successful.
Return none if all macros threw `Macro.Exception.unsupportedSyntax`.
-/
def expandMacroImpl? (env : Environment) : Syntax → MacroM (Option (Name × Except Macro.Exception Syntax)) := fun stx => do
for e in macroAttribute.getEntries env stx.getKind do
try
let stx' ← withFreshMacroScope (e.value stx)
return (e.declName, Except.ok stx')
catch
| Macro.Exception.unsupportedSyntax => pure ()
| ex => return (e.declName, Except.error ex)
return none
class MonadMacroAdapter (m : Type → Type) where
getCurrMacroScope : m MacroScope
getNextMacroScope : m MacroScope
setNextMacroScope : MacroScope → m Unit
instance (m n) [MonadLift m n] [MonadMacroAdapter m] : MonadMacroAdapter n := {
getCurrMacroScope := liftM (MonadMacroAdapter.getCurrMacroScope : m _)
getNextMacroScope := liftM (MonadMacroAdapter.getNextMacroScope : m _)
setNextMacroScope := fun s => liftM (MonadMacroAdapter.setNextMacroScope s : m _)
}
def liftMacroM {α} {m : Type → Type} [Monad m] [MonadMacroAdapter m] [MonadEnv m] [MonadRecDepth m] [MonadError m] [MonadResolveName m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] [MonadLiftT IO m] (x : MacroM α) : m α := do
let env ← getEnv
let currNamespace ← getCurrNamespace
let openDecls ← getOpenDecls
let methods := Macro.mkMethods {
-- TODO: record recursive expansions in info tree?
expandMacro? := fun stx => do
match (← expandMacroImpl? env stx) with
| some (_, stx?) => liftExcept stx?
| none => return none
hasDecl := fun declName => return env.contains declName
getCurrNamespace := return currNamespace
resolveNamespace := fun n => return ResolveName.resolveNamespace env currNamespace openDecls n
resolveGlobalName := fun n => return ResolveName.resolveGlobalName env currNamespace openDecls n
}
match x { methods := methods
ref := ← getRef
currMacroScope := ← MonadMacroAdapter.getCurrMacroScope
mainModule := env.mainModule
currRecDepth := ← MonadRecDepth.getRecDepth
maxRecDepth := ← MonadRecDepth.getMaxRecDepth
} { macroScope := (← MonadMacroAdapter.getNextMacroScope) } with
| EStateM.Result.error Macro.Exception.unsupportedSyntax _ => throwUnsupportedSyntax
| EStateM.Result.error (Macro.Exception.error ref msg) _ =>
if msg == maxRecDepthErrorMessage then
-- Make sure we can detect exception using `Exception.isMaxRecDepth`
throwMaxRecDepthAt ref
else
throwErrorAt ref msg
| EStateM.Result.ok a s =>
MonadMacroAdapter.setNextMacroScope s.macroScope
s.traceMsgs.reverse.forM fun (clsName, msg) => trace clsName fun _ => msg
return a
@[inline] def adaptMacro {m : Type → Type} [Monad m] [MonadMacroAdapter m] [MonadEnv m] [MonadRecDepth m] [MonadError m] [MonadResolveName m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] [MonadLiftT IO m] (x : Macro) (stx : Syntax) : m Syntax :=
liftMacroM (x stx)
partial def mkUnusedBaseName (baseName : Name) : MacroM Name := do
let currNamespace ← Macro.getCurrNamespace
if ← Macro.hasDecl (currNamespace ++ baseName) then
let rec loop (idx : Nat) := do
let name := baseName.appendIndexAfter idx
if ← Macro.hasDecl (currNamespace ++ name) then
loop (idx+1)
else
return name
loop 1
else
return baseName
def logException [Monad m] [MonadLog m] [AddMessageContext m] [MonadOptions m] [MonadLiftT IO m] (ex : Exception) : m Unit := do
match ex with
| Exception.error ref msg => logErrorAt ref msg
| Exception.internal id _ =>
unless isAbortExceptionId id do
let name ← id.getName
logError m!"internal exception: {name}"
def withLogging [Monad m] [MonadLog m] [MonadExcept Exception m] [AddMessageContext m] [MonadOptions m] [MonadLiftT IO m]
(x : m Unit) : m Unit := do
try x catch ex => logException ex
def nestedExceptionToMessageData [Monad m] [MonadLog m] (ex : Exception) : m MessageData := do
let pos ← getRefPos
match ex.getRef.getPos? with
| none => return ex.toMessageData
| some exPos =>
if pos == exPos then
return ex.toMessageData
else
let exPosition := (← getFileMap).toPosition exPos
return m!"{exPosition.line}:{exPosition.column} {ex.toMessageData}"
def throwErrorWithNestedErrors [MonadError m] [Monad m] [MonadLog m] (msg : MessageData) (exs : Array Exception) : m α := do
throwError "{msg}, errors {toMessageList (← exs.mapM fun | ex => nestedExceptionToMessageData ex)}"
builtin_initialize
registerTraceClass `Elab
registerTraceClass `Elab.step
registerTraceClass `Elab.step.result (inherited := true)
end Lean.Elab
|
0629ea3484854ffa84460cc0592700ebe565a160 | 4b846d8dabdc64e7ea03552bad8f7fa74763fc67 | /library/tools/super/superposition.lean | 81f27822a36d0e17d893f2640e98c216006632a5 | [
"Apache-2.0"
] | permissive | pacchiano/lean | 9324b33f3ac3b5c5647285160f9f6ea8d0d767dc | fdadada3a970377a6df8afcd629a6f2eab6e84e8 | refs/heads/master | 1,611,357,380,399 | 1,489,870,101,000 | 1,489,870,101,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,927 | lean | /-
Copyright (c) 2016 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import .clause .prover_state .utils
open tactic monad expr
namespace super
def position := list ℕ
meta def get_rwr_positions : expr → list position
| (app a b) := [[]] ++
do arg ← list.zip_with_index (get_app_args (app a b)),
pos ← get_rwr_positions arg.1,
[arg.2 :: pos]
| (var _) := []
| e := [[]]
meta def get_position : expr → position → expr
| (app a b) (p::ps) :=
match list.nth (get_app_args (app a b)) p with
| some arg := get_position arg ps
| none := (app a b)
end
| e _ := e
meta def replace_position (v : expr) : expr → position → expr
| (app a b) (p::ps) :=
let args := get_app_args (app a b) in
match args^.nth p with
| some arg := app_of_list a^.get_app_fn $ args^.update_nth p $ replace_position arg ps
| none := app a b
end
| e [] := v
| e _ := e
variable gt : expr → expr → bool
variables (c1 c2 : clause)
variables (ac1 ac2 : derived_clause)
variables (i1 i2 : nat)
variable pos : list ℕ
variable ltr : bool
variable lt_in_termorder : bool
variable congr_ax : name
lemma {u v w} sup_ltr (F : Sort u) (A : Sort v) (a1 a2) (f : A → Sort w) : (f a1 → F) → f a2 → a1 = a2 → F :=
take hnfa1 hfa2 heq, hnfa1 (@eq.rec A a2 f hfa2 a1 heq^.symm)
lemma {u v w} sup_rtl (F : Sort u) (A : Sort v) (a1 a2) (f : A → Sort w) : (f a1 → F) → f a2 → a2 = a1 → F :=
take hnfa1 hfa2 heq, hnfa1 (@eq.rec A a2 f hfa2 a1 heq)
meta def is_eq_dir (e : expr) (ltr : bool) : option (expr × expr) :=
match is_eq e with
| some (lhs, rhs) := if ltr then some (lhs, rhs) else some (rhs, lhs)
| none := none
end
meta def try_sup : tactic clause := do
guard $ (c1^.get_lit i1)^.is_pos,
qf1 ← c1^.open_metan c1^.num_quants,
qf2 ← c2^.open_metan c2^.num_quants,
(rwr_from, rwr_to) ← (is_eq_dir (qf1.1^.get_lit i1)^.formula ltr)^.to_monad,
atom ← return (qf2.1^.get_lit i2)^.formula,
eq_type ← infer_type rwr_from,
atom_at_pos ← return $ get_position atom pos,
atom_at_pos_type ← infer_type atom_at_pos,
unify eq_type atom_at_pos_type,
unify rwr_from atom_at_pos transparency.none,
rwr_from' ← instantiate_mvars atom_at_pos,
rwr_to' ← instantiate_mvars rwr_to,
if lt_in_termorder
then guard (gt rwr_from' rwr_to')
else guard (¬gt rwr_to' rwr_from'),
rwr_ctx_varn ← mk_fresh_name,
abs_rwr_ctx ← return $
lam rwr_ctx_varn binder_info.default eq_type
(if (qf2.1^.get_lit i2)^.is_neg
then replace_position (mk_var 0) atom pos
else imp (replace_position (mk_var 0) atom pos) c2^.local_false),
lf_univ ← infer_univ c1^.local_false,
univ ← infer_univ eq_type,
atom_univ ← infer_univ atom,
op1 ← qf1.1^.open_constn i1,
op2 ← qf2.1^.open_constn c2^.num_lits,
hi2 ← (op2.2^.nth i2)^.to_monad,
new_atom ← whnf_no_delta $ app abs_rwr_ctx rwr_to',
new_hi2 ← return $ local_const hi2^.local_uniq_name `H binder_info.default new_atom,
new_fin_prf ←
return $ app_of_list (const congr_ax [lf_univ, univ, atom_univ]) [c1^.local_false, eq_type, rwr_from, rwr_to,
abs_rwr_ctx, (op2.1^.close_const hi2)^.proof, new_hi2],
clause.meta_closure (qf1.2 ++ qf2.2) $ (op1.1^.inst new_fin_prf)^.close_constn (op1.2 ++ op2.2^.update_nth i2 new_hi2)
meta def rwr_positions (c : clause) (i : nat) : list (list ℕ) :=
get_rwr_positions (c^.get_lit i)^.formula
meta def try_add_sup : prover unit :=
(do c' ← try_sup gt ac1^.c ac2^.c i1 i2 pos ltr ff congr_ax,
inf_score 2 [ac1^.sc, ac2^.sc] >>= mk_derived c' >>= add_inferred)
<|> return ()
meta def superposition_back_inf : inference :=
take given, do active ← get_active, sequence' $ do
given_i ← given^.selected,
guard (given^.c^.get_lit given_i)^.is_pos,
option.to_monad $ is_eq (given^.c^.get_lit given_i)^.formula,
other ← rb_map.values active,
guard $ ¬given^.sc^.in_sos ∨ ¬other^.sc^.in_sos,
other_i ← other^.selected,
pos ← rwr_positions other^.c other_i,
-- FIXME(gabriel): ``sup_ltr fails to resolve at runtime
[do try_add_sup gt given other given_i other_i pos tt ``super.sup_ltr,
try_add_sup gt given other given_i other_i pos ff ``super.sup_rtl]
meta def superposition_fwd_inf : inference :=
take given, do active ← get_active, sequence' $ do
given_i ← given^.selected,
other ← rb_map.values active,
guard $ ¬given^.sc^.in_sos ∨ ¬other^.sc^.in_sos,
other_i ← other^.selected,
guard (other^.c^.get_lit other_i)^.is_pos,
option.to_monad $ is_eq (other^.c^.get_lit other_i)^.formula,
pos ← rwr_positions given^.c given_i,
[do try_add_sup gt other given other_i given_i pos tt ``super.sup_ltr,
try_add_sup gt other given other_i given_i pos ff ``super.sup_rtl]
@[super.inf]
meta def superposition_inf : inf_decl := inf_decl.mk 40 $
take given, do gt ← get_term_order,
superposition_fwd_inf gt given,
superposition_back_inf gt given
end super
|
9bc3a9c9c0cdc08dfdded3304c908afe16566a83 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/category_theory/monoidal/category.lean | 85dca9c1daee7f84c1a95e3fbe48014eedeb8f66 | [
"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 | 19,274 | lean | /-
Copyright (c) 2018 Michael Jendrusch. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Jendrusch, Scott Morrison
-/
import category_theory.products.basic
open category_theory
universes v u
open category_theory
open category_theory.category
open category_theory.iso
namespace category_theory
/--
In a monoidal category, we can take the tensor product of objects, `X ⊗ Y` and of morphisms `f ⊗ g`.
Tensor product does not need to be strictly associative on objects, but there is a
specified associator, `α_ X Y Z : (X ⊗ Y) ⊗ Z ≅ X ⊗ (Y ⊗ Z)`. There is a tensor unit `𝟙_ C`,
with specified left and right unitor isomorphisms `λ_ X : 𝟙_ C ⊗ X ≅ X` and `ρ_ X : X ⊗ 𝟙_ C ≅ X`.
These associators and unitors satisfy the pentagon and triangle equations.
See https://stacks.math.columbia.edu/tag/0FFK.
-/
class monoidal_category (C : Type u) [𝒞 : category.{v} C] :=
-- curried tensor product of objects:
(tensor_obj : C → C → C)
(infixr ` ⊗ `:70 := tensor_obj) -- This notation is only temporary
-- curried tensor product of morphisms:
(tensor_hom :
Π {X₁ Y₁ X₂ Y₂ : C}, (X₁ ⟶ Y₁) → (X₂ ⟶ Y₂) → ((X₁ ⊗ X₂) ⟶ (Y₁ ⊗ Y₂)))
(infixr ` ⊗' `:69 := tensor_hom) -- This notation is only temporary
-- tensor product laws:
(tensor_id' :
∀ (X₁ X₂ : C), (𝟙 X₁) ⊗' (𝟙 X₂) = 𝟙 (X₁ ⊗ X₂) . obviously)
(tensor_comp' :
∀ {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂),
(f₁ ≫ g₁) ⊗' (f₂ ≫ g₂) = (f₁ ⊗' f₂) ≫ (g₁ ⊗' g₂) . obviously)
-- tensor unit:
(tensor_unit [] : C)
(notation `𝟙_` := tensor_unit)
-- associator:
(associator :
Π X Y Z : C, (X ⊗ Y) ⊗ Z ≅ X ⊗ (Y ⊗ Z))
(notation `α_` := associator)
(associator_naturality' :
∀ {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃),
((f₁ ⊗' f₂) ⊗' f₃) ≫ (α_ Y₁ Y₂ Y₃).hom = (α_ X₁ X₂ X₃).hom ≫ (f₁ ⊗' (f₂ ⊗' f₃)) . obviously)
-- left unitor:
(left_unitor : Π X : C, 𝟙_ ⊗ X ≅ X)
(notation `λ_` := left_unitor)
(left_unitor_naturality' :
∀ {X Y : C} (f : X ⟶ Y), ((𝟙 𝟙_) ⊗' f) ≫ (λ_ Y).hom = (λ_ X).hom ≫ f . obviously)
-- right unitor:
(right_unitor : Π X : C, X ⊗ 𝟙_ ≅ X)
(notation `ρ_` := right_unitor)
(right_unitor_naturality' :
∀ {X Y : C} (f : X ⟶ Y), (f ⊗' (𝟙 𝟙_)) ≫ (ρ_ Y).hom = (ρ_ X).hom ≫ f . obviously)
-- pentagon identity:
(pentagon' : ∀ W X Y Z : C,
((α_ W X Y).hom ⊗' (𝟙 Z)) ≫ (α_ W (X ⊗ Y) Z).hom ≫ ((𝟙 W) ⊗' (α_ X Y Z).hom)
= (α_ (W ⊗ X) Y Z).hom ≫ (α_ W X (Y ⊗ Z)).hom . obviously)
-- triangle identity:
(triangle' :
∀ X Y : C, (α_ X 𝟙_ Y).hom ≫ ((𝟙 X) ⊗' (λ_ Y).hom) = (ρ_ X).hom ⊗' (𝟙 Y) . obviously)
restate_axiom monoidal_category.tensor_id'
attribute [simp] monoidal_category.tensor_id
restate_axiom monoidal_category.tensor_comp'
attribute [reassoc] monoidal_category.tensor_comp -- This would be redundant in the simp set.
attribute [simp] monoidal_category.tensor_comp
restate_axiom monoidal_category.associator_naturality'
attribute [reassoc] monoidal_category.associator_naturality
restate_axiom monoidal_category.left_unitor_naturality'
attribute [reassoc] monoidal_category.left_unitor_naturality
restate_axiom monoidal_category.right_unitor_naturality'
attribute [reassoc] monoidal_category.right_unitor_naturality
restate_axiom monoidal_category.pentagon'
restate_axiom monoidal_category.triangle'
attribute [simp, reassoc] monoidal_category.triangle
open monoidal_category
infixr ` ⊗ `:70 := tensor_obj
infixr ` ⊗ `:70 := tensor_hom
notation `𝟙_` := tensor_unit
notation `α_` := associator
notation `λ_` := left_unitor
notation `ρ_` := right_unitor
/-- The tensor product of two isomorphisms is an isomorphism. -/
@[simps]
def tensor_iso {C : Type u} {X Y X' Y' : C} [category.{v} C] [monoidal_category.{v} C] (f : X ≅ Y) (g : X' ≅ Y') :
X ⊗ X' ≅ Y ⊗ Y' :=
{ hom := f.hom ⊗ g.hom,
inv := f.inv ⊗ g.inv,
hom_inv_id' := by rw [←tensor_comp, iso.hom_inv_id, iso.hom_inv_id, ←tensor_id],
inv_hom_id' := by rw [←tensor_comp, iso.inv_hom_id, iso.inv_hom_id, ←tensor_id] }
infixr ` ⊗ `:70 := tensor_iso
namespace monoidal_category
section
variables {C : Type u} [category.{v} C] [monoidal_category.{v} C]
instance tensor_is_iso {W X Y Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] : is_iso (f ⊗ g) :=
{ ..(as_iso f ⊗ as_iso g) }
@[simp] lemma inv_tensor {W X Y Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] :
inv (f ⊗ g) = inv f ⊗ inv g := rfl
variables {U V W X Y Z : C}
-- When `rewrite_search` lands, add @[search] attributes to
-- monoidal_category.tensor_id monoidal_category.tensor_comp monoidal_category.associator_naturality
-- monoidal_category.left_unitor_naturality monoidal_category.right_unitor_naturality
-- monoidal_category.pentagon monoidal_category.triangle
-- tensor_comp_id tensor_id_comp comp_id_tensor_tensor_id
-- triangle_assoc_comp_left triangle_assoc_comp_right triangle_assoc_comp_left_inv triangle_assoc_comp_right_inv
-- left_unitor_tensor left_unitor_tensor_inv
-- right_unitor_tensor right_unitor_tensor_inv
-- pentagon_inv
-- associator_inv_naturality
-- left_unitor_inv_naturality
-- right_unitor_inv_naturality
@[simp] lemma comp_tensor_id (f : W ⟶ X) (g : X ⟶ Y) :
(f ≫ g) ⊗ (𝟙 Z) = (f ⊗ (𝟙 Z)) ≫ (g ⊗ (𝟙 Z)) :=
by { rw ←tensor_comp, simp }
@[simp] lemma id_tensor_comp (f : W ⟶ X) (g : X ⟶ Y) :
(𝟙 Z) ⊗ (f ≫ g) = (𝟙 Z ⊗ f) ≫ (𝟙 Z ⊗ g) :=
by { rw ←tensor_comp, simp }
@[simp, reassoc] lemma id_tensor_comp_tensor_id (f : W ⟶ X) (g : Y ⟶ Z) :
((𝟙 Y) ⊗ f) ≫ (g ⊗ (𝟙 X)) = g ⊗ f :=
by { rw [←tensor_comp], simp }
@[simp, reassoc] lemma tensor_id_comp_id_tensor (f : W ⟶ X) (g : Y ⟶ Z) :
(g ⊗ (𝟙 W)) ≫ ((𝟙 Z) ⊗ f) = g ⊗ f :=
by { rw [←tensor_comp], simp }
lemma left_unitor_inv_naturality {X X' : C} (f : X ⟶ X') :
f ≫ (λ_ X').inv = (λ_ X).inv ≫ (𝟙 _ ⊗ f) :=
begin
apply (cancel_mono (λ_ X').hom).1,
simp only [assoc, comp_id, iso.inv_hom_id],
rw [left_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp]
end
lemma right_unitor_inv_naturality {X X' : C} (f : X ⟶ X') :
f ≫ (ρ_ X').inv = (ρ_ X).inv ≫ (f ⊗ 𝟙 _) :=
begin
apply (cancel_mono (ρ_ X').hom).1,
simp only [assoc, comp_id, iso.inv_hom_id],
rw [right_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp]
end
@[simp]
lemma right_unitor_conjugation {X Y : C} (f : X ⟶ Y) : (ρ_ X).inv ≫ (f ⊗ (𝟙 (𝟙_ C))) ≫ (ρ_ Y).hom = f :=
by rw [right_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp]
@[simp]
lemma left_unitor_conjugation {X Y : C} (f : X ⟶ Y) : (λ_ X).inv ≫ ((𝟙 (𝟙_ C)) ⊗ f) ≫ (λ_ Y).hom = f :=
by rw [left_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp]
@[simp] lemma tensor_left_iff
{X Y : C} (f g : X ⟶ Y) :
((𝟙 (𝟙_ C)) ⊗ f = (𝟙 (𝟙_ C)) ⊗ g) ↔ (f = g) :=
begin
split,
{ intro h,
have h' := congr_arg (λ k, (λ_ _).inv ≫ k) h,
dsimp at h',
rw [←left_unitor_inv_naturality, ←left_unitor_inv_naturality] at h',
exact (cancel_mono _).1 h', },
{ intro h, subst h, }
end
@[simp] lemma tensor_right_iff
{X Y : C} (f g : X ⟶ Y) :
(f ⊗ (𝟙 (𝟙_ C)) = g ⊗ (𝟙 (𝟙_ C))) ↔ (f = g) :=
begin
split,
{ intro h,
have h' := congr_arg (λ k, (ρ_ _).inv ≫ k) h,
dsimp at h',
rw [←right_unitor_inv_naturality, ←right_unitor_inv_naturality] at h',
exact (cancel_mono _).1 h' },
{ intro h, subst h, }
end
-- We now prove:
-- ((α_ (𝟙_ C) X Y).hom) ≫
-- ((λ_ (X ⊗ Y)).hom)
-- = ((λ_ X).hom ⊗ (𝟙 Y))
-- (and the corresponding fact for right unitors)
-- following the proof on nLab:
-- Lemma 2.2 at <https://ncatlab.org/nlab/revision/monoidal+category/115>
lemma left_unitor_product_aux_perimeter (X Y : C) :
((α_ (𝟙_ C) (𝟙_ C) X).hom ⊗ (𝟙 Y)) ≫
(α_ (𝟙_ C) ((𝟙_ C) ⊗ X) Y).hom ≫
((𝟙 (𝟙_ C)) ⊗ (α_ (𝟙_ C) X Y).hom) ≫
((𝟙 (𝟙_ C)) ⊗ (λ_ (X ⊗ Y)).hom)
= (((ρ_ (𝟙_ C)).hom ⊗ (𝟙 X)) ⊗ (𝟙 Y)) ≫
(α_ (𝟙_ C) X Y).hom :=
begin
conv_lhs { congr, skip, rw [←category.assoc] },
rw [←category.assoc, monoidal_category.pentagon, associator_naturality, tensor_id,
←monoidal_category.triangle, ←category.assoc]
end
lemma left_unitor_product_aux_triangle (X Y : C) :
((α_ (𝟙_ C) (𝟙_ C) X).hom ⊗ (𝟙 Y)) ≫
(((𝟙 (𝟙_ C)) ⊗ (λ_ X).hom) ⊗ (𝟙 Y))
= ((ρ_ (𝟙_ C)).hom ⊗ (𝟙 X)) ⊗ (𝟙 Y) :=
by rw [←comp_tensor_id, ←monoidal_category.triangle]
lemma left_unitor_product_aux_square (X Y : C) :
(α_ (𝟙_ C) ((𝟙_ C) ⊗ X) Y).hom ≫
((𝟙 (𝟙_ C)) ⊗ (λ_ X).hom ⊗ (𝟙 Y))
= (((𝟙 (𝟙_ C)) ⊗ (λ_ X).hom) ⊗ (𝟙 Y)) ≫
(α_ (𝟙_ C) X Y).hom :=
by rw associator_naturality
lemma left_unitor_product_aux (X Y : C) :
((𝟙 (𝟙_ C)) ⊗ (α_ (𝟙_ C) X Y).hom) ≫
((𝟙 (𝟙_ C)) ⊗ (λ_ (X ⊗ Y)).hom)
= (𝟙 (𝟙_ C)) ⊗ ((λ_ X).hom ⊗ (𝟙 Y)) :=
begin
rw ←(cancel_epi (α_ (𝟙_ C) ((𝟙_ C) ⊗ X) Y).hom),
rw left_unitor_product_aux_square,
rw ←(cancel_epi ((α_ (𝟙_ C) (𝟙_ C) X).hom ⊗ (𝟙 Y))),
slice_rhs 1 2 { rw left_unitor_product_aux_triangle },
conv_lhs { rw [left_unitor_product_aux_perimeter] }
end
lemma right_unitor_product_aux_perimeter (X Y : C) :
((α_ X Y (𝟙_ C)).hom ⊗ (𝟙 (𝟙_ C))) ≫
(α_ X (Y ⊗ (𝟙_ C)) (𝟙_ C)).hom ≫
((𝟙 X) ⊗ (α_ Y (𝟙_ C) (𝟙_ C)).hom) ≫
((𝟙 X) ⊗ (𝟙 Y) ⊗ (λ_ (𝟙_ C)).hom)
= ((ρ_ (X ⊗ Y)).hom ⊗ (𝟙 (𝟙_ C))) ≫
(α_ X Y (𝟙_ C)).hom :=
begin
transitivity (((α_ X Y _).hom ⊗ 𝟙 _) ≫ (α_ X _ _).hom ≫
(𝟙 X ⊗ (α_ Y _ _).hom)) ≫
(𝟙 X ⊗ 𝟙 Y ⊗ (λ_ _).hom),
{ conv_lhs { congr, skip, rw [←category.assoc] },
conv_rhs { rw [category.assoc] } },
{ conv_lhs { congr, rw [monoidal_category.pentagon] },
conv_rhs { congr, rw [←monoidal_category.triangle] },
conv_rhs { rw [category.assoc] },
conv_rhs { congr, skip, congr, congr, rw [←tensor_id] },
conv_rhs { congr, skip, rw [associator_naturality] },
conv_rhs { rw [←category.assoc] } }
end
lemma right_unitor_product_aux_triangle (X Y : C) :
((𝟙 X) ⊗ (α_ Y (𝟙_ C) (𝟙_ C)).hom) ≫
((𝟙 X) ⊗ (𝟙 Y) ⊗ (λ_ (𝟙_ C)).hom)
= (𝟙 X) ⊗ (ρ_ Y).hom ⊗ (𝟙 (𝟙_ C)) :=
by rw [←id_tensor_comp, ←monoidal_category.triangle]
lemma right_unitor_product_aux_square (X Y : C) :
(α_ X (Y ⊗ (𝟙_ C)) (𝟙_ C)).hom ≫
((𝟙 X) ⊗ (ρ_ Y).hom ⊗ (𝟙 (𝟙_ C)))
= (((𝟙 X) ⊗ (ρ_ Y).hom) ⊗ (𝟙 (𝟙_ C))) ≫
(α_ X Y (𝟙_ C)).hom :=
by rw [associator_naturality]
lemma right_unitor_product_aux (X Y : C) :
((α_ X Y (𝟙_ C)).hom ⊗ (𝟙 (𝟙_ C))) ≫
(((𝟙 X) ⊗ (ρ_ Y).hom) ⊗ (𝟙 (𝟙_ C)))
= ((ρ_ (X ⊗ Y)).hom ⊗ (𝟙 (𝟙_ C))) :=
begin
rw ←(cancel_mono (α_ X Y (𝟙_ C)).hom),
slice_lhs 2 3 { rw ←right_unitor_product_aux_square },
rw [←right_unitor_product_aux_triangle, ←right_unitor_product_aux_perimeter],
end
-- See Proposition 2.2.4 of <http://www-math.mit.edu/~etingof/egnobookfinal.pdf>
lemma left_unitor_tensor' (X Y : C) :
((α_ (𝟙_ C) X Y).hom) ≫ ((λ_ (X ⊗ Y)).hom) = ((λ_ X).hom ⊗ (𝟙 Y)) :=
by rw [←tensor_left_iff, id_tensor_comp, left_unitor_product_aux]
@[simp]
lemma left_unitor_tensor (X Y : C) :
((λ_ (X ⊗ Y)).hom) = ((α_ (𝟙_ C) X Y).inv) ≫ ((λ_ X).hom ⊗ (𝟙 Y)) :=
by { rw [←left_unitor_tensor'], simp }
lemma left_unitor_tensor_inv' (X Y : C) :
((λ_ (X ⊗ Y)).inv) ≫ ((α_ (𝟙_ C) X Y).inv) = ((λ_ X).inv ⊗ (𝟙 Y)) :=
eq_of_inv_eq_inv (by simp)
@[simp]
lemma left_unitor_tensor_inv (X Y : C) :
((λ_ (X ⊗ Y)).inv) = ((λ_ X).inv ⊗ (𝟙 Y)) ≫ ((α_ (𝟙_ C) X Y).hom) :=
by { rw [←left_unitor_tensor_inv'], simp }
@[simp]
lemma right_unitor_tensor (X Y : C) :
((ρ_ (X ⊗ Y)).hom) = ((α_ X Y (𝟙_ C)).hom) ≫ ((𝟙 X) ⊗ (ρ_ Y).hom) :=
by rw [←tensor_right_iff, comp_tensor_id, right_unitor_product_aux]
@[simp]
lemma right_unitor_tensor_inv (X Y : C) :
((ρ_ (X ⊗ Y)).inv) = ((𝟙 X) ⊗ (ρ_ Y).inv) ≫ ((α_ X Y (𝟙_ C)).inv) :=
eq_of_inv_eq_inv (by simp)
lemma associator_inv_naturality {X Y Z X' Y' Z' : C} (f : X ⟶ X') (g : Y ⟶ Y') (h : Z ⟶ Z') :
(f ⊗ (g ⊗ h)) ≫ (α_ X' Y' Z').inv = (α_ X Y Z).inv ≫ ((f ⊗ g) ⊗ h) :=
begin
apply (cancel_mono (α_ X' Y' Z').hom).1,
simp only [assoc, comp_id, iso.inv_hom_id],
rw [associator_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp]
end
lemma pentagon_inv (W X Y Z : C) :
((𝟙 W) ⊗ (α_ X Y Z).inv) ≫ (α_ W (X ⊗ Y) Z).inv ≫ ((α_ W X Y).inv ⊗ (𝟙 Z))
= (α_ W X (Y ⊗ Z)).inv ≫ (α_ (W ⊗ X) Y Z).inv :=
begin
apply category_theory.eq_of_inv_eq_inv,
dsimp,
rw [category.assoc, monoidal_category.pentagon]
end
lemma triangle_assoc_comp_left (X Y : C) :
(α_ X (𝟙_ C) Y).hom ≫ ((𝟙 X) ⊗ (λ_ Y).hom) = (ρ_ X).hom ⊗ 𝟙 Y :=
monoidal_category.triangle X Y
@[simp] lemma triangle_assoc_comp_right (X Y : C) :
(α_ X (𝟙_ C) Y).inv ≫ ((ρ_ X).hom ⊗ 𝟙 Y) = ((𝟙 X) ⊗ (λ_ Y).hom) :=
by rw [←triangle_assoc_comp_left, ←category.assoc, iso.inv_hom_id, category.id_comp]
@[simp] lemma triangle_assoc_comp_right_inv (X Y : C) :
((ρ_ X).inv ⊗ 𝟙 Y) ≫ (α_ X (𝟙_ C) Y).hom = ((𝟙 X) ⊗ (λ_ Y).inv) :=
begin
apply (cancel_mono (𝟙 X ⊗ (λ_ Y).hom)).1,
simp only [assoc, triangle_assoc_comp_left],
rw [←comp_tensor_id, iso.inv_hom_id, ←id_tensor_comp, iso.inv_hom_id]
end
@[simp] lemma triangle_assoc_comp_left_inv (X Y : C) :
((𝟙 X) ⊗ (λ_ Y).inv) ≫ (α_ X (𝟙_ C) Y).inv = ((ρ_ X).inv ⊗ 𝟙 Y) :=
begin
apply (cancel_mono ((ρ_ X).hom ⊗ 𝟙 Y)).1,
simp only [triangle_assoc_comp_right, assoc],
rw [←id_tensor_comp, iso.inv_hom_id, ←comp_tensor_id, iso.inv_hom_id]
end
end
section
variables (C : Type u) [category.{v} C] [monoidal_category.{v} C]
/-- The tensor product expressed as a functor. -/
def tensor : (C × C) ⥤ C :=
{ obj := λ X, X.1 ⊗ X.2,
map := λ {X Y : C × C} (f : X ⟶ Y), f.1 ⊗ f.2 }
/-- The left-associated triple tensor product as a functor. -/
def left_assoc_tensor : (C × C × C) ⥤ C :=
{ obj := λ X, (X.1 ⊗ X.2.1) ⊗ X.2.2,
map := λ {X Y : C × C × C} (f : X ⟶ Y), (f.1 ⊗ f.2.1) ⊗ f.2.2 }
@[simp] lemma left_assoc_tensor_obj (X) :
(left_assoc_tensor C).obj X = (X.1 ⊗ X.2.1) ⊗ X.2.2 := rfl
@[simp] lemma left_assoc_tensor_map {X Y} (f : X ⟶ Y) :
(left_assoc_tensor C).map f = (f.1 ⊗ f.2.1) ⊗ f.2.2 := rfl
/-- The right-associated triple tensor product as a functor. -/
def right_assoc_tensor : (C × C × C) ⥤ C :=
{ obj := λ X, X.1 ⊗ (X.2.1 ⊗ X.2.2),
map := λ {X Y : C × C × C} (f : X ⟶ Y), f.1 ⊗ (f.2.1 ⊗ f.2.2) }
@[simp] lemma right_assoc_tensor_obj (X) :
(right_assoc_tensor C).obj X = X.1 ⊗ (X.2.1 ⊗ X.2.2) := rfl
@[simp] lemma right_assoc_tensor_map {X Y} (f : X ⟶ Y) :
(right_assoc_tensor C).map f = f.1 ⊗ (f.2.1 ⊗ f.2.2) := rfl
/-- The functor `λ X, 𝟙_ C ⊗ X`. -/
def tensor_unit_left : C ⥤ C :=
{ obj := λ X, 𝟙_ C ⊗ X,
map := λ {X Y : C} (f : X ⟶ Y), (𝟙 (𝟙_ C)) ⊗ f }
/-- The functor `λ X, X ⊗ 𝟙_ C`. -/
def tensor_unit_right : C ⥤ C :=
{ obj := λ X, X ⊗ 𝟙_ C,
map := λ {X Y : C} (f : X ⟶ Y), f ⊗ (𝟙 (𝟙_ C)) }
-- We can express the associator and the unitors, given componentwise above,
-- as natural isomorphisms.
/-- The associator as a natural isomorphism. -/
@[simps {rhs_md := semireducible}]
def associator_nat_iso :
left_assoc_tensor C ≅ right_assoc_tensor C :=
nat_iso.of_components
(by { intros, apply monoidal_category.associator })
(by { intros, apply monoidal_category.associator_naturality })
/-- The left unitor as a natural isomorphism. -/
@[simps {rhs_md := semireducible}]
def left_unitor_nat_iso :
tensor_unit_left C ≅ 𝟭 C :=
nat_iso.of_components
(by { intros, apply monoidal_category.left_unitor })
(by { intros, apply monoidal_category.left_unitor_naturality })
/-- The right unitor as a natural isomorphism. -/
@[simps {rhs_md := semireducible}]
def right_unitor_nat_iso :
tensor_unit_right C ≅ 𝟭 C :=
nat_iso.of_components
(by { intros, apply monoidal_category.right_unitor })
(by { intros, apply monoidal_category.right_unitor_naturality })
section
variables {C}
/-- Tensoring on the left with as fixed object, as a functor. -/
@[simps]
def tensor_left (X : C) : C ⥤ C :=
{ obj := λ Y, X ⊗ Y,
map := λ Y Y' f, (𝟙 X) ⊗ f, }
/--
Tensoring on the left with `X ⊗ Y` is naturally isomorphic to
tensoring on the left with `Y`, and then again with `X`.
-/
def tensor_left_tensor (X Y : C) : tensor_left (X ⊗ Y) ≅ tensor_left Y ⋙ tensor_left X :=
nat_iso.of_components
(associator _ _)
(λ Z Z' f, by { dsimp, rw[←tensor_id], apply associator_naturality })
@[simp] lemma tensor_left_tensor_hom_app (X Y Z : C) :
(tensor_left_tensor X Y).hom.app Z = (associator X Y Z).hom :=
rfl
@[simp] lemma tensor_left_tensor_inv_app (X Y Z : C) :
(tensor_left_tensor X Y).inv.app Z = (associator X Y Z).inv :=
rfl
/-- Tensoring on the right with as fixed object, as a functor. -/
@[simps]
def tensor_right (X : C) : C ⥤ C :=
{ obj := λ Y, Y ⊗ X,
map := λ Y Y' f, f ⊗ (𝟙 X), }
variables (C)
/--
Tensoring on the right, as a functor from `C` into endofunctors of `C`.
We later show this is a monoidal functor.
-/
@[simps]
def tensoring_right : C ⥤ (C ⥤ C) :=
{ obj := tensor_right,
map := λ X Y f,
{ app := λ Z, (𝟙 Z) ⊗ f } }
instance : faithful (tensoring_right C) :=
{ map_injective' := λ X Y f g h,
begin
injections with h,
replace h := congr_fun h (𝟙_ C),
simpa using h,
end }
variables {C}
/--
Tensoring on the right with `X ⊗ Y` is naturally isomorphic to
tensoring on the right with `X`, and then again with `Y`.
-/
def tensor_right_tensor (X Y : C) : tensor_right (X ⊗ Y) ≅ tensor_right X ⋙ tensor_right Y :=
nat_iso.of_components
(λ Z, (associator Z X Y).symm)
(λ Z Z' f, by { dsimp, rw[←tensor_id], apply associator_inv_naturality })
@[simp] lemma tensor_right_tensor_hom_app (X Y Z : C) :
(tensor_right_tensor X Y).hom.app Z = (associator Z X Y).inv :=
rfl
@[simp] lemma tensor_right_tensor_inv_app (X Y Z : C) :
(tensor_right_tensor X Y).inv.app Z = (associator Z X Y).hom :=
rfl
end
end
end monoidal_category
end category_theory
|
55f596afb05e9f53e8e01ec3e9a0d153437a066d | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/playground/perf.lean | 3ac030844d744268721c76c0e6edb7704147ef10 | [
"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 | 293 | lean | def g (a : Nat) (n : Nat) : List Nat :=
let xs := List.repeat a n in
xs.map (+2)
def h (xs : List Nat) : Nat :=
xs.foldl (+) 0
def rep (n : Nat) : Nat :=
n.repeat (λ i r, h (g i n)) 0
def act (n : Nat) : IO Unit :=
IO.println (toString (rep n))
def main : IO UInt32 :=
act 5000 *> pure 0
|
752d7160e7747a00d96dd983124ba1a6117f80bd | 4727251e0cd73359b15b664c3170e5d754078599 | /src/topology/sober.lean | b08a4f9582aa5d475d6975abf8c2bf619dcf08f0 | [
"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 | 12,493 | lean | /-
Copyright (c) 2021 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import topology.separation
import topology.continuous_function.basic
/-!
# Sober spaces
A quasi-sober space is a topological space where every
irreducible closed subset has a generic point.
A sober space is a quasi-sober space where every irreducible closed subset
has a *unique* generic point. This is if and only if the space is T0, and thus sober spaces can be
stated via `[quasi_sober α] [t0_space α]`.
## Main definition
* `specializes` : `specializes x y` (`x ⤳ y`) means that `x` specializes to `y`, i.e.
`y` is in the closure of `x`.
* `specialization_preorder` : specialization gives a preorder on a topological space.
* `specialization_order` : specialization gives a partial order on a T0 space.
* `is_generic_point` : `x` is the generic point of `S` if `S` is the closure of `x`.
* `quasi_sober` : A space is quasi-sober if every irreducible closed subset has a generic point.
-/
variables {α β : Type*} [topological_space α] [topological_space β]
section specialize_order
/-- `x` specializes to `y` if `y` is in the closure of `x`. The notation used is `x ⤳ y`. -/
def specializes (x y : α) : Prop := y ∈ closure ({x} : set α)
infix ` ⤳ `:300 := specializes
lemma specializes_def (x y : α) : x ⤳ y ↔ y ∈ closure ({x} : set α) := iff.rfl
lemma specializes_iff_closure_subset {x y : α} :
x ⤳ y ↔ closure ({y} : set α) ⊆ closure ({x} : set α) :=
is_closed_closure.mem_iff_closure_subset
lemma specializes_rfl {x : α} : x ⤳ x := subset_closure (set.mem_singleton x)
lemma specializes_refl (x : α) : x ⤳ x := specializes_rfl
lemma specializes.trans {x y z : α} : x ⤳ y → y ⤳ z → x ⤳ z :=
by { simp_rw specializes_iff_closure_subset, exact λ a b, b.trans a }
lemma specializes_iff_forall_closed {x y : α} :
x ⤳ y ↔ ∀ (Z : set α) (h : is_closed Z), x ∈ Z → y ∈ Z :=
begin
split,
{ intros h Z hZ,
rw [hZ.mem_iff_closure_subset, hZ.mem_iff_closure_subset],
exact (specializes_iff_closure_subset.mp h).trans },
{ intro h, exact h _ is_closed_closure (subset_closure $ set.mem_singleton x) }
end
lemma specializes_iff_forall_open {x y : α} :
x ⤳ y ↔ ∀ (U : set α) (h : is_open U), y ∈ U → x ∈ U :=
begin
rw specializes_iff_forall_closed,
exact ⟨λ h U hU, not_imp_not.mp (h _ (is_closed_compl_iff.mpr hU)),
λ h U hU, not_imp_not.mp (h _ (is_open_compl_iff.mpr hU))⟩,
end
lemma indistinguishable_iff_specializes_and (x y : α) :
indistinguishable x y ↔ x ⤳ y ∧ y ⤳ x :=
(indistinguishable_iff_closure x y).trans (and_comm _ _)
lemma specializes_antisymm [t0_space α] (x y : α) : x ⤳ y → y ⤳ x → x = y :=
λ h₁ h₂, ((indistinguishable_iff_specializes_and _ _).mpr ⟨h₁, h₂⟩).eq
lemma specializes.map {x y : α} (h : x ⤳ y) {f : α → β} (hf : continuous f) : f x ⤳ f y :=
begin
rw [specializes_def, ← set.image_singleton],
exact image_closure_subset_closure_image hf ⟨_, h, rfl⟩,
end
lemma continuous_map.map_specialization {x y : α} (h : x ⤳ y) (f : C(α, β)) : f x ⤳ f y :=
h.map f.2
lemma specializes.eq [t1_space α] {x y : α} (h : x ⤳ y) : x = y :=
(set.mem_singleton_iff.mp
((specializes_iff_forall_closed.mp h) _ (t1_space.t1 _) (set.mem_singleton _))).symm
@[simp] lemma specializes_iff_eq [t1_space α] {x y : α} : x ⤳ y ↔ x = y :=
⟨specializes.eq, λ h, h ▸ specializes_refl _⟩
variable (α)
/-- Specialization forms a preorder on the topological space. -/
def specialization_preorder : preorder α :=
{ le := λ x y, y ⤳ x,
le_refl := λ x, specializes_refl x,
le_trans := λ _ _ _ h₁ h₂, specializes.trans h₂ h₁ }
local attribute [instance] specialization_preorder
/-- Specialization forms a partial order on a t0 topological space. -/
def specialization_order [t0_space α] : partial_order α :=
{ le_antisymm := λ _ _ h₁ h₂, specializes_antisymm _ _ h₂ h₁,
.. specialization_preorder α }
variable {α}
lemma specialization_order.monotone_of_continuous (f : α → β) (hf : continuous f) : monotone f :=
λ x y h, specializes.map h hf
end specialize_order
section generic_point
/-- `x` is a generic point of `S` if `S` is the closure of `x`. -/
def is_generic_point (x : α) (S : set α) : Prop := closure ({x} : set α) = S
lemma is_generic_point_def {x : α} {S : set α} : is_generic_point x S ↔ closure ({x} : set α) = S :=
iff.rfl
lemma is_generic_point.def {x : α} {S : set α} (h : is_generic_point x S) :
closure ({x} : set α) = S := h
lemma is_generic_point_closure {x : α} : is_generic_point x (closure ({x} : set α)) := refl _
variables {x : α} {S : set α} (h : is_generic_point x S)
include h
lemma is_generic_point.specializes {y : α} (h' : y ∈ S) :
x ⤳ y := by rwa ← h.def at h'
lemma is_generic_point.mem : x ∈ S :=
h.def ▸ subset_closure (set.mem_singleton x)
lemma is_generic_point.is_closed : is_closed S :=
h.def ▸ is_closed_closure
lemma is_generic_point.is_irreducible : is_irreducible S :=
h.def ▸ is_irreducible_singleton.closure
lemma is_generic_point.eq [t0_space α] {y : α} (h' : is_generic_point y S) : x = y :=
specializes_antisymm _ _ (h.specializes h'.mem) (h'.specializes h.mem)
lemma is_generic_point.mem_open_set_iff
{U : set α} (hU : is_open U) : x ∈ U ↔ (S ∩ U).nonempty :=
⟨λ h', ⟨x, h.mem, h'⟩,
λ h', specializes_iff_forall_open.mp (h.specializes h'.some_spec.1) U hU h'.some_spec.2⟩
lemma is_generic_point.disjoint_iff
{U : set α} (hU : is_open U) : disjoint S U ↔ x ∉ U :=
by rw [h.mem_open_set_iff hU, ← set.ne_empty_iff_nonempty, not_not, set.disjoint_iff_inter_eq_empty]
lemma is_generic_point.mem_closed_set_iff
{Z : set α} (hZ : is_closed Z) : x ∈ Z ↔ S ⊆ Z :=
by rw [← is_generic_point_def.mp h, hZ.closure_subset_iff, set.singleton_subset_iff]
lemma is_generic_point.image {f : α → β} (hf : continuous f) :
is_generic_point (f x) (closure (f '' S)) :=
begin
rw [is_generic_point_def, ← is_generic_point_def.mp h],
apply le_antisymm,
{ exact closure_mono
(set.singleton_subset_iff.mpr ⟨_, subset_closure $ set.mem_singleton x, rfl⟩) },
{ convert is_closed_closure.closure_subset_iff.mpr (image_closure_subset_closure_image hf),
rw set.image_singleton }
end
omit h
lemma is_generic_point_iff_forall_closed {x : α} {S : set α} (hS : is_closed S) (hxS : x ∈ S) :
is_generic_point x S ↔ ∀ (Z : set α) (hZ : is_closed Z) (hxZ : x ∈ Z), S ⊆ Z :=
begin
split,
{ intros h Z hZ hxZ, exact (h.mem_closed_set_iff hZ).mp hxZ },
{ intro h,
apply le_antisymm,
{ rwa [set.le_eq_subset, hS.closure_subset_iff, set.singleton_subset_iff] },
{ exact h _ is_closed_closure (subset_closure $ set.mem_singleton x) } }
end
end generic_point
section sober
/-- A space is sober if every irreducible closed subset has a generic point. -/
@[mk_iff]
class quasi_sober (α : Type*) [topological_space α] : Prop :=
(sober : ∀ {S : set α} (hS₁ : is_irreducible S) (hS₂ : is_closed S), ∃ x, is_generic_point x S)
/-- A generic point of the closure of an irreducible space. -/
noncomputable
def is_irreducible.generic_point [quasi_sober α] {S : set α} (hS : is_irreducible S) : α :=
(quasi_sober.sober hS.closure is_closed_closure).some
lemma is_irreducible.generic_point_spec [quasi_sober α] {S : set α} (hS : is_irreducible S) :
is_generic_point hS.generic_point (closure S) :=
(quasi_sober.sober hS.closure is_closed_closure).some_spec
@[simp] lemma is_irreducible.generic_point_closure_eq [quasi_sober α] {S : set α}
(hS : is_irreducible S) : closure ({hS.generic_point} : set α) = closure S :=
hS.generic_point_spec
variable (α)
/-- A generic point of a sober irreducible space. -/
noncomputable
def generic_point [quasi_sober α] [irreducible_space α] : α :=
(irreducible_space.is_irreducible_univ α).generic_point
lemma generic_point_spec [quasi_sober α] [irreducible_space α] :
is_generic_point (generic_point α) ⊤ :=
by simpa using (irreducible_space.is_irreducible_univ α).generic_point_spec
@[simp]
lemma generic_point_closure [quasi_sober α] [irreducible_space α] :
closure ({generic_point α} : set α) = ⊤ := generic_point_spec α
variable {α}
lemma generic_point_specializes [quasi_sober α] [irreducible_space α] (x : α) :
generic_point α ⤳ x := (is_irreducible.generic_point_spec _).specializes (by simp)
local attribute [instance, priority 10] specialization_order
/-- The closed irreducible subsets of a sober space bijects with the points of the space. -/
noncomputable
def irreducible_set_equiv_points [quasi_sober α] [t0_space α] :
{ s : set α | is_irreducible s ∧ is_closed s } ≃o α :=
{ to_fun := λ s, s.prop.1.generic_point,
inv_fun := λ x, ⟨closure ({x} : set α), is_irreducible_singleton.closure, is_closed_closure⟩,
left_inv := λ s,
subtype.eq $ eq.trans (s.prop.1.generic_point_spec) $ closure_eq_iff_is_closed.mpr s.2.2,
right_inv := λ x, is_irreducible_singleton.closure.generic_point_spec.eq
(by { convert is_generic_point_closure using 1, rw closure_closure }),
map_rel_iff' := λ s t, by { change _ ⤳ _ ↔ _, rw specializes_iff_closure_subset,
simp [s.prop.2.closure_eq, t.prop.2.closure_eq, ← subtype.coe_le_coe] } }
lemma closed_embedding.quasi_sober {f : α → β} (hf : closed_embedding f) [quasi_sober β] :
quasi_sober α :=
begin
constructor,
intros S hS hS',
have hS'' := hS.image f hf.continuous.continuous_on,
obtain ⟨x, hx⟩ := quasi_sober.sober hS'' (hf.is_closed_map _ hS'),
obtain ⟨y, hy, rfl⟩ := hx.mem,
use y,
change _ = _ at hx,
apply set.image_injective.mpr hf.inj,
rw [← hx, ← hf.closure_image_eq, set.image_singleton]
end
lemma open_embedding.quasi_sober {f : α → β} (hf : open_embedding f) [quasi_sober β] :
quasi_sober α :=
begin
constructor,
intros S hS hS',
have hS'' := hS.image f hf.continuous.continuous_on,
obtain ⟨x, hx⟩ := quasi_sober.sober hS''.closure is_closed_closure,
obtain ⟨T, hT, rfl⟩ := hf.to_inducing.is_closed_iff.mp hS',
rw set.image_preimage_eq_inter_range at hx hS'',
have hxT : x ∈ T,
{ rw ← hT.closure_eq, exact closure_mono (set.inter_subset_left _ _) hx.mem },
have hxU : x ∈ set.range f,
{ rw hx.mem_open_set_iff hf.open_range,
refine set.nonempty.mono _ hS''.1,
simpa using subset_closure },
rcases hxU with ⟨y, rfl⟩,
use y,
change _ = _,
rw [hf.to_embedding.closure_eq_preimage_closure_image,
set.image_singleton, (show _ = _, from hx)],
apply set.image_injective.mpr hf.inj,
ext z,
simp only [set.image_preimage_eq_inter_range, set.mem_inter_eq, and.congr_left_iff],
exact λ hy, ⟨λ h, hT.closure_eq ▸ closure_mono (set.inter_subset_left _ _) h,
λ h, subset_closure ⟨h, hy⟩⟩
end
/-- A space is quasi sober if it can be covered by open quasi sober subsets. -/
lemma quasi_sober_of_open_cover (S : set (set α)) (hS : ∀ s : S, is_open (s : set α))
[hS' : ∀ s : S, quasi_sober s] (hS'' : ⋃₀ S = ⊤) : quasi_sober α :=
begin
rw quasi_sober_iff,
intros t h h',
obtain ⟨x, hx⟩ := h.1,
obtain ⟨U, hU, hU'⟩ : x ∈ ⋃₀S := by { rw hS'', trivial },
haveI : quasi_sober U := hS' ⟨U, hU⟩,
have H : is_preirreducible (coe ⁻¹' t : set U) :=
h.2.preimage (hS ⟨U, hU⟩).open_embedding_subtype_coe,
replace H : is_irreducible (coe ⁻¹' t : set U) := ⟨⟨⟨x, hU'⟩, by simpa using hx⟩, H⟩,
use H.generic_point,
have := continuous_subtype_coe.closure_preimage_subset _ H.generic_point_spec.mem,
rw h'.closure_eq at this,
apply le_antisymm,
{ apply h'.closure_subset_iff.mpr, simpa using this },
rw [← set.image_singleton, ← closure_closure],
have := closure_mono (image_closure_subset_closure_image (@continuous_subtype_coe α _ U)),
refine set.subset.trans _ this,
rw H.generic_point_spec.def,
refine (subset_closure_inter_of_is_preirreducible_of_is_open
h.2 (hS ⟨U, hU⟩) ⟨x, hx, hU'⟩).trans (closure_mono _),
rw ← subtype.image_preimage_coe,
exact set.image_subset _ subset_closure,
end
@[priority 100]
instance t2_space.quasi_sober [t2_space α] : quasi_sober α :=
begin
constructor,
rintro S h -,
obtain ⟨x, rfl⟩ := (is_irreducible_iff_singleton S).mp h,
exact ⟨x, closure_singleton⟩
end
end sober
|
29883feab4bd11ad043f48e30f42bfbca31f70cf | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/finbug2.lean | bcaf3b519c9315abc024c34c6925a2090e6ef779 | [
"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 | 944 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
Finite ordinals.
-/
open nat
inductive fin : nat → Type :=
| fz : Π n, fin (succ n)
| fs : Π {n}, fin n → fin (succ n)
namespace fin
definition to_nat : Π {n}, fin n → nat
| @to_nat (succ n) (fz n) := zero
| @to_nat (succ n) (fs f) := succ (@to_nat n f)
definition lift : Π {n : nat}, fin n → Π (m : nat), fin (add m n)
| @lift (succ n) (fz n) m := fz (add m n)
| @lift (succ n) (@fs n f) m := fs (@lift n f m)
theorem to_nat_lift : ∀ {n : nat} (f : fin n) (m : nat), to_nat f = to_nat (lift f m)
| to_nat_lift (fz n) m := rfl
| to_nat_lift (@fs n f) m := calc
to_nat (fs f) = (to_nat f) + 1 : rfl
... = (to_nat (lift f m)) + 1 : to_nat_lift f
... = to_nat (lift (fs f) m) : rfl
end fin
|
50827f2006ce926013ccc5d6f830f5ae4cef3d7b | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/rat/denumerable.lean | 37120717f6386cbb258b043bbcf943f9d184f5b1 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 1,185 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import set_theory.cardinal.basic
/-!
# Denumerability of ℚ
This file proves that ℚ is infinite, denumerable, and deduces that it has cardinality `omega`.
-/
namespace rat
open denumerable
instance : infinite ℚ :=
infinite.of_injective (coe : ℕ → ℚ) nat.cast_injective
private def denumerable_aux : ℚ ≃ { x : ℤ × ℕ // 0 < x.2 ∧ x.1.nat_abs.coprime x.2 } :=
{ to_fun := λ x, ⟨⟨x.1, x.2⟩, x.3, x.4⟩,
inv_fun := λ x, ⟨x.1.1, x.1.2, x.2.1, x.2.2⟩,
left_inv := λ ⟨_, _, _, _⟩, rfl,
right_inv := λ ⟨⟨_, _⟩, _, _⟩, rfl }
/-- **Denumerability of the Rational Numbers** -/
instance : denumerable ℚ :=
begin
let T := { x : ℤ × ℕ // 0 < x.2 ∧ x.1.nat_abs.coprime x.2 },
letI : infinite T := infinite.of_injective _ denumerable_aux.injective,
letI : encodable T := subtype.encodable,
letI : denumerable T := of_encodable_of_infinite T,
exact denumerable.of_equiv T denumerable_aux
end
end rat
open_locale cardinal
lemma cardinal.mk_rat : #ℚ = ℵ₀ := by simp
|
a0f5917bf65b792ba917880f2d411e05f939fe43 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/data/list/chain.lean | 40c95006a1aa52b950ae63f386ff7be8d994dfaa | [
"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 | 13,034 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kenny Lau, Yury Kudryashov
-/
import data.list.pairwise
import logic.relation
/-!
# Relation chain
This file provides basic results about `list.chain` (definition in `data.list.defs`).
A list `[a₂, ..., aₙ]` is a `chain` starting at `a₁` with respect to the relation `r` if `r a₁ a₂`
and `r a₂ a₃` and ... and `r aₙ₋₁ aₙ`. We write it `chain r a₁ [a₂, ..., aₙ]`.
A graph-specialized version is in development and will hopefully be added under `combinatorics.`
sometime soon.
-/
universes u v
open nat
namespace list
variables {α : Type u} {β : Type v} {R : α → α → Prop}
mk_iff_of_inductive_prop list.chain list.chain_iff
theorem rel_of_chain_cons {a b : α} {l : list α}
(p : chain R a (b :: l)) : R a b :=
(chain_cons.1 p).1
theorem chain_of_chain_cons {a b : α} {l : list α}
(p : chain R a (b :: l)) : chain R b l :=
(chain_cons.1 p).2
theorem chain.imp' {S : α → α → Prop}
(HRS : ∀ ⦃a b⦄, R a b → S a b) {a b : α} (Hab : ∀ ⦃c⦄, R a c → S b c)
{l : list α} (p : chain R a l) : chain S b l :=
by induction p with _ a c l r p IH generalizing b; constructor;
[exact Hab r, exact IH (@HRS _)]
theorem chain.imp {S : α → α → Prop}
(H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l :=
p.imp' H (H a)
theorem chain.iff {S : α → α → Prop}
(H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l :=
⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩
theorem chain.iff_mem {a : α} {l : list α} :
chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l :=
⟨λ p, by induction p with _ a b l r p IH; constructor;
[exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩,
exact IH.imp (λ a b ⟨am, bm, h⟩,
⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)],
chain.imp (λ a b h, h.2.2)⟩
theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b :=
by simp only [chain_cons, chain.nil, and_true]
theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁ ++ b :: l₂) ↔
chain R a (l₁ ++ [b]) ∧ chain R b l₂ :=
by induction l₁ with x l₁ IH generalizing a;
simp only [*, nil_append, cons_append, chain.nil, chain_cons, and_true, and_assoc]
theorem chain_map (f : β → α) {b : β} {l : list β} :
chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l :=
by induction l generalizing b; simp only [map, chain.nil, chain_cons, *]
theorem chain_of_chain_map {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α}
(p : chain S (f a) (map f l)) : chain R a l :=
((chain_map f).1 p).imp H
theorem chain_map_of_chain {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α}
(p : chain R a l) : chain S (f a) (map f l) :=
(chain_map f).2 $ p.imp H
theorem chain_pmap_of_chain {S : β → β → Prop} {p : α → Prop}
{f : Π a, p a → β}
(H : ∀ a b ha hb, R a b → S (f a ha) (f b hb))
{a : α} {l : list α}
(hl₁ : chain R a l) (ha : p a) (hl₂ : ∀ a ∈ l, p a) :
chain S (f a ha) (list.pmap f l hl₂) :=
begin
induction l with lh lt l_ih generalizing a,
{ simp },
{ simp [H _ _ _ _ (rel_of_chain_cons hl₁), l_ih _ (chain_of_chain_cons hl₁)] }
end
theorem chain_of_chain_pmap {S : β → β → Prop} {p : α → Prop}
(f : Π a, p a → β) {l : list α} (hl₁ : ∀ a ∈ l, p a)
{a : α} (ha : p a) (hl₂ : chain S (f a ha) (list.pmap f l hl₁))
(H : ∀ a b ha hb, S (f a ha) (f b hb) → R a b) :
chain R a l :=
begin
induction l with lh lt l_ih generalizing a,
{ simp },
{ simp [H _ _ _ _ (rel_of_chain_cons hl₂), l_ih _ _ (chain_of_chain_cons hl₂)] }
end
theorem chain_of_pairwise {a : α} {l : list α} (p : pairwise R (a :: l)) : chain R a l :=
begin
cases pairwise_cons.1 p with r p', clear p,
induction p' with b l r' p IH generalizing a, {exact chain.nil},
simp only [chain_cons, forall_mem_cons] at r,
exact chain_cons.2 ⟨r.1, IH r'⟩
end
theorem chain_iff_pairwise (tr : transitive R) {a : α} {l : list α} :
chain R a l ↔ pairwise R (a :: l) :=
⟨λ c, begin
induction c with b b c l r p IH, {exact pairwise_singleton _ _},
apply IH.cons _, simp only [mem_cons_iff, forall_eq_or_imp, r, true_and],
show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)),
end, chain_of_pairwise⟩
theorem chain_iff_nth_le {R} : ∀ {a : α} {l : list α},
chain R a l ↔ (∀ h : 0 < length l, R a (nth_le l 0 h)) ∧ (∀ i (h : i < length l - 1),
R (nth_le l i (lt_of_lt_pred h)) (nth_le l (i+1) (lt_pred_iff.mp h)))
| a [] := by simp
| a (b :: t) :=
begin
rw [chain_cons, chain_iff_nth_le],
split,
{ rintro ⟨R, ⟨h0, h⟩⟩,
split,
{ intro w, exact R },
intros i w,
cases i,
{ apply h0 },
convert h i _ using 1,
simp only [succ_eq_add_one, add_succ_sub_one, add_zero, length, add_lt_add_iff_right] at w,
exact lt_pred_iff.mpr w, },
rintro ⟨h0, h⟩, split,
{ apply h0, simp, },
split,
{ apply h 0, },
intros i w, convert h (i+1) _ using 1,
exact lt_pred_iff.mp w,
end
theorem chain'.imp {S : α → α → Prop}
(H : ∀ a b, R a b → S a b) {l : list α} (p : chain' R l) : chain' S l :=
by cases l; [trivial, exact p.imp H]
theorem chain'.iff {S : α → α → Prop}
(H : ∀ a b, R a b ↔ S a b) {l : list α} : chain' R l ↔ chain' S l :=
⟨chain'.imp (λ a b, (H a b).1), chain'.imp (λ a b, (H a b).2)⟩
theorem chain'.iff_mem : ∀ {l : list α}, chain' R l ↔ chain' (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l
| [] := iff.rfl
| (x :: l) :=
⟨λ h, (chain.iff_mem.1 h).imp $ λ a b ⟨h₁, h₂, h₃⟩, ⟨h₁, or.inr h₂, h₃⟩,
chain'.imp $ λ a b h, h.2.2⟩
@[simp] theorem chain'_nil : chain' R [] := trivial
@[simp] theorem chain'_singleton (a : α) : chain' R [a] := chain.nil
theorem chain'_split {a : α} : ∀ {l₁ l₂ : list α}, chain' R (l₁ ++ a :: l₂) ↔
chain' R (l₁ ++ [a]) ∧ chain' R (a :: l₂)
| [] l₂ := (and_iff_right (chain'_singleton a)).symm
| (b :: l₁) l₂ := chain_split
theorem chain'_map (f : β → α) {l : list β} :
chain' R (map f l) ↔ chain' (λ a b : β, R (f a) (f b)) l :=
by cases l; [refl, exact chain_map _]
theorem chain'_of_chain'_map {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α}
(p : chain' S (map f l)) : chain' R l :=
((chain'_map f).1 p).imp H
theorem chain'_map_of_chain' {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α}
(p : chain' R l) : chain' S (map f l) :=
(chain'_map f).2 $ p.imp H
theorem pairwise.chain' : ∀ {l : list α}, pairwise R l → chain' R l
| [] _ := trivial
| (a :: l) h := chain_of_pairwise h
theorem chain'_iff_pairwise (tr : transitive R) : ∀ {l : list α},
chain' R l ↔ pairwise R l
| [] := (iff_true_intro pairwise.nil).symm
| (a :: l) := chain_iff_pairwise tr
@[simp] theorem chain'_cons {x y l} : chain' R (x :: y :: l) ↔ R x y ∧ chain' R (y :: l) :=
chain_cons
theorem chain'.cons {x y l} (h₁ : R x y) (h₂ : chain' R (y :: l)) :
chain' R (x :: y :: l) :=
chain'_cons.2 ⟨h₁, h₂⟩
theorem chain'.tail : ∀ {l} (h : chain' R l), chain' R l.tail
| [] _ := trivial
| [x] _ := trivial
| (x :: y :: l) h := (chain'_cons.mp h).right
theorem chain'.rel_head {x y l} (h : chain' R (x :: y :: l)) : R x y :=
rel_of_chain_cons h
theorem chain'.rel_head' {x l} (h : chain' R (x :: l)) ⦃y⦄ (hy : y ∈ head' l) : R x y :=
by { rw ← cons_head'_tail hy at h, exact h.rel_head }
theorem chain'.cons' {x} :
∀ {l : list α}, chain' R l → (∀ y ∈ l.head', R x y) → chain' R (x :: l)
| [] _ _ := chain'_singleton x
| (a :: l) hl H := hl.cons $ H _ rfl
theorem chain'_cons' {x l} : chain' R (x :: l) ↔ (∀ y ∈ head' l, R x y) ∧ chain' R l :=
⟨λ h, ⟨h.rel_head', h.tail⟩, λ ⟨h₁, h₂⟩, h₂.cons' h₁⟩
theorem chain'.append : ∀ {l₁ l₂ : list α} (h₁ : chain' R l₁) (h₂ : chain' R l₂)
(h : ∀ (x ∈ l₁.last') (y ∈ l₂.head'), R x y),
chain' R (l₁ ++ l₂)
| [] l₂ h₁ h₂ h := h₂
| [a] l₂ h₁ h₂ h := h₂.cons' $ h _ rfl
| (a :: b :: l) l₂ h₁ h₂ h :=
begin
simp only [last'] at h,
have : chain' R (b :: l) := h₁.tail,
exact (this.append h₂ h).cons h₁.rel_head
end
theorem chain'_pair {x y} : chain' R [x, y] ↔ R x y :=
by simp only [chain'_singleton, chain'_cons, and_true]
theorem chain'.imp_head {x y} (h : ∀ {z}, R x z → R y z) {l} (hl : chain' R (x :: l)) :
chain' R (y :: l) :=
hl.tail.cons' $ λ z hz, h $ hl.rel_head' hz
theorem chain'_reverse : ∀ {l}, chain' R (reverse l) ↔ chain' (flip R) l
| [] := iff.rfl
| [a] := by simp only [chain'_singleton, reverse_singleton]
| (a :: b :: l) := by rw [chain'_cons, reverse_cons, reverse_cons, append_assoc, cons_append,
nil_append, chain'_split, ← reverse_cons, @chain'_reverse (b :: l), and_comm, chain'_pair, flip]
theorem chain'_iff_nth_le {R} : ∀ {l : list α},
chain' R l ↔ ∀ i (h : i < length l - 1),
R (nth_le l i (lt_of_lt_pred h)) (nth_le l (i+1) (lt_pred_iff.mp h))
| [] := by simp
| [a] := by simp
| (a :: b :: t) :=
begin
rw [chain'_cons, chain'_iff_nth_le],
split,
{ rintro ⟨R, h⟩ i w,
cases i,
{ exact R, },
{ convert h i _ using 1,
simp only [succ_eq_add_one, add_succ_sub_one, add_zero, length, add_lt_add_iff_right] at w,
simpa using w, } },
{ rintro h, split,
{ apply h 0, simp, },
{ intros i w, convert h (i+1) _ using 1,
simp only [add_zero, length, add_succ_sub_one] at w,
simpa using w, } },
end
/-- If `l₁ l₂` and `l₃` are lists and `l₁ ++ l₂` and `l₂ ++ l₃` both satisfy
`chain' R`, then so does `l₁ ++ l₂ ++ l₃` provided `l₂ ≠ []` -/
lemma chain'.append_overlap : ∀ {l₁ l₂ l₃ : list α}
(h₁ : chain' R (l₁ ++ l₂)) (h₂ : chain' R (l₂ ++ l₃)) (hn : l₂ ≠ []),
chain' R (l₁ ++ l₂ ++ l₃)
| [] l₂ l₃ h₁ h₂ hn := h₂
| l₁ [] l₃ h₁ h₂ hn := (hn rfl).elim
| [a] (b :: l₂) l₃ h₁ h₂ hn := by { simp at *, tauto }
| (a :: b :: l₁) (c :: l₂) l₃ h₁ h₂ hn := begin
simp only [cons_append, chain'_cons] at h₁ h₂ ⊢,
simp only [← cons_append] at h₁ h₂ ⊢,
exact ⟨h₁.1, chain'.append_overlap h₁.2 h₂ (cons_ne_nil _ _)⟩
end
variables {r : α → α → Prop} {a b : α}
/--
If `a` and `b` are related by the reflexive transitive closure of `r`, then there is a `r`-chain
starting from `a` and ending on `b`.
The converse of `relation_refl_trans_gen_of_exists_chain`.
-/
lemma exists_chain_of_relation_refl_trans_gen (h : relation.refl_trans_gen r a b) :
∃ l, chain r a l ∧ last (a :: l) (cons_ne_nil _ _) = b :=
begin
apply relation.refl_trans_gen.head_induction_on h,
{ exact ⟨[], chain.nil, rfl⟩ },
{ intros c d e t ih,
obtain ⟨l, hl₁, hl₂⟩ := ih,
refine ⟨d :: l, chain.cons e hl₁, _⟩,
rwa last_cons_cons }
end
/--
Given a chain from `a` to `b`, and a predicate true at `b`, if `r x y → p y → p x` then
the predicate is true everywhere in the chain and at `a`.
That is, we can propagate the predicate up the chain.
-/
lemma chain.induction (p : α → Prop)
(l : list α) (h : chain r a l)
(hb : last (a :: l) (cons_ne_nil _ _) = b)
(carries : ∀ ⦃x y : α⦄, r x y → p y → p x) (final : p b) : ∀ i ∈ a :: l, p i :=
begin
induction l generalizing a,
{ cases hb,
simp [final] },
{ rw chain_cons at h,
rintro _ (rfl | _),
apply carries h.1 (l_ih h.2 hb _ (or.inl rfl)),
apply l_ih h.2 hb _ H }
end
/--
Given a chain from `a` to `b`, and a predicate true at `b`, if `r x y → p y → p x` then
the predicate is true at `a`.
That is, we can propagate the predicate all the way up the chain.
-/
@[elab_as_eliminator]
lemma chain.induction_head (p : α → Prop)
(l : list α) (h : chain r a l)
(hb : last (a :: l) (cons_ne_nil _ _) = b)
(carries : ∀ ⦃x y : α⦄, r x y → p y → p x) (final : p b) : p a :=
(chain.induction p l h hb carries final) _ (mem_cons_self _ _)
/--
If there is an `r`-chain starting from `a` and ending at `b`, then `a` and `b` are related by the
reflexive transitive closure of `r`. The converse of `exists_chain_of_relation_refl_trans_gen`.
-/
lemma relation_refl_trans_gen_of_exists_chain (l) (hl₁ : chain r a l)
(hl₂ : last (a :: l) (cons_ne_nil _ _) = b) :
relation.refl_trans_gen r a b :=
chain.induction_head _ l hl₁ hl₂ (λ x y, relation.refl_trans_gen.head) relation.refl_trans_gen.refl
end list
|
613b0c4936e5792dd9c78a20cc675c1a8f25f79c | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/lie/tensor_product.lean | 3bb2cac1c2aa38b024c70126eef52e96900e36a7 | [
"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 | 8,824 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.abelian
/-!
# Tensor products of Lie modules
Tensor products of Lie modules carry natural Lie module structures.
## Tags
lie module, tensor product, universal property
-/
universes u v w w₁ w₂ w₃
variables {R : Type u} [comm_ring R]
namespace tensor_product
open_locale tensor_product
namespace lie_module
open lie_module
variables {L : Type v} {M : Type w} {N : Type w₁} {P : Type w₂} {Q : Type w₃}
variables [lie_ring L] [lie_algebra R L]
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
variables [add_comm_group N] [module R N] [lie_ring_module L N] [lie_module R L N]
variables [add_comm_group P] [module R P] [lie_ring_module L P] [lie_module R L P]
variables [add_comm_group Q] [module R Q] [lie_ring_module L Q] [lie_module R L Q]
/-- It is useful to define the bracket via this auxiliary function so that we have a type-theoretic
expression of the fact that `L` acts by linear endomorphisms. It simplifies the proofs in
`lie_ring_module` below. -/
def has_bracket_aux (x : L) : module.End R (M ⊗[R] N) :=
(to_endomorphism R L M x).rtensor N + (to_endomorphism R L N x).ltensor M
/-- The tensor product of two Lie modules is a Lie ring module. -/
instance lie_ring_module : lie_ring_module L (M ⊗[R] N) :=
{ bracket := λ x, has_bracket_aux x,
add_lie := λ x y t, by
{ simp only [has_bracket_aux, linear_map.ltensor_add, linear_map.rtensor_add, lie_hom.map_add,
linear_map.add_apply], abel, },
lie_add := λ x, linear_map.map_add _,
leibniz_lie := λ x y t, by
{ suffices : (has_bracket_aux x).comp (has_bracket_aux y) =
has_bracket_aux ⁅x,y⁆ + (has_bracket_aux y).comp (has_bracket_aux x),
{ simp only [← linear_map.comp_apply, ← linear_map.add_apply], rw this, },
ext m n,
simp only [has_bracket_aux, lie_ring.of_associative_ring_bracket, linear_map.mul_apply,
mk_apply, linear_map.ltensor_sub, linear_map.compr₂_apply, function.comp_app,
linear_map.coe_comp, linear_map.rtensor_tmul, lie_hom.map_lie,
to_endomorphism_apply_apply, linear_map.add_apply, linear_map.map_add,
linear_map.rtensor_sub, linear_map.sub_apply, linear_map.ltensor_tmul],
abel, }, }
/-- The tensor product of two Lie modules is a Lie module. -/
instance lie_module : lie_module R L (M ⊗[R] N) :=
{ smul_lie := λ c x t, by
{ change has_bracket_aux (c • x) _ = c • has_bracket_aux _ _,
simp only [has_bracket_aux, smul_add, linear_map.rtensor_smul, linear_map.smul_apply,
linear_map.ltensor_smul, lie_hom.map_smul, linear_map.add_apply], },
lie_smul := λ c x, linear_map.map_smul _ c, }
@[simp] lemma lie_tmul_right (x : L) (m : M) (n : N) :
⁅x, m ⊗ₜ[R] n⁆ = ⁅x, m⁆ ⊗ₜ n + m ⊗ₜ ⁅x, n⁆ :=
show has_bracket_aux x (m ⊗ₜ[R] n) = _,
by simp only [has_bracket_aux, linear_map.rtensor_tmul, to_endomorphism_apply_apply,
linear_map.add_apply, linear_map.ltensor_tmul]
variables (R L M N P Q)
/-- The universal property for tensor product of modules of a Lie algebra: the `R`-linear
tensor-hom adjunction is equivariant with respect to the `L` action. -/
def lift : (M →ₗ[R] N →ₗ[R] P) ≃ₗ⁅R,L⁆ (M ⊗[R] N →ₗ[R] P) :=
{ map_lie' := λ x f, by
{ ext m n, simp only [mk_apply, linear_map.compr₂_apply, lie_tmul_right, linear_map.sub_apply,
lift.equiv_apply, linear_equiv.to_fun_eq_coe, lie_hom.lie_apply, linear_map.map_add],
abel, },
..tensor_product.lift.equiv R M N P }
@[simp] lemma lift_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) :
lift R L M N P f (m ⊗ₜ n) = f m n :=
lift.equiv_apply R M N P f m n
/-- A weaker form of the universal property for tensor product of modules of a Lie algebra.
Note that maps `f` of type `M →ₗ⁅R,L⁆ N →ₗ[R] P` are exactly those `R`-bilinear maps satisfying
`⁅x, f m n⁆ = f ⁅x, m⁆ n + f m ⁅x, n⁆` for all `x, m, n` (see e.g, `lie_module_hom.map_lie₂`). -/
def lift_lie : (M →ₗ⁅R,L⁆ N →ₗ[R] P) ≃ₗ[R] (M ⊗[R] N →ₗ⁅R,L⁆ P) :=
(max_triv_linear_map_equiv_lie_module_hom.symm.trans
↑(max_triv_equiv (lift R L M N P))).trans
max_triv_linear_map_equiv_lie_module_hom
@[simp] lemma coe_lift_lie_eq_lift_coe (f : M →ₗ⁅R,L⁆ N →ₗ[R] P) :
⇑(lift_lie R L M N P f) = lift R L M N P f :=
begin
suffices : (lift_lie R L M N P f : M ⊗[R] N →ₗ[R] P) = lift R L M N P f,
{ rw [← this, lie_module_hom.coe_to_linear_map], },
ext m n,
simp only [lift_lie, linear_equiv.trans_apply, lie_module_equiv.coe_to_linear_equiv,
coe_linear_map_max_triv_linear_map_equiv_lie_module_hom, coe_max_triv_equiv_apply,
coe_linear_map_max_triv_linear_map_equiv_lie_module_hom_symm],
end
lemma lift_lie_apply (f : M →ₗ⁅R,L⁆ N →ₗ[R] P) (m : M) (n : N) :
lift_lie R L M N P f (m ⊗ₜ n) = f m n :=
by simp only [coe_lift_lie_eq_lift_coe, lie_module_hom.coe_to_linear_map, lift_apply]
variables {R L M N P Q}
/-- A pair of Lie module morphisms `f : M → P` and `g : N → Q`, induce a Lie module morphism:
`M ⊗ N → P ⊗ Q`. -/
def map (f : M →ₗ⁅R,L⁆ P) (g : N →ₗ⁅R,L⁆ Q) : M ⊗[R] N →ₗ⁅R,L⁆ P ⊗[R] Q :=
{ map_lie' := λ x t, by
{ simp only [linear_map.to_fun_eq_coe],
apply t.induction_on,
{ simp only [linear_map.map_zero, lie_zero], },
{ intros m n, simp only [lie_module_hom.coe_to_linear_map, lie_tmul_right,
lie_module_hom.map_lie, map_tmul, linear_map.map_add], },
{ intros t₁ t₂ ht₁ ht₂, simp only [ht₁, ht₂, lie_add, linear_map.map_add], }, },
.. map (f : M →ₗ[R] P) (g : N →ₗ[R] Q), }
@[simp] lemma coe_linear_map_map (f : M →ₗ⁅R,L⁆ P) (g : N →ₗ⁅R,L⁆ Q) :
(map f g : M ⊗[R] N →ₗ[R] P ⊗[R] Q) = tensor_product.map (f : M →ₗ[R] P) (g : N →ₗ[R] Q) :=
rfl
@[simp] lemma map_tmul (f : M →ₗ⁅R,L⁆ P) (g : N →ₗ⁅R,L⁆ Q) (m : M) (n : N) :
map f g (m ⊗ₜ n) = (f m) ⊗ₜ (g n) :=
map_tmul f g m n
/-- Given Lie submodules `M' ⊆ M` and `N' ⊆ N`, this is the natural map: `M' ⊗ N' → M ⊗ N`. -/
def map_incl (M' : lie_submodule R L M) (N' : lie_submodule R L N) :
M' ⊗[R] N' →ₗ⁅R,L⁆ M ⊗[R] N :=
map M'.incl N'.incl
@[simp] lemma map_incl_def (M' : lie_submodule R L M) (N' : lie_submodule R L N) :
map_incl M' N' = map M'.incl N'.incl :=
rfl
end lie_module
end tensor_product
namespace lie_module
open_locale tensor_product
variables (R) (L : Type v) (M : Type w)
variables [lie_ring L] [lie_algebra R L]
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
/-- The action of the Lie algebra on one of its modules, regarded as a morphism of Lie modules. -/
def to_module_hom : L ⊗[R] M →ₗ⁅R,L⁆ M :=
tensor_product.lie_module.lift_lie R L L M M
{ map_lie' := λ x m, by { ext n, simp [lie_ring.of_associative_ring_bracket], },
..(to_endomorphism R L M : L →ₗ[R] M →ₗ[R] M), }
@[simp] lemma to_module_hom_apply (x : L) (m : M) :
to_module_hom R L M (x ⊗ₜ m) = ⁅x, m⁆ :=
by simp only [to_module_hom, tensor_product.lie_module.lift_lie_apply, to_endomorphism_apply_apply,
lie_hom.coe_to_linear_map, lie_module_hom.coe_mk, linear_map.to_fun_eq_coe]
end lie_module
namespace lie_submodule
open_locale tensor_product
open tensor_product.lie_module
open lie_module
variables {L : Type v} {M : Type w}
variables [lie_ring L] [lie_algebra R L]
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
variables (I : lie_ideal R L) (N : lie_submodule R L M)
/-- A useful alternative characterisation of Lie ideal operations on Lie submodules.
Given a Lie ideal `I ⊆ L` and a Lie submodule `N ⊆ M`, by tensoring the inclusion maps and then
applying the action of `L` on `M`, we obtain morphism of Lie modules `f : I ⊗ N → L ⊗ M → M`.
This lemma states that `⁅I, N⁆ = range f`. -/
lemma lie_ideal_oper_eq_tensor_map_range :
⁅I, N⁆ = ((to_module_hom R L M).comp (map_incl I N : ↥I ⊗ ↥N →ₗ⁅R,L⁆ L ⊗ M)).range :=
begin
rw [← coe_to_submodule_eq_iff, lie_ideal_oper_eq_linear_span, lie_module_hom.coe_submodule_range,
lie_module_hom.coe_linear_map_comp, linear_map.range_comp, map_incl_def, coe_linear_map_map,
tensor_product.map_range_eq_span_tmul, submodule.map_span],
congr, ext m, split,
{ rintros ⟨⟨x, hx⟩, ⟨n, hn⟩, rfl⟩, use x ⊗ₜ n, split,
{ use [⟨x, hx⟩, ⟨n, hn⟩], simp, },
{ simp, }, },
{ rintros ⟨t, ⟨⟨x, hx⟩, ⟨n, hn⟩, rfl⟩, h⟩, rw ← h, use [⟨x, hx⟩, ⟨n, hn⟩], simp, },
end
end lie_submodule
|
d4f9880c5adc68faf84032a114cd48d29606be60 | 76c77df8a58af24dbf1d75c7012076a42244d728 | /src/ch4.lean | 7beacf95152e83ca1259e7a820b5d0d5606bd8f8 | [] | no_license | kris-brown/theorem_proving_in_lean | 7a7a584ba2c657a35335dc895d49d991c997a0c9 | 774460c21bf857daff158210741bd88d1c8323cd | refs/heads/master | 1,668,278,123,743 | 1,593,445,161,000 | 1,593,445,161,000 | 265,748,924 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 23,936 | lean | #check function.const
-- Section 4.1: The universal quantifier
namespace s41
section
variables (α : Type) (p q : α → Prop)
-- ∀ is more natural than Π when p is a proposition
example : (∀ x : α, p x ∧ q x) → ∀ y : α, p y :=
assume h : ∀ x : α, p x ∧ q x,
assume y : α, -- prove for an arbitrary α
show p y, from (h y).left
-- Alpha-equivalent version
example : (∀ x : α, p x ∧ q x) → ∀ x : α, p x :=
assume h : ∀ x : α, p x ∧ q x,
assume z : α,
show p z, from and.elim_left (h z)
end
-- Transitivity
section
variables (α : Type) (r : α → α → Prop)
variable trans_r : ∀ x y z, r x y → r y z → r x z
variables a b c : α
variables (hab : r a b) (hbc : r b c)
#check trans_r -- ∀ (x y z : α), r x y → r y z → r x z
#check trans_r a b c
#check trans_r a b c hab
#check trans_r a b c hab hbc
end
-- Less tedious with implicit variables
section
universe u
variables (β : Type u) (r : β → β → Prop)
variable trans_r : ∀ {x y z}, r x y → r y z → r x z
variables (a b c : β)
variables (hab : r a b) (hbc : r b c)
#check trans_r
#check trans_r hab
#check trans_r hab hbc
end
-- Equivalence relation
variables (α : Type) (r : α → α → Prop)
--variables (r : α → α → Prop)
variable refl_r : ∀ x, r x x
variable symm_r : ∀ {x y}, r x y → r y x
variable trans_r : ∀ {x y z}, r x y → r y z → r x z
example (a b c d : α) (hab : r a b) (hcb : r c b) (hcd : r c d) :
r a d :=
trans_r (trans_r hab (symm_r hcb)) hcd
end s41
-- Section 4.2: Equality
namespace s42
#check eq.refl -- ∀ (a : ?M_1), a = a
#check eq.symm -- ?M_2 = ?M_3 → ?M_3 = ?M_2
#check eq.trans -- ?M_2 = ?M_3 → ?M_3 = ?M_4 → ?M_2 = ?M_4
section
universe u
#check @eq.refl.{u} -- ∀ {α : Sort u} (a : α), a = a
#check @eq.symm.{u} -- ∀ {α : Sort u} {a b : α}, a = b → b = a
#check @eq.trans.{u} -- ∀ {α : Sort u} {a b c : α},
-- a = b → b = c → a = c
variables (α : Type u) (a b c d : α)
variables (hab : a = b) (hcb : c = b) (hcd : c = d)
example : a = d :=
eq.trans (eq.trans hab (eq.symm hcb)) hcd
-- Equivalent, using the 'projection' notation
example : a = d := (hab.trans hcb.symm).trans hcd
end
section
-- Reflexivity example
universe u
variables (α β : Type u)
example (f : α → β) (a : α) : (λ x, f x) a = f a := eq.refl _
example (a : α) (b : α) : (a, b).1 = a := eq.refl _
example : 2 + 3 = 5 := eq.refl _
-- Shorthand for eq.refl _
example (f : α → β) (a : α) : (λ x, f x) a = f a := rfl
example (a : α) (b : α) : (a, b).1 = a := rfl
example : 2 + 3 = 5 := rfl
end
section
-- = is special equivalenc relation: every assertion respects the equivalence
universe u
example (α : Type u) (a b : α) (p : α → Prop)
(h1 : a = b) (h2 : p a) : p b :=
eq.subst h1 h2
-- shorthand for eq.subst
example (α : Type u) (a b : α) (p : α → Prop)
(h1 : a = b) (h2 : p a) : p b :=
h1 ▸ h2
end
section
-- More explicit subsitutions: arg, fun, or both arg and fun
variable α : Type
variables a b : α
variables f g : α → ℕ
variable h₁ : a = b
variable h₂ : f = g
example : f a = f b := congr_arg f h₁
example : f a = g a := congr_fun h₂ a
example : f a = g b := congr h₂ h₁
#check congr_arg
end
-- Common identities in library
section
variables a b c d : ℤ
example : a + 0 = a := add_zero a
example : 0 + a = a := zero_add a
example : a * 1 = a := mul_one a
example : 1 * a = a := one_mul a
example : -a + a = 0 := neg_add_self a
example : a + -a = 0 := add_neg_self a
example : a - a = 0 := sub_self a
example : a + b = b + a := add_comm a b
example : a + b + c = a + (b + c) := add_assoc a b c
example : a * b = b * a := mul_comm a b
example : a * b * c = a * (b * c) := mul_assoc a b c
example : a * (b + c) = a * b + a * c := mul_add a b c
example : a * (b + c) = a * b + a * c := left_distrib a b c
example : (a + b) * c = a * c + b * c := add_mul a b c
example : (a + b) * c = a * c + b * c := right_distrib a b c
example : a * (b - c) = a * b - a * c := mul_sub a b c
example : (a - b) * c = a * c - b * c := sub_mul a b c
end
section
variables x y z : ℤ
example (x y z : ℕ) : x * (y + z) = x * y + x * z := mul_add x y z
example (x y z : ℕ) : (x + y) * z = x * z + y * z := add_mul x y z
example (x y z : ℕ) : x + y + z = x + (y + z) := add_assoc x y z
example (x y : ℕ) :
(x + y) * (x + y) = x * x + y * x + x * y + y * y :=
have h1 : (x + y) * (x + y) = (x + y) * x + (x + y) * y,
from mul_add (x + y) x y,
have h2 : (x + y) * (x + y) = x * x + y * x + (x * y + y * y),
from (add_mul x y x) ▸ (add_mul x y y) ▸ h1,
h2.trans (add_assoc (x * x + y * x) (x * y) (y * y)).symm
end
end s42
-- Section 4.3: Calculational proofs
namespace s43
section
variables (a b c d e : ℕ)
variable h1 : a = b
variable h2 : b = c + 1
variable h3 : c = d
variable h4 : e = 1 + d
theorem T : a = e :=
calc
a = b : h1
... = c + 1 : h2
... = d + 1 : congr_arg _ h3
... = 1 + d : add_comm d (1 : ℕ)
... = e : eq.symm h4
-- Multiple rewrites sequentially
include h1 h2 h3 h4
theorem T2 : a = e :=
calc
a = d + 1 : by rw [h1, h2, h3]
... = 1 + d : by rw add_comm
... = e : by rw h4
-- Apply any rewrite in any order
theorem T3 : a = e :=
by simp [h1, h2, h3, h4]
end
section
-- Can use other transitive relations with the calc block
theorem T4 (a b c d : ℕ)
(h1 : a = b) (h2 : b ≤ c) (h3 : c + 1 < d) : a < d :=
calc
a = b : h1
... < b + 1 : nat.lt_succ_self b
... ≤ c + 1 : nat.succ_le_succ h2
... < d : h3
-- Rewriting of the proof in 4.2 in a much more legible way
example (x y : ℕ) :
(x + y) * (x + y) = x * x + y * x + x * y + y * y :=
calc
(x + y) * (x + y) = (x + y) * x + (x + y) * y : by rw mul_add
... = x * x + y * x + (x + y) * y : by rw add_mul
... = x * x + y * x + (x * y + y * y) : by rw add_mul
... = x * x + y * x + x * y + y * y : by rw ←add_assoc
-- Sequential
example (x y : ℕ) :
(x + y) * (x + y) = x * x + y * x + x * y + y * y :=
by rw [mul_add, add_mul, add_mul, ←add_assoc]
-- Auto simplification
example (x y : ℕ) :
(x + y) * (x + y) = x * x + y * x + x * y + y * y :=
by simp [mul_add, add_mul]
end
end s43
-- Section 4.4: Existential quantifier
namespace s44
section
-- Introduction
open nat
example : ∃ x : ℕ, x > 0 :=
have h : 1 > 0, from zero_lt_succ 0,
exists.intro 1 h
example (x : ℕ) (h : x > 0) : ∃ y, y < x :=
exists.intro 0 h
example (x y z : ℕ) (hxy : x < y) (hyz : y < z) :
∃ w, x < w ∧ w < z :=
exists.intro y (and.intro hxy hyz)
#check @exists.intro
-- Anonymous constructor for exists.intro
example : ∃ x : ℕ, x > 0 :=
⟨1, zero_lt_succ 0⟩
example (x : ℕ) (h : x > 0) : ∃ y, y < x :=
⟨0, h⟩
example (x y z : ℕ) (hxy : x < y) (hyz : y < z) :
∃ w, x < w ∧ w < z :=
⟨y, hxy, hyz⟩
-- Implicit arguments to exists.intro
variable g : ℕ → ℕ → ℕ
variable hg : g 0 0 = 0
theorem gex1 : ∃ x, g x x = x := ⟨0, hg⟩
theorem gex2 : ∃ x, g x 0 = x := ⟨0, hg⟩
theorem gex3 : ∃ x, g 0 0 = x := ⟨0, hg⟩
theorem gex4 : ∃ x, g x x = 0 := ⟨0, hg⟩
set_option pp.implicit true -- display implicit arguments
#print gex1
#print gex2
#print gex3
#print gex4
end
section
-- Exists elim
variables (α : Type) (p q : α → Prop)
example (h : ∃ x, p x ∧ q x) : ∃ x, q x ∧ p x :=
exists.elim h -- think as a generalization of or.elim, for each possible x
(assume w,
assume hw : p w ∧ q w,
show ∃ x, q x ∧ p x, from ⟨w, hw.right, hw.left⟩)
-- More convenient way to eliminate ∃
example (h : ∃ x, p x ∧ q x) : ∃ x, q x ∧ p x :=
match h with ⟨w, hw⟩ :=
⟨w, hw.right, hw.left⟩
end
-- match “destructs” the ∃ into components which are used in the body to prove the proposition
-- Now with type annotation
example (h : ∃ x, p x ∧ q x) : ∃ x, q x ∧ p x :=
match h with ⟨w, hpw, hqw⟩ :=
⟨w, hqw, hpw⟩
end
-- Even more convenient
example (h : ∃ x, p x ∧ q x) : ∃ x, q x ∧ p x :=
let ⟨w, hpw, hqw⟩ := h in ⟨w, hqw, hpw⟩
--Implicit "match" in the assume statement
example : (∃ x, p x ∧ q x) → ∃ x, q x ∧ p x :=
assume ⟨w, hpw, hqw⟩, ⟨w, hqw, hpw⟩
end
section
-- Sum of two even numbers is even
def is_even (a : nat) := ∃ b, a = 2 * b
theorem even_plus_even {a b : nat}
(h1 : is_even a) (h2 : is_even b) : is_even (a + b) :=
exists.elim h1 (assume w1, assume hw1 : a = 2 * w1,
exists.elim h2 (assume w2, assume hw2 : b = 2 * w2,
exists.intro (w1 + w2)
(calc
a + b = 2 * w1 + 2 * w2 : by rw [hw1, hw2]
... = 2*(w1 + w2) : by rw mul_add)))
--Succinct
theorem even_plus_even2 {a b : nat}
(h1 : is_even a) (h2 : is_even b) : is_even (a + b) :=
match h1, h2 with
⟨w1, hw1⟩, ⟨w2, hw2⟩ := ⟨w1 + w2, by rw [hw1, hw2, mul_add]⟩
end
end
section
-- A proof that requires classical logic
-- Knowing that something is false isn't constructively the same
-- as knowing the thing that makes it false
open classical
variables (α : Type) (p : α → Prop)
example (h : ¬ ∀ x, ¬ p x) : ∃ x, p x :=
by_contradiction
(assume h1 : ¬ ∃ x, p x,
have h2 : ∀ x, ¬ p x, from
assume x,
assume h3 : p x,
have h4 : ∃ x, p x, from ⟨x, h3⟩,
show false, from h1 h4,
show false, from h h2)
end
end s44
-- Section 4.5: More on proof language
namespace s45
-- "this" to refer to previous
variable f : ℕ → ℕ
variable h : ∀ x : ℕ, f x ≤ f (x + 1)
example : f 0 ≤ f 3 :=
have f 0 ≤ f 1, from h 0,
have f 0 ≤ f 2, from le_trans this (h 1),
show f 0 ≤ f 3, from le_trans this (h 2)
-- assumption
example : f 0 ≤ f 3 :=
have f 0 ≤ f 1, from h 0,
have f 0 ≤ f 2, from le_trans (by assumption) (h 1),
show f 0 ≤ f 3, from le_trans (by assumption) (h 2)
-- notation `‹` p `›` := show p, by assumption
example : f 0 ≥ f 1 → f 1 ≥ f 2 → f 0 = f 2 :=
assume : f 0 ≥ f 1,
assume : f 1 ≥ f 2,
have f 0 ≥ f 2, from le_trans this ‹f 0 ≥ f 1›,
have f 0 ≤ f 2, from le_trans (h 0) (h 1),
show f 0 = f 2, from le_antisymm this ‹f 0 ≥ f 2›
example : f 0 ≤ f 3 :=
have f 0 ≤ f 1, from h 0,
have f 1 ≤ f 2, from h 1,
have f 2 ≤ f 3, from h 2,
show f 0 ≤ f 3, from le_trans ‹f 0 ≤ f 1›
(le_trans ‹f 1 ≤ f 2› ‹f 2 ≤ f 3›)
-- assume hypothesis w/o a label
example : f 0 ≥ f 1 → f 0 = f 1 :=
assume : f 0 ≥ f 1,
show f 0 = f 1, from le_antisymm (h 0) this
-- anonymous Assumption used later in a proof
example : f 0 ≥ f 1 → f 1 ≥ f 2 → f 0 = f 2 :=
assume : f 0 ≥ f 1,
assume : f 1 ≥ f 2,
have f 0 ≥ f 2, from le_trans ‹f 2 ≤ f 1› ‹f 1 ≤ f 0›,
have f 0 ≤ f 2, from le_trans (h 0) (h 1),
show f 0 = f 2, from le_antisymm this ‹f 0 ≥ f 2›
end s45
-- Exercises
namespace s4x
--1
section
variables (α : Type) (p q : α → Prop)
example : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := iff.intro
(assume h : (∀ x, p x ∧ q x),
have hp : ∀ x, p x, from (λ a, (h a).left),
have hq : ∀ x, q x, from (λ a, (h a).right),
show (∀ x, p x) ∧ (∀ x, q x), from and.intro hp hq)
(assume h : (∀ x, p x) ∧ (∀ x, q x),
(assume a : α,
show p a ∧ q a, from and.intro (h.left a) (h.right a)))
example : (∀ x, p x → q x) → (∀ x, p x) → (∀ x, q x) :=
assume h : ∀ x, p x → q x,
assume hp : ∀ x, p x,
assume a : α,
have pa : p a, from hp a,
show q a, from (h a) pa
example : (∀ x, p x) ∨ (∀ x, q x) → ∀ x, p x ∨ q x :=
assume h : (∀ x, p x) ∨ (∀ x, q x),
assume a : α,
show p a ∨ q a, from or.elim h
(assume hp : ∀ x, p x, or.inl (hp a))
(assume hq : ∀ x, q x, or.inr (hq a))
-- Why the reverse implication is not derivable in the last example?
-- Because some elements may be p whereas other elements may be q.
end
--2
section
variables (α : Type) (p q : α → Prop)
variable r : Prop
example : α → ((∀ x : α, r) ↔ r) :=
assume a : α, iff.intro
(assume h : ∀ x : α, r, h a)
(assume hr : r, λ _, hr)
example : (∀ x, r → p x) ↔ (r → ∀ x, p x) := iff.intro
(assume h : ∀ x, r → p x,
assume hr : r,
assume a : α, h a hr)
(assume h : r → ∀ x, p x,
assume a : α,
assume hr : r, h hr a)
open classical -- One direction needs it
example : (∀ x, p x ∨ r) ↔ (∀ x, p x) ∨ r := iff.intro
(assume h : ∀ x, p x ∨ r,
have emr : r ∨ ¬ r, from em r,
or.elim emr
or.inr
(assume hnr : ¬ r,
have hpx: ∀ x, p x, from
assume a : α,
have hpar : p a ∨ r, from h a,
show p a, from or.elim hpar id (flip absurd hnr),
or.inl hpx))
(assume h : (∀ x, p x) ∨ r,
assume a : α , or.elim h
(assume hx : ∀ x, p x, or.inl (hx a))
or.inr)
end
--3: barber paradox
section
variables (men : Type) (barber : men)
variable (shaves : men → men → Prop)
open classical
example (h : ∀ x : men, shaves barber x ↔ ¬ shaves x x) :
false :=
have hf: shaves barber barber → ¬shaves barber barber, from (h barber).mp,
have hfr: ¬shaves barber barber → shaves barber barber, from (h barber).mpr,
have e : shaves barber barber ∨ ¬ shaves barber barber, from em (shaves barber barber),
or.elim e
(assume h: shaves barber barber, absurd h (hf h))
(assume h : ¬ shaves barber barber, absurd (hfr h) h)
end
--4
namespace hidden
def divides (m n : ℕ) : Prop := ∃ k, m * k = n
instance : has_dvd nat := ⟨divides⟩
def even (n : ℕ) : Prop := 2 ∣ n -- You can enter the '∣' character by typing \mid
section
variables m n : ℕ
#check m ∣ n
#check m^n
#check even (m^n +3)
end
def prime (n : ℕ) : Prop := ∀ m : ℕ, divides m n → m=1 ∨ m=n
def infinitely_many_primes : Prop := ∀ n : ℕ, ∃ p: ℕ, prime(p) ∧ p > n
def Fermat_prime (n : ℕ) : Prop := prime(n) ∧ (∃ m : ℕ, n=2^(2^m))
def infinitely_many_Fermat_primes : Prop := ∀ n : ℕ, ∃ p: ℕ, Fermat_prime(p) ∧ p > n
def goldbach_conjecture : Prop :=
∀ n : ℕ,
even(n) ∧ n > 2
→ ∃ a b : ℕ,
prime(a) ∧ prime(b) ∧ n=a+b
def Goldbach's_weak_conjecture : Prop :=
∀ n : ℕ,
¬ even(n) ∧ n > 5
→ ∃ a b c : ℕ,
prime(a) ∧ prime(b) ∧ prime(c) ∧ n=a+b+c
def Fermat's_last_theorem : Prop :=
∀ n : ℕ,
n > 2
→ ∀ a b c : ℕ,
¬ (a^n+b^n = c^n)
end hidden
--5
section
open classical
variables (α : Type) (p q : α → Prop)
variable a : α
variable r : Prop
example : (∃ x : α, r) → r :=
assume h : ∃ x : α, r,
exists.elim h
(assume _, id)
example : r → (∃ x : α, r) :=
assume hr : r,
⟨a, hr⟩
example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r := iff.intro
(assume h: ∃ x, p x ∧ r,
match h with ⟨w, pw_r⟩ :=
and.intro ⟨w, pw_r.left⟩ pw_r.right
end)
(assume h: (∃ x, p x) ∧ r,
match h.left with ⟨w, pw⟩ :=
⟨w, and.intro pw h.right⟩
end)
example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := iff.intro
(assume h : (∃ x, p x ∨ q x),
match h with ⟨w, pwqw⟩ :=
or.elim pwqw
(assume hl : p w, or.inl ⟨w, hl⟩)
(assume hr : q w, or.inr ⟨w, hr⟩)
end )
(assume h : (∃ x, p x) ∨ (∃ x, q x), or.elim h
(assume hl: ∃ x, p x,
match hl with ⟨w,pw⟩ := ⟨w,or.inl pw⟩ end)
(assume hr: ∃ x, q x,
match hr with ⟨w,qw⟩ := ⟨w,or.inr qw⟩ end))
example : (∀ x, p x) ↔ ¬ (∃ x, ¬ p x) := iff.intro
(assume h : ∀ x, p x,
assume hn : ∃ x, ¬ p x,
match hn with ⟨w, npw⟩ := absurd (h w) npw end)
(assume h : ¬ (∃ x, ¬ p x),
assume z: α,
have ep: p z ∨ ¬(p z), from em (p z),
or.elim ep id
(assume hnpz : ¬(p z), false.elim (h ⟨z, hnpz⟩)))
example : (∃ x, p x) ↔ ¬ (∀ x, ¬ p x) := iff.intro
(assume h : ∃ x, p x,
match h with ⟨w, pw⟩ :=
assume h2: ∀ x, ¬ p x,
absurd pw (h2 w)
end)
(assume h : ¬ (∀ x, ¬ p x),
have hem: (∃ x, p x) ∨ (¬ ∃ x, p x), from em ∃ x, p x,
or.elim hem id
(assume hn: ¬ ∃ x, p x,
false.elim (h
(assume b: α,
have hem2: p b ∨ ¬p b, from em (p b),
or.elim hem2
(assume hpb: p b, false.elim (hn ⟨b, hpb⟩))
id))))
example : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) := iff.intro
(assume h : ¬ ∃ x, p x,
assume b: α,
have hem: p b ∨ ¬p b, from em (p b),
or.elim hem
(assume hpb: p b, false.elim (h ⟨b, hpb⟩))
id)
(assume h : ∀ x, ¬ p x,
assume hx: ∃ x, p x,
match hx with ⟨w, hpw⟩ := absurd hpw (h w) end)
example : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := iff.intro
(assume h : ¬ ∀ x, p x,
have ep: (∃ x, ¬ p x) ∨ ¬(∃ x, ¬ p x), from em (∃ x, ¬ p x),
or.elim ep id
(assume hn :¬(∃ x, ¬ p x),
false.elim (h
(assume b: α,
have hem2: p b ∨ ¬p b, from em (p b),
or.elim hem2 id
(assume hnpb: ¬ p b, false.elim (hn ⟨b, hnpb⟩))))))
(assume h : ∃ x, ¬ p x,
match h with ⟨w, npw⟩ :=
assume h2: ∀ x, p x,
have h3: p w, from h2 w,
show false, from absurd h3 npw
end)
example : (∀ x, p x → r) ↔ (∃ x, p x) → r := iff.intro
(assume h : ∀ x, p x → r,
assume hx : ∃ x, p x,
match hx with ⟨w, hpw⟩ :=
show r, from h w hpw
end)
(assume h : (∃ x, p x) → r,
assume b: α,
assume hpb : p b,
show r, from h ⟨b, hpb⟩)
example : (∃ x, p x → r) ↔ (∀ x, p x) → r := iff.intro
(assume h : (∃ x, p x → r),
(assume hb: ∀ x, p x,
match h with ⟨w, hpwr⟩ :=
show r, from hpwr (hb w)
end))
(assume h1 : (∀ x, p x) → r,
show ∃ x, p x → r, from
by_cases
(assume hap : ∀ x, p x, ⟨a, λ h', h1 hap⟩)
(assume hnap : ¬ ∀ x, p x,
by_contradiction
(assume hnex : ¬ ∃ x, p x → r,
have hap : ∀ x, p x, from
assume x,
by_contradiction
(assume hnp : ¬ p x,
have hex : ∃ x, p x → r,
from ⟨x, (assume hp, absurd hp hnp)⟩,
show false, from hnex hex),
show false, from hnap hap)))
example : (∃ x, r → p x) ↔ (r → ∃ x, p x) := iff.intro
(assume h : (∃ x, r → p x),
(assume hr : r,
match h with ⟨w, rpw⟩ :=
⟨w, rpw hr⟩
end ))
(assume h : (r → ∃ x, p x),
by_cases
(assume hr: r,
have hx: ∃ x, p x, from h hr,
match hx with ⟨w, hpw⟩ := ⟨w, λ _, hpw⟩
end )
(assume nhr: ¬r, ⟨a,(assume hr:r, absurd hr nhr)⟩))
end
--6: give a calculational proof
section
variables (real : Type) [ordered_ring real]
variables (log exp : real → real)
variable log_exp_eq : ∀ x, log (exp x) = x
variable exp_log_eq : ∀ {x}, x > 0 → exp (log x) = x
variable exp_pos : ∀ x, exp x > 0
variable exp_add : ∀ x y, exp (x + y) = exp x * exp y
-- this ensures the assumptions are available in tactic proofs
include log_exp_eq exp_log_eq exp_pos exp_add
example (x y z : real) :
exp (x + y + z) = exp x * exp y * exp z :=
by rw [exp_add, exp_add]
example (y : real) (h : y > 0) : exp (log y) = y :=
exp_log_eq h
-- don't understand
theorem log_mul {x y : real} (hx : x > 0) (hy : y > 0) :
log (x * y) = log x + log y :=
begin
rw[<-exp_log_eq hx, <-exp_log_eq hy, <-exp_add],
simp only [log_exp_eq]
end
end
--7
--use only ring properties of ℤ in Section 4.2 + the theorem sub_self.
#check sub_self
example (x : ℤ) :
x * 0 = 0 :=
by simp
-- IDK why this doesn't work
-- rw [<-neg_add_self, sub_mul, sub_self]
end s4x
|
3f8be55e1b206aac5f66f91d66821d5f27ad50f0 | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /stage0/src/Lean/Widget/InteractiveGoal.lean | 527f6595f6b4132c3a317c4229c618e1e9361d56 | [
"Apache-2.0"
] | permissive | subfish-zhou/leanprover-zh_CN.github.io | 30b9fba9bd790720bd95764e61ae796697d2f603 | 8b2985d4a3d458ceda9361ac454c28168d920d3f | refs/heads/master | 1,689,709,967,820 | 1,632,503,056,000 | 1,632,503,056,000 | 409,962,097 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,043 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Wojciech Nawrocki
-/
import Lean.Meta.PPGoal
import Lean.Widget.InteractiveCode
/-! RPC procedures for retrieving tactic and term goals with embedded `CodeWithInfos`. -/
namespace Lean.Widget
open Server
structure InteractiveHypothesis where
names : Array String
type : CodeWithInfos
val? : Option CodeWithInfos := none
deriving Inhabited, RpcEncoding
structure InteractiveGoal where
hyps : Array InteractiveHypothesis
type : CodeWithInfos
userName? : Option String
deriving Inhabited, RpcEncoding
namespace InteractiveGoal
private def addLine (fmt : Format) : Format :=
if fmt.isNil then fmt else fmt ++ Format.line
def pretty (g : InteractiveGoal) : Format := do
let indent := 2 -- Use option
let mut ret := match g.userName? with
| some userName => f!"case {userName}"
| none => Format.nil
for hyp in g.hyps do
ret := addLine ret
let names := " ".intercalate hyp.names.toList
match hyp.val? with
| some val =>
ret := ret ++ Format.group f!"{names} : {hyp.type.stripTags} :={Format.nest indent (Format.line ++ val.stripTags)}"
| none =>
ret := ret ++ Format.group f!"{names} :{Format.nest indent (Format.line ++ hyp.type.stripTags)}"
ret := addLine ret
ret ++ f!"⊢ {Format.nest indent g.type.stripTags}"
end InteractiveGoal
structure InteractiveTermGoal where
hyps : Array InteractiveHypothesis
type : CodeWithInfos
range : Lsp.Range
deriving Inhabited, RpcEncoding
namespace InteractiveTermGoal
def toInteractiveGoal (g : InteractiveTermGoal) : InteractiveGoal :=
{ g with userName? := none }
end InteractiveTermGoal
structure InteractiveGoals where
goals : Array InteractiveGoal
deriving RpcEncoding
open Meta in
/-- A variant of `Meta.ppGoal` which preserves subexpression information for interactivity. -/
def goalToInteractive (mvarId : MVarId) : MetaM InteractiveGoal := do
let some mvarDecl ← (← getMCtx).findDecl? mvarId
| throwError "unknown goal {mvarId.name}"
let ppAuxDecls := pp.auxDecls.get (← getOptions)
let lctx := mvarDecl.lctx
let lctx := lctx.sanitizeNames.run' { options := (← getOptions) }
withLCtx lctx mvarDecl.localInstances do
let (hidden, hiddenProp) ← ToHide.collect mvarDecl.type
-- The following two `let rec`s are being used to control the generated code size.
-- Then should be remove after we rewrite the compiler in Lean
let rec pushPending (ids : Array Name) (type? : Option Expr) (hyps : Array InteractiveHypothesis)
: MetaM (Array InteractiveHypothesis) :=
if ids.isEmpty then
pure hyps
else
match ids, type? with
| _, none => pure hyps
| _, some type =>
return hyps.push { names := ids.map toString, type := ← exprToInteractive type }
let rec ppVars (varNames : Array Name) (prevType? : Option Expr) (hyps : Array InteractiveHypothesis) (localDecl : LocalDecl)
: MetaM (Array Name × Option Expr × Array InteractiveHypothesis) := do
if hiddenProp.contains localDecl.fvarId then
let hyps ← pushPending varNames prevType? hyps
let type ← instantiateMVars localDecl.type
let hyps := hyps.push { names := #[], type := ← exprToInteractive type }
pure (#[], none, hyps)
else
match localDecl with
| LocalDecl.cdecl _ _ varName type _ =>
let varName := varName.simpMacroScopes
let type ← instantiateMVars type
if prevType? == none || prevType? == some type then
pure (varNames.push varName, some type, hyps)
else do
let hyps ← pushPending varNames prevType? hyps
pure (#[varName], some type, hyps)
| LocalDecl.ldecl _ _ varName type val _ => do
let varName := varName.simpMacroScopes
let hyps ← pushPending varNames prevType? hyps
let type ← instantiateMVars type
let val ← instantiateMVars val
let typeFmt ← exprToInteractive type
let valFmt ← exprToInteractive val
let hyps := hyps.push { names := #[toString varName], type := typeFmt, val? := valFmt }
pure (#[], none, hyps)
let (varNames, type?, hyps) ← lctx.foldlM (init := (#[], none, #[]))
fun (varNames, prevType?, hyps) (localDecl : LocalDecl) =>
if !ppAuxDecls && localDecl.isAuxDecl || hidden.contains localDecl.fvarId then
pure (varNames, prevType?, hyps)
else
ppVars varNames prevType? hyps localDecl
let hyps ← pushPending varNames type? hyps
let goalTp ← instantiateMVars mvarDecl.type
let goalFmt ← exprToInteractive goalTp
let userName? := match mvarDecl.userName with
| Name.anonymous => none
| name => some <| toString name.eraseMacroScopes
return { hyps, type := goalFmt, userName? }
end Lean.Widget
|
dc569992f07c235a6e213efcf5c4e3e30b015745 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/ring_theory/witt_vector/structure_polynomial.lean | 7f1bd9976425b70a03d340caecef33b17839a231 | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,599 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Robert Y. Lewis
-/
import data.matrix.notation
import field_theory.mv_polynomial
import field_theory.finite.polynomial
import number_theory.basic
import ring_theory.witt_vector.witt_polynomial
/-!
# Witt structure polynomials
In this file we prove the main theorem that makes the whole theory of Witt vectors work.
Briefly, consider a polynomial `Φ : mv_polynomial idx ℤ` over the integers,
with polynomials variables indexed by an arbitrary type `idx`.
Then there exists a unique family of polynomials `φ : ℕ → mv_polynomial (idx × ℕ) Φ`
such that for all `n : ℕ` we have (`witt_structure_int_exists_unique`)
```
bind₁ φ (witt_polynomial p ℤ n) = bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℤ n))) Φ
```
In other words: evaluating the `n`-th Witt polynomial on the family `φ`
is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials.
N.b.: As far as we know, these polynomials do not have a name in the literature,
so we have decided to call them the “Witt structure polynomials”. See `witt_structure_int`.
## Special cases
With the main result of this file in place, we apply it to certain special polynomials.
For example, by taking `Φ = X tt + X ff` resp. `Φ = X tt * X ff`
we obtain families of polynomials `witt_add` resp. `witt_mul`
(with type `ℕ → mv_polynomial (bool × ℕ) ℤ`) that will be used in later files to define the
addition and multiplication on the ring of Witt vectors.
## Outline of the proof
The proof of `witt_structure_int_exists_unique` is rather technical, and takes up most of this file.
We start by proving the analogous version for polynomials with rational coefficients,
instead of integer coefficients.
In this case, the solution is rather easy,
since the Witt polynomials form a faithful change of coordinates
in the polynomial ring `mv_polynomial ℕ ℚ`.
We therefore obtain a family of polynomials `witt_structure_rat Φ`
for every `Φ : mv_polynomial idx ℚ`.
If `Φ` has integer coefficients, then the polynomials `witt_structure_rat Φ n` do so as well.
Proving this claim is the essential core of this file, and culminates in
`map_witt_structure_int`, which proves that upon mapping the coefficients
of `witt_structure_int Φ n` from the integers to the rationals,
one obtains `witt_structure_rat Φ n`.
Ultimately, the proof of `map_witt_structure_int` relies on
```
dvd_sub_pow_of_dvd_sub {R : Type*} [comm_ring R] {p : ℕ} {a b : R} :
(p : R) ∣ a - b → ∀ (k : ℕ), (p : R) ^ (k + 1) ∣ a ^ p ^ k - b ^ p ^ k
```
## Main results
* `witt_structure_rat Φ`: the family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℚ`
associated with `Φ : mv_polynomial idx ℚ` and satisfying the property explained above.
* `witt_structure_rat_prop`: the proof that `witt_structure_rat` indeed satisfies the property.
* `witt_structure_int Φ`: the family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℤ`
associated with `Φ : mv_polynomial idx ℤ` and satisfying the property explained above.
* `map_witt_structure_int`: the proof that the integral polynomials `with_structure_int Φ`
are equal to `witt_structure_rat Φ` when mapped to polynomials with rational coefficients.
* `witt_structure_int_prop`: the proof that `witt_structure_int` indeed satisfies the property.
* Five families of polynomials that will be used to define the ring structure
on the ring of Witt vectors:
- `witt_vector.witt_zero`
- `witt_vector.witt_one`
- `witt_vector.witt_add`
- `witt_vector.witt_mul`
- `witt_vector.witt_neg`
(We also define `witt_vector.witt_sub`, and later we will prove that it describes subtraction,
which is defined as `λ a b, a + -b`. See `witt_vector.sub_coeff` for this proof.)
## References
* [Hazewinkel, *Witt Vectors*][Haze09]
* [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21]
-/
open mv_polynomial
open set
open finset (range)
open finsupp (single)
-- This lemma reduces a bundled morphism to a "mere" function,
-- and consequently the simplifier cannot use a lot of powerful simp-lemmas.
-- We disable this locally, and probably it should be disabled globally in mathlib.
local attribute [-simp] coe_eval₂_hom
variables {p : ℕ} {R : Type*} {idx : Type*} [comm_ring R]
open_locale witt
open_locale big_operators
section p_prime
variables (p) [hp : fact p.prime]
include hp
/-- `witt_structure_rat Φ` is a family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℚ`
that are uniquely characterised by the property that
```
bind₁ (witt_structure_rat p Φ) (witt_polynomial p ℚ n) =
bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℚ n))) Φ
```
In other words: evaluating the `n`-th Witt polynomial on the family `witt_structure_rat Φ`
is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials.
See `witt_structure_rat_prop` for this property,
and `witt_structure_rat_exists_unique` for the fact that `witt_structure_rat`
gives the unique family of polynomials with this property.
These polynomials turn out to have integral coefficients,
but it requires some effort to show this.
See `witt_structure_int` for the version with integral coefficients,
and `map_witt_structure_int` for the fact that it is equal to `witt_structure_rat`
when mapped to polynomials over the rationals. -/
noncomputable def witt_structure_rat (Φ : mv_polynomial idx ℚ) (n : ℕ) :
mv_polynomial (idx × ℕ) ℚ :=
bind₁ (λ k, bind₁ (λ i, rename (prod.mk i) (W_ ℚ k)) Φ) (X_in_terms_of_W p ℚ n)
theorem witt_structure_rat_prop (Φ : mv_polynomial idx ℚ) (n : ℕ) :
bind₁ (witt_structure_rat p Φ) (W_ ℚ n) =
bind₁ (λ i, (rename (prod.mk i) (W_ ℚ n))) Φ :=
calc bind₁ (witt_structure_rat p Φ) (W_ ℚ n)
= bind₁ (λ k, bind₁ (λ i, (rename (prod.mk i)) (W_ ℚ k)) Φ)
(bind₁ (X_in_terms_of_W p ℚ) (W_ ℚ n)) :
by { rw bind₁_bind₁, apply eval₂_hom_congr (ring_hom.ext_rat _ _) rfl rfl }
... = bind₁ (λ i, (rename (prod.mk i) (W_ ℚ n))) Φ :
by rw [bind₁_X_in_terms_of_W_witt_polynomial p _ n, bind₁_X_right]
theorem witt_structure_rat_exists_unique (Φ : mv_polynomial idx ℚ) :
∃! (φ : ℕ → mv_polynomial (idx × ℕ) ℚ),
∀ (n : ℕ), bind₁ φ (W_ ℚ n) = bind₁ (λ i, (rename (prod.mk i) (W_ ℚ n))) Φ :=
begin
refine ⟨witt_structure_rat p Φ, _, _⟩,
{ intro n, apply witt_structure_rat_prop },
{ intros φ H,
funext n,
rw show φ n = bind₁ φ (bind₁ (W_ ℚ) (X_in_terms_of_W p ℚ n)),
{ rw [bind₁_witt_polynomial_X_in_terms_of_W p, bind₁_X_right] },
rw [bind₁_bind₁],
exact eval₂_hom_congr (ring_hom.ext_rat _ _) (funext H) rfl },
end
lemma witt_structure_rat_rec_aux (Φ : mv_polynomial idx ℚ) (n : ℕ) :
witt_structure_rat p Φ n * C (p ^ n : ℚ) =
bind₁ (λ b, rename (λ i, (b, i)) (W_ ℚ n)) Φ -
∑ i in range n, C (p ^ i : ℚ) * (witt_structure_rat p Φ i) ^ p ^ (n - i) :=
begin
have := X_in_terms_of_W_aux p ℚ n,
replace := congr_arg (bind₁ (λ k : ℕ, bind₁ (λ i, rename (prod.mk i) (W_ ℚ k)) Φ)) this,
rw [alg_hom.map_mul, bind₁_C_right] at this,
rw [witt_structure_rat, this], clear this,
conv_lhs { simp only [alg_hom.map_sub, bind₁_X_right] },
rw sub_right_inj,
simp only [alg_hom.map_sum, alg_hom.map_mul, bind₁_C_right, alg_hom.map_pow],
refl
end
/-- Write `witt_structure_rat p φ n` in terms of `witt_structure_rat p φ i` for `i < n`. -/
lemma witt_structure_rat_rec (Φ : mv_polynomial idx ℚ) (n : ℕ) :
(witt_structure_rat p Φ n) = C (1 / p ^ n : ℚ) *
(bind₁ (λ b, (rename (λ i, (b, i)) (W_ ℚ n))) Φ -
∑ i in range n, C (p ^ i : ℚ) * (witt_structure_rat p Φ i) ^ p ^ (n - i)) :=
begin
calc witt_structure_rat p Φ n
= C (1 / p ^ n : ℚ) * (witt_structure_rat p Φ n * C (p ^ n : ℚ)) : _
... = _ : by rw witt_structure_rat_rec_aux,
rw [mul_left_comm, ← C_mul, div_mul_cancel, C_1, mul_one],
exact pow_ne_zero _ (nat.cast_ne_zero.2 hp.1.ne_zero),
end
/-- `witt_structure_int Φ` is a family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℤ`
that are uniquely characterised by the property that
```
bind₁ (witt_structure_int p Φ) (witt_polynomial p ℤ n) =
bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℤ n))) Φ
```
In other words: evaluating the `n`-th Witt polynomial on the family `witt_structure_int Φ`
is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials.
See `witt_structure_int_prop` for this property,
and `witt_structure_int_exists_unique` for the fact that `witt_structure_int`
gives the unique family of polynomials with this property. -/
noncomputable def witt_structure_int (Φ : mv_polynomial idx ℤ) (n : ℕ) :
mv_polynomial (idx × ℕ) ℤ :=
finsupp.map_range rat.num (rat.coe_int_num 0)
(witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) n)
variable {p}
lemma bind₁_rename_expand_witt_polynomial (Φ : mv_polynomial idx ℤ) (n : ℕ)
(IH : ∀ m : ℕ, m < (n + 1) →
map (int.cast_ring_hom ℚ) (witt_structure_int p Φ m) =
witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) m) :
bind₁ (λ b, rename (λ i, (b, i)) (expand p (W_ ℤ n))) Φ =
bind₁ (λ i, expand p (witt_structure_int p Φ i)) (W_ ℤ n) :=
begin
apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective,
simp only [map_bind₁, map_rename, map_expand, rename_expand, map_witt_polynomial],
have key := (witt_structure_rat_prop p (map (int.cast_ring_hom ℚ) Φ) n).symm,
apply_fun expand p at key,
simp only [expand_bind₁] at key,
rw key, clear key,
apply eval₂_hom_congr' rfl _ rfl,
rintro i hi -,
rw [witt_polynomial_vars, finset.mem_range] at hi,
simp only [IH i hi],
end
lemma C_p_pow_dvd_bind₁_rename_witt_polynomial_sub_sum (Φ : mv_polynomial idx ℤ) (n : ℕ)
(IH : ∀ m : ℕ, m < n →
map (int.cast_ring_hom ℚ) (witt_structure_int p Φ m) =
witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) m) :
C ↑(p ^ n) ∣
(bind₁ (λ (b : idx), rename (λ i, (b, i)) (witt_polynomial p ℤ n)) Φ -
∑ i in range n, C (↑p ^ i) * witt_structure_int p Φ i ^ p ^ (n - i)) :=
begin
cases n,
{ simp only [is_unit_one, int.coe_nat_zero, int.coe_nat_succ,
zero_add, pow_zero, C_1, is_unit.dvd] },
-- prepare a useful equation for rewriting
have key := bind₁_rename_expand_witt_polynomial Φ n IH,
apply_fun (map (int.cast_ring_hom (zmod (p ^ (n + 1))))) at key,
conv_lhs at key { simp only [map_bind₁, map_rename, map_expand, map_witt_polynomial] },
-- clean up and massage
rw [nat.succ_eq_add_one, C_dvd_iff_zmod, ring_hom.map_sub, sub_eq_zero, map_bind₁],
simp only [map_rename, map_witt_polynomial, witt_polynomial_zmod_self],
rw key, clear key IH,
rw [bind₁, aeval_witt_polynomial, ring_hom.map_sum, ring_hom.map_sum, finset.sum_congr rfl],
intros k hk,
rw [finset.mem_range, nat.lt_succ_iff] at hk,
simp only [← sub_eq_zero, ← ring_hom.map_sub, ← C_dvd_iff_zmod, C_eq_coe_nat, ← mul_sub,
← int.nat_cast_eq_coe_nat, ← nat.cast_pow],
rw show p ^ (n + 1) = p ^ k * p ^ (n - k + 1),
{ rw [← pow_add, ←add_assoc], congr' 2, rw [add_comm, ←nat.sub_eq_iff_eq_add hk] },
rw [nat.cast_mul, nat.cast_pow, nat.cast_pow],
apply mul_dvd_mul_left,
rw show p ^ (n + 1 - k) = p * p ^ (n - k),
{ rw [← pow_succ, nat.sub_add_comm hk] },
rw [pow_mul],
-- the machine!
apply dvd_sub_pow_of_dvd_sub,
rw [← C_eq_coe_nat, int.nat_cast_eq_coe_nat, C_dvd_iff_zmod, ring_hom.map_sub,
sub_eq_zero, map_expand, ring_hom.map_pow, mv_polynomial.expand_zmod],
end
variables (p)
@[simp] lemma map_witt_structure_int (Φ : mv_polynomial idx ℤ) (n : ℕ) :
map (int.cast_ring_hom ℚ) (witt_structure_int p Φ n) =
witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) n :=
begin
apply nat.strong_induction_on n, clear n,
intros n IH,
rw [witt_structure_int, map_map_range_eq_iff, int.coe_cast_ring_hom],
intro c,
rw [witt_structure_rat_rec, coeff_C_mul, mul_comm, mul_div_assoc', mul_one],
have sum_induction_steps : map (int.cast_ring_hom ℚ)
(∑ i in range n, C (p ^ i : ℤ) *
(witt_structure_int p Φ i) ^ p ^ (n - i)) =
∑ i in range n, C (p ^ i : ℚ) *
(witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) i) ^ p ^ (n - i),
{ rw [ring_hom.map_sum],
apply finset.sum_congr rfl,
intros i hi,
rw finset.mem_range at hi,
simp only [IH i hi, ring_hom.map_mul, ring_hom.map_pow, map_C],
refl },
simp only [← sum_induction_steps, ← map_witt_polynomial p (int.cast_ring_hom ℚ),
← map_rename, ← map_bind₁, ← ring_hom.map_sub, coeff_map],
rw show (p : ℚ)^n = ((p^n : ℕ) : ℤ), by norm_cast,
rw [← rat.denom_eq_one_iff, ring_hom.eq_int_cast, rat.denom_div_cast_eq_one_iff],
swap, { exact_mod_cast pow_ne_zero n hp.1.ne_zero },
revert c, rw [← C_dvd_iff_dvd_coeff],
exact C_p_pow_dvd_bind₁_rename_witt_polynomial_sub_sum Φ n IH,
end
variables (p)
theorem witt_structure_int_prop (Φ : mv_polynomial idx ℤ) (n) :
bind₁ (witt_structure_int p Φ) (witt_polynomial p ℤ n) =
bind₁ (λ i, rename (prod.mk i) (W_ ℤ n)) Φ :=
begin
apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective,
have := witt_structure_rat_prop p (map (int.cast_ring_hom ℚ) Φ) n,
simpa only [map_bind₁, ← eval₂_hom_map_hom, eval₂_hom_C_left, map_rename,
map_witt_polynomial, alg_hom.coe_to_ring_hom, map_witt_structure_int],
end
lemma eq_witt_structure_int (Φ : mv_polynomial idx ℤ) (φ : ℕ → mv_polynomial (idx × ℕ) ℤ)
(h : ∀ n, bind₁ φ (witt_polynomial p ℤ n) = bind₁ (λ i, rename (prod.mk i) (W_ ℤ n)) Φ) :
φ = witt_structure_int p Φ :=
begin
funext k,
apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective,
rw map_witt_structure_int,
refine congr_fun _ k,
apply unique_of_exists_unique (witt_structure_rat_exists_unique p (map (int.cast_ring_hom ℚ) Φ)),
{ intro n,
specialize h n,
apply_fun map (int.cast_ring_hom ℚ) at h,
simpa only [map_bind₁, ← eval₂_hom_map_hom, eval₂_hom_C_left, map_rename,
map_witt_polynomial, alg_hom.coe_to_ring_hom] using h, },
{ intro n, apply witt_structure_rat_prop }
end
theorem witt_structure_int_exists_unique (Φ : mv_polynomial idx ℤ) :
∃! (φ : ℕ → mv_polynomial (idx × ℕ) ℤ),
∀ (n : ℕ), bind₁ φ (witt_polynomial p ℤ n) = bind₁ (λ i : idx, (rename (prod.mk i) (W_ ℤ n))) Φ :=
⟨witt_structure_int p Φ, witt_structure_int_prop _ _, eq_witt_structure_int _ _⟩
theorem witt_structure_prop (Φ : mv_polynomial idx ℤ) (n) :
aeval (λ i, map (int.cast_ring_hom R) (witt_structure_int p Φ i)) (witt_polynomial p ℤ n) =
aeval (λ i, rename (prod.mk i) (W n)) Φ :=
begin
convert congr_arg (map (int.cast_ring_hom R)) (witt_structure_int_prop p Φ n) using 1;
rw hom_bind₁; apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl,
{ refl },
{ simp only [map_rename, map_witt_polynomial] }
end
lemma witt_structure_int_rename {σ : Type*} (Φ : mv_polynomial idx ℤ) (f : idx → σ) (n : ℕ) :
witt_structure_int p (rename f Φ) n = rename (prod.map f id) (witt_structure_int p Φ n) :=
begin
apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective,
simp only [map_rename, map_witt_structure_int, witt_structure_rat, rename_bind₁, rename_rename,
bind₁_rename],
refl
end
@[simp]
lemma constant_coeff_witt_structure_rat_zero (Φ : mv_polynomial idx ℚ) :
constant_coeff (witt_structure_rat p Φ 0) = constant_coeff Φ :=
by simp only [witt_structure_rat, bind₁, map_aeval, X_in_terms_of_W_zero, constant_coeff_rename,
constant_coeff_witt_polynomial, aeval_X, constant_coeff_comp_algebra_map,
eval₂_hom_zero', ring_hom.id_apply]
lemma constant_coeff_witt_structure_rat (Φ : mv_polynomial idx ℚ)
(h : constant_coeff Φ = 0) (n : ℕ) :
constant_coeff (witt_structure_rat p Φ n) = 0 :=
by simp only [witt_structure_rat, eval₂_hom_zero', h, bind₁, map_aeval, constant_coeff_rename,
constant_coeff_witt_polynomial, constant_coeff_comp_algebra_map, ring_hom.id_apply,
constant_coeff_X_in_terms_of_W]
@[simp]
lemma constant_coeff_witt_structure_int_zero (Φ : mv_polynomial idx ℤ) :
constant_coeff (witt_structure_int p Φ 0) = constant_coeff Φ :=
begin
have inj : function.injective (int.cast_ring_hom ℚ),
{ intros m n, exact int.cast_inj.mp, },
apply inj,
rw [← constant_coeff_map, map_witt_structure_int,
constant_coeff_witt_structure_rat_zero, constant_coeff_map],
end
lemma constant_coeff_witt_structure_int (Φ : mv_polynomial idx ℤ)
(h : constant_coeff Φ = 0) (n : ℕ) :
constant_coeff (witt_structure_int p Φ n) = 0 :=
begin
have inj : function.injective (int.cast_ring_hom ℚ),
{ intros m n, exact int.cast_inj.mp, },
apply inj,
rw [← constant_coeff_map, map_witt_structure_int,
constant_coeff_witt_structure_rat, ring_hom.map_zero],
rw [constant_coeff_map, h, ring_hom.map_zero],
end
variable (R)
-- we could relax the fintype on `idx`, but then we need to cast from finset to set.
-- for our applications `idx` is always finite.
lemma witt_structure_rat_vars [fintype idx] (Φ : mv_polynomial idx ℚ) (n : ℕ) :
(witt_structure_rat p Φ n).vars ⊆ finset.univ.product (finset.range (n + 1)) :=
begin
rw witt_structure_rat,
intros x hx,
simp only [finset.mem_product, true_and, finset.mem_univ, finset.mem_range],
obtain ⟨k, hk, hx'⟩ := mem_vars_bind₁ _ _ hx,
obtain ⟨i, -, hx''⟩ := mem_vars_bind₁ _ _ hx',
obtain ⟨j, hj, rfl⟩ := mem_vars_rename _ _ hx'',
rw [witt_polynomial_vars, finset.mem_range] at hj,
replace hk := X_in_terms_of_W_vars_subset p _ hk,
rw finset.mem_range at hk,
exact lt_of_lt_of_le hj hk,
end
-- we could relax the fintype on `idx`, but then we need to cast from finset to set.
-- for our applications `idx` is always finite.
lemma witt_structure_int_vars [fintype idx] (Φ : mv_polynomial idx ℤ) (n : ℕ) :
(witt_structure_int p Φ n).vars ⊆ finset.univ.product (finset.range (n + 1)) :=
begin
have : function.injective (int.cast_ring_hom ℚ) := int.cast_injective,
rw [← vars_map_of_injective _ this, map_witt_structure_int],
apply witt_structure_rat_vars,
end
end p_prime
|
17e2ecddd3a7e1b221e4c1fd300206006c5e8418 | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /library/init/data/int/default.lean | 07e5cc322734a00740ebb8e3e5aef2f33ef72964 | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 245 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.data.int.basic init.data.int.order init.data.int.comp_lemmas
|
096f1e0daeea2c5d5faecf2af2c5fe08d7b6b8b7 | 947b78d97130d56365ae2ec264df196ce769371a | /tests/playground/webserver/Webserver.lean | 13bc0569ca26bcd31c3a2932deda21490ed853ed | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,069 | lean | -- -*- origami-fold-style: triple-braces -*-
import Lean
-- namespace Webserver {{{
namespace Webserver
structure State :=
(verb : String)
(path : String)
(status := "200 OK")
(outHeaders : Array String := #[])
(out : String := "")
(tryNextHandler := false)
abbrev HandlerM := StateT State IO
abbrev Handler := HandlerM Unit
def checkVerb (verb : String) : Handler := do
st ← get;
when (st.verb != verb) $
throw $ IO.userError "invalid verb"
def checkPathLiteral (p : String) : Handler := do
st ← get;
if p.isPrefixOf st.path then
set { st with path := st.path.extract p.bsize st.path.bsize }
else
throw $ IO.userError "invalid path"
def getPathPart : HandlerM String := do
st ← get;
let stop := st.path.posOf '/';
set { st with path := st.path.extract stop st.path.bsize };
pure $ st.path.extract 0 stop
def checkPathConsumed : Handler := do
st ← get;
when (st.path != "") $
throw $ IO.userError "invalid path"
def write (out : String) : Handler := do
modify fun st => { st with out := st.out ++ out }
def redirect (url : String) : Handler := do
modify fun st => { st with status := "307 Temporary Redirect", outHeaders := #["Location: " ++ url] }
def notFound : Handler := do
modify fun st => { st with status := "404 Not Found" };
write "whoops"
def mkHandlersRef : IO (IO.Ref (List Handler)) :=
IO.mkRef ∅
@[init mkHandlersRef]
constant handlersRef : IO.Ref (List Handler) := arbitrary _
def registerHandler (h : Handler) : IO Unit := do
handlersRef.modify fun hs => h::hs
partial def parseHeaders : IO.FS.Handle → IO Unit
| hIn => do
line ← hIn.getLine;
if line == "" || line == "\r\n" then pure () else parseHeaders hIn
partial def run : IO.FS.Handle → IO.FS.Handle → IO Unit
| hIn, hOut => do
line ← hIn.getLine;
when (line != "") do
[verb, path, proto] ← pure $ line.splitOn " "
| panic! "failed to parse request: " ++ line;
stderr ← IO.stderr; stderr.putStrLn $ "=> " ++ verb ++ " " ++ path;
headers ← parseHeaders hIn;
handlers ← handlersRef.get | panic! "no handlers";
(_, st) ← handlers.foldr (fun h₁ h₂ => h₁ <|> h₂) notFound { verb := verb, path := path };
stderr ← IO.stderr; stderr.putStrLn $ "<= " ++ st.status;
hOut.putStrLn $ "HTTP/1.1 " ++ st.status;
hOut.putStrLn "Content-Type: text/html";
hOut.putStrLn $ "Content-Length: " ++ toString st.out.bsize;
st.outHeaders.forM hOut.putStrLn;
hOut.putStrLn "";
hOut.putStr st.out;
hOut.flush;
run hIn hOut
end Webserver
--}}}
new_frontend
open Lean
open Lean.Parser
-- declare_syntax_cat element {{{
declare_syntax_cat element
declare_syntax_cat child
syntax "<" ident "/>" : element
syntax "<" ident ">" child* "</" ident ">" : element
-- "JSXTextCharacter : SourceCharacter but not one of {, <, > or }"
def text : Parser := -- {{{
withAntiquot (mkAntiquot "text" `LX.text) {
fn := fun c s =>
let startPos := s.pos;
let s := takeWhile1Fn (not ∘ "{<>}$".contains) "HTML text" c s;
mkNodeToken `LX.text startPos c s } -- }}}
syntax text : child
syntax "{" term "}" : child
syntax element : child
syntax element : term
macro_rules
| `(<$n/>) => mkStxStrLit ("<" ++ toString n.getId ++ ">")
| `(<$n>$cs*</$m>) => -- {{{
if n.getId == m.getId then do
cs ← cs.mapM fun c => match_syntax c with
| `(child|$t:text) => pure $ mkStxStrLit (t.getArg 0).getAtomVal!
| `(child|{$t}) => pure t
| `(child|$e:element) => `($e:element)
| _ => unreachable!;
let cs := cs.push (mkStxStrLit ("</" ++ toString m.getId ++ ">"));
cs.foldlM (fun s e => `($s ++ $e)) (mkStxStrLit ("<" ++ toString n.getId ++ ">"))
else Macro.throwError m ("expected </" ++ toString n.getId ++ ">")
-- }}}
-- }}}
-- open Webserver {{{
open Webserver
def pathLiteral : Parser := -- {{{
withAntiquot (mkAntiquot "pathLiteral" `pathLiteral) {
fn := fun c s =>
let startPos := s.pos;
let s := takeWhile1Fn (fun c => c == '/' || c.isAlphanum) "URL path" c s;
mkNodeToken `pathLiteral startPos c s } -- }}}
declare_syntax_cat pathItem
syntax pathLiteral : pathItem
syntax "{" ident "}" : pathItem
syntax path := pathItem*
declare_syntax_cat verb
syntax "GET" : verb
syntax "POST" : verb
macro v:verb p:path " => " t:term : command => do -- {{{
t ← `(do checkPathConsumed; $t:term);
t ← p.getArgs.foldrM (fun pi t => match_syntax pi with
| `(pathItem|$l:pathLiteral) => `(do checkPathLiteral $(mkStxStrLit (l.getArg 0).getAtomVal!); $t:term)
| `(pathItem|{$id}) => `(do $id:ident ← getPathPart; $t:term)
| _ => unreachable!) t;
`(def handler : Handler := do
checkVerb $(mkStxStrLit (v.getArg 0).getAtomVal!);
$t:term
@[init] def reg : IO Unit := registerHandler handler)
-- }}}
GET / => redirect "/greet/stranger"
GET /greet/{name} => write
<html>
<h1>Hello, {name}!</h1>
</html>
def main : IO Unit := do
hIn ← IO.stdin;
hOut ← IO.stdout;
Webserver.run hIn hOut
-- }}}
#check let name := "PLDI"; <h1>Hello, {name}!<br/></h1>
|
e33dc0824417fe8ecaaf1736263646d9fb1cdcb3 | 618003631150032a5676f229d13a079ac875ff77 | /src/field_theory/subfield.lean | 3e803846c1e1349ff15b3a900ba212ebba05f052 | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 4,920 | lean | /-
Copyright (c) 2018 Andreas Swerdlow. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andreas Swerdlow
-/
import ring_theory.subring
variables {F : Type*} [field F] (S : set F)
section prio
set_option default_priority 100 -- see Note [default priority]
class is_subfield extends is_subring S : Prop :=
(inv_mem : ∀ {x : F}, x ∈ S → x⁻¹ ∈ S)
end prio
instance is_subfield.field [is_subfield S] : field S :=
{ inv := λ x, ⟨x⁻¹, is_subfield.inv_mem x.2⟩,
zero_ne_one := λ h, zero_ne_one (subtype.ext.1 h),
mul_inv_cancel := λ a ha, subtype.ext.2 (mul_inv_cancel
(λ h, ha $ subtype.ext.2 h)),
inv_zero := subtype.ext.2 inv_zero,
..show comm_ring S, by apply_instance }
instance univ.is_subfield : is_subfield (@set.univ F) :=
{ inv_mem := by intros; trivial }
/- note: in the next two declarations, if we let type-class inference figure out the instance
`ring_hom.is_subring_preimage` then that instance only applies when particular instances of
`is_add_subgroup _` and `is_submonoid _` are chosen (which are not the default ones).
If we specify it explicitly, then it doesn't complain. -/
instance preimage.is_subfield {K : Type*} [field K]
(f : F →+* K) (s : set K) [is_subfield s] : is_subfield (f ⁻¹' s) :=
{ inv_mem := λ a (ha : f a ∈ s), show f a⁻¹ ∈ s,
by { rw [f.map_inv],
exact is_subfield.inv_mem ha },
..f.is_subring_preimage s }
instance image.is_subfield {K : Type*} [field K]
(f : F →+* K) (s : set F) [is_subfield s] : is_subfield (f '' s) :=
{ inv_mem := λ a ⟨x, xmem, ha⟩, ⟨x⁻¹, is_subfield.inv_mem xmem, ha ▸ f.map_inv⟩,
..f.is_subring_image s }
instance range.is_subfield {K : Type*} [field K]
(f : F →+* K) : is_subfield (set.range f) :=
by { rw ← set.image_univ, apply_instance }
namespace field
/-- `field.closure s` is the minimal subfield that includes `s`. -/
def closure : set F :=
{ x | ∃ y ∈ ring.closure S, ∃ z ∈ ring.closure S, y / z = x }
variables {S}
theorem ring_closure_subset : ring.closure S ⊆ closure S :=
λ x hx, ⟨x, hx, 1, is_submonoid.one_mem, div_one x⟩
instance closure.is_submonoid : is_submonoid (closure S) :=
{ mul_mem := by rintros _ _ ⟨p, hp, q, hq, hq0, rfl⟩ ⟨r, hr, s, hs, hs0, rfl⟩;
exact ⟨p * r,
is_submonoid.mul_mem hp hr,
q * s,
is_submonoid.mul_mem hq hs,
(div_mul_div _ _ _ _).symm⟩,
one_mem := ring_closure_subset $ is_submonoid.one_mem }
instance closure.is_subfield : is_subfield (closure S) :=
have h0 : (0:F) ∈ closure S, from ring_closure_subset $ is_add_submonoid.zero_mem,
{ add_mem := begin
intros a b ha hb,
rcases (id ha) with ⟨p, hp, q, hq, rfl⟩,
rcases (id hb) with ⟨r, hr, s, hs, rfl⟩,
classical, by_cases hq0 : q = 0, by simp [hb, hq0], by_cases hs0 : s = 0, by simp [ha, hs0],
exact ⟨p * s + q * r, is_add_submonoid.add_mem (is_submonoid.mul_mem hp hs)
(is_submonoid.mul_mem hq hr), q * s, is_submonoid.mul_mem hq hs,
(div_add_div p r hq0 hs0).symm⟩
end,
zero_mem := h0,
neg_mem := begin
rintros _ ⟨p, hp, q, hq, rfl⟩,
exact ⟨-p, is_add_subgroup.neg_mem hp, q, hq, neg_div q p⟩
end,
inv_mem := begin
rintros _ ⟨p, hp, q, hq, rfl⟩,
classical, by_cases hp0 : p = 0, by simp [hp0, h0],
exact ⟨q, hq, p, hp, inv_div.symm⟩
end }
theorem mem_closure {a : F} (ha : a ∈ S) : a ∈ closure S :=
ring_closure_subset $ ring.mem_closure ha
theorem subset_closure : S ⊆ closure S :=
λ _, mem_closure
theorem closure_subset {T : set F} [is_subfield T] (H : S ⊆ T) : closure S ⊆ T :=
by rintros _ ⟨p, hp, q, hq, hq0, rfl⟩; exact is_submonoid.mul_mem (ring.closure_subset H hp)
(is_subfield.inv_mem $ ring.closure_subset H hq)
theorem closure_subset_iff (s t : set F) [is_subfield t] : closure s ⊆ t ↔ s ⊆ t :=
⟨set.subset.trans subset_closure, closure_subset⟩
theorem closure_mono {s t : set F} (H : s ⊆ t) : closure s ⊆ closure t :=
closure_subset $ set.subset.trans H subset_closure
end field
lemma is_subfield_Union_of_directed {ι : Type*} [hι : nonempty ι]
(s : ι → set F) [∀ i, is_subfield (s i)]
(directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) :
is_subfield (⋃i, s i) :=
{ inv_mem := λ x hx, let ⟨i, hi⟩ := set.mem_Union.1 hx in
set.mem_Union.2 ⟨i, is_subfield.inv_mem hi⟩,
to_is_subring := is_subring_Union_of_directed s directed }
instance is_subfield.inter (S₁ S₂ : set F) [is_subfield S₁] [is_subfield S₂] :
is_subfield (S₁ ∩ S₂) :=
{ inv_mem := λ x hx, ⟨is_subfield.inv_mem hx.1, is_subfield.inv_mem hx.2⟩ }
instance is_subfield.Inter {ι : Sort*} (S : ι → set F) [h : ∀ y : ι, is_subfield (S y)] :
is_subfield (set.Inter S) :=
{ inv_mem := λ x hx, set.mem_Inter.2 $ λ y, is_subfield.inv_mem $ set.mem_Inter.1 hx y }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.