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
36851d6561a38a689c8792edc4efc7f8349212a9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/sites/types.lean
1c5d7b81c911c9a7532e5c4b89f3e9fa32e92b45
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
7,734
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import category_theory.sites.canonical /-! # Grothendieck Topology and Sheaves on the Category of Types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define a Grothendieck topology on the category of types, and construct the canonical functor that sends a type to a sheaf over the category of types, and make this an equivalence of categories. Then we prove that the topology defined is the canonical topology. -/ universe u namespace category_theory open_locale category_theory.Type /-- A Grothendieck topology associated to the category of all types. A sieve is a covering iff it is jointly surjective. -/ def types_grothendieck_topology : grothendieck_topology (Type u) := { sieves := λ α S, ∀ x : α, S (λ _ : punit, x), top_mem' := λ α x, trivial, pullback_stable' := λ α β S f hs x, hs (f x), transitive' := λ α S hs R hr x, hr (hs x) punit.star } /-- The discrete sieve on a type, which only includes arrows whose image is a subsingleton. -/ @[simps] def discrete_sieve (α : Type u) : sieve α := { arrows := λ β f, ∃ x, ∀ y, f y = x, downward_closed' := λ β γ f ⟨x, hx⟩ g, ⟨x, λ y, hx $ g y⟩ } lemma discrete_sieve_mem (α : Type u) : discrete_sieve α ∈ types_grothendieck_topology α := λ x, ⟨x, λ y, rfl⟩ /-- The discrete presieve on a type, which only includes arrows whose domain is a singleton. -/ def discrete_presieve (α : Type u) : presieve α := λ β f, ∃ x : β, ∀ y : β, y = x lemma generate_discrete_presieve_mem (α : Type u) : sieve.generate (discrete_presieve α) ∈ types_grothendieck_topology α := λ x, ⟨punit, id, λ _, x, ⟨punit.star, λ _, subsingleton.elim _ _⟩, rfl⟩ open presieve theorem is_sheaf_yoneda' {α : Type u} : is_sheaf types_grothendieck_topology (yoneda.obj α) := λ β S hs x hx, ⟨λ y, x _ (hs y) punit.star, λ γ f h, funext $ λ z, have _ := congr_fun (hx (𝟙 _) (λ _, z) (hs $ f z) h rfl) punit.star, by { convert this, exact rfl }, λ f hf, funext $ λ y, by convert congr_fun (hf _ (hs y)) punit.star⟩ /-- The yoneda functor that sends a type to a sheaf over the category of types -/ @[simps] def yoneda' : Type u ⥤ SheafOfTypes types_grothendieck_topology := { obj := λ α, ⟨yoneda.obj α, is_sheaf_yoneda'⟩, map := λ α β f, ⟨yoneda.map f⟩ } @[simp] lemma yoneda'_comp : yoneda'.{u} ⋙ SheafOfTypes_to_presheaf _ = yoneda := rfl open opposite /-- Given a presheaf `P` on the category of types, construct a map `P(α) → (α → P(*))` for all type `α`. -/ def eval (P : (Type u)ᵒᵖ ⥤ Type u) (α : Type u) (s : P.obj (op α)) (x : α) : P.obj (op punit) := P.map (↾λ _, x).op s /-- Given a sheaf `S` on the category of types, construct a map `(α → S(*)) → S(α)` that is inverse to `eval`. -/ noncomputable def types_glue (S : (Type u)ᵒᵖ ⥤ Type u) (hs : is_sheaf types_grothendieck_topology S) (α : Type u) (f : α → S.obj (op punit)) : S.obj (op α) := (hs.is_sheaf_for _ _ (generate_discrete_presieve_mem α)).amalgamate (λ β g hg, S.map (↾λ x, punit.star).op $ f $ g $ classical.some hg) (λ β γ δ g₁ g₂ f₁ f₂ hf₁ hf₂ h, (hs.is_sheaf_for _ _ (generate_discrete_presieve_mem δ)).is_separated_for.ext $ λ ε g ⟨x, hx⟩, have f₁ (classical.some hf₁) = f₂ (classical.some hf₂), from classical.some_spec hf₁ (g₁ $ g x) ▸ classical.some_spec hf₂ (g₂ $ g x) ▸ congr_fun h _, by { simp_rw [← functor_to_types.map_comp_apply, this, ← op_comp], refl }) lemma eval_types_glue {S hs α} (f) : eval.{u} S α (types_glue S hs α f) = f := funext $ λ x, (is_sheaf_for.valid_glue _ _ _ $ by exact ⟨punit.star, λ _, subsingleton.elim _ _⟩).trans $ by { convert functor_to_types.map_id_apply _ _, rw ← op_id, congr } lemma types_glue_eval {S hs α} (s) : types_glue.{u} S hs α (eval S α s) = s := (hs.is_sheaf_for _ _ (generate_discrete_presieve_mem α)).is_separated_for.ext $ λ β f hf, (is_sheaf_for.valid_glue _ _ _ hf).trans $ (functor_to_types.map_comp_apply _ _ _ _).symm.trans $ by { rw ← op_comp, congr' 2, exact funext (λ x, congr_arg f (classical.some_spec hf x).symm) } /-- Given a sheaf `S`, construct an equivalence `S(α) ≃ (α → S(*))`. -/ @[simps] noncomputable def eval_equiv (S : (Type u)ᵒᵖ ⥤ Type u) (hs : is_sheaf types_grothendieck_topology S) (α : Type u) : S.obj (op α) ≃ (α → S.obj (op punit)) := { to_fun := eval S α, inv_fun := types_glue S hs α, left_inv := types_glue_eval, right_inv := eval_types_glue } lemma eval_map (S : (Type u)ᵒᵖ ⥤ Type u) (α β) (f : β ⟶ α) (s x) : eval S β (S.map f.op s) x = eval S α s (f x) := by { simp_rw [eval, ← functor_to_types.map_comp_apply, ← op_comp], refl } /-- Given a sheaf `S`, construct an isomorphism `S ≅ [-, S(*)]`. -/ @[simps] noncomputable def equiv_yoneda (S : (Type u)ᵒᵖ ⥤ Type u) (hs : is_sheaf types_grothendieck_topology S) : S ≅ yoneda.obj (S.obj (op punit)) := nat_iso.of_components (λ α, equiv.to_iso $ eval_equiv S hs $ unop α) $ λ α β f, funext $ λ s, funext $ λ x, eval_map S (unop α) (unop β) f.unop _ _ /-- Given a sheaf `S`, construct an isomorphism `S ≅ [-, S(*)]`. -/ @[simps] noncomputable def equiv_yoneda' (S : SheafOfTypes types_grothendieck_topology) : S ≅ yoneda'.obj (S.1.obj (op punit)) := { hom := ⟨(equiv_yoneda S.1 S.2).hom⟩, inv := ⟨(equiv_yoneda S.1 S.2).inv⟩, hom_inv_id' := by { ext1, apply (equiv_yoneda S.1 S.2).hom_inv_id }, inv_hom_id' := by { ext1, apply (equiv_yoneda S.1 S.2).inv_hom_id } } lemma eval_app (S₁ S₂ : SheafOfTypes.{u} types_grothendieck_topology) (f : S₁ ⟶ S₂) (α : Type u) (s : S₁.1.obj (op α)) (x : α) : eval S₂.1 α (f.val.app (op α) s) x = f.val.app (op punit) (eval S₁.1 α s x) := (congr_fun (f.val.naturality (↾λ _ : punit, x).op) s).symm /-- `yoneda'` induces an equivalence of category between `Type u` and `Sheaf types_grothendieck_topology`. -/ @[simps] noncomputable def type_equiv : Type u ≌ SheafOfTypes types_grothendieck_topology := equivalence.mk yoneda' (SheafOfTypes_to_presheaf _ ⋙ (evaluation _ _).obj (op punit)) (nat_iso.of_components (λ α, /- α ≅ punit ⟶ α -/ { hom := λ x _, x, inv := λ f, f punit.star, hom_inv_id' := funext $ λ x, rfl, inv_hom_id' := funext $ λ f, funext $ λ y, punit.cases_on y rfl }) (λ α β f, rfl)) (iso.symm $ nat_iso.of_components (λ S, equiv_yoneda' S) (λ S₁ S₂ f, SheafOfTypes.hom.ext _ _ $ nat_trans.ext _ _ $ funext $ λ α, funext $ λ s, funext $ λ x, eval_app S₁ S₂ f (unop α) s x)) lemma subcanonical_types_grothendieck_topology : sheaf.subcanonical types_grothendieck_topology.{u} := sheaf.subcanonical.of_yoneda_is_sheaf _ (λ X, is_sheaf_yoneda') lemma types_grothendieck_topology_eq_canonical : types_grothendieck_topology.{u} = sheaf.canonical_topology (Type u) := le_antisymm subcanonical_types_grothendieck_topology $ Inf_le ⟨yoneda.obj (ulift bool), ⟨_, rfl⟩, grothendieck_topology.ext $ funext $ λ α, set.ext $ λ S, ⟨λ hs x, classical.by_contradiction $ λ hsx, have (λ _, ulift.up tt : (yoneda.obj (ulift bool)).obj (op punit)) = λ _, ulift.up ff := (hs punit (λ _, x)).is_separated_for.ext $ λ β f hf, funext $ λ y, hsx.elim $ S.2 hf $ λ _, y, bool.no_confusion $ ulift.up.inj $ (congr_fun this punit.star : _), λ hs β f, is_sheaf_yoneda' _ $ λ y, hs _⟩⟩ end category_theory
d8b10242eb6e6642c7e96db81da4eb1f695a0139
97f752b44fd85ec3f635078a2dd125ddae7a82b6
/library/theories/measure_theory/sigma_algebra.lean
1c23d8cb847e9a13185d276a2710da0f0c896617
[ "Apache-2.0" ]
permissive
tectronics/lean
ab977ba6be0fcd46047ddbb3c8e16e7c26710701
f38af35e0616f89c6e9d7e3eb1d48e47ee666efe
refs/heads/master
1,532,358,526,384
1,456,276,623,000
1,456,276,623,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,383
lean
/- Copyright (c) 2016 Jacob Gross. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jacob Gross, Jeremy Avigad Sigma algebras. -/ import data.set data.nat theories.topology.basic open eq.ops set nat structure sigma_algebra [class] (X : Type) := (sets : set (set X)) (univ_mem_sets : univ ∈ sets) (comp_mem_sets : ∀ {s : set X}, s ∈ sets → (-s ∈ sets)) (cUnion_mem_sets : ∀ {s : ℕ → set X}, (∀ i, s i ∈ sets) → (⋃ i, s i) ∈ sets) /- Closure properties -/ namespace measure_theory open sigma_algebra variables {X : Type} [sigma_algebra X] definition measurable (t : set X) : Prop := t ∈ sets X theorem measurable_univ : measurable (@univ X) := univ_mem_sets X theorem measurable_compl {s : set X} (H : measurable s) : measurable (-s) := comp_mem_sets H theorem measurable_of_measurable_compl {s : set X} (H : measurable (-s)) : measurable s := !compl_compl ▸ measurable_compl H theorem measurable_empty : measurable (∅ : set X) := compl_univ ▸ measurable_compl measurable_univ theorem measurable_cUnion {s : ℕ → set X} (H : ∀ i, measurable (s i)) : measurable (⋃ i, s i) := cUnion_mem_sets H theorem measurable_cInter {s : ℕ → set X} (H : ∀ i, measurable (s i)) : measurable (⋂ i, s i) := have ∀ i, measurable (-(s i)), from take i, measurable_compl (H i), have measurable (-(⋃ i, -(s i))), from measurable_compl (measurable_cUnion this), show measurable (⋂ i, s i), using this, by rewrite Inter_eq_comp_Union_comp; apply this theorem measurable_union {s t : set X} (Hs : measurable s) (Ht : measurable t) : measurable (s ∪ t) := have ∀ i, measurable (bin_ext s t i), by intro i; cases i; exact Hs; exact Ht, show measurable (s ∪ t), using this, by rewrite -Union_bin_ext; exact measurable_cUnion this theorem measurable_inter {s t : set X} (Hs : measurable s) (Ht : measurable t) : measurable (s ∩ t) := have ∀ i, measurable (bin_ext s t i), by intro i; cases i; exact Hs; exact Ht, show measurable (s ∩ t), using this, by rewrite -Inter_bin_ext; exact measurable_cInter this theorem measurable_diff {s t : set X} (Hs : measurable s) (Ht : measurable t) : measurable (s \ t) := measurable_inter Hs (measurable_compl Ht) theorem measurable_insert {x : X} {s : set X} (Hx : measurable '{x}) (Hs : measurable s) : measurable (insert x s) := !insert_eq⁻¹ ▸ measurable_union Hx Hs end measure_theory /- -- Properties of sigma algebras -/ namespace sigma_algebra open measure_theory variable {X : Type} protected theorem eq {M N : sigma_algebra X} (H : @sets X M = @sets X N) : M = N := by cases M; cases N; cases H; apply rfl /- sigma algebra generated by a set -/ inductive sets_generated_by (G : set (set X)) : set X → Prop := | generators_mem : ∀ ⦃s : set X⦄, s ∈ G → sets_generated_by G s | univ_mem : sets_generated_by G univ | comp_mem : ∀ ⦃s : set X⦄, sets_generated_by G s → sets_generated_by G (-s) | cUnion_mem : ∀ ⦃s : ℕ → set X⦄, (∀ i, sets_generated_by G (s i)) → sets_generated_by G (⋃ i, s i) protected definition generated_by {X : Type} (G : set (set X)) : sigma_algebra X := ⦃sigma_algebra, sets := sets_generated_by G, univ_mem_sets := sets_generated_by.univ_mem G, comp_mem_sets := sets_generated_by.comp_mem , cUnion_mem_sets := sets_generated_by.cUnion_mem ⦄ theorem sets_generated_by_initial {G : set (set X)} {M : sigma_algebra X} (H : G ⊆ @sets _ M) : sets_generated_by G ⊆ @sets _ M := begin intro s Hs, induction Hs with s sG s Hs ssX s Hs sisX, {exact H sG}, {exact measurable_univ}, {exact measurable_compl ssX}, exact measurable_cUnion sisX end theorem measurable_generated_by {G : set (set X)} : ∀₀ s ∈ G, @measurable _ (sigma_algebra.generated_by G) s := λ s H, sets_generated_by.generators_mem H /- The collection of sigma algebras forms a complete lattice. -/ protected definition le (M N : sigma_algebra X) : Prop := @sets _ M ⊆ @sets _ N definition sigma_algebra_has_le [reducible] [instance] : has_le (sigma_algebra X) := has_le.mk sigma_algebra.le protected theorem le_refl (M : sigma_algebra X) : M ≤ M := subset.refl (@sets _ M) protected theorem le_trans (M N L : sigma_algebra X) : M ≤ N → N ≤ L → M ≤ L := assume H1, assume H2, subset.trans H1 H2 protected theorem le_antisymm (M N : sigma_algebra X) : M ≤ N → N ≤ M → M = N := assume H1, assume H2, sigma_algebra.eq (subset.antisymm H1 H2) protected theorem generated_by_initial {G : set (set X)} {M : sigma_algebra X} (H : G ⊆ @sets X M) : sigma_algebra.generated_by G ≤ M := sets_generated_by_initial H protected definition inf (M N : sigma_algebra X) : sigma_algebra X := ⦃sigma_algebra, sets := @sets X M ∩ @sets X N, univ_mem_sets := abstract and.intro (@measurable_univ X M) (@measurable_univ X N) end, comp_mem_sets := abstract take s, assume Hs, and.intro (@measurable_compl X M s (and.elim_left Hs)) (@measurable_compl X N s (and.elim_right Hs)) end, cUnion_mem_sets := abstract take s, assume Hs, and.intro (@measurable_cUnion X M s (λ i, and.elim_left (Hs i))) (@measurable_cUnion X N s (λ i, and.elim_right (Hs i))) end⦄ protected theorem inf_le_left (M N : sigma_algebra X) : sigma_algebra.inf M N ≤ M := λ s, !inter_subset_left protected theorem inf_le_right (M N : sigma_algebra X) : sigma_algebra.inf M N ≤ N := λ s, !inter_subset_right protected theorem le_inf (M N L : sigma_algebra X) (H1 : L ≤ M) (H2 : L ≤ N) : L ≤ sigma_algebra.inf M N := λ s H, and.intro (H1 s H) (H2 s H) protected definition Inf (MS : set (sigma_algebra X)) : sigma_algebra X := ⦃sigma_algebra, sets := ⋂ M ∈ MS, @sets _ M, univ_mem_sets := abstract take M, assume HM, @measurable_univ X M end, comp_mem_sets := abstract take s, assume Hs, take M, assume HM, measurable_compl (Hs M HM) end, cUnion_mem_sets := abstract take s, assume Hs, take M, assume HM, measurable_cUnion (λ i, Hs i M HM) end ⦄ protected theorem Inf_le {M : sigma_algebra X} {MS : set (sigma_algebra X)} (MMS : M ∈ MS) : sigma_algebra.Inf MS ≤ M := bInter_subset_of_mem MMS protected theorem le_Inf {M : sigma_algebra X} {MS : set (sigma_algebra X)} (H : ∀₀ N ∈ MS, M ≤ N) : M ≤ sigma_algebra.Inf MS := take s, assume Hs : s ∈ @sets _ M, take N, assume NMS : N ∈ MS, show s ∈ @sets _ N, from H NMS s Hs protected definition sup (M N : sigma_algebra X) : sigma_algebra X := sigma_algebra.generated_by (@sets _ M ∪ @sets _ N) protected theorem le_sup_left (M N : sigma_algebra X) : M ≤ sigma_algebra.sup M N := take s, assume Hs : s ∈ @sets _ M, measurable_generated_by (or.inl Hs) protected theorem le_sup_right (M N : sigma_algebra X) : N ≤ sigma_algebra.sup M N := take s, assume Hs : s ∈ @sets _ N, measurable_generated_by (or.inr Hs) protected theorem sup_le {M N L : sigma_algebra X} (H1 : M ≤ L) (H2 : N ≤ L) : sigma_algebra.sup M N ≤ L := have @sets _ M ∪ @sets _ N ⊆ @sets _ L, from union_subset H1 H2, sets_generated_by_initial this protected definition Sup (MS : set (sigma_algebra X)) : sigma_algebra X := sigma_algebra.generated_by (⋃ M ∈ MS, @sets _ M) protected theorem le_Sup {M : sigma_algebra X} {MS : set (sigma_algebra X)} (MMS : M ∈ MS) : M ≤ sigma_algebra.Sup MS := take s, assume Hs : s ∈ @sets _ M, measurable_generated_by (mem_bUnion MMS Hs) protected theorem Sup_le {N : sigma_algebra X} {MS : set (sigma_algebra X)} (H : ∀₀ M ∈ MS, M ≤ N) : sigma_algebra.Sup MS ≤ N := have (⋃ M ∈ MS, @sets _ M) ⊆ @sets _ N, from bUnion_subset H, sets_generated_by_initial this protected definition complete_lattice [reducible] [trans_instance] : complete_lattice (sigma_algebra X) := ⦃complete_lattice, le := sigma_algebra.le, le_refl := sigma_algebra.le_refl, le_trans := sigma_algebra.le_trans, le_antisymm := sigma_algebra.le_antisymm, inf := sigma_algebra.inf, sup := sigma_algebra.sup, inf_le_left := sigma_algebra.inf_le_left, inf_le_right := sigma_algebra.inf_le_right, le_inf := sigma_algebra.le_inf, le_sup_left := sigma_algebra.le_sup_left, le_sup_right := sigma_algebra.le_sup_right, sup_le := @sigma_algebra.sup_le X, Inf := sigma_algebra.Inf, Sup := sigma_algebra.Sup, Inf_le := @sigma_algebra.Inf_le X, le_Inf := @sigma_algebra.le_Inf X, le_Sup := @sigma_algebra.le_Sup X, Sup_le := @sigma_algebra.Sup_le X⦄ end sigma_algebra /- Borel sets -/ namespace measure_theory section open topology variables (X : Type) [topology X] definition borel_algebra : sigma_algebra X := sigma_algebra.generated_by (opens X) variable {X} definition borel (s : set X) : Prop := @measurable _ (borel_algebra X) s theorem borel_of_open {s : set X} (H : Open s) : borel s := sigma_algebra.measurable_generated_by H theorem borel_of_closed {s : set X} (H : closed s) : borel s := have borel (-s), from borel_of_open H, @measurable_of_measurable_compl _ (borel_algebra X) _ this end end measure_theory
ff70d13f08ac59efa91f3ccdbfbcdfa630bdb35d
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/class11.lean
e45990c6837167635c23d0d202488d91070b5285
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
185
lean
inductive [class] C {A : Type} : A → Prop constant f {A : Type} (a : A) [H : C a] : Prop noncomputable definition g {A : Type} (a b : A) {H1 : C a} {H2 : C b} : Prop := f a ∧ f b
67f69819fe007404266ba27eec6fdb14bd75e219
05b503addd423dd68145d68b8cde5cd595d74365
/src/measure_theory/borel_space.lean
c9e81e65ff066613d10aab6947c808fa3d5e3457
[ "Apache-2.0" ]
permissive
aestriplex/mathlib
77513ff2b176d74a3bec114f33b519069788811d
e2fa8b2b1b732d7c25119229e3cdfba8370cb00f
refs/heads/master
1,621,969,960,692
1,586,279,279,000
1,586,279,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,534
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import measure_theory.measurable_space topology.instances.ennreal analysis.normed_space.basic /-! # Borel (measurable) space ## Main definitions * `borel α` : the least `σ`-algebra that contains all open sets; * `class borel_space` : a space with `topological_space` and `measurable_space` structures such that `‹measurable_space α› = borel α`; * `class opens_measurable_space` : a space with `topological_space` and `measurable_space` structures such that all open sets are measurable; equivalently, `borel α ≤ ‹measurable_space α›`. * `borel_space` instances on `empty`, `unit`, `bool`, `nat`, `int`, `rat`; * `measurable` and `borel_space` instances on `ℝ`, `ℝ≥0`, `ennreal`. ## Main statements * `is_open.is_measurable`, `is_closed.is_measurable`: open and closed sets are measurable; * `continuous.measurable` : a continuous function is measurable; * `continuous.measurable2` : if `f : α → β` and `g : α → γ` are measurable and `op : β × γ → δ` is continuous, then `λ x, op (f x, g y)` is measurable; * `measurable.add` etc : dot notation for arithmetic operations on `measurable` predicates, and similarly for `dist` and `edist`; * `measurable.ennreal*` : special cases for arithmetic operations on `ennreal`s. -/ noncomputable theory open classical set open_locale classical universes u v w x y variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort y} {s t u : set α} open measurable_space topological_space /-- `measurable_space` structure generated by `topological_space`. -/ def borel (α : Type u) [topological_space α] : measurable_space α := generate_from {s : set α | is_open s} lemma borel_eq_top_of_discrete [topological_space α] [discrete_topology α] : borel α = ⊤ := top_le_iff.1 $ λ s hs, generate_measurable.basic s (is_open_discrete s) lemma borel_eq_top_of_encodable [topological_space α] [t1_space α] [encodable α] : borel α = ⊤ := begin refine (top_le_iff.1 $ λ s hs, bUnion_of_singleton s ▸ _), apply is_measurable.bUnion s.countable_encodable, intros x hx, apply is_measurable.of_compl, apply generate_measurable.basic, exact is_closed_singleton end lemma borel_eq_generate_from_of_subbasis {s : set (set α)} [t : topological_space α] [second_countable_topology α] (hs : t = generate_from s) : borel α = generate_from s := le_antisymm (generate_from_le $ assume u (hu : t.is_open u), begin rw [hs] at hu, induction hu, case generate_open.basic : u hu { exact generate_measurable.basic u hu }, case generate_open.univ { exact @is_measurable.univ α (generate_from s) }, case generate_open.inter : s₁ s₂ _ _ hs₁ hs₂ { exact @is_measurable.inter α (generate_from s) _ _ hs₁ hs₂ }, case generate_open.sUnion : f hf ih { rcases is_open_sUnion_countable f (by rwa hs) with ⟨v, hv, vf, vu⟩, rw ← vu, exact @is_measurable.sUnion α (generate_from s) _ hv (λ x xv, ih _ (vf xv)) } end) (generate_from_le $ assume u hu, generate_measurable.basic _ $ show t.is_open u, by rw [hs]; exact generate_open.basic _ hu) lemma borel_eq_generate_Iio (α) [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] : borel α = generate_from (range Iio) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (order_topology.topology_eq_generate_intervals α), have H : ∀ a:α, is_measurable (measurable_space.generate_from (range Iio)) (Iio a) := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩; [skip, apply H], by_cases h : ∃ a', ∀ b, a < b ↔ a' ≤ b, { rcases h with ⟨a', ha'⟩, rw (_ : Ioi a = -Iio a'), {exact (H _).compl _}, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a < a'}, {b | a'.1 < b}) (λ a', is_open_lt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : Ioi a = ⋃ x : v, -Iio x.1.1, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_lt_of_le h ax⟩, rcases (vu x).2 _ with ⟨a', h₁, h₂⟩, { exact ⟨a', h₁, le_of_lt h₂⟩ }, refine not_imp_comm.1 (λ h, _) h, exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩), lt_of_lt_of_le ax⟩⟩ }, rw this, resetI, apply is_measurable.Union, exact λ _, (H _).compl _ } }, { simp, rintro _ a rfl, exact generate_measurable.basic _ is_open_Iio } end lemma borel_eq_generate_Ioi (α) [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] : borel α = generate_from (range Ioi) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (order_topology.topology_eq_generate_intervals α), have H : ∀ a:α, is_measurable (measurable_space.generate_from (range (λ a, {x | a < x}))) {x | a < x} := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩, {apply H}, by_cases h : ∃ a', ∀ b, b < a ↔ b ≤ a', { rcases h with ⟨a', ha'⟩, rw (_ : Iio a = -Ioi a'), {exact (H _).compl _}, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a' < a}, {b | b < a'.1}) (λ a', is_open_gt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : Iio a = ⋃ x : v, -Ioi x.1.1, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_le_of_lt ax h⟩, rcases (vu x).2 _ with ⟨a', h₁, h₂⟩, { exact ⟨a', h₁, le_of_lt h₂⟩ }, refine not_imp_comm.1 (λ h, _) h, exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩), λ h, lt_of_le_of_lt h ax⟩⟩ }, rw this, resetI, apply is_measurable.Union, exact λ _, (H _).compl _ } }, { simp, rintro _ a rfl, exact generate_measurable.basic _ (is_open_lt' _) } end lemma borel_comap {f : α → β} {t : topological_space β} : @borel α (t.induced f) = (@borel β t).comap f := comap_generate_from.symm lemma continuous.borel_measurable [topological_space α] [topological_space β] {f : α → β} (hf : continuous f) : @measurable α β (borel α) (borel β) f := generate_from_le $ λ s hs, generate_measurable.basic (f ⁻¹' s) (hf s hs) /-- A space with `measurable_space` and `topological_space` structures such that all open sets are measurable. -/ class opens_measurable_space (α : Type*) [topological_space α] [h : measurable_space α] : Prop := (borel_le : borel α ≤ h) /-- A space with `measurable_space` and `topological_space` structures such that the `σ`-algebra of measurable sets is exactly the `σ`-algebra generated by open sets. -/ class borel_space (α : Type*) [topological_space α] [measurable_space α] : Prop := (measurable_eq : ‹measurable_space α› = borel α) /-- In a `borel_space` all open sets are measurable. -/ @[priority 100] instance borel_space.opens_measurable {α : Type*} [topological_space α] [measurable_space α] [borel_space α] : opens_measurable_space α := ⟨ge_of_eq $ borel_space.measurable_eq α⟩ instance subtype.borel_space {α : Type*} [topological_space α] [measurable_space α] [hα : borel_space α] (s : set α) : borel_space s := ⟨by { rw [hα.1, subtype.measurable_space, ← borel_comap], refl }⟩ instance subtype.opens_measurable_space {α : Type*} [topological_space α] [measurable_space α] [h : opens_measurable_space α] (s : set α) : opens_measurable_space s := ⟨by { rw [borel_comap], exact comap_mono h.1 }⟩ section variables [topological_space α] [measurable_space α] [opens_measurable_space α] [topological_space β] [measurable_space β] [opens_measurable_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [measurable_space δ] lemma is_open.is_measurable (h : is_open s) : is_measurable s := opens_measurable_space.borel_le α _ $ generate_measurable.basic _ h lemma is_measurable_interior : is_measurable (interior s) := is_open_interior.is_measurable lemma is_closed.is_measurable (h : is_closed s) : is_measurable s := is_measurable.compl_iff.1 $ h.is_measurable lemma is_measurable_singleton [t1_space α] {x : α} : is_measurable ({x} : set α) := is_closed_singleton.is_measurable -- TODO (Lean 3.8): this will become `= is_measurable_singleton` lemma is_measurable_eq [t1_space α] {a : α} : is_measurable {x | x = a} := by { convert is_measurable_singleton; try { apply_instance }, ext x, exact mem_singleton_iff.symm } lemma is_measurable_closure : is_measurable (closure s) := is_closed_closure.is_measurable section order_closed_topology variables [preorder α] [order_closed_topology α] {a b : α} lemma is_measurable_Ici : is_measurable (Ici a) := is_closed_Ici.is_measurable lemma is_measurable_Iic : is_measurable (Iic a) := is_closed_Iic.is_measurable lemma is_measurable_Icc : is_measurable (Icc a b) := is_closed_Icc.is_measurable end order_closed_topology section order_closed_topology variables [linear_order α] [order_closed_topology α] {a b : α} lemma is_measurable_Iio : is_measurable (Iio a) := is_open_Iio.is_measurable lemma is_measurable_Ioi : is_measurable (Ioi a) := is_open_Ioi.is_measurable lemma is_measurable_Ioo : is_measurable (Ioo a b) := is_open_Ioo.is_measurable lemma is_measurable_Ioc : is_measurable (Ioc a b) := is_measurable_Ioi.inter is_measurable_Iic lemma is_measurable_Ico : is_measurable (Ico a b) := is_measurable_Ici.inter is_measurable_Iio end order_closed_topology lemma is_measurable_interval [decidable_linear_order α] [order_closed_topology α] {a b : α} : is_measurable (interval a b) := is_measurable_Icc instance prod.opens_measurable_space [second_countable_topology α] [second_countable_topology β] : opens_measurable_space (α × β) := begin refine ⟨_⟩, rcases is_open_generated_countable_inter α with ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩, rcases is_open_generated_countable_inter β with ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩, have : prod.topological_space = generate_from {g | ∃u∈a, ∃v∈b, g = set.prod u v}, { rw [ha₅, hb₅], exact prod_generate_from_generate_from_eq ha₄ hb₄ }, rw [borel_eq_generate_from_of_subbasis this], apply generate_from_le, rintros _ ⟨u, hu, v, hv, rfl⟩, have hu : is_open u, by { rw [ha₅], exact generate_open.basic _ hu }, have hv : is_open v, by { rw [hb₅], exact generate_open.basic _ hv }, exact hu.is_measurable.prod hv.is_measurable end /-- A continuous function from an `opens_measurable_space` to a `borel_space` is measurable. -/ lemma continuous.measurable {f : α → γ} (hf : continuous f) : measurable f := hf.borel_measurable.mono (opens_measurable_space.borel_le _) (le_of_eq $ borel_space.measurable_eq _) /-- A homeomorphism between two Borel spaces is a measurable equivalence.-/ def homeomorph.to_measurable_equiv {α : Type*} {β : Type*} [topological_space α] [measurable_space α] [borel_space α] [topological_space β] [measurable_space β] [borel_space β] (h : α ≃ₜ β) : measurable_equiv α β := { measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable, .. h } lemma measurable_of_continuous_on_compl_singleton [t1_space α] {f : α → γ} (a : α) (hf : continuous_on f {x | x ≠ a}) : measurable f := measurable_of_measurable_on_compl_singleton a is_measurable_singleton (continuous_on_iff_continuous_restrict.1 hf).measurable lemma continuous.measurable2 [second_countable_topology α] [second_countable_topology β] {f : δ → α} {g : δ → β} {c : α → β → γ} (h : continuous (λp:α×β, c p.1 p.2)) (hf : measurable f) (hg : measurable g) : measurable (λa, c (f a) (g a)) := h.measurable.comp (hf.prod_mk hg) lemma measurable.smul [semiring α] [second_countable_topology α] [add_comm_monoid γ] [second_countable_topology γ] [semimodule α γ] [topological_semimodule α γ] {f : δ → α} {g : δ → γ} (hf : measurable f) (hg : measurable g) : measurable (λ c, f c • g c) := continuous_smul.measurable2 hf hg lemma measurable.const_smul {α : Type*} [topological_space α] [semiring α] [add_comm_monoid γ] [semimodule α γ] [topological_semimodule α γ] {f : δ → γ} (hf : measurable f) (c : α) : measurable (λ x, c • f x) := (continuous_const.smul continuous_id).measurable.comp hf lemma measurable_const_smul_iff {α : Type*} [topological_space α] [division_ring α] [add_comm_monoid γ] [semimodule α γ] [topological_semimodule α γ] {f : δ → γ} {c : α} (hc : c ≠ 0) : measurable (λ x, c • f x) ↔ measurable f := ⟨λ h, by simpa only [smul_smul, inv_mul_cancel hc, one_smul] using h.const_smul c⁻¹, λ h, h.const_smul c⟩ lemma is_measurable_le' [partial_order α] [order_closed_topology α] [second_countable_topology α] : is_measurable {p : α × α | p.1 ≤ p.2} := (order_closed_topology.is_closed_le' _).is_measurable lemma is_measurable_le [partial_order α] [order_closed_topology α] [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : is_measurable {a | f a ≤ g a} := (hf.prod_mk hg).preimage is_measurable_le' lemma measurable.max [decidable_linear_order α] [order_closed_topology α] [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λa, max (f a) (g a)) := measurable.if (is_measurable_le hf hg) hg hf lemma measurable.min [decidable_linear_order α] [order_closed_topology α] [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λa, min (f a) (g a)) := measurable.if (is_measurable_le hf hg) hf hg end section borel_space variables [topological_space α] [measurable_space α] [borel_space α] [topological_space β] [measurable_space β] [borel_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [measurable_space δ] lemma prod_le_borel_prod : prod.measurable_space ≤ borel (α × β) := begin rw [‹borel_space α›.measurable_eq, ‹borel_space β›.measurable_eq], refine sup_le _ _, { exact comap_le_iff_le_map.mpr continuous_fst.borel_measurable }, { exact comap_le_iff_le_map.mpr continuous_snd.borel_measurable } end instance prod.borel_space [second_countable_topology α] [second_countable_topology β] : borel_space (α × β) := ⟨le_antisymm prod_le_borel_prod (opens_measurable_space.borel_le (α × β))⟩ @[to_additive] lemma measurable_mul [monoid α] [topological_monoid α] [second_countable_topology α] : measurable (λ p : α × α, p.1 * p.2) := continuous_mul.measurable @[to_additive] lemma measurable.mul [monoid α] [topological_monoid α] [second_countable_topology α] {f : δ → α} {g : δ → α} : measurable f → measurable g → measurable (λa, f a * g a) := continuous_mul.measurable2 @[to_additive] lemma finset.measurable_prod {ι : Type*} [comm_monoid α] [topological_monoid α] [second_countable_topology α] {f : ι → δ → α} (s : finset ι) (hf : ∀i, measurable (f i)) : measurable (λa, s.prod (λi, f i a)) := finset.induction_on s (by simp only [finset.prod_empty, measurable_const]) (assume i s his ih, by simpa [his] using (hf i).mul ih) @[to_additive] lemma measurable_inv [group α] [topological_group α] : measurable (has_inv.inv : α → α) := continuous_inv.measurable @[to_additive] lemma measurable.inv [group α] [topological_group α] {f : δ → α} (hf : measurable f) : measurable (λa, (f a)⁻¹) := measurable_inv.comp hf lemma measurable_inv' {α : Type*} [normed_field α] [measurable_space α] [borel_space α] : measurable (has_inv.inv : α → α) := measurable_of_continuous_on_compl_singleton 0 normed_field.continuous_on_inv lemma measurable.inv' {α : Type*} [normed_field α] [measurable_space α] [borel_space α] {f : δ → α} (hf : measurable f) : measurable (λa, (f a)⁻¹) := measurable_inv'.comp hf @[to_additive] lemma measurable.of_inv [group α] [topological_group α] {f : δ → α} (hf : measurable (λ a, (f a)⁻¹)) : measurable f := by simpa only [inv_inv] using hf.inv @[to_additive] lemma measurable_inv_iff [group α] [topological_group α] {f : δ → α} : measurable (λ a, (f a)⁻¹) ↔ measurable f := ⟨measurable.of_inv, measurable.inv⟩ lemma measurable.sub [add_group α] [topological_add_group α] [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ x, f x - g x) := hf.add hg.neg lemma measurable.is_lub [linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_lub {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_lub (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_Ioi α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp only [set.preimage, mem_Ioi, lt_is_lub_iff (hg _), exists_range_iff, set_of_exists], exact is_measurable.Union (λ i, hf i _ (is_open_lt' _).is_measurable) end lemma measurable.is_glb [linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_glb {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_glb (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_Iio α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp only [set.preimage, mem_Iio, is_glb_lt_iff (hg _), exists_range_iff, set_of_exists], exact is_measurable.Union (λ i, hf i _ (is_open_gt' _).is_measurable) end lemma measurable_supr [complete_linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i, f i b) := measurable.is_lub hf $ λ b, is_lub_supr lemma measurable_infi [complete_linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i, f i b) := measurable.is_glb hf $ λ b, is_glb_infi lemma measurable.supr_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨆ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact supr_pos h end) (assume h : ¬p, begin convert measurable_const, funext, exact supr_neg h end) lemma measurable.infi_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨅ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact infi_pos h end ) (assume h : ¬p, begin convert measurable_const, funext, exact infi_neg h end) lemma measurable_bsupr [complete_linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] (p : ι → Prop) {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i (hi : p i), f i b) := measurable_supr $ λ i, (hf i).supr_Prop (p i) lemma measurable_binfi [complete_linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] (p : ι → Prop) {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i (hi : p i), f i b) := measurable_infi $ λ i, (hf i).infi_Prop (p i) /-- Convert a `homeomorph` to a `measurable_equiv`. -/ def homemorph.to_measurable_equiv (h : α ≃ₜ β) : measurable_equiv α β := { to_equiv := h.to_equiv, measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable } end borel_space instance empty.borel_space : borel_space empty := ⟨borel_eq_top_of_discrete.symm⟩ instance unit.borel_space : borel_space unit := ⟨borel_eq_top_of_discrete.symm⟩ instance bool.borel_space : borel_space bool := ⟨borel_eq_top_of_discrete.symm⟩ instance nat.borel_space : borel_space ℕ := ⟨borel_eq_top_of_discrete.symm⟩ instance int.borel_space : borel_space ℤ := ⟨borel_eq_top_of_discrete.symm⟩ instance rat.borel_space : borel_space ℚ := ⟨borel_eq_top_of_encodable.symm⟩ instance real.measurable_space : measurable_space ℝ := borel ℝ instance real.borel_space : borel_space ℝ := ⟨rfl⟩ instance nnreal.measurable_space : measurable_space nnreal := borel nnreal instance nnreal.borel_space : borel_space nnreal := ⟨rfl⟩ instance ennreal.measurable_space : measurable_space ennreal := borel ennreal instance ennreal.borel_space : borel_space ennreal := ⟨rfl⟩ section metric_space variables [metric_space α] [measurable_space α] [opens_measurable_space α] {x : α} {ε : ℝ} lemma is_measurable_ball : is_measurable (metric.ball x ε) := metric.is_open_ball.is_measurable lemma is_measurable_closed_ball : is_measurable (metric.closed_ball x ε) := metric.is_closed_ball.is_measurable lemma measurable_dist [second_countable_topology α] : measurable (λp:α×α, dist p.1 p.2) := continuous_dist.measurable lemma measurable.dist [second_countable_topology α] [measurable_space β] {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, dist (f b) (g b)) := continuous_dist.measurable2 hf hg lemma measurable_nndist [second_countable_topology α] : measurable (λp:α×α, nndist p.1 p.2) := continuous_nndist.measurable lemma measurable.nndist [second_countable_topology α] [measurable_space β] {f g : β → α} : measurable f → measurable g → measurable (λ b, nndist (f b) (g b)) := continuous_nndist.measurable2 end metric_space section emetric_space variables [emetric_space α] [measurable_space α] [opens_measurable_space α] {x : α} {ε : ennreal} lemma is_measurable_eball : is_measurable (emetric.ball x ε) := emetric.is_open_ball.is_measurable lemma measurable_edist [second_countable_topology α] : measurable (λp:α×α, edist p.1 p.2) := continuous_edist.measurable lemma measurable.edist [second_countable_topology α] [measurable_space β] {f g : β → α} : measurable f → measurable g → measurable (λ b, edist (f b) (g b)) := continuous_edist.measurable2 end emetric_space namespace real open measurable_space lemma borel_eq_generate_from_Ioo_rat : borel ℝ = generate_from (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := borel_eq_generate_from_of_subbasis is_topological_basis_Ioo_rat.2.2 lemma borel_eq_generate_from_Iio_rat : borel ℝ = generate_from (⋃a:ℚ, {Iio a}) := begin let g, swap, apply le_antisymm (_ : _ ≤ g) (measurable_space.generate_from_le (λ t, _)), { rw borel_eq_generate_from_Ioo_rat, refine generate_from_le (λ t, _), simp only [mem_Union], rintro ⟨a, b, h, rfl|⟨⟨⟩⟩⟩, rw (set.ext (λ x, _) : Ioo (a:ℝ) b = (⋃c>a, - Iio c) ∩ Iio b), { have hg : ∀q:ℚ, g.is_measurable (Iio q) := λ q, generate_measurable.basic _ (by simp; exact ⟨_, rfl⟩), refine @is_measurable.inter _ g _ _ _ (hg _), refine @is_measurable.bUnion _ _ g _ _ (countable_encodable _) (λ c h, _), exact @is_measurable.compl _ _ g (hg _) }, { simp [Ioo, Iio], refine and_congr _ iff.rfl, exact ⟨λ h, let ⟨c, ac, cx⟩ := exists_rat_btwn h in ⟨c, rat.cast_lt.1 ac, le_of_lt cx⟩, λ ⟨c, ac, cx⟩, lt_of_lt_of_le (rat.cast_lt.2 ac) cx⟩ } }, { simp, rintro r rfl, exact is_open_Iio.is_measurable } end end real lemma measurable.sub_nnreal [measurable_space α] {f g : α → nnreal} : measurable f → measurable g → measurable (λ a, f a - g a) := nnreal.continuous_sub.measurable2 lemma measurable.nnreal_of_real [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable (λ x, nnreal.of_real (f x)) := nnreal.continuous_of_real.measurable.comp hf lemma measurable.nnreal_coe [measurable_space α] {f : α → nnreal} (hf : measurable f) : measurable (λ x, (f x : ℝ)) := nnreal.continuous_coe.measurable.comp hf lemma measurable.ennreal_coe [measurable_space α] {f : α → nnreal} (hf : measurable f) : measurable (λ x, (f x : ennreal)) := (ennreal.continuous_coe.2 continuous_id).measurable.comp hf lemma measurable.ennreal_of_real [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable (λ x, ennreal.of_real (f x)) := ennreal.continuous_of_real.measurable.comp hf /-- The set of finite `ennreal` numbers is `measurable_equiv` to `nnreal`. -/ def measurable_equiv.ennreal_equiv_nnreal : measurable_equiv {r : ennreal | r ≠ ⊤} nnreal := ennreal.ne_top_homeomorph_nnreal.to_measurable_equiv namespace ennreal open filter lemma measurable_coe : measurable (coe : nnreal → ennreal) := measurable_id.ennreal_coe lemma measurable_of_measurable_nnreal [measurable_space α] {f : ennreal → α} (h : measurable (λp:nnreal, f p)) : measurable f := measurable_of_measurable_on_compl_singleton ⊤ is_measurable_singleton (measurable_equiv.ennreal_equiv_nnreal.symm.measurable_coe_iff.1 h) /-- `ennreal` is `measurable_equiv` to `nnreal ⊕ unit`. -/ def ennreal_equiv_sum : measurable_equiv ennreal (nnreal ⊕ unit) := { measurable_to_fun := measurable_of_measurable_nnreal measurable_inl, measurable_inv_fun := measurable_sum measurable_coe (@measurable_const ennreal unit _ _ ⊤), .. equiv.option_equiv_sum_punit nnreal } lemma measurable_of_measurable_nnreal_nnreal [measurable_space α] [measurable_space β] (f : ennreal → ennreal → β) {g : α → ennreal} {h : α → ennreal} (h₁ : measurable (λp:nnreal × nnreal, f p.1 p.2)) (h₂ : measurable (λr:nnreal, f ⊤ r)) (h₃ : measurable (λr:nnreal, f r ⊤)) (hg : measurable g) (hh : measurable h) : measurable (λa, f (g a) (h a)) := let e : measurable_equiv (ennreal × ennreal) (((nnreal × nnreal) ⊕ (nnreal × unit)) ⊕ ((unit × nnreal) ⊕ (unit × unit))) := (measurable_equiv.prod_congr ennreal_equiv_sum ennreal_equiv_sum).trans (measurable_equiv.sum_prod_sum _ _ _ _) in have measurable (λp:ennreal×ennreal, f p.1 p.2), begin refine e.symm.measurable_coe_iff.1 (measurable_sum (measurable_sum _ _) (measurable_sum _ _)), { show measurable (λp:nnreal × nnreal, f p.1 p.2), exact h₁ }, { show measurable (λp:nnreal × unit, f p.1 ⊤), exact h₃.comp (measurable.fst measurable_id) }, { show measurable ((λp:nnreal, f ⊤ p) ∘ (λp:unit × nnreal, p.2)), exact h₂.comp (measurable.snd measurable_id) }, { show measurable (λp:unit × unit, f ⊤ ⊤), exact measurable_const } end, this.comp (measurable.prod_mk hg hh) lemma measurable_of_real : measurable ennreal.of_real := ennreal.continuous_of_real.measurable end ennreal lemma measurable.ennreal_mul {α : Type*} [measurable_space α] {f g : α → ennreal} : measurable f → measurable g → measurable (λa, f a * g a) := begin refine ennreal.measurable_of_measurable_nnreal_nnreal (*) _ _ _, { simp only [ennreal.coe_mul.symm], exact ennreal.measurable_coe.comp measurable_mul }, { simp [ennreal.top_mul], exact measurable.if (is_closed_eq continuous_id continuous_const).is_measurable measurable_const measurable_const }, { simp [ennreal.mul_top], exact measurable.if (is_closed_eq continuous_id continuous_const).is_measurable measurable_const measurable_const } end lemma measurable.ennreal_add {α : Type*} [measurable_space α] {f g : α → ennreal} : measurable f → measurable g → measurable (λa, f a + g a) := begin refine ennreal.measurable_of_measurable_nnreal_nnreal (+) _ _ _, { simp only [ennreal.coe_add.symm], exact ennreal.measurable_coe.comp measurable_add }, { simp [measurable_const] }, { simp [measurable_const] } end lemma measurable.ennreal_sub {α : Type*} [measurable_space α] {f g : α → ennreal} : measurable f → measurable g → measurable (λa, f a - g a) := begin refine ennreal.measurable_of_measurable_nnreal_nnreal (has_sub.sub) _ _ _, { simp only [ennreal.coe_sub.symm], exact ennreal.measurable_coe.comp nnreal.continuous_sub.measurable }, { simp [measurable_const] }, { simp [measurable_const] } end section normed_group variables [measurable_space α] [normed_group α] [opens_measurable_space α] [measurable_space β] lemma measurable_norm : measurable (norm : α → ℝ) := continuous_norm.measurable lemma measurable.norm {f : β → α} (hf : measurable f) : measurable (λa, norm (f a)) := measurable_norm.comp hf lemma measurable_nnnorm : measurable (nnnorm : α → nnreal) := continuous_nnnorm.measurable lemma measurable.nnnorm {f : β → α} (hf : measurable f) : measurable (λa, nnnorm (f a)) := measurable_nnnorm.comp hf lemma measurable.ennnorm {f : β → α} (hf : measurable f) : measurable (λa, (nnnorm (f a) : ennreal)) := hf.nnnorm.ennreal_coe end normed_group
77ff98901c1c4a3b2566c0fd5529a4aeae0d4a3e
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/rel.lean
00ce75a8d0fa2ec89bc417b6458e5df43c833992
[ "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
6,431
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Operations on set-valued functions, aka partial multifunctions, aka relations. -/ import data.set.lattice variables {α : Type*} {β : Type*} {γ : Type*} /-- A relation on `α` and `β`, aka a set-valued function, aka a partial multifunction --/ @[derive complete_lattice, derive inhabited] def rel (α : Type*) (β : Type*) := α → β → Prop namespace rel variables {δ : Type*} (r : rel α β) /-- The inverse relation : `r.inv x y ↔ r y x`. Note that this is *not* a groupoid inverse. -/ def inv : rel β α := flip r lemma inv_def (x : α) (y : β) : r.inv y x ↔ r x y := iff.rfl lemma inv_inv : inv (inv r) = r := by { ext x y, reflexivity } /-- Domain of a relation -/ def dom := {x | ∃ y, r x y} /-- Codomain aka range of a relation-/ def codom := {y | ∃ x, r x y} lemma codom_inv : r.inv.codom = r.dom := by { ext x y, reflexivity } lemma dom_inv : r.inv.dom = r.codom := by { ext x y, reflexivity} /-- Composition of relation; note that it follows the `category_theory/` order of arguments. -/ def comp (r : rel α β) (s : rel β γ) : rel α γ := λ x z, ∃ y, r x y ∧ s y z local infixr ` ∘ ` :=rel.comp lemma comp_assoc (r : rel α β) (s : rel β γ) (t : rel γ δ) : (r ∘ s) ∘ t = r ∘ s ∘ t := begin unfold comp, ext x w, split, { rintros ⟨z, ⟨y, rxy, syz⟩, tzw⟩, exact ⟨y, rxy, z, syz, tzw⟩ }, rintros ⟨y, rxy, z, syz, tzw⟩, exact ⟨z, ⟨y, rxy, syz⟩, tzw⟩ end @[simp] lemma comp_right_id (r : rel α β) : r ∘ @eq β = r := by { unfold comp, ext y, simp } @[simp] lemma comp_left_id (r : rel α β) : @eq α ∘ r = r := by { unfold comp, ext x, simp } lemma inv_id : inv (@eq α) = @eq α := by { ext x y, split; apply eq.symm } lemma inv_comp (r : rel α β) (s : rel β γ) : inv (r ∘ s) = inv s ∘ inv r := by { ext x z, simp [comp, inv, flip, and.comm] } /-- Image of a set under a relation -/ def image (s : set α) : set β := {y | ∃ x ∈ s, r x y} lemma mem_image (y : β) (s : set α) : y ∈ image r s ↔ ∃ x ∈ s, r x y := iff.rfl lemma image_subset : ((⊆) ⇒ (⊆)) r.image r.image := assume s t h y ⟨x, xs, rxy⟩, ⟨x, h xs, rxy⟩ lemma image_mono : monotone r.image := r.image_subset lemma image_inter (s t : set α) : r.image (s ∩ t) ⊆ r.image s ∩ r.image t := r.image_mono.map_inf_le s t lemma image_union (s t : set α) : r.image (s ∪ t) = r.image s ∪ r.image t := le_antisymm (λ y ⟨x, xst, rxy⟩, xst.elim (λ xs, or.inl ⟨x, ⟨xs, rxy⟩⟩) (λ xt, or.inr ⟨x, ⟨xt, rxy⟩⟩)) (r.image_mono.le_map_sup s t) @[simp] lemma image_id (s : set α) : image (@eq α) s = s := by { ext x, simp [mem_image] } lemma image_comp (s : rel β γ) (t : set α) : image (r ∘ s) t = image s (image r t) := begin ext z, simp only [mem_image, comp], split, { rintros ⟨x, xt, y, rxy, syz⟩, exact ⟨y, ⟨x, xt, rxy⟩, syz⟩ }, rintros ⟨y, ⟨x, xt, rxy⟩, syz⟩, exact ⟨x, xt, y, rxy, syz⟩ end lemma image_univ : r.image set.univ = r.codom := by { ext y, simp [mem_image, codom] } /-- Preimage of a set under a relation `r`. Same as the image of `s` under `r.inv` -/ def preimage (s : set β) : set α := image (inv r) s lemma mem_preimage (x : α) (s : set β) : x ∈ preimage r s ↔ ∃ y ∈ s, r x y := iff.rfl lemma preimage_def (s : set β) : preimage r s = {x | ∃ y ∈ s, r x y} := set.ext $ λ x, mem_preimage _ _ _ lemma preimage_mono {s t : set β} (h : s ⊆ t) : r.preimage s ⊆ r.preimage t := image_mono _ h lemma preimage_inter (s t : set β) : r.preimage (s ∩ t) ⊆ r.preimage s ∩ r.preimage t := image_inter _ s t lemma preimage_union (s t : set β) : r.preimage (s ∪ t) = r.preimage s ∪ r.preimage t := image_union _ s t lemma preimage_id (s : set α) : preimage (@eq α) s = s := by simp only [preimage, inv_id, image_id] lemma preimage_comp (s : rel β γ) (t : set γ) : preimage (r ∘ s) t = preimage r (preimage s t) := by simp only [preimage, inv_comp, image_comp] lemma preimage_univ : r.preimage set.univ = r.dom := by { rw [preimage, image_univ, codom_inv] } /-- Core of a set `s : set β` w.r.t `r : rel α β` is the set of `x : α` that are related *only* to elements of `s`. -/ def core (s : set β) := {x | ∀ y, r x y → y ∈ s} lemma mem_core (x : α) (s : set β) : x ∈ core r s ↔ ∀ y, r x y → y ∈ s := iff.rfl lemma core_subset : ((⊆) ⇒ (⊆)) r.core r.core := assume s t h x h' y rxy, h (h' y rxy) lemma core_mono : monotone r.core := r.core_subset lemma core_inter (s t : set β) : r.core (s ∩ t) = r.core s ∩ r.core t := set.ext (by simp [mem_core, imp_and_distrib, forall_and_distrib]) lemma core_union (s t : set β) : r.core s ∪ r.core t ⊆ r.core (s ∪ t) := r.core_mono.le_map_sup s t @[simp] lemma core_univ : r.core set.univ = set.univ := set.ext (by simp [mem_core]) lemma core_id (s : set α) : core (@eq α) s = s := by simp [core] lemma core_comp (s : rel β γ) (t : set γ) : core (r ∘ s) t = core r (core s t) := begin ext x, simp [core, comp], split, { intros h y rxy z syz, exact h z y rxy syz }, intros h z y rzy syz, exact h y rzy z syz end /-- Restrict the domain of a relation to a subtype. -/ def restrict_domain (s : set α) : rel {x // x ∈ s} β := λ x y, r x.val y theorem image_subset_iff (s : set α) (t : set β) : image r s ⊆ t ↔ s ⊆ core r t := iff.intro (λ h x xs y rxy, h ⟨x, xs, rxy⟩) (λ h y ⟨x, xs, rxy⟩, h xs y rxy) theorem core_preimage_gc : galois_connection (image r) (core r) := image_subset_iff _ end rel namespace function /-- The graph of a function as a relation. -/ def graph (f : α → β) : rel α β := λ x y, f x = y end function namespace set -- TODO: if image were defined with bounded quantification in corelib, the next two would -- be definitional lemma image_eq (f : α → β) (s : set α) : f '' s = (function.graph f).image s := by simp [set.image, function.graph, rel.image] lemma preimage_eq (f : α → β) (s : set β) : f ⁻¹' s = (function.graph f).preimage s := by simp [set.preimage, function.graph, rel.preimage, rel.inv, flip, rel.image] lemma preimage_eq_core (f : α → β) (s : set β) : f ⁻¹' s = (function.graph f).core s := by simp [set.preimage, function.graph, rel.core] end set
3d5e267790225c4b9e3d6b07db67cf6d9135afcc
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/wlog.lean
e17096f710494469abb8a957d80229b6b3bfbf72
[ "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
9,314
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Without loss of generality tactic. -/ import tactic.tauto tactic.core data.list.perm open expr tactic lean lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic private meta def update_pp_name : expr → name → expr | (local_const n _ bi d) pp := local_const n pp bi d | e n := e private meta def elim_or : ℕ → expr → tactic (list expr) | 0 h := fail "zero cases" | 1 h := return [h] | (n + 1) h := do [(_, [hl], []), (_, [hr], [])] ← induction h, -- there should be no dependent terms [gl, gr] ← get_goals, set_goals [gr], hsr ← elim_or n hr, gsr ← get_goals, set_goals (gl :: gsr), return (hl :: hsr) private meta def dest_or : expr → tactic (list expr) | e := do `(%%a ∨ %%b) ← whnf e | return [e], lb ← dest_or b, return (a :: lb) private meta def match_perms (pat : pattern) : expr → tactic (list $ list expr) | t := (do m ← match_pattern pat t, guard (m.2.all expr.is_local_constant), return [m.2]) <|> (do `(%%l ∨ %%r) ← whnf t, m ← match_pattern pat l, rs ← match_perms r, return (m.2 :: rs)) private meta def update_type : expr → expr → expr | (local_const n pp bi d) t := local_const n pp bi t | e t := e private meta def intron' : ℕ → tactic (list expr) | 0 := return [] | (i + 1) := do n ← intro1, ls ← intron' i, return (n :: ls) meta def wlog (vars' : list expr) (h_cases fst_case : expr) (perms : list (list expr)) : tactic unit := do guard h_cases.is_local_constant, -- reorder s.t. context is Γ ⬝ vars ⬝ cases ⊢ ∀deps, … nr ← revert_lst (vars' ++ [h_cases]), vars ← intron' vars'.length, h_cases ← intro h_cases.local_pp_name, cases ← infer_type h_cases, h_fst_case ← mk_local_def h_cases.local_pp_name (fst_case.instantiate_locals $ (vars'.zip vars).map $ λ⟨o, n⟩, (o.local_uniq_name, n)), ((), pr) ← solve_aux cases (repeat $ exact h_fst_case <|> left >> skip), t ← target, fixed_vars ← vars.mmap (λv, do t ← infer_type v, return (update_type v t) ), let t' := (instantiate_local h_cases.local_uniq_name pr t).pis (fixed_vars ++ [h_fst_case]), (h, [g]) ← local_proof `this t' (do clear h_cases, vars.mmap clear, intron nr), h₀ :: hs ← elim_or perms.length h_cases, solve1 (do exact (h.mk_app $ vars ++ [h₀])), focus ((hs.zip perms.tail).map $ λ⟨h_case, perm⟩, do let p_v := (vars'.zip vars).map (λ⟨p, v⟩, (p.local_uniq_name, v)), let p := perm.map (λp, p.instantiate_locals p_v), note `this none (h.mk_app $ p ++ [h_case]), clear h, return ()), gs ← get_goals, set_goals (g :: gs) namespace interactive open interactive interactive.types expr private meta def parse_permutations : option (list (list name)) → tactic (list (list expr)) | none := return [] | (some []) := return [] | (some perms@(p₀ :: ps)) := do (guard p₀.nodup <|> fail "No permutation `xs_i` in `using [xs_1, …, xs_n]` should contain the same variable twice."), (guard (perms.all $ λp, p.perm p₀) <|> fail "The permutations `xs_i` in `using [xs_1, …, xs_n]` must be permutations of the same variables."), perms.mmap (λp, p.mmap get_local) /-- Without loss of generality: reduces to one goal under variables permutations. Given a goal of the form `g xs`, a predicate `p` over a set of variables, as well as variable permutations `xs_i`. Then `wlog` produces goals of the form The case goal, i.e. the permutation `xs_i` covers all possible cases: `⊢ p xs_0 ∨ ⋯ ∨ p xs_n` The main goal, i.e. the goal reduced to `xs_0`: `(h : p xs_0) ⊢ g xs_0` The invariant goals, i.e. `g` is invariant under `xs_i`: `(h : p xs_i) (this : g xs_0) ⊢ gs xs_i` Either the permutation is provided, or a proof of the disjunction is provided to compute the permutation. The disjunction need to be in assoc normal form, e.g. `p₀ ∨ (p₁ ∨ p₂)`. In many cases the invariant goals can be solved by AC rewriting using `cc` etc. Example: On a state `(n m : ℕ) ⊢ p n m` the tactic `wlog h : n ≤ m using [n m, m n]` produces the following states: `(n m : ℕ) ⊢ n ≤ m ∨ m ≤ n` `(n m : ℕ) (h : n ≤ m) ⊢ p n m` `(n m : ℕ) (h : m ≤ n) (this : p n m) ⊢ p m n` `wlog` supports different calling conventions. The name `h` is used to give a name to the introduced case hypothesis. If the name is avoided, the default will be `case`. (1) `wlog : p xs0 using [xs0, …, xsn]` Results in the case goal `p xs0 ∨ ⋯ ∨ ps xsn`, the main goal `(case : p xs0) ⊢ g xs0` and the invariance goals `(case : p xsi) (this : g xs0) ⊢ g xsi`. (2) `wlog : p xs0 := r using xs0` The expression `r` is a proof of the shape `p xs0 ∨ ⋯ ∨ p xsi`, it is also used to compute the variable permutations. (3) `wlog := r using xs0` The expression `r` is a proof of the shape `p xs0 ∨ ⋯ ∨ p xsi`, it is also used to compute the variable permutations. This is not as stable as (2), for example `p` cannot be a disjunction. (4) `wlog : R x y using x y` and `wlog : R x y` Produces the case `R x y ∨ R y x`. If `R` is ≤, then the disjunction discharged using linearity. If `using x y` is avoided then `x` and `y` are the last two variables appearing in the expression `R x y`. -/ meta def wlog (h : parse ident?) (pat : parse (tk ":" *> texpr)?) (cases : parse (tk ":=" *> texpr)?) (perms : parse (tk "using" *> (list_of (ident*) <|> (λx, [x]) <$> ident*))?) (discharger : tactic unit := (tactic.solve_by_elim <|> tactic.tautology tt <|> using_smt (smt_tactic.intros >> smt_tactic.solve_goals))) : tactic unit := do perms ← parse_permutations perms, (pat, cases_pr, cases_goal, vars, perms) ← (match cases with | some r := do vars::_ ← return perms | fail "At least one set of variables expected, i.e. `using x y` or `using [x y, y x]`.", cases_pr ← to_expr r, cases_pr ← (if cases_pr.is_local_constant then return $ match h with some n := update_pp_name cases_pr n | none := cases_pr end else do note (h.get_or_else `case) none cases_pr), cases ← infer_type cases_pr, (pat, perms') ← match pat with | some pat := do pat ← to_expr pat, let vars' := vars.filter $ λv, v.occurs pat, case_pat ← mk_pattern [] vars' pat [] vars', perms' ← match_perms case_pat cases, return (pat, perms') | none := do (p :: ps) ← dest_or cases, let vars' := vars.filter $ λv, v.occurs p, case_pat ← mk_pattern [] vars' p [] vars', perms' ← (p :: ps).mmap (λp, do m ← match_pattern case_pat p, return m.2), return (p, perms') end, let vars_name := vars.map local_uniq_name, guard (perms'.all $ λp, p.all $ λv, v.is_local_constant ∧ v.local_uniq_name ∈ vars_name) <|> fail "Cases contains variables not declared in `using x y z`", perms ← (if perms.length = 1 then do return (perms'.map $ λp, p ++ vars.filter (λv, p.all (λv', v'.local_uniq_name ≠ v.local_uniq_name))) else do guard (perms.length = perms'.length) <|> fail "The provided permutation list has a different length then the provided cases.", return perms), return (pat, cases_pr, @none expr, vars, perms) | none := do let name_h := h.get_or_else `case, some pat ← return pat | fail "Either specify cases or a pattern with permutations", pat ← to_expr pat, (do [x, y] ← match perms with | [] := return pat.list_local_consts | [l] := return l | _ := failed end, let cases := mk_or_lst [pat, pat.instantiate_locals [(x.local_uniq_name, y), (y.local_uniq_name, x)]], (do `(%%x' ≤ %%y') ← return pat, (cases_pr, []) ← local_proof name_h cases (exact ``(le_total %%x' %%y')), return (pat, cases_pr, none, [x, y], [[x, y], [y, x]])) <|> (do (cases_pr, [g]) ← local_proof name_h cases skip, return (pat, cases_pr, some g, [x, y], [[x, y], [y, x]]))) <|> (do guard (perms.length ≥ 2) <|> fail ("To generate cases at least two permutations are required, i.e. `using [x y, y x]`" ++ " or exactly 0 or 2 variables"), (vars :: perms') ← return perms, let names := vars.map local_uniq_name, let cases := mk_or_lst (pat :: perms'.map (λp, pat.instantiate_locals (names.zip p))), (cases_pr, [g]) ← local_proof name_h cases skip, return (pat, cases_pr, some g, vars, perms)) end), let name_fn := (if perms.length = 2 then λi, `invariant else λi, mk_simple_name ("invariant_" ++ to_string (i + 1))), with_enable_tags $ tactic.focus1 $ do t ← get_main_tag, tactic.wlog vars cases_pr pat perms, tactic.focus (set_main_tag (mk_num_name `_case 0 :: `main :: t) :: (list.range (perms.length - 1)).map (λi, do set_main_tag (mk_num_name `_case 0 :: name_fn i :: t), try discharger)), match cases_goal with | some g := do set_tag g (mk_num_name `_case 0 :: `cases :: t), gs ← get_goals, set_goals (g :: gs) | none := skip end end interactive end tactic
3dd32e35b6c60c27788dd5f924a94821df88b230
6e41ee3ac9b96e8980a16295cc21f131e731884f
/library/data/bool.lean
36f1b16e72cc38a12c1bbe99690b7baf120c06e1
[ "Apache-2.0" ]
permissive
EgbertRijke/lean
3426cfa0e5b3d35d12fc3fd7318b35574cb67dc3
4f2e0c6d7fc9274d953cfa1c37ab2f3e799ab183
refs/heads/master
1,610,834,871,476
1,422,159,801,000
1,422,159,801,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,583
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.bool Author: Leonardo de Moura -/ import logic.eq open eq eq.ops decidable namespace bool attribute bor [reducible] attribute band [reducible] theorem dichotomy (b : bool) : b = ff ∨ b = tt := cases_on b (or.inl rfl) (or.inr rfl) theorem cond.ff {A : Type} (t e : A) : cond ff t e = e := rfl theorem cond.tt {A : Type} (t e : A) : cond tt t e = t := rfl theorem ff_ne_tt : ¬ ff = tt := assume H : ff = tt, absurd (calc true = cond tt true false : !cond.tt⁻¹ ... = cond ff true false : {H⁻¹} ... = false : cond.ff) true_ne_false theorem bor.tt_left (a : bool) : bor tt a = tt := rfl notation a || b := bor a b theorem bor.tt_right (a : bool) : a || tt = tt := cases_on a rfl rfl theorem bor.ff_left (a : bool) : ff || a = a := cases_on a rfl rfl theorem bor.ff_right (a : bool) : a || ff = a := cases_on a rfl rfl theorem bor.id (a : bool) : a || a = a := cases_on a rfl rfl theorem bor.comm (a b : bool) : a || b = b || a := cases_on a (cases_on b rfl rfl) (cases_on b rfl rfl) theorem bor.assoc (a b c : bool) : (a || b) || c = a || (b || c) := cases_on a (calc (ff || b) || c = b || c : {!bor.ff_left} ... = ff || (b || c) : !bor.ff_left⁻¹) (calc (tt || b) || c = tt || c : {!bor.tt_left} ... = tt : !bor.tt_left ... = tt || (b || c) : !bor.tt_left⁻¹) theorem bor.to_or {a b : bool} : a || b = tt → a = tt ∨ b = tt := rec_on a (assume H : ff || b = tt, have Hb : b = tt, from !bor.ff_left ▸ H, or.inr Hb) (assume H, or.inl rfl) theorem band.ff_left (a : bool) : ff && a = ff := rfl theorem band.tt_left (a : bool) : tt && a = a := cases_on a rfl rfl theorem band.ff_right (a : bool) : a && ff = ff := cases_on a rfl rfl theorem band.tt_right (a : bool) : a && tt = a := cases_on a rfl rfl theorem band.id (a : bool) : a && a = a := cases_on a rfl rfl theorem band.comm (a b : bool) : a && b = b && a := cases_on a (cases_on b rfl rfl) (cases_on b rfl rfl) theorem band.assoc (a b c : bool) : (a && b) && c = a && (b && c) := cases_on a (calc (ff && b) && c = ff && c : {!band.ff_left} ... = ff : !band.ff_left ... = ff && (b && c) : !band.ff_left⁻¹) (calc (tt && b) && c = b && c : {!band.tt_left} ... = tt && (b && c) : !band.tt_left⁻¹) theorem band.eq_tt_elim_left {a b : bool} (H : a && b = tt) : a = tt := or.elim (dichotomy a) (assume H0 : a = ff, absurd (calc ff = ff && b : !band.ff_left⁻¹ ... = a && b : {H0⁻¹} ... = tt : H) ff_ne_tt) (assume H1 : a = tt, H1) theorem band.eq_tt_elim_right {a b : bool} (H : a && b = tt) : b = tt := band.eq_tt_elim_left (!band.comm ⬝ H) theorem bnot.bnot (a : bool) : bnot (bnot a) = a := cases_on a rfl rfl theorem bnot.false : bnot ff = tt := rfl theorem bnot.true : bnot tt = ff := rfl protected definition is_inhabited [instance] : inhabited bool := inhabited.mk ff protected definition has_decidable_eq [instance] : decidable_eq bool := take a b : bool, rec_on a (rec_on b (inl rfl) (inr ff_ne_tt)) (rec_on b (inr (ne.symm ff_ne_tt)) (inl rfl)) end bool
0cffc8cfa8570b35f005cde5dd26bb7655954819
46125763b4dbf50619e8846a1371029346f4c3db
/src/tactic/converter/binders.lean
6f31530dca1317965f836be5c31a5880b051c9d1
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
7,777
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 Binder elimination -/ import order tactic.converter.old_conv namespace old_conv open tactic monad meta instance : monad_fail old_conv := { fail := λ α s, (λr e, tactic.fail (to_fmt s) : old_conv α), ..old_conv.monad } meta instance : has_monad_lift tactic old_conv := ⟨λα, lift_tactic⟩ meta instance (α : Type) : has_coe (tactic α) (old_conv α) := ⟨monad_lift⟩ meta def current_relation : old_conv name := λr lhs, return ⟨r, lhs, none⟩ meta def head_beta : old_conv unit := λ r e, do n ← tactic.head_beta e, return ⟨(), n, none⟩ /- congr should forward data! -/ meta def congr_arg : old_conv unit → old_conv unit := congr_core (return ()) meta def congr_fun : old_conv unit → old_conv unit := λc, congr_core c (return ()) meta def congr_rule (congr : expr) (cs : list (list expr → old_conv unit)) : old_conv unit := λr lhs, do meta_rhs ← infer_type lhs >>= mk_meta_var, -- is maybe overly restricted for `heq` t ← mk_app r [lhs, meta_rhs], ((), meta_pr) ← solve_aux t (do apply congr, focus $ cs.map $ λc, (do xs ← intros, conversion (head_beta >> c xs)), done), rhs ← instantiate_mvars meta_rhs, pr ← instantiate_mvars meta_pr, return ⟨(), rhs, some pr⟩ meta def congr_binder (congr : name) (cs : expr → old_conv unit) : old_conv unit := do e ← mk_const congr, congr_rule e [λbs, do [b] ← return bs, cs b] meta def funext' : (expr → old_conv unit) → old_conv unit := congr_binder ``_root_.funext meta def propext' {α : Type} (c : old_conv α) : old_conv α := λr lhs, (do guard (r = `iff), c r lhs) <|> (do guard (r = `eq), ⟨res, rhs, pr⟩ ← c `iff lhs, match pr with | some pr := return ⟨res, rhs, (expr.const `propext [] : expr) lhs rhs pr⟩ | none := return ⟨res, rhs, none⟩ end) meta def apply (pr : expr) : old_conv unit := λ r e, do sl ← simp_lemmas.mk.add pr, apply_lemmas sl r e meta def applyc (n : name) : old_conv unit := λ r e, do sl ← simp_lemmas.mk.add_simp n, apply_lemmas sl r e meta def apply' (n : name) : old_conv unit := do e ← mk_const n, congr_rule e [] end old_conv open expr tactic old_conv /- Binder elimination: We assume a binder `B : p → Π (α : Sort u), (α → t) → t`, where `t` is a type depending on `p`. Examples: ∃: there is no `p` and `t` is `Prop`. ⨅, ⨆: here p is `β` and `[complete_lattice β]`, `p` is `β` Problem: ∀x, _ should be a binder, but is not a constant! Provide a mechanism to rewrite: B (x : α) ..x.. (h : x = t), p x = B ..x/t.., p t Here ..x.. are binders, maybe also some constants which provide commutativity rules with `B`. -/ meta structure binder_eq_elim := (match_binder : expr → tactic (expr × expr)) -- returns the bound type and body (adapt_rel : old_conv unit → old_conv unit) -- optionally adapt `eq` to `iff` (apply_comm : old_conv unit) -- apply commutativity rule (apply_congr : (expr → old_conv unit) → old_conv unit) -- apply congruence rule (apply_elim_eq : old_conv unit) -- (B (x : β) (h : x = t), s x) = s t meta def binder_eq_elim.check_eq (b : binder_eq_elim) (x : expr) : expr → tactic unit | `(@eq %%β %%l %%r) := guard ((l = x ∧ ¬ x.occurs r) ∨ (r = x ∧ ¬ x.occurs l)) | _ := fail "no match" meta def binder_eq_elim.pull (b : binder_eq_elim) (x : expr) : old_conv unit := do (β, f) ← lhs >>= (lift_tactic ∘ b.match_binder), guard (¬ x.occurs β) <|> b.check_eq x β <|> (do b.apply_congr $ λx, binder_eq_elim.pull, b.apply_comm) meta def binder_eq_elim.push (b : binder_eq_elim) : old_conv unit := b.apply_elim_eq <|> (do b.apply_comm, b.apply_congr $ λx, binder_eq_elim.push) <|> (do b.apply_congr $ b.pull, binder_eq_elim.push) meta def binder_eq_elim.check (b : binder_eq_elim) (x : expr) : expr → tactic unit | e := do (β, f) ← b.match_binder e, b.check_eq x β <|> (do (lam n bi d bd) ← return f, x ← mk_local' n bi d, binder_eq_elim.check $ bd.instantiate_var x) meta def binder_eq_elim.old_conv (b : binder_eq_elim) : old_conv unit := do (β, f) ← lhs >>= (lift_tactic ∘ b.match_binder), (lam n bi d bd) ← return f, x ← mk_local' n bi d, b.check x (bd.instantiate_var x), b.adapt_rel b.push theorem {u v} exists_comm {α : Sort u} {β : Sort v} (p : α → β → Prop) : (∃a b, p a b) ↔ (∃b a, p a b) := ⟨λ⟨a, ⟨b, h⟩⟩, ⟨b, ⟨a, h⟩⟩, λ⟨a, ⟨b, h⟩⟩, ⟨b, ⟨a, h⟩⟩⟩ theorem {u v} exists_elim_eq_left {α : Sort u} (a : α) (p : Π(a':α), a' = a → Prop) : (∃(a':α)(h : a' = a), p a' h) ↔ p a rfl := ⟨λ⟨a', ⟨h, p_h⟩⟩, match a', h, p_h with ._, rfl, h := h end, λh, ⟨a, rfl, h⟩⟩ theorem {u v} exists_elim_eq_right {α : Sort u} (a : α) (p : Π(a':α), a = a' → Prop) : (∃(a':α)(h : a = a'), p a' h) ↔ p a rfl := ⟨λ⟨a', ⟨h, p_h⟩⟩, match a', h, p_h with ._, rfl, h := h end, λh, ⟨a, rfl, h⟩⟩ meta def exists_eq_elim : binder_eq_elim := { match_binder := λe, (do `(@Exists %%β %%f) ← return e, return (β, f)), adapt_rel := propext', apply_comm := applyc ``exists_comm, apply_congr := congr_binder ``exists_congr, apply_elim_eq := apply' ``exists_elim_eq_left <|> apply' ``exists_elim_eq_right } theorem {u v} forall_comm {α : Sort u} {β : Sort v} (p : α → β → Prop) : (∀a b, p a b) ↔ (∀b a, p a b) := ⟨assume h b a, h a b, assume h b a, h a b⟩ theorem {u v} forall_elim_eq_left {α : Sort u} (a : α) (p : Π(a':α), a' = a → Prop) : (∀(a':α)(h : a' = a), p a' h) ↔ p a rfl := ⟨λh, h a rfl, λh a' h_eq, match a', h_eq with ._, rfl := h end⟩ theorem {u v} forall_elim_eq_right {α : Sort u} (a : α) (p : Π(a':α), a = a' → Prop) : (∀(a':α)(h : a = a'), p a' h) ↔ p a rfl := ⟨λh, h a rfl, λh a' h_eq, match a', h_eq with ._, rfl := h end⟩ meta def forall_eq_elim : binder_eq_elim := { match_binder := λe, (do (expr.pi n bi d bd) ← return e, return (d, expr.lam n bi d bd)), adapt_rel := propext', apply_comm := applyc ``forall_comm, apply_congr := congr_binder ``forall_congr, apply_elim_eq := apply' ``forall_elim_eq_left <|> apply' ``forall_elim_eq_right } meta def supr_eq_elim : binder_eq_elim := { match_binder := λe, (do `(@lattice.supr %%α %%β %%cl %%f) ← return e, return (β, f)), adapt_rel := λc, (do r ← current_relation, guard (r = `eq), c), apply_comm := applyc ``lattice.supr_comm, apply_congr := congr_arg ∘ funext', apply_elim_eq := applyc ``lattice.supr_supr_eq_left <|> applyc ``lattice.supr_supr_eq_right } meta def infi_eq_elim : binder_eq_elim := { match_binder := λe, (do `(@lattice.infi %%α %%β %%cl %%f) ← return e, return (β, f)), adapt_rel := λc, (do r ← current_relation, guard (r = `eq), c), apply_comm := applyc ``lattice.infi_comm, apply_congr := congr_arg ∘ funext', apply_elim_eq := applyc ``lattice.infi_infi_eq_left <|> applyc ``lattice.infi_infi_eq_right } universes u v w w₂ variables {α : Type u} {β : Type v} {ι : Sort w} {ι₂ : Sort w₂} {s t : set α} {a : α} section open lattice variables [complete_lattice α] theorem Inf_image {s : set β} {f : β → α} : Inf (set.image f s) = (⨅ a ∈ s, f a) := begin simp [Inf_eq_infi, infi_and], conversion infi_eq_elim.old_conv, end theorem Sup_image {s : set β} {f : β → α} : Sup (set.image f s) = (⨆ a ∈ s, f a) := begin simp [Sup_eq_supr, supr_and], conversion supr_eq_elim.old_conv, end end
151a4f0ca0a990c56a0c29b379889faf20a8dd2b
e9dbaaae490bc072444e3021634bf73664003760
/src/Problems/2006/IMO_2006_P1.lean
a9eef6c5121879641e4e9494a6d4b1b184965a87
[ "Apache-2.0" ]
permissive
liaofei1128/geometry
566d8bfe095ce0c0113d36df90635306c60e975b
3dd128e4eec8008764bb94e18b932f9ffd66e6b3
refs/heads/master
1,678,996,510,399
1,581,454,543,000
1,583,337,839,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
354
lean
import Geo.Geo.Core namespace Geo open Seg Triangle def IMO_2006_P1 : Prop := ∀ (A B C P : Point), let I := incenter ⟨A, B, C⟩; inside P (Triangle.mk A B C) → uangle ⟨P, B, A⟩ + uangle ⟨P, C, A⟩ = uangle ⟨P, B, C⟩ + uangle ⟨P, C, B⟩ → ulen (Seg.mk A P) ≥ ulen (Seg.mk A I) → cong ⟨A, P⟩ ⟨A, I⟩ ↔ P = I end Geo
fdfbb6e410b47cb4737d563934391aa63c6cf010
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/pfunctor/multivariate/W_auto.lean
d0e85b72f2051e8b881f4844ef7a7727524d69b7
[]
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
12,362
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.pfunctor.multivariate.basic import Mathlib.PostPort universes u l u_1 u_2 namespace Mathlib /-! # The W construction as a multivariate polynomial functor. W types are well-founded tree-like structures. They are defined as the least fixpoint of a polynomial functor. ## Main definitions * `W_mk` - constructor * `W_dest - destructor * `W_rec` - recursor: basis for defining functions by structural recursion on `P.W α` * `W_rec_eq` - defining equation for `W_rec` * `W_ind` - induction principle for `P.W α` ## Implementation notes Three views of M-types: * `Wp`: polynomial functor * `W`: data type inductively defined by a triple: shape of the root, data in the root and children of the root * `W`: least fixed point of a polynomial functor Specifically, we define the polynomial functor `Wp` as: * A := a tree-like structure without information in the nodes * B := given the tree-like structure `t`, `B t` is a valid path (specified inductively by `W_path`) from the root of `t` to any given node. As a result `Wp.obj α` is made of a dataless tree and a function from its valid paths to values of `α` ## Reference * [Jeremy Avigad, Mario M. Carneiro and Simon Hudon, *Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019] -/ namespace mvpfunctor /-- A path from the root of a tree to one of its node -/ inductive W_path {n : ℕ} (P : mvpfunctor (n + 1)) : pfunctor.W (last P) → fin2 n → Type u where | root : (a : A P) → (f : pfunctor.B (last P) a → pfunctor.W (last P)) → (i : fin2 n) → B (drop P) a i → W_path P (W_type.mk a f) i | child : (a : A P) → (f : pfunctor.B (last P) a → pfunctor.W (last P)) → (i : fin2 n) → (j : pfunctor.B (last P) a) → W_path P (f j) i → W_path P (W_type.mk a f) i protected instance W_path.inhabited {n : ℕ} (P : mvpfunctor (n + 1)) (x : pfunctor.W (last P)) {i : fin2 n} [I : Inhabited (B (drop P) (pfunctor.W.head x) i)] : Inhabited (W_path P x i) := { default := sorry } /-- Specialized destructor on `W_path` -/ def W_path_cases_on {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {a : A P} {f : pfunctor.B (last P) a → pfunctor.W (last P)} (g' : typevec.arrow (B (drop P) a) α) (g : (j : pfunctor.B (last P) a) → typevec.arrow (W_path P (f j)) α) : typevec.arrow (W_path P (W_type.mk a f)) α := sorry /-- Specialized destructor on `W_path` -/ def W_path_dest_left {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {a : A P} {f : pfunctor.B (last P) a → pfunctor.W (last P)} (h : typevec.arrow (W_path P (W_type.mk a f)) α) : typevec.arrow (B (drop P) a) α := fun (i : fin2 n) (c : B (drop P) a i) => h i (W_path.root a f i c) /-- Specialized destructor on `W_path` -/ def W_path_dest_right {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {a : A P} {f : pfunctor.B (last P) a → pfunctor.W (last P)} (h : typevec.arrow (W_path P (W_type.mk a f)) α) (j : pfunctor.B (last P) a) : typevec.arrow (W_path P (f j)) α := fun (i : fin2 n) (c : W_path P (f j) i) => h i (W_path.child a f i j c) theorem W_path_dest_left_W_path_cases_on {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {a : A P} {f : pfunctor.B (last P) a → pfunctor.W (last P)} (g' : typevec.arrow (B (drop P) a) α) (g : (j : pfunctor.B (last P) a) → typevec.arrow (W_path P (f j)) α) : W_path_dest_left P (W_path_cases_on P g' g) = g' := rfl theorem W_path_dest_right_W_path_cases_on {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {a : A P} {f : pfunctor.B (last P) a → pfunctor.W (last P)} (g' : typevec.arrow (B (drop P) a) α) (g : (j : pfunctor.B (last P) a) → typevec.arrow (W_path P (f j)) α) : W_path_dest_right P (W_path_cases_on P g' g) = g := rfl theorem W_path_cases_on_eta {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {a : A P} {f : pfunctor.B (last P) a → pfunctor.W (last P)} (h : typevec.arrow (W_path P (W_type.mk a f)) α) : W_path_cases_on P (W_path_dest_left P h) (W_path_dest_right P h) = h := sorry theorem comp_W_path_cases_on {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {β : typevec n} (h : typevec.arrow α β) {a : A P} {f : pfunctor.B (last P) a → pfunctor.W (last P)} (g' : typevec.arrow (B (drop P) a) α) (g : (j : pfunctor.B (last P) a) → typevec.arrow (W_path P (f j)) α) : typevec.comp h (W_path_cases_on P g' g) = W_path_cases_on P (typevec.comp h g') fun (i : pfunctor.B (last P) a) => typevec.comp h (g i) := sorry /-- Polynomial functor for the W-type of `P`. `A` is a data-less well-founded tree whereas, for a given `a : A`, `B a` is a valid path in tree `a` so that `Wp.obj α` is made of a tree and a function from its valid paths to the values it contains -/ def Wp {n : ℕ} (P : mvpfunctor (n + 1)) : mvpfunctor n := mk (pfunctor.W (last P)) (W_path P) /-- W-type of `P` -/ def W {n : ℕ} (P : mvpfunctor (n + 1)) (α : typevec n) := obj (Wp P) α protected instance mvfunctor_W {n : ℕ} (P : mvpfunctor (n + 1)) : mvfunctor (W P) := id (obj.mvfunctor (Wp P)) /-! First, describe operations on `W` as a polynomial functor. -/ /-- Constructor for `Wp` -/ def Wp_mk {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} (a : A P) (f : pfunctor.B (last P) a → pfunctor.W (last P)) (f' : typevec.arrow (W_path P (W_type.mk a f)) α) : W P α := sigma.mk (W_type.mk a f) f' /-- Recursor for `Wp` -/ def Wp_rec {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {C : Type u_2} (g : (a : A P) → (f : pfunctor.B (last P) a → pfunctor.W (last P)) → typevec.arrow (W_path P (W_type.mk a f)) α → (pfunctor.B (last P) a → C) → C) (x : pfunctor.W (last P)) (f' : typevec.arrow (W_path P x) α) : C := sorry theorem Wp_rec_eq {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {C : Type u_2} (g : (a : A P) → (f : pfunctor.B (last P) a → pfunctor.W (last P)) → typevec.arrow (W_path P (W_type.mk a f)) α → (pfunctor.B (last P) a → C) → C) (a : A P) (f : pfunctor.B (last P) a → pfunctor.W (last P)) (f' : typevec.arrow (W_path P (W_type.mk a f)) α) : Wp_rec P g (W_type.mk a f) f' = g a f f' fun (i : pfunctor.B (last P) a) => Wp_rec P g (f i) (W_path_dest_right P f' i) := rfl -- Note: we could replace Prop by Type* and obtain a dependent recursor theorem Wp_ind {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {C : (x : pfunctor.W (last P)) → typevec.arrow (W_path P x) α → Prop} (ih : ∀ (a : A P) (f : pfunctor.B (last P) a → pfunctor.W (last P)) (f' : typevec.arrow (W_path P (W_type.mk a f)) α), (∀ (i : pfunctor.B (last P) a), C (f i) (W_path_dest_right P f' i)) → C (W_type.mk a f) f') (x : pfunctor.W (last P)) (f' : typevec.arrow (W_path P x) α) : C x f' := sorry /-! Now think of W as defined inductively by the data ⟨a, f', f⟩ where - `a : P.A` is the shape of the top node - `f' : P.drop.B a ⟹ α` is the contents of the top node - `f : P.last.B a → P.last.W` are the subtrees -/ /-- Constructor for `W` -/ def W_mk {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} (a : A P) (f' : typevec.arrow (B (drop P) a) α) (f : pfunctor.B (last P) a → W P α) : W P α := let g : pfunctor.B (last P) a → pfunctor.W (last P) := fun (i : pfunctor.B (last P) a) => sigma.fst (f i); let g' : typevec.arrow (W_path P (W_type.mk a g)) α := W_path_cases_on P f' fun (i : pfunctor.B (last P) a) => sigma.snd (f i); sigma.mk (W_type.mk a g) g' /-- Recursor for `W` -/ def W_rec {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {C : Type u_1} (g : (a : A P) → typevec.arrow (B (drop P) a) α → (pfunctor.B (last P) a → W P α) → (pfunctor.B (last P) a → C) → C) : W P α → C := sorry /-- Defining equation for the recursor of `W` -/ theorem W_rec_eq {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {C : Type u_1} (g : (a : A P) → typevec.arrow (B (drop P) a) α → (pfunctor.B (last P) a → W P α) → (pfunctor.B (last P) a → C) → C) (a : A P) (f' : typevec.arrow (B (drop P) a) α) (f : pfunctor.B (last P) a → W P α) : W_rec P g (W_mk P a f' f) = g a f' f fun (i : pfunctor.B (last P) a) => W_rec P g (f i) := sorry /-- Induction principle for `W` -/ theorem W_ind {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {C : W P α → Prop} (ih : ∀ (a : A P) (f' : typevec.arrow (B (drop P) a) α) (f : pfunctor.B (last P) a → W P α), (∀ (i : pfunctor.B (last P) a), C (f i)) → C (W_mk P a f' f)) (x : W P α) : C x := sorry theorem W_cases {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {C : W P α → Prop} (ih : ∀ (a : A P) (f' : typevec.arrow (B (drop P) a) α) (f : pfunctor.B (last P) a → W P α), C (W_mk P a f' f)) (x : W P α) : C x := W_ind P fun (a : A P) (f' : typevec.arrow (B (drop P) a) α) (f : pfunctor.B (last P) a → W P α) (ih' : ∀ (i : pfunctor.B (last P) a), C (f i)) => ih a f' f /-- W-types are functorial -/ def W_map {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {β : typevec n} (g : typevec.arrow α β) : W P α → W P β := fun (x : W P α) => mvfunctor.map g x theorem W_mk_eq {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} (a : A P) (f : pfunctor.B (last P) a → pfunctor.W (last P)) (g' : typevec.arrow (B (drop P) a) α) (g : (j : pfunctor.B (last P) a) → typevec.arrow (W_path P (f j)) α) : (W_mk P a g' fun (i : pfunctor.B (last P) a) => sigma.mk (f i) (g i)) = sigma.mk (W_type.mk a f) (W_path_cases_on P g' g) := rfl theorem W_map_W_mk {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {β : typevec n} (g : typevec.arrow α β) (a : A P) (f' : typevec.arrow (B (drop P) a) α) (f : pfunctor.B (last P) a → W P α) : mvfunctor.map g (W_mk P a f' f) = W_mk P a (typevec.comp g f') fun (i : pfunctor.B (last P) a) => mvfunctor.map g (f i) := sorry -- TODO: this technical theorem is used in one place in constructing the initial algebra. -- Can it be avoided? /-- Constructor of a value of `P.obj (α ::: β)` from components. Useful to avoid complicated type annotation -/ def obj_append1 {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {β : Type u} (a : A P) (f' : typevec.arrow (B (drop P) a) α) (f : pfunctor.B (last P) a → β) : obj P (α ::: β) := sigma.mk a (typevec.split_fun f' f) theorem map_obj_append1 {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} {γ : typevec n} (g : typevec.arrow α γ) (a : A P) (f' : typevec.arrow (B (drop P) a) α) (f : pfunctor.B (last P) a → W P α) : mvfunctor.map (g ::: W_map P g) (obj_append1 P a f' f) = obj_append1 P a (typevec.comp g f') fun (x : pfunctor.B (last P) a) => W_map P g (f x) := sorry /-! Yet another view of the W type: as a fixed point for a multivariate polynomial functor. These are needed to use the W-construction to construct a fixed point of a qpf, since the qpf axioms are expressed in terms of `map` on `P`. -/ /-- Constructor for the W-type of `P` -/ def W_mk' {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} : obj P (α ::: W P α) → W P α := sorry /-- Destructor for the W-type of `P` -/ def W_dest' {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} : W P α → obj P (α ::: W P α) := W_rec P fun (a : A P) (f' : typevec.arrow (B (drop P) a) α) (f : pfunctor.B (last P) a → W P α) (_x : pfunctor.B (last P) a → obj P (α ::: W P α)) => sigma.mk a (typevec.split_fun f' f) theorem W_dest'_W_mk {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} (a : A P) (f' : typevec.arrow (B (drop P) a) α) (f : pfunctor.B (last P) a → W P α) : W_dest' P (W_mk P a f' f) = sigma.mk a (typevec.split_fun f' f) := sorry theorem W_dest'_W_mk' {n : ℕ} (P : mvpfunctor (n + 1)) {α : typevec n} (x : obj P (α ::: W P α)) : W_dest' P (W_mk' P x) = x := sorry end Mathlib
6e8b7ad058c9541e18a67a9559e814501f3e7f63
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/monoidal/internal/Module.lean
ffe881f0ea08955ca408020923e448b1e7436b40
[ "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
5,229
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Module.monoidal import algebra.category.Algebra.basic import category_theory.monoidal.Mon_ /-! # `Mon_ (Module R) ≌ Algebra R` The category of internal monoid objects in `Module R` is equivalent to the category of "native" bundled `R`-algebras. Moreover, this equivalence is compatible with the forgetful functors to `Module R`. -/ universes v u open category_theory open linear_map open_locale tensor_product namespace Module variables {R : Type u} [comm_ring R] namespace Mon_Module_equivalence_Algebra @[simps] instance (A : Mon_ (Module.{u} R)) : ring A.X := { one := A.one (1 : R), mul := λ x y, A.mul (x ⊗ₜ y), one_mul := λ x, by { convert linear_map.congr_fun A.one_mul ((1 : R) ⊗ₜ x), simp, }, mul_one := λ x, by { convert linear_map.congr_fun A.mul_one (x ⊗ₜ (1 : R)), simp, }, mul_assoc := λ x y z, by convert linear_map.congr_fun A.mul_assoc ((x ⊗ₜ y) ⊗ₜ z), left_distrib := λ x y z, begin convert A.mul.map_add (x ⊗ₜ y) (x ⊗ₜ z), rw ←tensor_product.tmul_add, refl, end, right_distrib := λ x y z, begin convert A.mul.map_add (x ⊗ₜ z) (y ⊗ₜ z), rw ←tensor_product.add_tmul, refl, end, ..(by apply_instance : add_comm_group A.X) } instance (A : Mon_ (Module.{u} R)) : algebra R A.X := { map_zero' := A.one.map_zero, map_one' := rfl, map_mul' := λ x y, begin have h := linear_map.congr_fun A.one_mul.symm (x ⊗ₜ (A.one y)), rwa [monoidal_category.left_unitor_hom_apply, ←A.one.map_smul] at h, end, commutes' := λ r a, begin dsimp, have h₁ := linear_map.congr_fun A.one_mul (r ⊗ₜ a), have h₂ := linear_map.congr_fun A.mul_one (a ⊗ₜ r), exact h₁.trans h₂.symm, end, smul_def' := λ r a, by { convert (linear_map.congr_fun A.one_mul (r ⊗ₜ a)).symm, simp, }, ..A.one } @[simp] lemma algebra_map (A : Mon_ (Module.{u} R)) (r : R) : algebra_map R A.X r = A.one r := rfl /-- Converting a monoid object in `Module R` to a bundled algebra. -/ @[simps] def functor : Mon_ (Module.{u} R) ⥤ Algebra R := { obj := λ A, Algebra.of R A.X, map := λ A B f, { to_fun := f.hom, map_one' := linear_map.congr_fun f.one_hom (1 : R), map_mul' := λ x y, linear_map.congr_fun f.mul_hom (x ⊗ₜ y), commutes' := λ r, linear_map.congr_fun f.one_hom r, ..(f.hom.to_add_monoid_hom) }, }. /-- Converting a bundled algebra to a monoid object in `Module R`. -/ @[simps] def inverse_obj (A : Algebra.{u} R) : Mon_ (Module.{u} R) := { X := Module.of R A, one := algebra.linear_map R A, mul := @algebra.lmul' R A _ _ _, one_mul' := begin ext x, dsimp, rw [algebra.lmul'_apply, monoidal_category.left_unitor_hom_apply, algebra.smul_def], refl, end, mul_one' := begin ext x, dsimp, rw [algebra.lmul'_apply, monoidal_category.right_unitor_hom_apply, ←algebra.commutes, algebra.smul_def], refl, end, mul_assoc' := begin ext xy z, dsimp, apply tensor_product.induction_on xy, { simp only [linear_map.map_zero, tensor_product.zero_tmul], }, { intros x y, dsimp, simp only [mul_assoc, algebra.lmul'_apply], }, { intros x y hx hy, dsimp, simp only [tensor_product.add_tmul, hx, hy, map_add], }, end } /-- Converting a bundled algebra to a monoid object in `Module R`. -/ @[simps] def inverse : Algebra.{u} R ⥤ Mon_ (Module.{u} R) := { obj := inverse_obj, map := λ A B f, { hom := f.to_linear_map, }, }. end Mon_Module_equivalence_Algebra open Mon_Module_equivalence_Algebra /-- The category of internal monoid objects in `Module R` is equivalent to the category of "native" bundled `R`-algebras. -/ def Mon_Module_equivalence_Algebra : Mon_ (Module.{u} R) ≌ Algebra R := { functor := functor, inverse := inverse, unit_iso := nat_iso.of_components (λ A, { hom := { hom := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ r a, rfl, } }, inv := { hom := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ r a, rfl, } } }) (by tidy), counit_iso := nat_iso.of_components (λ A, { hom := { to_fun := id, map_zero' := rfl, map_add' := λ x y, rfl, map_one' := (algebra_map R A).map_one, map_mul' := λ x y, algebra.lmul'_apply, commutes' := λ r, rfl, }, inv := { to_fun := id, map_zero' := rfl, map_add' := λ x y, rfl, map_one' := (algebra_map R A).map_one.symm, map_mul' := λ x y, algebra.lmul'_apply.symm, commutes' := λ r, rfl } }) (by tidy), }. /-- The equivalence `Mon_ (Module R) ≌ Algebra R` is naturally compatible with the forgetful functors to `Module R`. -/ def Mon_Module_equivalence_Algebra_forget : Mon_Module_equivalence_Algebra.functor ⋙ forget₂ (Algebra.{u} R) (Module.{u} R) ≅ Mon_.forget (Module.{u} R):= nat_iso.of_components (λ A, { hom := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ c x, rfl }, inv := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ c x, rfl }, }) (by tidy) end Module
5f66860675f2d99d962f621cd0c16ce22ec5da30
d29d82a0af640c937e499f6be79fc552eae0aa13
/src/ring_theory/integral_closure.lean
670e90734b5eb9bf7ea515844039d52cab1a1c9a
[ "Apache-2.0" ]
permissive
AbdulMajeedkhurasani/mathlib
835f8a5c5cf3075b250b3737172043ab4fa1edf6
79bc7323b164aebd000524ebafd198eb0e17f956
refs/heads/master
1,688,003,895,660
1,627,788,521,000
1,627,788,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,830
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.adjoin.basic import ring_theory.polynomial.scale_roots import ring_theory.polynomial.tower /-! # Integral closure of a subring. If A is an R-algebra then `a : A` is integral over R if it is a root of a monic polynomial with coefficients in R. Enough theory is developed to prove that integral elements form a sub-R-algebra of A. ## Main definitions Let `R` be a `comm_ring` and let `A` be an R-algebra. * `ring_hom.is_integral_elem (f : R →+* A) (x : A)` : `x` is integral with respect to the map `f`, * `is_integral (x : A)` : `x` is integral over `R`, i.e., is a root of a monic polynomial with coefficients in `R`. * `integral_closure R A` : the integral closure of `R` in `A`, regarded as a sub-`R`-algebra of `A`. -/ open_locale classical open_locale big_operators open polynomial submodule section ring variables {R S A : Type*} variables [comm_ring R] [ring A] [ring S] (f : R →+* S) /-- An element `x` of `A` is said to be integral over `R` with respect to `f` if it is a root of a monic polynomial `p : polynomial R` evaluated under `f` -/ def ring_hom.is_integral_elem (f : R →+* A) (x : A) := ∃ p : polynomial R, monic p ∧ eval₂ f x p = 0 /-- A ring homomorphism `f : R →+* A` is said to be integral if every element `A` is integral with respect to the map `f` -/ def ring_hom.is_integral (f : R →+* A) := ∀ x : A, f.is_integral_elem x variables [algebra R A] (R) /-- An element `x` of an algebra `A` over a commutative ring `R` is said to be *integral*, if it is a root of some monic polynomial `p : polynomial R`. Equivalently, the element is integral over `R` with respect to the induced `algebra_map` -/ def is_integral (x : A) : Prop := (algebra_map R A).is_integral_elem x variable (A) /-- An algebra is integral if every element of the extension is integral over the base ring -/ def algebra.is_integral : Prop := (algebra_map R A).is_integral variables {R A} lemma ring_hom.is_integral_map {x : R} : f.is_integral_elem (f x) := ⟨X - C x, monic_X_sub_C _, by simp⟩ theorem is_integral_algebra_map {x : R} : is_integral R (algebra_map R A x) := (algebra_map R A).is_integral_map theorem is_integral_of_noetherian (H : is_noetherian R A) (x : A) : is_integral R x := begin let leval : @linear_map R (polynomial R) A _ _ _ _ _ := (aeval x).to_linear_map, let D : ℕ → submodule R A := λ n, (degree_le R n).map leval, let M := well_founded.min (is_noetherian_iff_well_founded.1 H) (set.range D) ⟨_, ⟨0, rfl⟩⟩, have HM : M ∈ set.range D := well_founded.min_mem _ _ _, cases HM with N HN, have HM : ¬M < D (N+1) := well_founded.not_lt_min (is_noetherian_iff_well_founded.1 H) (set.range D) _ ⟨N+1, rfl⟩, rw ← HN at HM, have HN2 : D (N+1) ≤ D N := classical.by_contradiction (λ H, HM (lt_of_le_not_le (map_mono (degree_le_mono (with_bot.coe_le_coe.2 (nat.le_succ N)))) H)), have HN3 : leval (X^(N+1)) ∈ D N, { exact HN2 (mem_map_of_mem (mem_degree_le.2 (degree_X_pow_le _))) }, rcases HN3 with ⟨p, hdp, hpe⟩, refine ⟨X^(N+1) - p, monic_X_pow_sub (mem_degree_le.1 hdp), _⟩, show leval (X ^ (N + 1) - p) = 0, rw [linear_map.map_sub, hpe, sub_self] end theorem is_integral_of_submodule_noetherian (S : subalgebra R A) (H : is_noetherian R S.to_submodule) (x : A) (hx : x ∈ S) : is_integral R x := begin suffices : is_integral R (show S, from ⟨x, hx⟩), { rcases this with ⟨p, hpm, hpx⟩, replace hpx := congr_arg S.val hpx, refine ⟨p, hpm, eq.trans _ hpx⟩, simp only [aeval_def, eval₂, sum_def], rw S.val.map_sum, refine finset.sum_congr rfl (λ n hn, _), rw [S.val.map_mul, S.val.map_pow, S.val.commutes, S.val_apply, subtype.coe_mk], }, refine is_integral_of_noetherian H ⟨x, hx⟩ end end ring section variables {R A B S : Type*} variables [comm_ring R] [comm_ring A] [comm_ring B] [comm_ring S] variables [algebra R A] [algebra R B] (f : R →+* S) theorem is_integral_alg_hom (f : A →ₐ[R] B) {x : A} (hx : is_integral R x) : is_integral R (f x) := let ⟨p, hp, hpx⟩ := hx in ⟨p, hp, by rw [← aeval_def, aeval_alg_hom_apply, aeval_def, hpx, f.map_zero]⟩ theorem is_integral_of_is_scalar_tower [algebra A B] [is_scalar_tower R A B] (x : B) (hx : is_integral R x) : is_integral A x := let ⟨p, hp, hpx⟩ := hx in ⟨p.map $ algebra_map R A, monic_map _ hp, by rw [← aeval_def, ← is_scalar_tower.aeval_apply, aeval_def, hpx]⟩ section local attribute [instance] subset.comm_ring algebra.of_is_subring theorem is_integral_of_subring {x : A} (T : set R) [is_subring T] (hx : is_integral T x) : is_integral R x := is_integral_of_is_scalar_tower x hx lemma is_integral_algebra_map_iff [algebra A B] [is_scalar_tower R A B] {x : A} (hAB : function.injective (algebra_map A B)) : is_integral R (algebra_map A B x) ↔ is_integral R x := begin split; rintros ⟨f, hf, hx⟩; use [f, hf], { exact is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero R A B hAB hx }, { rw [is_scalar_tower.algebra_map_eq R A B, ← hom_eval₂, hx, ring_hom.map_zero] } end theorem is_integral_iff_is_integral_closure_finite {r : A} : is_integral R r ↔ ∃ s : set R, s.finite ∧ is_integral (ring.closure s) r := begin split; intro hr, { rcases hr with ⟨p, hmp, hpr⟩, refine ⟨_, set.finite_mem_finset _, p.restriction, monic_restriction.2 hmp, _⟩, erw [← aeval_def, is_scalar_tower.aeval_apply _ R, map_restriction, aeval_def, hpr] }, rcases hr with ⟨s, hs, hsr⟩, exact is_integral_of_subring _ hsr end end theorem fg_adjoin_singleton_of_integral (x : A) (hx : is_integral R x) : (algebra.adjoin R ({x} : set A)).to_submodule.fg := begin rcases hx with ⟨f, hfm, hfx⟩, existsi finset.image ((^) x) (finset.range (nat_degree f + 1)), apply le_antisymm, { rw span_le, intros s hs, rw finset.mem_coe at hs, rcases finset.mem_image.1 hs with ⟨k, hk, rfl⟩, clear hk, exact is_submonoid.pow_mem (algebra.subset_adjoin (set.mem_singleton _)) }, intros r hr, change r ∈ algebra.adjoin R ({x} : set A) at hr, rw algebra.adjoin_singleton_eq_range at hr, rcases (aeval x).mem_range.mp hr with ⟨p, rfl⟩, rw ← mod_by_monic_add_div p hfm, rw ← aeval_def at hfx, rw [alg_hom.map_add, alg_hom.map_mul, hfx, zero_mul, add_zero], have : degree (p %ₘ f) ≤ degree f := degree_mod_by_monic_le p hfm, generalize_hyp : p %ₘ f = q at this ⊢, rw [← sum_C_mul_X_eq q, aeval_def, eval₂_sum, sum_def], refine sum_mem _ (λ k hkq, _), rw [eval₂_mul, eval₂_C, eval₂_pow, eval₂_X, ← algebra.smul_def], refine smul_mem _ _ (subset_span _), rw finset.mem_coe, refine finset.mem_image.2 ⟨_, _, rfl⟩, rw [finset.mem_range, nat.lt_succ_iff], refine le_of_not_lt (λ hk, _), rw [degree_le_iff_coeff_zero] at this, rw [mem_support_iff] at hkq, apply hkq, apply this, exact lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 hk) end theorem fg_adjoin_of_finite {s : set A} (hfs : s.finite) (his : ∀ x ∈ s, is_integral R x) : (algebra.adjoin R s).to_submodule.fg := set.finite.induction_on hfs (λ _, ⟨{1}, submodule.ext $ λ x, by { erw [algebra.adjoin_empty, finset.coe_singleton, ← one_eq_span, one_eq_range, linear_map.mem_range, algebra.mem_bot], refl }⟩) (λ a s has hs ih his, by rw [← set.union_singleton, algebra.adjoin_union_coe_submodule]; exact fg_mul _ _ (ih $ λ i hi, his i $ set.mem_insert_of_mem a hi) (fg_adjoin_singleton_of_integral _ $ his a $ set.mem_insert a s)) his theorem is_integral_of_mem_of_fg (S : subalgebra R A) (HS : S.to_submodule.fg) (x : A) (hx : x ∈ S) : is_integral R x := begin cases HS with y hy, obtain ⟨lx, hlx1, hlx2⟩ : ∃ (l : A →₀ R) (H : l ∈ finsupp.supported R R ↑y), (finsupp.total A A R id) l = x, { rwa [←(@finsupp.mem_span_image_iff_total A A R _ _ _ id ↑y x), set.image_id ↑y, hy] }, have hyS : ∀ {p}, p ∈ y → p ∈ S := λ p hp, show p ∈ S.to_submodule, by { rw ← hy, exact subset_span hp }, have : ∀ (jk : (↑(y.product y) : set (A × A))), jk.1.1 * jk.1.2 ∈ S.to_submodule := λ jk, S.mul_mem (hyS (finset.mem_product.1 jk.2).1) (hyS (finset.mem_product.1 jk.2).2), rw [← hy, ← set.image_id ↑y] at this, simp only [finsupp.mem_span_image_iff_total] at this, choose ly hly1 hly2, let S₀ : set R := ring.closure ↑(lx.frange ∪ finset.bUnion finset.univ (finsupp.frange ∘ ly)), refine is_integral_of_subring S₀ _, letI : comm_ring S₀ := @subtype.comm_ring _ _ _ ring.closure.is_subring, letI : algebra S₀ A := algebra.of_is_subring _, have : span S₀ (insert 1 ↑y : set A) * span S₀ (insert 1 ↑y : set A) ≤ span S₀ (insert 1 ↑y : set A), { rw span_mul_span, refine span_le.2 (λ z hz, _), rcases set.mem_mul.1 hz with ⟨p, q, rfl | hp, hq, rfl⟩, { rw one_mul, exact subset_span hq }, rcases hq with rfl | hq, { rw mul_one, exact subset_span (or.inr hp) }, erw ← hly2 ⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩, rw [finsupp.total_apply, finsupp.sum], refine (span S₀ (insert 1 ↑y : set A)).sum_mem (λ t ht, _), have : ly ⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩ t ∈ S₀ := ring.subset_closure (finset.mem_union_right _ $ finset.mem_bUnion.2 ⟨⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩, finset.mem_univ _, finsupp.mem_frange.2 ⟨finsupp.mem_support_iff.1 ht, _, rfl⟩⟩), change (⟨_, this⟩ : S₀) • t ∈ _, exact smul_mem _ _ (subset_span $ or.inr $ hly1 _ ht) }, haveI : is_subring (span S₀ (insert 1 ↑y : set A) : set A) := { one_mem := subset_span $ or.inl rfl, mul_mem := λ p q hp hq, this $ mul_mem_mul hp hq, zero_mem := (span S₀ (insert 1 ↑y : set A)).zero_mem, add_mem := λ _ _, (span S₀ (insert 1 ↑y : set A)).add_mem, neg_mem := λ _, (span S₀ (insert 1 ↑y : set A)).neg_mem }, have : span S₀ (insert 1 ↑y : set A) = (algebra.adjoin S₀ (↑y : set A)).to_submodule, { refine le_antisymm (span_le.2 $ set.insert_subset.2 ⟨(algebra.adjoin S₀ ↑y).one_mem, algebra.subset_adjoin⟩) (λ z hz, _), rw [subalgebra.mem_to_submodule, algebra.mem_adjoin_iff] at hz, rw ← set_like.mem_coe, refine ring.closure_subset (set.union_subset (set.range_subset_iff.2 $ λ t, _) (λ t ht, subset_span $ or.inr ht)) hz, rw algebra.algebra_map_eq_smul_one, exact smul_mem (span S₀ (insert 1 ↑y : set A)) _ (subset_span $ or.inl rfl) }, haveI : is_noetherian_ring ↥S₀ := is_noetherian_ring_closure _ (finset.finite_to_set _), refine is_integral_of_submodule_noetherian (algebra.adjoin S₀ ↑y) (is_noetherian_of_fg_of_noetherian _ ⟨insert 1 y, by rw [finset.coe_insert, this]⟩) _ _, rw [← hlx2, finsupp.total_apply, finsupp.sum], refine subalgebra.sum_mem _ (λ r hr, _), have : lx r ∈ S₀ := ring.subset_closure (finset.mem_union_left _ (finset.mem_image_of_mem _ hr)), change (⟨_, this⟩ : S₀) • r ∈ _, rw finsupp.mem_supported at hlx1, exact subalgebra.smul_mem _ (algebra.subset_adjoin $ hlx1 hr) _ end lemma ring_hom.is_integral_of_mem_closure {x y z : S} (hx : f.is_integral_elem x) (hy : f.is_integral_elem y) (hz : z ∈ ring.closure ({x, y} : set S)) : f.is_integral_elem z := begin letI : algebra R S := f.to_algebra, have := fg_mul _ _ (fg_adjoin_singleton_of_integral x hx) (fg_adjoin_singleton_of_integral y hy), rw [← algebra.adjoin_union_coe_submodule, set.singleton_union] at this, exact is_integral_of_mem_of_fg (algebra.adjoin R {x, y}) this z (algebra.mem_adjoin_iff.2 $ ring.closure_mono (set.subset_union_right _ _) hz), end theorem is_integral_of_mem_closure {x y z : A} (hx : is_integral R x) (hy : is_integral R y) (hz : z ∈ ring.closure ({x, y} : set A)) : is_integral R z := (algebra_map R A).is_integral_of_mem_closure hx hy hz lemma ring_hom.is_integral_zero : f.is_integral_elem 0 := f.map_zero ▸ f.is_integral_map theorem is_integral_zero : is_integral R (0:A) := (algebra_map R A).is_integral_zero lemma ring_hom.is_integral_one : f.is_integral_elem 1 := f.map_one ▸ f.is_integral_map theorem is_integral_one : is_integral R (1:A) := (algebra_map R A).is_integral_one lemma ring_hom.is_integral_add {x y : S} (hx : f.is_integral_elem x) (hy : f.is_integral_elem y) : f.is_integral_elem (x + y) := f.is_integral_of_mem_closure hx hy (is_add_submonoid.add_mem (ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl))) theorem is_integral_add {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x + y) := (algebra_map R A).is_integral_add hx hy lemma ring_hom.is_integral_neg {x : S} (hx : f.is_integral_elem x) : f.is_integral_elem (-x) := f.is_integral_of_mem_closure hx hx (is_add_subgroup.neg_mem (ring.subset_closure (or.inl rfl))) theorem is_integral_neg {x : A} (hx : is_integral R x) : is_integral R (-x) := (algebra_map R A).is_integral_neg hx lemma ring_hom.is_integral_sub {x y : S} (hx : f.is_integral_elem x) (hy : f.is_integral_elem y) : f.is_integral_elem (x - y) := by simpa only [sub_eq_add_neg] using f.is_integral_add hx (f.is_integral_neg hy) theorem is_integral_sub {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x - y) := (algebra_map R A).is_integral_sub hx hy lemma ring_hom.is_integral_mul {x y : S} (hx : f.is_integral_elem x) (hy : f.is_integral_elem y) : f.is_integral_elem (x * y) := f.is_integral_of_mem_closure hx hy (is_submonoid.mul_mem (ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl))) theorem is_integral_mul {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x * y) := (algebra_map R A).is_integral_mul hx hy variables (R A) /-- The integral closure of R in an R-algebra A. -/ def integral_closure : subalgebra R A := { carrier := { r | is_integral R r }, zero_mem' := is_integral_zero, one_mem' := is_integral_one, add_mem' := λ _ _, is_integral_add, mul_mem' := λ _ _, is_integral_mul, algebra_map_mem' := λ x, is_integral_algebra_map } theorem mem_integral_closure_iff_mem_fg {r : A} : r ∈ integral_closure R A ↔ ∃ M : subalgebra R A, M.to_submodule.fg ∧ r ∈ M := ⟨λ hr, ⟨algebra.adjoin R {r}, fg_adjoin_singleton_of_integral _ hr, algebra.subset_adjoin rfl⟩, λ ⟨M, Hf, hrM⟩, is_integral_of_mem_of_fg M Hf _ hrM⟩ variables {R} {A} /-- Mapping an integral closure along an `alg_equiv` gives the integral closure. -/ lemma integral_closure_map_alg_equiv (f : A ≃ₐ[R] B) : (integral_closure R A).map (f : A →ₐ[R] B) = integral_closure R B := begin ext y, rw subalgebra.mem_map, split, { rintros ⟨x, hx, rfl⟩, exact is_integral_alg_hom f hx }, { intro hy, use [f.symm y, is_integral_alg_hom (f.symm : B →ₐ[R] A) hy], simp } end lemma integral_closure.is_integral (x : integral_closure R A) : is_integral R x := let ⟨p, hpm, hpx⟩ := x.2 in ⟨p, hpm, subtype.eq $ by rwa [← aeval_def, subtype.val_eq_coe, ← subalgebra.val_apply, aeval_alg_hom_apply] at hpx⟩ lemma ring_hom.is_integral_of_is_integral_mul_unit (x y : S) (r : R) (hr : f r * y = 1) (hx : f.is_integral_elem (x * y)) : f.is_integral_elem x := begin obtain ⟨p, ⟨p_monic, hp⟩⟩ := hx, refine ⟨scale_roots p r, ⟨(monic_scale_roots_iff r).2 p_monic, _⟩⟩, convert scale_roots_eval₂_eq_zero f hp, rw [mul_comm x y, ← mul_assoc, hr, one_mul], end theorem is_integral_of_is_integral_mul_unit {x y : A} {r : R} (hr : algebra_map R A r * y = 1) (hx : is_integral R (x * y)) : is_integral R x := (algebra_map R A).is_integral_of_is_integral_mul_unit x y r hr hx /-- Generalization of `is_integral_of_mem_closure` bootstrapped up from that lemma -/ lemma is_integral_of_mem_closure' (G : set A) (hG : ∀ x ∈ G, is_integral R x) : ∀ x ∈ (subring.closure G), is_integral R x := λ x hx, subring.closure_induction hx hG is_integral_zero is_integral_one (λ _ _, is_integral_add) (λ _, is_integral_neg) (λ _ _, is_integral_mul) lemma is_integral_of_mem_closure'' {S : Type*} [comm_ring S] {f : R →+* S} (G : set S) (hG : ∀ x ∈ G, f.is_integral_elem x) : ∀ x ∈ (subring.closure G), f.is_integral_elem x := λ x hx, @is_integral_of_mem_closure' R S _ _ f.to_algebra G hG x hx end section algebra open algebra variables {R A B S T : Type*} variables [comm_ring R] [comm_ring A] [comm_ring B] [comm_ring S] [comm_ring T] variables [algebra A B] [algebra R B] (f : R →+* S) (g : S →+* T) lemma is_integral_trans_aux (x : B) {p : polynomial A} (pmonic : monic p) (hp : aeval x p = 0) : is_integral (adjoin R (↑(p.map $ algebra_map A B).frange : set B)) x := begin generalize hS : (↑(p.map $ algebra_map A B).frange : set B) = S, have coeffs_mem : ∀ i, (p.map $ algebra_map A B).coeff i ∈ adjoin R S, { intro i, by_cases hi : (p.map $ algebra_map A B).coeff i = 0, { rw hi, exact subalgebra.zero_mem _ }, rw ← hS, exact subset_adjoin (coeff_mem_frange _ _ hi) }, obtain ⟨q, hq⟩ : ∃ q : polynomial (adjoin R S), q.map (algebra_map (adjoin R S) B) = (p.map $ algebra_map A B), { rw ← set.mem_range, exact (polynomial.mem_map_range _).2 (λ i, ⟨⟨_, coeffs_mem i⟩, rfl⟩) }, use q, split, { suffices h : (q.map (algebra_map (adjoin R S) B)).monic, { refine monic_of_injective _ h, exact subtype.val_injective }, { rw hq, exact monic_map _ pmonic } }, { convert hp using 1, replace hq := congr_arg (eval x) hq, convert hq using 1; symmetry; apply eval_map }, end variables [algebra R A] [is_scalar_tower R A B] /-- If A is an R-algebra all of whose elements are integral over R, and x is an element of an A-algebra that is integral over A, then x is integral over R.-/ lemma is_integral_trans (A_int : is_integral R A) (x : B) (hx : is_integral A x) : is_integral R x := begin rcases hx with ⟨p, pmonic, hp⟩, let S : set B := ↑(p.map $ algebra_map A B).frange, refine is_integral_of_mem_of_fg (adjoin R (S ∪ {x})) _ _ (subset_adjoin $ or.inr rfl), refine fg_trans (fg_adjoin_of_finite (finset.finite_to_set _) (λ x hx, _)) _, { rw [finset.mem_coe, frange, finset.mem_image] at hx, rcases hx with ⟨i, _, rfl⟩, rw coeff_map, exact is_integral_alg_hom (is_scalar_tower.to_alg_hom R A B) (A_int _) }, { apply fg_adjoin_singleton_of_integral, exact is_integral_trans_aux _ pmonic hp } end /-- If A is an R-algebra all of whose elements are integral over R, and B is an A-algebra all of whose elements are integral over A, then all elements of B are integral over R.-/ lemma algebra.is_integral_trans (hA : is_integral R A) (hB : is_integral A B) : is_integral R B := λ x, is_integral_trans hA x (hB x) lemma ring_hom.is_integral_trans (hf : f.is_integral) (hg : g.is_integral) : (g.comp f).is_integral := @algebra.is_integral_trans R S T _ _ _ g.to_algebra (g.comp f).to_algebra f.to_algebra (@is_scalar_tower.of_algebra_map_eq R S T _ _ _ f.to_algebra g.to_algebra (g.comp f).to_algebra (ring_hom.comp_apply g f)) hf hg lemma ring_hom.is_integral_of_surjective (hf : function.surjective f) : f.is_integral := λ x, (hf x).rec_on (λ y hy, (hy ▸ f.is_integral_map : f.is_integral_elem x)) lemma is_integral_of_surjective (h : function.surjective (algebra_map R A)) : is_integral R A := (algebra_map R A).is_integral_of_surjective h /-- If `R → A → B` is an algebra tower with `A → B` injective, then if the entire tower is an integral extension so is `R → A` -/ lemma is_integral_tower_bot_of_is_integral (H : function.injective (algebra_map A B)) {x : A} (h : is_integral R (algebra_map A B x)) : is_integral R x := begin rcases h with ⟨p, ⟨hp, hp'⟩⟩, refine ⟨p, ⟨hp, _⟩⟩, rw [is_scalar_tower.algebra_map_eq R A B, ← eval₂_map, eval₂_hom, ← ring_hom.map_zero (algebra_map A B)] at hp', rw [eval₂_eq_eval_map], exact H hp', end lemma ring_hom.is_integral_tower_bot_of_is_integral (hg : function.injective g) (hfg : (g.comp f).is_integral) : f.is_integral := λ x, @is_integral_tower_bot_of_is_integral R S T _ _ _ g.to_algebra (g.comp f).to_algebra f.to_algebra (@is_scalar_tower.of_algebra_map_eq R S T _ _ _ f.to_algebra g.to_algebra (g.comp f).to_algebra (ring_hom.comp_apply g f)) hg x (hfg (g x)) lemma is_integral_tower_bot_of_is_integral_field {R A B : Type*} [comm_ring R] [field A] [comm_ring B] [nontrivial B] [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B] {x : A} (h : is_integral R (algebra_map A B x)) : is_integral R x := is_integral_tower_bot_of_is_integral (algebra_map A B).injective h lemma ring_hom.is_integral_elem_of_is_integral_elem_comp {x : T} (h : (g.comp f).is_integral_elem x) : g.is_integral_elem x := let ⟨p, ⟨hp, hp'⟩⟩ := h in ⟨p.map f, monic_map f hp, by rwa ← eval₂_map at hp'⟩ lemma ring_hom.is_integral_tower_top_of_is_integral (h : (g.comp f).is_integral) : g.is_integral := λ x, ring_hom.is_integral_elem_of_is_integral_elem_comp f g (h x) /-- If `R → A → B` is an algebra tower, then if the entire tower is an integral extension so is `A → B`. -/ lemma is_integral_tower_top_of_is_integral {x : B} (h : is_integral R x) : is_integral A x := begin rcases h with ⟨p, ⟨hp, hp'⟩⟩, refine ⟨p.map (algebra_map R A), ⟨monic_map (algebra_map R A) hp, _⟩⟩, rw [is_scalar_tower.algebra_map_eq R A B, ← eval₂_map] at hp', exact hp', end lemma ring_hom.is_integral_quotient_of_is_integral {I : ideal S} (hf : f.is_integral) : (ideal.quotient_map I f le_rfl).is_integral := begin rintros ⟨x⟩, obtain ⟨p, ⟨p_monic, hpx⟩⟩ := hf x, refine ⟨p.map (ideal.quotient.mk _), ⟨monic_map _ p_monic, _⟩⟩, simpa only [hom_eval₂, eval₂_map] using congr_arg (ideal.quotient.mk I) hpx end lemma is_integral_quotient_of_is_integral {I : ideal A} (hRA : is_integral R A) : is_integral (I.comap (algebra_map R A)).quotient I.quotient := (algebra_map R A).is_integral_quotient_of_is_integral hRA lemma is_integral_quotient_map_iff {I : ideal S} : (ideal.quotient_map I f le_rfl).is_integral ↔ ((ideal.quotient.mk I).comp f : R →+* I.quotient).is_integral := begin let g := ideal.quotient.mk (I.comap f), have := ideal.quotient_map_comp_mk le_rfl, refine ⟨λ h, _, λ h, ring_hom.is_integral_tower_top_of_is_integral g _ (this ▸ h)⟩, refine this ▸ ring_hom.is_integral_trans g (ideal.quotient_map I f le_rfl) _ h, exact ring_hom.is_integral_of_surjective g ideal.quotient.mk_surjective, end /-- If the integral extension `R → S` is injective, and `S` is a field, then `R` is also a field. -/ lemma is_field_of_is_integral_of_is_field {R S : Type*} [integral_domain R] [integral_domain S] [algebra R S] (H : is_integral R S) (hRS : function.injective (algebra_map R S)) (hS : is_field S) : is_field R := begin refine ⟨⟨0, 1, zero_ne_one⟩, mul_comm, λ a ha, _⟩, -- Let `a_inv` be the inverse of `algebra_map R S a`, -- then we need to show that `a_inv` is of the form `algebra_map R S b`. obtain ⟨a_inv, ha_inv⟩ := hS.mul_inv_cancel (λ h, ha (hRS (trans h (ring_hom.map_zero _).symm))), -- Let `p : polynomial R` be monic with root `a_inv`, -- and `q` be `p` with coefficients reversed (so `q(a) = q'(a) * a + 1`). -- We claim that `q(a) = 0`, so `-q'(a)` is the inverse of `a`. obtain ⟨p, p_monic, hp⟩ := H a_inv, use -∑ (i : ℕ) in finset.range p.nat_degree, (p.coeff i) * a ^ (p.nat_degree - i - 1), -- `q(a) = 0`, because multiplying everything with `a_inv^n` gives `p(a_inv) = 0`. -- TODO: this could be a lemma for `polynomial.reverse`. have hq : ∑ (i : ℕ) in finset.range (p.nat_degree + 1), (p.coeff i) * a ^ (p.nat_degree - i) = 0, { apply (algebra_map R S).injective_iff.mp hRS, have a_inv_ne_zero : a_inv ≠ 0 := right_ne_zero_of_mul (mt ha_inv.symm.trans one_ne_zero), refine (mul_eq_zero.mp _).resolve_right (pow_ne_zero p.nat_degree a_inv_ne_zero), rw [eval₂_eq_sum_range] at hp, rw [ring_hom.map_sum, finset.sum_mul], refine (finset.sum_congr rfl (λ i hi, _)).trans hp, rw [ring_hom.map_mul, mul_assoc], congr, have : a_inv ^ p.nat_degree = a_inv ^ (p.nat_degree - i) * a_inv ^ i, { rw [← pow_add a_inv, nat.sub_add_cancel (nat.le_of_lt_succ (finset.mem_range.mp hi))] }, rw [ring_hom.map_pow, this, ← mul_assoc, ← mul_pow, ha_inv, one_pow, one_mul] }, -- Since `q(a) = 0` and `q(a) = q'(a) * a + 1`, we have `a * -q'(a) = 1`. -- TODO: we could use a lemma for `polynomial.div_X` here. rw [finset.sum_range_succ_comm, p_monic.coeff_nat_degree, one_mul, nat.sub_self, pow_zero, add_eq_zero_iff_eq_neg, eq_comm] at hq, rw [mul_comm, ← neg_mul_eq_neg_mul, finset.sum_mul], convert hq using 2, refine finset.sum_congr rfl (λ i hi, _), have : 1 ≤ p.nat_degree - i := nat.le_sub_left_of_add_le (finset.mem_range.mp hi), rw [mul_assoc, ← pow_succ', nat.sub_add_cancel this] end end algebra section local attribute [instance] subset.comm_ring algebra.of_is_subring theorem integral_closure_idem {R : Type*} {A : Type*} [comm_ring R] [comm_ring A] [algebra R A] : integral_closure (integral_closure R A : set A) A = ⊥ := eq_bot_iff.2 $ λ x hx, algebra.mem_bot.2 ⟨⟨x, @is_integral_trans _ _ _ _ _ _ _ _ (integral_closure R A).algebra _ integral_closure.is_integral x hx⟩, rfl⟩ end section integral_domain variables {R S : Type*} [comm_ring R] [integral_domain S] [algebra R S] instance : integral_domain (integral_closure R S) := infer_instance end integral_domain
509307a7292af9d242b6d69711012607a6950571
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/leanpkg/cyclic/Cyclic/A/B.lean
41c84985d2a232f841b90aa4306f44b57431b12f
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
14
lean
import Cyclic
275b6a68bff13b96d4a329a67d6112898354e4d7
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/compiler/partial.lean
b061a0f177a6b4e5a56ea6d9726b57d1adcccccd
[ "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
373
lean
set_option pp.implicit true set_option pp.binder_types false -- set_option trace.compiler.boxed true partial def contains : String → Char → Nat → Bool | s, c, i => if s.atEnd i then false else if s.get i == c then true else contains s c (s.next i) def main : IO Unit := let s1 := "hello"; IO.println (contains s1 'a' 0) *> IO.println (contains s1 'o' 0)
62cd94be6bfb7d96a0f5e3888f29a570d8737f28
a047a4718edfa935d17231e9e6ecec8c7b701e05
/src/analysis/analytic/composition.lean
a12a57d57a242b106fb079486566ad72de805ef2
[ "Apache-2.0" ]
permissive
utensil-contrib/mathlib
bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767
b91909e77e219098a2f8cc031f89d595fe274bd2
refs/heads/master
1,668,048,976,965
1,592,442,701,000
1,592,442,701,000
273,197,855
0
0
null
1,592,472,812,000
1,592,472,811,000
null
UTF-8
Lean
false
false
56,619
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Johan Commelin -/ import analysis.analytic.basic import combinatorics.composition /-! # Composition of analytic functions in this file we prove that the composition of analytic functions is analytic. The argument is the following. Assume `g z = ∑' qₙ (z, ..., z)` and `f y = ∑' pₖ (y, ..., y)`. Then `g (f y) = ∑' qₙ (∑' pₖ (y, ..., y), ..., ∑' pₖ (y, ..., y)) = ∑' qₙ (p_{i₁} (y, ..., y), ..., p_{iₙ} (y, ..., y))`. For each `n` and `i₁, ..., iₙ`, define a `i₁ + ... + iₙ` multilinear function mapping `(y₀, ..., y_{i₁ + ... + iₙ - 1})` to `qₙ (p_{i₁} (y₀, ..., y_{i₁-1}), p_{i₂} (y_{i₁}, ..., y_{i₁ + i₂ - 1}), ..., p_{iₙ} (....)))`. Then `g ∘ f` is obtained by summing all these multilinear functions. To formalize this, we use compositions of an integer `N`, i.e., its decompositions into a sum `i₁ + ... + iₙ` of positive integers. Given such a composition `c` and two formal multilinear series `q` and `p`, let `q.comp_along_composition p c` be the above multilinear function. Then the `N`-th coefficient in the power series expansion of `g ∘ f` is the sum of these terms over all `c : composition N`. To complete the proof, we need to show that this power series has a positive radius of convergence. This follows from the fact that `composition N` has cardinality `2^(N-1)` and estimates on the norm of `qₙ` and `pₖ`, which give summability. We also need to show that it indeed converges to `g ∘ f`. For this, we note that the composition of partial sums converges to `g ∘ f`, and that it corresponds to a part of the whole sum, on a subset that increases to the whole space. By summability of the norms, this implies the overall convergence. ## Main results * `q.comp p` is the formal composition of the formal multilinear series `q` and `p`. * `has_fpower_series_at.comp` states that if two functions `g` and `f` admit power series expansions `q` and `p`, then `g ∘ f` admits a power series expansion given by `q.comp p`. * `analytic_at.comp` states that the composition of analytic functions is analytic. * `formal_multilinear_series.comp_assoc` states that composition is associative on formal multilinear series. ## Implementation details The main technical difficulty is to write down things. In particular, we need to define precisely `q.comp_along_composition p c` and to show that it is indeed a continuous multilinear function. This requires a whole interface built on the class `composition`. Once this is set, the main difficulty is to reorder the sums, writing the composition of the partial sums as a sum over some subset of `Σ n, composition n`. We need to check that the reordering is a bijection, running over difficulties due to the dependent nature of the types under consideration, that are controlled thanks to the interface for `composition`. The associativity of composition on formal multilinear series is a nontrivial result: it does not follow from the associativity of composition of analytic functions, as there is no uniqueness for the formal multilinear series representing a function (and also, it holds even when the radius of convergence of the series is `0`). Instead, we give a direct proof, which amounts to reordering double sums in a careful way. The change of variables is a canonical (combinatorial) bijection `composition.sigma_equiv_sigma_pi` between `(Σ (a : composition n), composition a.length)` and `(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i))`, and is described in more details below in the paragraph on associativity. -/ noncomputable theory variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] {H : Type*} [normed_group H] [normed_space 𝕜 H] open filter list open_locale topological_space big_operators classical /-! ### Composing formal multilinear series -/ namespace formal_multilinear_series /-! In this paragraph, we define the composition of formal multilinear series, by summing over all possible compositions of `n`. -/ /-- Given a formal multilinear series `p`, a composition `c` of `n` and the index `i` of a block of `c`, we may define a function on `fin n → E` by picking the variables in the `i`-th block of `n`, and applying the corresponding coefficient of `p` to these variables. This function is called `p.apply_composition c v i` for `v : fin n → E` and `i : fin c.length`. -/ def apply_composition (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) : (fin n → E) → (fin (c.length) → F) := λ v i, p (c.blocks_fun i) (v ∘ (c.embedding i)) lemma apply_composition_ones (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : apply_composition p (composition.ones n) = λ v i, p 1 (λ _, v (i.cast_le (composition.length_le _))) := begin funext v i, apply p.congr (composition.ones_blocks_fun _ _), intros j hjn hj1, obtain rfl : j = 0, { linarith }, refine congr_arg v _, rw [fin.ext_iff, fin.cast_le_val, composition.ones_embedding], end /-- Technical lemma stating how `p.apply_composition` commutes with updating variables. This will be the key point to show that functions constructed from `apply_composition` retain multilinearity. -/ lemma apply_composition_update (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) (j : fin n) (v : fin n → E) (z : E) : p.apply_composition c (function.update v j z) = function.update (p.apply_composition c v) (c.index j) (p (c.blocks_fun (c.index j)) (function.update (v ∘ (c.embedding (c.index j))) (c.inv_embedding j) z)) := begin ext k, by_cases h : k = c.index j, { rw h, let r : fin (c.blocks_fun (c.index j)) → fin n := c.embedding (c.index j), simp only [function.update_same], change p (c.blocks_fun (c.index j)) ((function.update v j z) ∘ r) = _, let j' := c.inv_embedding j, suffices B : (function.update v j z) ∘ r = function.update (v ∘ r) j' z, by rw B, suffices C : (function.update v (r j') z) ∘ r = function.update (v ∘ r) j' z, by { convert C, exact (c.embedding_comp_inv j).symm }, exact function.update_comp_eq_of_injective _ (c.embedding_inj _) _ _ }, { simp only [h, function.update_eq_self, function.update_noteq, ne.def, not_false_iff], let r : fin (c.blocks_fun k) → fin n := c.embedding k, change p (c.blocks_fun k) ((function.update v j z) ∘ r) = p (c.blocks_fun k) (v ∘ r), suffices B : (function.update v j z) ∘ r = v ∘ r, by rw B, apply function.update_comp_eq_of_not_mem_range, rwa c.mem_range_embedding_iff' } end /-- Given two formal multilinear series `q` and `p` and a composition `c` of `n`, one may form a multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `q c.length` to the resulting vector. It is called `q.comp_along_composition_multilinear p c`. This function admits a version as a continuous multilinear map, called `q.comp_along_composition p c` below. -/ def comp_along_composition_multilinear {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : multilinear_map 𝕜 (λ i : fin n, E) G := { to_fun := λ v, q c.length (p.apply_composition c v), map_add' := λ v i x y, by simp only [apply_composition_update, continuous_multilinear_map.map_add], map_smul' := λ v i c x, by simp only [apply_composition_update, continuous_multilinear_map.map_smul] } /-- The norm of `q.comp_along_composition_multilinear p c` is controlled by the product of the norms of the relevant bits of `q` and `p`. -/ lemma comp_along_composition_multilinear_bound {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) (v : fin n → E) : ∥q.comp_along_composition_multilinear p c v∥ ≤ ∥q c.length∥ * (∏ i, ∥p (c.blocks_fun i)∥) * (∏ i : fin n, ∥v i∥) := calc ∥q.comp_along_composition_multilinear p c v∥ = ∥q c.length (p.apply_composition c v)∥ : rfl ... ≤ ∥q c.length∥ * ∏ i, ∥p.apply_composition c v i∥ : continuous_multilinear_map.le_op_norm _ _ ... ≤ ∥q c.length∥ * ∏ i, ∥p (c.blocks_fun i)∥ * ∏ j : fin (c.blocks_fun i), ∥(v ∘ (c.embedding i)) j∥ : begin apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), refine finset.prod_le_prod (λ i hi, norm_nonneg _) (λ i hi, _), apply continuous_multilinear_map.le_op_norm, end ... = ∥q c.length∥ * (∏ i, ∥p (c.blocks_fun i)∥) * ∏ i (j : fin (c.blocks_fun i)), ∥(v ∘ (c.embedding i)) j∥ : by rw [finset.prod_mul_distrib, mul_assoc] ... = ∥q c.length∥ * (∏ i, ∥p (c.blocks_fun i)∥) * (∏ i : fin n, ∥v i∥) : by { rw [← finset.prod_equiv c.blocks_fin_equiv, ← finset.univ_sigma_univ, finset.prod_sigma], congr } /-- Given two formal multilinear series `q` and `p` and a composition `c` of `n`, one may form a continuous multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `q c.length` to the resulting vector. It is called `q.comp_along_composition p c`. It is constructed from the analogous multilinear function `q.comp_along_composition_multilinear p c`, together with a norm control to get the continuity. -/ def comp_along_composition {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : continuous_multilinear_map 𝕜 (λ i : fin n, E) G := (q.comp_along_composition_multilinear p c).mk_continuous _ (q.comp_along_composition_multilinear_bound p c) @[simp] lemma comp_along_composition_apply {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) (v : fin n → E) : (q.comp_along_composition p c) v = q c.length (p.apply_composition c v) := rfl /-- The norm of `q.comp_along_composition p c` is controlled by the product of the norms of the relevant bits of `q` and `p`. -/ lemma comp_along_composition_norm {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : ∥q.comp_along_composition p c∥ ≤ ∥q c.length∥ * ∏ i, ∥p (c.blocks_fun i)∥ := multilinear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (finset.prod_nonneg (λ i hi, norm_nonneg _))) _ lemma comp_along_composition_nnnorm {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : nnnorm (q.comp_along_composition p c) ≤ nnnorm (q c.length) * ∏ i, nnnorm (p (c.blocks_fun i)) := by simpa only [← nnreal.coe_le_coe, coe_nnnorm, nnreal.coe_mul, coe_nnnorm, nnreal.coe_prod, coe_nnnorm] using q.comp_along_composition_norm p c /-- Formal composition of two formal multilinear series. The `n`-th coefficient in the composition is defined to be the sum of `q.comp_along_composition p c` over all compositions of `n`. In other words, this term (as a multilinear function applied to `v_0, ..., v_{n-1}`) is `∑'_{k} ∑'_{i₁ + ... + iₖ = n} pₖ (q_{i_1} (...), ..., q_{i_k} (...))`, where one puts all variables `v_0, ..., v_{n-1}` in increasing order in the dots.-/ protected def comp (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series 𝕜 E G := λ n, ∑ c : composition n, q.comp_along_composition p c /-- The `0`-th coefficient of `q.comp p` is `q 0`. Since these maps are multilinear maps in zero variables, but on different spaces, we can not state this directly, so we state it when applied to arbitrary vectors (which have to be the zero vector). -/ lemma comp_coeff_zero (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 0 → E) (v' : fin 0 → F) : (q.comp p) 0 v = q 0 v' := begin let c : composition 0 := composition.ones 0, dsimp [formal_multilinear_series.comp], have : {c} = (finset.univ : finset (composition 0)), { apply finset.eq_of_subset_of_card_le; simp [finset.card_univ, composition_card 0] }, rw ← this, simp only [finset.sum_singleton, continuous_multilinear_map.sum_apply], change q c.length (p.apply_composition c v) = q 0 v', congr, ext i, simp only [composition.ones_length] at i, exact fin_zero_elim i end @[simp] lemma comp_coeff_zero' (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 0 → E) : (q.comp p) 0 v = q 0 (λ i, 0) := q.comp_coeff_zero p v _ /-- The `0`-th coefficient of `q.comp p` is `q 0`. When `p` goes from `E` to `E`, this can be expressed as a direct equality -/ lemma comp_coeff_zero'' (q : formal_multilinear_series 𝕜 E F) (p : formal_multilinear_series 𝕜 E E) : (q.comp p) 0 = q 0 := by { ext v, exact q.comp_coeff_zero p _ _ } /-! ### The identity formal power series We will now define the identity power series, and show that it is a neutral element for left and right composition. -/ section variables (𝕜 E) /-- The identity formal multilinear series, with all coefficients equal to `0` except for `n = 1` where it is (the continuous multilinear version of) the identity. -/ def id : formal_multilinear_series 𝕜 E E | 0 := 0 | 1 := (continuous_multilinear_curry_fin1 𝕜 E E).symm (continuous_linear_map.id 𝕜 E) | _ := 0 /-- The first coefficient of `id 𝕜 E` is the identity. -/ @[simp] lemma id_apply_one (v : fin 1 → E) : (formal_multilinear_series.id 𝕜 E) 1 v = v 0 := rfl /-- The `n`th coefficient of `id 𝕜 E` is the identity when `n = 1`. We state this in a dependent way, as it will often appear in this form. -/ lemma id_apply_one' {n : ℕ} (h : n = 1) (v : fin n → E) : (id 𝕜 E) n v = v ⟨0, h.symm ▸ zero_lt_one⟩ := begin let w : fin 1 → E := λ i, v ⟨i.1, h.symm ▸ i.2⟩, have : v ⟨0, h.symm ▸ zero_lt_one⟩ = w 0 := rfl, rw [this, ← id_apply_one 𝕜 E w], apply congr _ h, intros, obtain rfl : i = 0, { linarith }, exact this, end /-- For `n ≠ 1`, the `n`-th coefficient of `id 𝕜 E` is zero, by definition. -/ @[simp] lemma id_apply_ne_one {n : ℕ} (h : n ≠ 1) : (formal_multilinear_series.id 𝕜 E) n = 0 := by { cases n, { refl }, cases n, { contradiction }, refl } end @[simp] theorem comp_id (p : formal_multilinear_series 𝕜 E F) : p.comp (id 𝕜 E) = p := begin ext1 n, dsimp [formal_multilinear_series.comp], rw finset.sum_eq_single (composition.ones n), show comp_along_composition p (id 𝕜 E) (composition.ones n) = p n, { ext v, rw comp_along_composition_apply, apply p.congr (composition.ones_length n), intros, rw apply_composition_ones, refine congr_arg v _, rw [fin.ext_iff, fin.cast_le_val], }, show ∀ (b : composition n), b ∈ finset.univ → b ≠ composition.ones n → comp_along_composition p (id 𝕜 E) b = 0, { assume b _ hb, obtain ⟨k, hk, lt_k⟩ : ∃ (k : ℕ) (H : k ∈ composition.blocks b), 1 < k := composition.ne_ones_iff.1 hb, obtain ⟨i, i_lt, hi⟩ : ∃ (i : ℕ) (h : i < b.blocks.length), b.blocks.nth_le i h = k := nth_le_of_mem hk, let j : fin b.length := ⟨i, b.blocks_length ▸ i_lt⟩, have A : 1 < b.blocks_fun j := by convert lt_k, ext v, rw [comp_along_composition_apply, continuous_multilinear_map.zero_apply], apply continuous_multilinear_map.map_coord_zero _ j, dsimp [apply_composition], rw id_apply_ne_one _ _ (ne_of_gt A), refl }, { simp } end theorem id_comp (p : formal_multilinear_series 𝕜 E F) (h : p 0 = 0) : (id 𝕜 F).comp p = p := begin ext1 n, by_cases hn : n = 0, { rw [hn, h], ext v, rw [comp_coeff_zero', id_apply_ne_one _ _ zero_ne_one], refl }, { dsimp [formal_multilinear_series.comp], have n_pos : 0 < n := bot_lt_iff_ne_bot.mpr hn, rw finset.sum_eq_single (composition.single n n_pos), show comp_along_composition (id 𝕜 F) p (composition.single n n_pos) = p n, { ext v, rw [comp_along_composition_apply, id_apply_one' _ _ (composition.single_length n_pos)], dsimp [apply_composition], apply p.congr rfl, intros, rw [function.comp_app, composition.single_embedding] }, show ∀ (b : composition n), b ∈ finset.univ → b ≠ composition.single n n_pos → comp_along_composition (id 𝕜 F) p b = 0, { assume b _ hb, have A : b.length ≠ 1, by simpa [composition.eq_single_iff] using hb, ext v, rw [comp_along_composition_apply, id_apply_ne_one _ _ A], refl }, { simp } } end /-! ### Summability properties of the composition of formal power series-/ /-- If two formal multilinear series have positive radius of convergence, then the terms appearing in the definition of their composition are also summable (when multiplied by a suitable positive geometric term). -/ theorem comp_summable_nnreal (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (hq : 0 < q.radius) (hp : 0 < p.radius) : ∃ (r : nnreal), 0 < r ∧ summable (λ i, nnnorm (q.comp_along_composition p i.2) * r ^ i.1 : (Σ n, composition n) → nnreal) := begin /- This follows from the fact that the growth rate of `∥qₙ∥` and `∥pₙ∥` is at most geometric, giving a geometric bound on each `∥q.comp_along_composition p op∥`, together with the fact that there are `2^(n-1)` compositions of `n`, giving at most a geometric loss. -/ rcases ennreal.lt_iff_exists_nnreal_btwn.1 hq with ⟨rq, rq_pos, hrq⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hp with ⟨rp, rp_pos, hrp⟩, obtain ⟨Cq, hCq⟩ : ∃ (Cq : nnreal), ∀ n, nnnorm (q n) * rq^n ≤ Cq := q.bound_of_lt_radius hrq, obtain ⟨Cp, hCp⟩ : ∃ (Cp : nnreal), ∀ n, nnnorm (p n) * rp^n ≤ Cp := p.bound_of_lt_radius hrp, let r0 : nnreal := (4 * max Cp 1)⁻¹, set r := min rp 1 * min rq 1 * r0, have r_pos : 0 < r, { apply mul_pos (mul_pos _ _), { rw [nnreal.inv_pos], apply mul_pos, { norm_num }, { exact lt_of_lt_of_le zero_lt_one (le_max_right _ _) } }, { rw ennreal.coe_pos at rp_pos, simp [rp_pos, zero_lt_one] }, { rw ennreal.coe_pos at rq_pos, simp [rq_pos, zero_lt_one] } }, let a : ennreal := ((4 : nnreal) ⁻¹ : nnreal), have two_a : 2 * a < 1, { change ((2 : nnreal) : ennreal) * ((4 : nnreal) ⁻¹ : nnreal) < (1 : nnreal), rw [← ennreal.coe_mul, ennreal.coe_lt_coe, ← nnreal.coe_lt_coe, nnreal.coe_mul], change (2 : ℝ) * (4 : ℝ)⁻¹ < 1, norm_num }, have I : ∀ (i : Σ (n : ℕ), composition n), ↑(nnnorm (q.comp_along_composition p i.2) * r ^ i.1) ≤ (Cq : ennreal) * a ^ i.1, { rintros ⟨n, c⟩, rw [← ennreal.coe_pow, ← ennreal.coe_mul, ennreal.coe_le_coe], calc nnnorm (q.comp_along_composition p c) * r ^ n ≤ (nnnorm (q c.length) * ∏ i, nnnorm (p (c.blocks_fun i))) * r ^ n : mul_le_mul_of_nonneg_right (q.comp_along_composition_nnnorm p c) (bot_le) ... = (nnnorm (q c.length) * (min rq 1)^n) * ((∏ i, nnnorm (p (c.blocks_fun i))) * (min rp 1) ^ n) * r0 ^ n : by { dsimp [r], ring_exp } ... ≤ (nnnorm (q c.length) * (min rq 1) ^ c.length) * (∏ i, nnnorm (p (c.blocks_fun i)) * (min rp 1) ^ (c.blocks_fun i)) * r0 ^ n : begin apply_rules [mul_le_mul, bot_le, le_refl, pow_le_pow_of_le_one, min_le_right, c.length_le], apply le_of_eq, rw finset.prod_mul_distrib, congr' 1, conv_lhs { rw [← c.sum_blocks_fun, ← finset.prod_pow_eq_pow_sum] }, end ... ≤ Cq * (∏ i : fin c.length, Cp) * r0 ^ n : begin apply_rules [mul_le_mul, bot_le, le_trans _ (hCq c.length), le_refl, finset.prod_le_prod'], { assume i hi, refine le_trans (mul_le_mul (le_refl _) _ bot_le bot_le) (hCp (c.blocks_fun i)), exact pow_le_pow_of_le_left bot_le (min_le_left _ _) _ }, { refine mul_le_mul (le_refl _) _ bot_le bot_le, exact pow_le_pow_of_le_left bot_le (min_le_left _ _) _ } end ... ≤ Cq * (max Cp 1) ^ n * r0 ^ n : begin apply_rules [mul_le_mul, bot_le, le_refl], simp only [finset.card_fin, finset.prod_const], refine le_trans (pow_le_pow_of_le_left bot_le (le_max_left Cp 1) c.length) _, apply pow_le_pow (le_max_right Cp 1) c.length_le, end ... = Cq * 4⁻¹ ^ n : begin dsimp [r0], have A : (4 : nnreal) ≠ 0, by norm_num, have B : max Cp 1 ≠ 0 := ne_of_gt (lt_of_lt_of_le zero_lt_one (le_max_right Cp 1)), field_simp [A, B], ring_exp end }, refine ⟨r, r_pos, _⟩, rw [← ennreal.tsum_coe_ne_top_iff_summable], apply ne_of_lt, calc (∑' (i : Σ (n : ℕ), composition n), ↑(nnnorm (q.comp_along_composition p i.2) * r ^ i.1)) ≤ (∑' (i : Σ (n : ℕ), composition n), (Cq : ennreal) * a ^ i.1) : ennreal.tsum_le_tsum I ... = (∑' (n : ℕ), (∑' (c : composition n), (Cq : ennreal) * a ^ n)) : ennreal.tsum_sigma' _ ... = (∑' (n : ℕ), ↑(fintype.card (composition n)) * (Cq : ennreal) * a ^ n) : begin congr' 1, ext1 n, rw [tsum_fintype, finset.sum_const, nsmul_eq_mul, finset.card_univ, mul_assoc] end ... ≤ (∑' (n : ℕ), (2 : ennreal) ^ n * (Cq : ennreal) * a ^ n) : begin apply ennreal.tsum_le_tsum (λ n, _), apply ennreal.mul_le_mul (ennreal.mul_le_mul _ (le_refl _)) (le_refl _), rw composition_card, simp only [nat.cast_bit0, nat.cast_one, nat.cast_pow], apply ennreal.pow_le_pow _ (nat.sub_le n 1), have : (1 : nnreal) ≤ (2 : nnreal), by norm_num, rw ← ennreal.coe_le_coe at this, exact this end ... = (∑' (n : ℕ), (Cq : ennreal) * (2 * a) ^ n) : by { congr' 1, ext1 n, rw mul_pow, ring } ... = (Cq : ennreal) * (1 - 2 * a) ⁻¹ : by rw [ennreal.tsum_mul_left, ennreal.tsum_geometric] ... < ⊤ : by simp [lt_top_iff_ne_top, ennreal.mul_eq_top, two_a] end /-- Bounding below the radius of the composition of two formal multilinear series assuming summability over all compositions. -/ theorem le_comp_radius_of_summable (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (r : nnreal) (hr : summable (λ i, nnnorm (q.comp_along_composition p i.2) * r ^ i.1 : (Σ n, composition n) → nnreal)) : (r : ennreal) ≤ (q.comp p).radius := begin apply le_radius_of_bound _ (tsum (λ (i : Σ (n : ℕ), composition n), (nnnorm (comp_along_composition q p i.snd) * r ^ i.fst))), assume n, calc nnnorm (formal_multilinear_series.comp q p n) * r ^ n ≤ ∑' (c : composition n), nnnorm (comp_along_composition q p c) * r ^ n : begin rw [tsum_fintype, ← finset.sum_mul], exact mul_le_mul_of_nonneg_right (nnnorm_sum_le _ _) bot_le end ... ≤ ∑' (i : Σ (n : ℕ), composition n), nnnorm (comp_along_composition q p i.snd) * r ^ i.fst : begin let f : composition n → (Σ (n : ℕ), composition n) := λ c, ⟨n, c⟩, have : function.injective f, by tidy, convert nnreal.tsum_comp_le_tsum_of_inj hr this end end /-! ### Composing analytic functions Now, we will prove that the composition of the partial sums of `q` and `p` up to order `N` is given by a sum over some large subset of `Σ n, composition n` of `q.comp_along_composition p`, to deduce that the series for `q.comp p` indeed converges to `g ∘ f` when `q` is a power series for `g` and `p` is a power series for `f`. This proof is a big reindexing argument of a sum. Since it is a bit involved, we define first the source of the change of variables (`comp_partial_source`), its target (`comp_partial_target`) and the change of variables itself (`comp_change_of_variables`) before giving the main statement in `comp_partial_sum`. -/ /-- Source set in the change of variables to compute the composition of partial sums of formal power series. See also `comp_partial_sum`. -/ def comp_partial_sum_source (N : ℕ) : finset (Σ n, (fin n) → ℕ) := finset.sigma (finset.range N) (λ (n : ℕ), fintype.pi_finset (λ (i : fin n), finset.Ico 1 N) : _) @[simp] lemma mem_comp_partial_sum_source_iff (N : ℕ) (i : Σ n, (fin n) → ℕ) : i ∈ comp_partial_sum_source N ↔ i.1 < N ∧ ∀ (a : fin i.1), 1 ≤ i.2 a ∧ i.2 a < N := by simp only [comp_partial_sum_source, finset.Ico.mem, fintype.mem_pi_finset, finset.mem_sigma, finset.mem_range] /-- Change of variables appearing to compute the composition of partial sums of formal power series -/ def comp_change_of_variables (N : ℕ) (i : Σ n, (fin n) → ℕ) (hi : i ∈ comp_partial_sum_source N) : (Σ n, composition n) := begin rcases i with ⟨n, f⟩, rw mem_comp_partial_sum_source_iff at hi, refine ⟨∑ j, f j, of_fn (λ a, f a), λ i hi', _, by simp [sum_of_fn]⟩, obtain ⟨j, rfl⟩ : ∃ (j : fin n), f j = i, by rwa [mem_of_fn, set.mem_range] at hi', exact (hi.2 j).1 end @[simp] lemma comp_change_of_variables_length (N : ℕ) {i : Σ n, (fin n) → ℕ} (hi : i ∈ comp_partial_sum_source N) : composition.length (comp_change_of_variables N i hi).2 = i.1 := begin rcases i with ⟨k, blocks_fun⟩, dsimp [comp_change_of_variables], simp only [composition.length, map_of_fn, length_of_fn] end lemma comp_change_of_variables_blocks_fun (N : ℕ) {i : Σ n, (fin n) → ℕ} (hi : i ∈ comp_partial_sum_source N) (j : fin i.1) : (comp_change_of_variables N i hi).2.blocks_fun ⟨j.val, (comp_change_of_variables_length N hi).symm ▸ j.2⟩ = i.2 j := begin rcases i with ⟨n, f⟩, dsimp [composition.blocks_fun, composition.blocks, comp_change_of_variables], simp only [map_of_fn, nth_le_of_fn', function.comp_app], apply congr_arg, rw fin.ext_iff end /-- Target set in the change of variables to compute the composition of partial sums of formal power series, here given a a set. -/ def comp_partial_sum_target_set (N : ℕ) : set (Σ n, composition n) := {i | (i.2.length < N) ∧ (∀ (j : fin i.2.length), i.2.blocks_fun j < N)} lemma comp_partial_sum_target_subset_image_comp_partial_sum_source (N : ℕ) (i : Σ n, composition n) (hi : i ∈ comp_partial_sum_target_set N) : ∃ j (hj : j ∈ comp_partial_sum_source N), i = comp_change_of_variables N j hj := begin rcases i with ⟨n, c⟩, refine ⟨⟨c.length, c.blocks_fun⟩, _, _⟩, { simp only [comp_partial_sum_target_set, set.mem_set_of_eq] at hi, simp only [mem_comp_partial_sum_source_iff, hi.left, hi.right, true_and, and_true], exact λ a, c.one_le_blocks' _ }, { dsimp [comp_change_of_variables], rw composition.sigma_eq_iff_blocks_eq, simp only [composition.blocks_fun, composition.blocks, subtype.coe_eta, nth_le_map'], conv_lhs { rw ← of_fn_nth_le c.blocks } } end /-- Target set in the change of variables to compute the composition of partial sums of formal power series, here given a a finset. See also `comp_partial_sum`. -/ def comp_partial_sum_target (N : ℕ) : finset (Σ n, composition n) := set.finite.to_finset $ set.finite_dependent_image (finset.finite_to_set _) (comp_partial_sum_target_subset_image_comp_partial_sum_source N) @[simp] lemma mem_comp_partial_sum_target_iff {N : ℕ} {a : Σ n, composition n} : a ∈ comp_partial_sum_target N ↔ a.2.length < N ∧ (∀ (j : fin a.2.length), a.2.blocks_fun j < N) := by simp [comp_partial_sum_target, comp_partial_sum_target_set] /-- The auxiliary set corresponding to the composition of partial sums asymptotically contains all possible compositions. -/ lemma comp_partial_sum_target_tendsto_at_top : tendsto comp_partial_sum_target at_top at_top := begin apply monotone.tendsto_at_top_finset, { assume m n hmn a ha, have : ∀ i, i < m → i < n := λ i hi, lt_of_lt_of_le hi hmn, tidy }, { rintros ⟨n, c⟩, simp only [mem_comp_partial_sum_target_iff], obtain ⟨n, hn⟩ : bdd_above ↑(finset.univ.image (λ (i : fin c.length), c.blocks_fun i)) := finset.bdd_above _, refine ⟨max n c.length + 1, lt_of_le_of_lt (le_max_right n c.length) (lt_add_one _), λ j, lt_of_le_of_lt (le_trans _ (le_max_left _ _)) (lt_add_one _)⟩, apply hn, simp only [finset.mem_image_of_mem, finset.mem_coe, finset.mem_univ] } end /-- Composing the partial sums of two multilinear series coincides with the sum over all compositions in `comp_partial_sum_target N`. This is precisely the motivation for the definition of `comp_partial_sum_target N`. -/ lemma comp_partial_sum (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (N : ℕ) (z : E) : q.partial_sum N (∑ i in finset.Ico 1 N, p i (λ j, z)) = ∑ i in comp_partial_sum_target N, q.comp_along_composition_multilinear p i.2 (λ j, z) := begin -- we expand the composition, using the multilinearity of `q` to expand along each coordinate. suffices H : ∑ n in finset.range N, ∑ r in fintype.pi_finset (λ (i : fin n), finset.Ico 1 N), q n (λ (i : fin n), p (r i) (λ j, z)) = ∑ i in comp_partial_sum_target N, q.comp_along_composition_multilinear p i.2 (λ j, z), by simpa only [formal_multilinear_series.partial_sum, continuous_multilinear_map.map_sum_finset] using H, -- rewrite the first sum as a big sum over a sigma type rw ← @finset.sum_sigma _ _ _ _ (finset.range N) (λ (n : ℕ), (fintype.pi_finset (λ (i : fin n), finset.Ico 1 N)) : _) (λ i, q i.1 (λ (j : fin i.1), p (i.2 j) (λ (k : fin (i.2 j)), z))), show ∑ i in comp_partial_sum_source N, q i.1 (λ (j : fin i.1), p (i.2 j) (λ (k : fin (i.2 j)), z)) = ∑ i in comp_partial_sum_target N, q.comp_along_composition_multilinear p i.2 (λ j, z), -- show that the two sums correspond to each other by reindexing the variables. apply finset.sum_bij (comp_change_of_variables N), -- To conclude, we should show that the correspondance we have set up is indeed a bijection -- between the index sets of the two sums. -- 1 - show that the image belongs to `comp_partial_sum_target N` { rintros ⟨k, blocks_fun⟩ H, rw mem_comp_partial_sum_source_iff at H, simp only [mem_comp_partial_sum_target_iff, composition.length, composition.blocks, H.left, map_of_fn, length_of_fn, true_and, comp_change_of_variables], assume j, simp only [composition.blocks_fun, (H.right _).right, nth_le_of_fn'] }, -- 2 - show that the composition gives the `comp_along_composition` application { rintros ⟨k, blocks_fun⟩ H, apply congr _ (comp_change_of_variables_length N H).symm, intros, rw ← comp_change_of_variables_blocks_fun N H, refl }, -- 3 - show that the map is injective { rintros ⟨k, blocks_fun⟩ ⟨k', blocks_fun'⟩ H H' heq, obtain rfl : k = k', { have := (comp_change_of_variables_length N H).symm, rwa [heq, comp_change_of_variables_length] at this, }, congr, funext i, calc blocks_fun i = (comp_change_of_variables N _ H).2.blocks_fun _ : (comp_change_of_variables_blocks_fun N H i).symm ... = (comp_change_of_variables N _ H').2.blocks_fun _ : begin apply composition.blocks_fun_congr; try { rw heq }, refl end ... = blocks_fun' i : comp_change_of_variables_blocks_fun N H' i }, -- 4 - show that the map is surjective { assume i hi, apply comp_partial_sum_target_subset_image_comp_partial_sum_source N i, simpa [comp_partial_sum_target] using hi } end end formal_multilinear_series open formal_multilinear_series /-- If two functions `g` and `f` have power series `q` and `p` respectively at `f x` and `x`, then `g ∘ f` admits the power series `q.comp p` at `x`. -/ theorem has_fpower_series_at.comp {g : F → G} {f : E → F} {q : formal_multilinear_series 𝕜 F G} {p : formal_multilinear_series 𝕜 E F} {x : E} (hg : has_fpower_series_at g q (f x)) (hf : has_fpower_series_at f p x) : has_fpower_series_at (g ∘ f) (q.comp p) x := begin /- Consider `rf` and `rg` such that `f` and `g` have power series expansion on the disks of radius `rf` and `rg`. -/ rcases hg with ⟨rg, Hg⟩, rcases hf with ⟨rf, Hf⟩, /- The terms defining `q.comp p` are geometrically summable in a disk of some radius `r`. -/ rcases q.comp_summable_nnreal p Hg.radius_pos Hf.radius_pos with ⟨r, r_pos, hr⟩, /- We will consider `y` which is smaller than `r` and `rf`, and also small enough that `f (x + y)` is close enough to `f x` to be in the disk where `g` is well behaved. Let `min (r, rf, δ)` be this new radius.-/ have : continuous_at f x := Hf.analytic_at.continuous_at, obtain ⟨δ, δpos, hδ⟩ : ∃ (δ : ennreal) (H : 0 < δ), ∀ {z : E}, z ∈ emetric.ball x δ → f z ∈ emetric.ball (f x) rg, { have : emetric.ball (f x) rg ∈ 𝓝 (f x) := emetric.ball_mem_nhds _ Hg.r_pos, rcases emetric.mem_nhds_iff.1 (Hf.analytic_at.continuous_at this) with ⟨δ, δpos, Hδ⟩, exact ⟨δ, δpos, λ z hz, Hδ hz⟩ }, let rf' := min rf δ, have min_pos : 0 < min rf' r, by simp only [r_pos, Hf.r_pos, δpos, lt_min_iff, ennreal.coe_pos, and_self], /- We will show that `g ∘ f` admits the power series `q.comp p` in the disk of radius `min (r, rf', δ)`. -/ refine ⟨min rf' r, _⟩, refine ⟨le_trans (min_le_right rf' r) (formal_multilinear_series.le_comp_radius_of_summable q p r hr), min_pos, λ y hy, _⟩, /- Let `y` satisfy `∥y∥ < min (r, rf', δ)`. We want to show that `g (f (x + y))` is the sum of `q.comp p` applied to `y`. -/ -- First, check that `y` is small enough so that estimates for `f` and `g` apply. have y_mem : y ∈ emetric.ball (0 : E) rf := (emetric.ball_subset_ball (le_trans (min_le_left _ _) (min_le_left _ _))) hy, have fy_mem : f (x + y) ∈ emetric.ball (f x) rg, { apply hδ, have : y ∈ emetric.ball (0 : E) δ := (emetric.ball_subset_ball (le_trans (min_le_left _ _) (min_le_right _ _))) hy, simpa [edist_eq_coe_nnnorm_sub, edist_eq_coe_nnnorm] }, /- Now the proof starts. To show that the sum of `q.comp p` at `y` is `g (f (x + y))`, we will write `q.comp p` applied to `y` as a big sum over all compositions. Since the sum is summable, to get its convergence it suffices to get the convergence along some increasing sequence of sets. We will use the sequence of sets `comp_partial_sum_target n`, along which the sum is exactly the composition of the partial sums of `q` and `p`, by design. To show that it converges to `g (f (x + y))`, pointwise convergence would not be enough, but we have uniform convergence to save the day. -/ -- First step: the partial sum of `p` converges to `f (x + y)`. have A : tendsto (λ n, ∑ a in finset.Ico 1 n, p a (λ b, y)) at_top (𝓝 (f (x + y) - f x)), { have L : ∀ᶠ n in at_top, ∑ a in finset.range n, p a (λ b, y) - f x = ∑ a in finset.Ico 1 n, p a (λ b, y), { rw eventually_at_top, refine ⟨1, λ n hn, _⟩, symmetry, rw [eq_sub_iff_add_eq', finset.range_eq_Ico, ← Hf.coeff_zero (λi, y), finset.sum_eq_sum_Ico_succ_bot hn] }, have : tendsto (λ n, ∑ a in finset.range n, p a (λ b, y) - f x) at_top (𝓝 (f (x + y) - f x)) := (Hf.has_sum y_mem).tendsto_sum_nat.sub tendsto_const_nhds, exact tendsto.congr' L this }, -- Second step: the composition of the partial sums of `q` and `p` converges to `g (f (x + y))`. have B : tendsto (λ n, q.partial_sum n (∑ a in finset.Ico 1 n, p a (λ b, y))) at_top (𝓝 (g (f (x + y)))), { -- we use the fact that the partial sums of `q` converge locally uniformly to `g`, and that -- composition passes to the limit under locally uniform convergence. have B₁ : continuous_at (λ (z : F), g (f x + z)) (f (x + y) - f x), { refine continuous_at.comp _ (continuous_const.add continuous_id).continuous_at, simp only [add_sub_cancel'_right, id.def], exact Hg.continuous_on.continuous_at (mem_nhds_sets (emetric.is_open_ball) fy_mem) }, have B₂ : f (x + y) - f x ∈ emetric.ball (0 : F) rg, by simpa [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] using fy_mem, rw [← nhds_within_eq_of_open B₂ emetric.is_open_ball] at A, convert Hg.tendsto_locally_uniformly_on.tendsto_comp B₁.continuous_within_at B₂ A, simp only [add_sub_cancel'_right] }, -- Third step: the sum over all compositions in `comp_partial_sum_target n` converges to -- `g (f (x + y))`. As this sum is exactly the composition of the partial sum, this is a direct -- consequence of the second step have C : tendsto (λ n, ∑ i in comp_partial_sum_target n, q.comp_along_composition_multilinear p i.2 (λ j, y)) at_top (𝓝 (g (f (x + y)))), by simpa [comp_partial_sum] using B, -- Fourth step: the sum over all compositions is `g (f (x + y))`. This follows from the -- convergence along a subsequence proved in the third step, and the fact that the sum is Cauchy -- thanks to the summability properties. have D : has_sum (λ i : (Σ n, composition n), q.comp_along_composition_multilinear p i.2 (λ j, y)) (g (f (x + y))), { have cau : cauchy_seq (λ (s : finset (Σ n, composition n)), ∑ i in s, q.comp_along_composition_multilinear p i.2 (λ j, y)), { apply cauchy_seq_finset_of_norm_bounded _ (nnreal.summable_coe.2 hr) _, simp only [coe_nnnorm, nnreal.coe_mul, nnreal.coe_pow], rintros ⟨n, c⟩, calc ∥(comp_along_composition q p c) (λ (j : fin n), y)∥ ≤ ∥comp_along_composition q p c∥ * ∏ j : fin n, ∥y∥ : by apply continuous_multilinear_map.le_op_norm ... ≤ ∥comp_along_composition q p c∥ * (r : ℝ) ^ n : begin apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), rw [finset.prod_const, finset.card_fin], apply pow_le_pow_of_le_left (norm_nonneg _), rw [emetric.mem_ball, edist_eq_coe_nnnorm] at hy, have := (le_trans (le_of_lt hy) (min_le_right _ _)), rwa [ennreal.coe_le_coe, ← nnreal.coe_le_coe, coe_nnnorm] at this end }, exact tendsto_nhds_of_cauchy_seq_of_subseq cau at_top_ne_bot comp_partial_sum_target_tendsto_at_top C }, -- Fifth step: the sum over `n` of `q.comp p n` can be expressed as a particular resummation of -- the sum over all compositions, by grouping together the compositions of the same -- integer `n`. The convergence of the whole sum therefore implies the converence of the sum -- of `q.comp p n` have E : has_sum (λ n, (q.comp p) n (λ j, y)) (g (f (x + y))), { apply D.sigma, assume n, dsimp [formal_multilinear_series.comp], convert has_sum_fintype _, simp only [continuous_multilinear_map.sum_apply], refl }, exact E end /-- If two functions `g` and `f` are analytic respectively at `f x` and `x`, then `g ∘ f` is analytic at `x`. -/ theorem analytic_at.comp {g : F → G} {f : E → F} {x : E} (hg : analytic_at 𝕜 g (f x)) (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (g ∘ f) x := let ⟨q, hq⟩ := hg, ⟨p, hp⟩ := hf in (hq.comp hp).analytic_at /-! ### Associativity of the composition of formal multilinear series In this paragraph, we us prove the associativity of the composition of formal power series. By definition, ``` (r.comp q).comp p n v = ∑_{i₁ + ... + iₖ = n} (r.comp q)ₖ (p_{i₁} (v₀, ..., v_{i₁ -1}), p_{i₂} (...), ..., p_{iₖ}(...)) = ∑_{a : composition n} (r.comp q) a.length (apply_composition p a v) ``` decomposing `r.comp q` in the same way, we get ``` (r.comp q).comp p n v = ∑_{a : composition n} ∑_{b : composition a.length} r b.length (apply_composition q b (apply_composition p a v)) ``` On the other hand, ``` r.comp (q.comp p) n v = ∑_{c : composition n} r c.length (apply_composition (q.comp p) c v) ``` Here, `apply_composition (q.comp p) c v` is a vector of length `c.length`, whose `i`-th term is given by `(q.comp p) (c.blocks_fun i) (v_l, v_{l+1}, ..., v_{m-1})` where `{l, ..., m-1}` is the `i`-th block in the composition `c`, of length `c.blocks_fun i` by definition. To compute this term, we expand it as `∑_{dᵢ : composition (c.blocks_fun i)} q dᵢ.length (apply_composition p dᵢ v')`, where `v' = (v_l, v_{l+1}, ..., v_{m-1})`. Therefore, we get ``` r.comp (q.comp p) n v = ∑_{c : composition n} ∑_{d₀ : composition (c.blocks_fun 0), ..., d_{c.length - 1} : composition (c.blocks_fun (c.length - 1))} r c.length (λ i, q dᵢ.length (apply_composition p dᵢ v'ᵢ)) ``` To show that these terms coincide, we need to explain how to reindex the sums to put them in bijection (and then the terms we are summing will correspond to each other). Suppose we have a composition `a` of `n`, and a composition `b` of `a.length`. Then `b` indicates how to group together some blocks of `a`, giving altogether `b.length` blocks of blocks. These blocks of blocks can be called `d₀, ..., d_{a.length - 1}`, and one obtains a composition `c` of `n` by saying that each `dᵢ` is one single block. Conversely, if one starts from `c` and the `dᵢ`s, one can concatenate the `dᵢ`s to obtain a composition `a` of `n`, and register the lengths of the `dᵢ`s in a composition `b` of `a.length`. An example might be enlightening. Suppose `a = [2, 2, 3, 4, 2]`. It is a composition of length 5 of 13. The content of the blocks may be represented as `0011222333344`. Now take `b = [2, 3]` as a composition of `a.length = 5`. It says that the first 2 blocks of `a` should be merged, and the last 3 blocks of `a` should be merged, giving a new composition of `13` made of two blocks of length `4` and `9`, i.e., `c = [4, 9]`. But one can also remember that the new first block was initially made of two blocks of size `2`, so `d₀ = [2, 2]`, and the new second block was initially made of three blocks of size `3`, `4` and `2`, so `d₁ = [3, 4, 2]`. This equivalence is called `composition.sigma_equiv_sigma_pi n` below. We start with preliminary results on compositions, of a very specialized nature, then define the equivalence `composition.sigma_equiv_sigma_pi n`, and we deduce finally the associativity of composition of formal multilinear series in `formal_multilinear_series.comp_assoc`. -/ namespace composition variable {n : ℕ} /-- Rewriting equality in the dependent type `Σ (a : composition n), composition a.length)` in non-dependent terms with lists, requiring that the blocks coincide. -/ lemma sigma_composition_eq_iff (i j : Σ (a : composition n), composition a.length) : i = j ↔ i.1.blocks = j.1.blocks ∧ i.2.blocks = j.2.blocks := begin refine ⟨by rintro rfl; exact ⟨rfl, rfl⟩, _⟩, rcases i with ⟨a, b⟩, rcases j with ⟨a', b'⟩, rintros ⟨h, h'⟩, have H : a = a', by { ext1, exact h }, induction H, congr, ext1, exact h' end /-- Rewriting equality in the dependent type `Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)` in non-dependent terms with lists, requiring that the lists of blocks coincide. -/ lemma sigma_pi_composition_eq_iff (u v : Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) : u = v ↔ of_fn (λ i, (u.2 i).blocks) = of_fn (λ i, (v.2 i).blocks) := begin refine ⟨λ H, by rw H, λ H, _⟩, rcases u with ⟨a, b⟩, rcases v with ⟨a', b'⟩, dsimp at H, have h : a = a', { ext1, have : map list.sum (of_fn (λ (i : fin (composition.length a)), (b i).blocks)) = map list.sum (of_fn (λ (i : fin (composition.length a')), (b' i).blocks)), by rw H, simp only [map_of_fn] at this, change of_fn (λ (i : fin (composition.length a)), (b i).blocks.sum) = of_fn (λ (i : fin (composition.length a')), (b' i).blocks.sum) at this, simpa [composition.blocks_sum, composition.of_fn_blocks_fun] using this }, induction h, simp only [true_and, eq_self_iff_true, heq_iff_eq], ext i : 2, have : nth_le (of_fn (λ (i : fin (composition.length a)), (b i).blocks)) i.1 (by simp [i.2]) = nth_le (of_fn (λ (i : fin (composition.length a)), (b' i).blocks)) i.1 (by simp [i.2]) := nth_le_of_eq H _, rwa [nth_le_of_fn, nth_le_of_fn] at this end /-- When `a` is a composition of `n` and `b` is a composition of `a.length`, `a.gather b` is the composition of `n` obtained by gathering all the blocks of `a` corresponding to a block of `b`. For instance, if `a = [6, 5, 3, 5, 2]` and `b = [2, 3]`, one should gather together the first two blocks of `a` and its last three blocks, giving `a.gather b = [11, 10]`. -/ def gather (a : composition n) (b : composition a.length) : composition n := { blocks := (a.blocks.split_wrt_composition b).map sum, blocks_pos := begin rw forall_mem_map_iff, intros j hj, suffices H : ∀ i ∈ j, 1 ≤ i, from calc 0 < j.length : length_pos_of_mem_split_wrt_composition hj ... ≤ j.sum : length_le_sum_of_one_le _ H, intros i hi, apply a.one_le_blocks, rw ← a.blocks.join_split_wrt_composition b, exact mem_join_of_mem hj hi, end, blocks_sum := by { rw [← sum_join, join_split_wrt_composition, a.blocks_sum] } } lemma length_gather (a : composition n) (b : composition a.length) : length (a.gather b) = b.length := show (map list.sum (a.blocks.split_wrt_composition b)).length = b.blocks.length, by rw [length_map, length_split_wrt_composition] /-- An auxiliary function used in the definition of `sigma_equiv_sigma_pi` below, associating to two compositions `a` of `n` and `b` of `a.length`, and an index `i` bounded by the length of `a.gather b`, the subcomposition of `a` made of those blocks belonging to the `i`-th block of `a.gather b`. -/ def sigma_composition_aux (a : composition n) (b : composition a.length) (i : fin (a.gather b).length) : composition ((a.gather b).blocks_fun i) := { blocks := nth_le (a.blocks.split_wrt_composition b) i.val (by { rw [length_split_wrt_composition, ← length_gather], exact i.2 }), blocks_pos := assume i hi, a.blocks_pos (by { rw ← a.blocks.join_split_wrt_composition b, exact mem_join_of_mem (nth_le_mem _ _ _) hi }), blocks_sum := by simp only [composition.blocks_fun, nth_le_map', composition.gather] } lemma length_sigma_composition_aux (a : composition n) (b : composition a.length) (i : fin b.length) : composition.length (composition.sigma_composition_aux a b ⟨i.val, (length_gather a b).symm ▸ i.2⟩) = composition.blocks_fun b i := show list.length (nth_le (split_wrt_composition a.blocks b) i.val _) = blocks_fun b i, by { rw [nth_le_map_rev list.length, nth_le_of_eq (map_length_split_wrt_composition _ _)], refl } lemma blocks_fun_sigma_composition_aux (a : composition n) (b : composition a.length) (i : fin b.length) (j : fin (blocks_fun b i)) : blocks_fun (sigma_composition_aux a b ⟨i.val, (length_gather a b).symm ▸ i.2⟩) ⟨j.val, (length_sigma_composition_aux a b i).symm ▸ j.2⟩ = blocks_fun a (embedding b i j) := show nth_le (nth_le _ _ _) _ _ = nth_le a.blocks _ _, by { rw [nth_le_of_eq (nth_le_split_wrt_composition _ _ _), nth_le_drop', nth_le_take'], refl } /-- Auxiliary lemma to prove that the composition of formal multilinear series is associative. Consider a composition `a` of `n` and a composition `b` of `a.length`. Grouping together some blocks of `a` according to `b` as in `a.gather b`, one can compute the total size of the blocks of `a` up to an index `size_up_to b i + j` (where the `j` corresponds to a set of blocks of `a` that do not fill a whole block of `a.gather b`). The first part corresponds to a sum of blocks in `a.gather b`, and the second one to a sum of blocks in the next block of `sigma_composition_aux a b`. This is the content of this lemma. -/ lemma size_up_to_size_up_to_add (a : composition n) (b : composition a.length) {i j : ℕ} (hi : i < b.length) (hj : j < blocks_fun b ⟨i, hi⟩) : size_up_to a (size_up_to b i + j) = size_up_to (a.gather b) i + (size_up_to (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ hi⟩) j) := begin induction j with j IHj, { show sum (take ((b.blocks.take i).sum) a.blocks) = sum (take i (map sum (split_wrt_composition a.blocks b))), induction i with i IH, { refl }, { have A : i < b.length := nat.lt_of_succ_lt hi, have B : i < list.length (map list.sum (split_wrt_composition a.blocks b)), by simp [A], have C : 0 < blocks_fun b ⟨i, A⟩ := composition.blocks_pos' _ _ _, rw [sum_take_succ _ _ B, ← IH A C], have : take (sum (take i b.blocks)) a.blocks = take (sum (take i b.blocks)) (take (sum (take (i+1) b.blocks)) a.blocks), { rw [take_take, min_eq_left], apply monotone_sum_take _ (nat.le_succ _) }, rw [this, nth_le_map', nth_le_split_wrt_composition, ← take_append_drop (sum (take i b.blocks)) ((take (sum (take (nat.succ i) b.blocks)) a.blocks)), sum_append], congr, rw [take_append_drop] } }, { have A : j < blocks_fun b ⟨i, hi⟩ := lt_trans (lt_add_one j) hj, have B : j < length (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ hi⟩), by { convert A, rw ← length_sigma_composition_aux }, have C : size_up_to b i + j < size_up_to b (i + 1), { simp only [size_up_to_succ b hi, add_lt_add_iff_left], exact A }, have D : size_up_to b i + j < length a := lt_of_lt_of_le C (b.size_up_to_le _), have : size_up_to b i + nat.succ j = (size_up_to b i + j).succ := rfl, rw [this, size_up_to_succ _ D, IHj A, size_up_to_succ _ B], simp only [sigma_composition_aux, add_assoc, add_left_inj], rw [nth_le_of_eq (nth_le_split_wrt_composition _ _ _), nth_le_drop', nth_le_take _ _ C] } end /-- Natural equivalence between `(Σ (a : composition n), composition a.length)` and `(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i))`, that shows up as a change of variables in the proof that composition of formal multilinear series is associative. Consider a composition `a` of `n` and a composition `b` of `a.length`. Then `b` indicates how to group together some blocks of `a`, giving altogether `b.length` blocks of blocks. These blocks of blocks can be called `d₀, ..., d_{a.length - 1}`, and one obtains a composition `c` of `n` by saying that each `dᵢ` is one single block. The map `⟨a, b⟩ → ⟨c, (d₀, ..., d_{a.length - 1})⟩` is the direct map in the equiv. Conversely, if one starts from `c` and the `dᵢ`s, one can join the `dᵢ`s to obtain a composition `a` of `n`, and register the lengths of the `dᵢ`s in a composition `b` of `a.length`. This is the inverse map of the equiv. -/ def sigma_equiv_sigma_pi (n : ℕ) : (Σ (a : composition n), composition a.length) ≃ (Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) := { to_fun := λ i, ⟨i.1.gather i.2, i.1.sigma_composition_aux i.2⟩, inv_fun := λ i, ⟨ { blocks := (of_fn (λ j, (i.2 j).blocks)).join, blocks_pos := begin simp only [and_imp, mem_join, exists_imp_distrib, forall_mem_of_fn_iff], exact λ i j hj, composition.blocks_pos _ hj end, blocks_sum := by simp [sum_of_fn, composition.blocks_sum, composition.sum_blocks_fun] }, { blocks := of_fn (λ j, (i.2 j).length), blocks_pos := forall_mem_of_fn_iff.2 (λ j, composition.length_pos_of_pos _ (composition.blocks_pos' _ _ _)), blocks_sum := by { dsimp only [composition.length], simp [sum_of_fn] } }⟩, left_inv := begin -- the fact that we have a left inverse is essentially `join_split_wrt_composition`, -- but we need to massage it to take care of the dependent setting. rintros ⟨a, b⟩, rw sigma_composition_eq_iff, dsimp, split, { have A := length_map list.sum (split_wrt_composition a.blocks b), conv_rhs { rw [← join_split_wrt_composition a.blocks b, ← of_fn_nth_le (split_wrt_composition a.blocks b)] }, congr, { exact A }, { exact (fin.heq_fun_iff A).2 (λ i, rfl) } }, { have B : composition.length (composition.gather a b) = list.length b.blocks := composition.length_gather _ _, conv_rhs { rw [← of_fn_nth_le b.blocks] }, congr' 1, { exact B }, { apply (fin.heq_fun_iff B).2 (λ i, _), rw [sigma_composition_aux, composition.length, nth_le_map_rev list.length, nth_le_of_eq (map_length_split_wrt_composition _ _)] } } end, right_inv := begin -- the fact that we have a right inverse is essentially `split_wrt_composition_join`, -- but we need to massage it to take care of the dependent setting. rintros ⟨c, d⟩, have : map list.sum (of_fn (λ (i : fin (composition.length c)), (d i).blocks)) = c.blocks, by simp [map_of_fn, (∘), composition.blocks_sum, composition.of_fn_blocks_fun], rw sigma_pi_composition_eq_iff, dsimp, congr, { ext1, dsimp [composition.gather], rwa split_wrt_composition_join, simp only [map_of_fn] }, { rw fin.heq_fun_iff, { assume i, dsimp [composition.sigma_composition_aux], rw [nth_le_of_eq (split_wrt_composition_join _ _ _)], { simp only [nth_le_of_fn'] }, { simp only [map_of_fn] } }, { congr, ext1, dsimp [composition.gather], rwa split_wrt_composition_join, simp only [map_of_fn] } } end } end composition namespace formal_multilinear_series open composition theorem comp_assoc (r : formal_multilinear_series 𝕜 G H) (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) : (r.comp q).comp p = r.comp (q.comp p) := begin ext n v, /- First, rewrite the two compositions appearing in the theorem as two sums over complicated sigma types, as in the description of the proof above. -/ let f : (Σ (a : composition n), composition a.length) → H := λ ⟨a, b⟩, r b.length (apply_composition q b (apply_composition p a v)), let g : (Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) → H := λ ⟨c, d⟩, r c.length (λ (i : fin c.length), q (d i).length (apply_composition p (d i) (v ∘ c.embedding i))), suffices A : ∑ c, f c = ∑ c, g c, { dsimp [formal_multilinear_series.comp], simp only [continuous_multilinear_map.sum_apply, comp_along_composition_apply], rw ← @finset.sum_sigma _ _ _ _ (finset.univ : finset (composition n)) _ f, dsimp [apply_composition], simp only [continuous_multilinear_map.sum_apply, comp_along_composition_apply, continuous_multilinear_map.map_sum], rw ← @finset.sum_sigma _ _ _ _ (finset.univ : finset (composition n)) _ g, exact A }, /- Now, we use `composition.sigma_equiv_sigma_pi n` to change variables in the second sum, and check that we get exactly the same sums. -/ rw ← finset.sum_equiv (sigma_equiv_sigma_pi n), /- To check that we have the same terms, we should check that we apply the same component of `r`, and the same component of `q`, and the same component of `p`, to the same coordinate of `v`. This is true by definition, but at each step one needs to convince Lean that the types one considers are the same, using a suitable congruence lemma to avoid dependent type issues. This dance has to be done three times, one for `r`, one for `q` and one for `p`.-/ apply finset.sum_congr rfl, rintros ⟨a, b⟩ _, dsimp [f, g, sigma_equiv_sigma_pi], -- check that the `r` components are the same. Based on `composition.length_gather` apply r.congr (composition.length_gather a b).symm, intros i hi1 hi2, -- check that the `q` components are the same. Based on `length_sigma_composition_aux` apply q.congr (length_sigma_composition_aux a b _).symm, intros j hj1 hj2, -- check that the `p` components are the same. Based on `blocks_fun_sigma_composition_aux` apply p.congr (blocks_fun_sigma_composition_aux a b _ _).symm, intros k hk1 hk2, -- finally, check that the coordinates of `v` one is using are the same. Based on -- `size_up_to_size_up_to_add`. refine congr_arg v (fin.eq_of_veq _), dsimp [composition.embedding], rw [size_up_to_size_up_to_add _ _ hi1 hj1, add_assoc], end end formal_multilinear_series
617b9461e131467f138a887430052fc4823aceac
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/limits/shapes/binary_products.lean
3a6301e637bd0753bbc6b8a03388aa2be4a06ef4
[ "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
48,266
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.limits.shapes.terminal import category_theory.discrete_category import category_theory.epi_mono import category_theory.over /-! # Binary (co)products > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define a category `walking_pair`, which is the index category for a binary (co)product diagram. A convenience method `pair X Y` constructs the functor from the walking pair, hitting the given objects. We define `prod X Y` and `coprod X Y` as limits and colimits of such functors. Typeclasses `has_binary_products` and `has_binary_coproducts` assert the existence of (co)limits shaped as walking pairs. We include lemmas for simplifying equations involving projections and coprojections, and define braiding and associating isomorphisms, and the product comparison morphism. ## References * [Stacks: Products of pairs](https://stacks.math.columbia.edu/tag/001R) * [Stacks: coproducts of pairs](https://stacks.math.columbia.edu/tag/04AN) -/ noncomputable theory universes v u u₂ open category_theory namespace category_theory.limits /-- The type of objects for the diagram indexing a binary (co)product. -/ @[derive decidable_eq, derive inhabited] inductive walking_pair : Type | left | right open walking_pair /-- The equivalence swapping left and right. -/ def walking_pair.swap : walking_pair ≃ walking_pair := { to_fun := λ j, walking_pair.rec_on j right left, inv_fun := λ j, walking_pair.rec_on j right left, left_inv := λ j, by { cases j; refl, }, right_inv := λ j, by { cases j; refl, }, } @[simp] lemma walking_pair.swap_apply_left : walking_pair.swap left = right := rfl @[simp] lemma walking_pair.swap_apply_right : walking_pair.swap right = left := rfl @[simp] lemma walking_pair.swap_symm_apply_tt : walking_pair.swap.symm left = right := rfl @[simp] lemma walking_pair.swap_symm_apply_ff : walking_pair.swap.symm right = left := rfl /-- An equivalence from `walking_pair` to `bool`, sometimes useful when reindexing limits. -/ def walking_pair.equiv_bool : walking_pair ≃ bool := { to_fun := λ j, walking_pair.rec_on j tt ff, -- to match equiv.sum_equiv_sigma_bool inv_fun := λ b, bool.rec_on b right left, left_inv := λ j, by { cases j; refl, }, right_inv := λ b, by { cases b; refl, }, } @[simp] lemma walking_pair.equiv_bool_apply_left : walking_pair.equiv_bool left = tt := rfl @[simp] lemma walking_pair.equiv_bool_apply_right : walking_pair.equiv_bool right = ff := rfl @[simp] lemma walking_pair.equiv_bool_symm_apply_tt : walking_pair.equiv_bool.symm tt = left := rfl @[simp] lemma walking_pair.equiv_bool_symm_apply_ff : walking_pair.equiv_bool.symm ff = right := rfl variables {C : Type u} /-- The function on the walking pair, sending the two points to `X` and `Y`. -/ def pair_function (X Y : C) : walking_pair → C := λ j, walking_pair.cases_on j X Y @[simp] lemma pair_function_left (X Y : C) : pair_function X Y left = X := rfl @[simp] lemma pair_function_right (X Y : C) : pair_function X Y right = Y := rfl variables [category.{v} C] /-- The diagram on the walking pair, sending the two points to `X` and `Y`. -/ def pair (X Y : C) : discrete walking_pair ⥤ C := discrete.functor (λ j, walking_pair.cases_on j X Y) @[simp] lemma pair_obj_left (X Y : C) : (pair X Y).obj ⟨left⟩ = X := rfl @[simp] lemma pair_obj_right (X Y : C) : (pair X Y).obj ⟨right⟩ = Y := rfl section variables {F G : discrete walking_pair ⥤ C} (f : F.obj ⟨left⟩ ⟶ G.obj ⟨left⟩) (g : F.obj ⟨right⟩ ⟶ G.obj ⟨right⟩) local attribute [tidy] tactic.discrete_cases /-- The natural transformation between two functors out of the walking pair, specified by its components. -/ def map_pair : F ⟶ G := { app := λ j, discrete.rec_on j (λ j, walking_pair.cases_on j f g) } @[simp] lemma map_pair_left : (map_pair f g).app ⟨left⟩ = f := rfl @[simp] lemma map_pair_right : (map_pair f g).app ⟨right⟩ = g := rfl /-- The natural isomorphism between two functors out of the walking pair, specified by its components. -/ @[simps] def map_pair_iso (f : F.obj ⟨left⟩ ≅ G.obj ⟨left⟩) (g : F.obj ⟨right⟩ ≅ G.obj ⟨right⟩) : F ≅ G := nat_iso.of_components (λ j, discrete.rec_on j (λ j, walking_pair.cases_on j f g)) (by tidy) end /-- Every functor out of the walking pair is naturally isomorphic (actually, equal) to a `pair` -/ @[simps] def diagram_iso_pair (F : discrete walking_pair ⥤ C) : F ≅ pair (F.obj ⟨walking_pair.left⟩) (F.obj ⟨walking_pair.right⟩) := map_pair_iso (iso.refl _) (iso.refl _) section variables {D : Type u} [category.{v} D] /-- The natural isomorphism between `pair X Y ⋙ F` and `pair (F.obj X) (F.obj Y)`. -/ def pair_comp (X Y : C) (F : C ⥤ D) : pair X Y ⋙ F ≅ pair (F.obj X) (F.obj Y) := diagram_iso_pair _ end /-- A binary fan is just a cone on a diagram indexing a product. -/ abbreviation binary_fan (X Y : C) := cone (pair X Y) /-- The first projection of a binary fan. -/ abbreviation binary_fan.fst {X Y : C} (s : binary_fan X Y) := s.π.app ⟨walking_pair.left⟩ /-- The second projection of a binary fan. -/ abbreviation binary_fan.snd {X Y : C} (s : binary_fan X Y) := s.π.app ⟨walking_pair.right⟩ @[simp] lemma binary_fan.π_app_left {X Y : C} (s : binary_fan X Y) : s.π.app ⟨walking_pair.left⟩ = s.fst := rfl @[simp] lemma binary_fan.π_app_right {X Y : C} (s : binary_fan X Y) : s.π.app ⟨walking_pair.right⟩ = s.snd := rfl /-- A convenient way to show that a binary fan is a limit. -/ def binary_fan.is_limit.mk {X Y : C} (s : binary_fan X Y) (lift : Π {T : C} (f : T ⟶ X) (g : T ⟶ Y), T ⟶ s.X) (hl₁ : ∀ {T : C} (f : T ⟶ X) (g : T ⟶ Y), lift f g ≫ s.fst = f) (hl₂ : ∀ {T : C} (f : T ⟶ X) (g : T ⟶ Y), lift f g ≫ s.snd = g) (uniq : ∀ {T : C} (f : T ⟶ X) (g : T ⟶ Y) (m : T ⟶ s.X) (h₁ : m ≫ s.fst = f) (h₂ : m ≫ s.snd = g), m = lift f g) : is_limit s := is_limit.mk (λ t, lift (binary_fan.fst t) (binary_fan.snd t)) (by { rintros t (rfl|rfl), { exact hl₁ _ _ }, { exact hl₂ _ _ } }) (λ t m h, uniq _ _ _ (h ⟨walking_pair.left⟩) (h ⟨walking_pair.right⟩)) lemma binary_fan.is_limit.hom_ext {W X Y : C} {s : binary_fan X Y} (h : is_limit s) {f g : W ⟶ s.X} (h₁ : f ≫ s.fst = g ≫ s.fst) (h₂ : f ≫ s.snd = g ≫ s.snd) : f = g := h.hom_ext $ λ j, discrete.rec_on j (λ j, walking_pair.cases_on j h₁ h₂) /-- A binary cofan is just a cocone on a diagram indexing a coproduct. -/ abbreviation binary_cofan (X Y : C) := cocone (pair X Y) /-- The first inclusion of a binary cofan. -/ abbreviation binary_cofan.inl {X Y : C} (s : binary_cofan X Y) := s.ι.app ⟨walking_pair.left⟩ /-- The second inclusion of a binary cofan. -/ abbreviation binary_cofan.inr {X Y : C} (s : binary_cofan X Y) := s.ι.app ⟨walking_pair.right⟩ @[simp] lemma binary_cofan.ι_app_left {X Y : C} (s : binary_cofan X Y) : s.ι.app ⟨walking_pair.left⟩ = s.inl := rfl @[simp] lemma binary_cofan.ι_app_right {X Y : C} (s : binary_cofan X Y) : s.ι.app ⟨walking_pair.right⟩ = s.inr := rfl /-- A convenient way to show that a binary cofan is a colimit. -/ def binary_cofan.is_colimit.mk {X Y : C} (s : binary_cofan X Y) (desc : Π {T : C} (f : X ⟶ T) (g : Y ⟶ T), s.X ⟶ T) (hd₁ : ∀ {T : C} (f : X ⟶ T) (g : Y ⟶ T), s.inl ≫ desc f g = f) (hd₂ : ∀ {T : C} (f : X ⟶ T) (g : Y ⟶ T), s.inr ≫ desc f g = g) (uniq : ∀ {T : C} (f : X ⟶ T) (g : Y ⟶ T) (m : s.X ⟶ T) (h₁ : s.inl ≫ m = f) (h₂ : s.inr ≫ m = g), m = desc f g) : is_colimit s := is_colimit.mk (λ t, desc (binary_cofan.inl t) (binary_cofan.inr t)) (by { rintros t (rfl|rfl), { exact hd₁ _ _ }, { exact hd₂ _ _ }}) (λ t m h, uniq _ _ _ (h ⟨walking_pair.left⟩) (h ⟨walking_pair.right⟩)) lemma binary_cofan.is_colimit.hom_ext {W X Y : C} {s : binary_cofan X Y} (h : is_colimit s) {f g : s.X ⟶ W} (h₁ : s.inl ≫ f = s.inl ≫ g) (h₂ : s.inr ≫ f = s.inr ≫ g) : f = g := h.hom_ext $ λ j, discrete.rec_on j (λ j, walking_pair.cases_on j h₁ h₂) variables {X Y : C} section local attribute [tidy] tactic.discrete_cases /-- A binary fan with vertex `P` consists of the two projections `π₁ : P ⟶ X` and `π₂ : P ⟶ Y`. -/ @[simps X] def binary_fan.mk {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : binary_fan X Y := { X := P, π := { app := λ j, discrete.rec_on j (λ j, walking_pair.cases_on j π₁ π₂) }} /-- A binary cofan with vertex `P` consists of the two inclusions `ι₁ : X ⟶ P` and `ι₂ : Y ⟶ P`. -/ @[simps X] def binary_cofan.mk {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : binary_cofan X Y := { X := P, ι := { app := λ j, discrete.rec_on j (λ j, walking_pair.cases_on j ι₁ ι₂) }} end @[simp] lemma binary_fan.mk_fst {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).fst = π₁ := rfl @[simp] lemma binary_fan.mk_snd {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).snd = π₂ := rfl @[simp] lemma binary_cofan.mk_inl {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).inl = ι₁ := rfl @[simp] lemma binary_cofan.mk_inr {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).inr = ι₂ := rfl /-- Every `binary_fan` is isomorphic to an application of `binary_fan.mk`. -/ def iso_binary_fan_mk {X Y : C} (c : binary_fan X Y) : c ≅ binary_fan.mk c.fst c.snd := cones.ext (iso.refl _) (λ j, by discrete_cases; cases j; tidy) /-- Every `binary_fan` is isomorphic to an application of `binary_fan.mk`. -/ def iso_binary_cofan_mk {X Y : C} (c : binary_cofan X Y) : c ≅ binary_cofan.mk c.inl c.inr := cocones.ext (iso.refl _) (λ j, by discrete_cases; cases j; tidy) /-- This is a more convenient formulation to show that a `binary_fan` constructed using `binary_fan.mk` is a limit cone. -/ def binary_fan.is_limit_mk {W : C} {fst : W ⟶ X} {snd : W ⟶ Y} (lift : Π (s : binary_fan X Y), s.X ⟶ W) (fac_left : ∀ (s : binary_fan X Y), lift s ≫ fst = s.fst) (fac_right : ∀ (s : binary_fan X Y), lift s ≫ snd = s.snd) (uniq : ∀ (s : binary_fan X Y) (m : s.X ⟶ W) (w_fst : m ≫ fst = s.fst) (w_snd : m ≫ snd = s.snd), m = lift s) : is_limit (binary_fan.mk fst snd) := { lift := lift, fac' := λ s j, by { rcases j with ⟨⟨⟩⟩, exacts [fac_left s, fac_right s], }, uniq' := λ s m w, uniq s m (w ⟨walking_pair.left⟩) (w ⟨walking_pair.right⟩) } /-- This is a more convenient formulation to show that a `binary_cofan` constructed using `binary_cofan.mk` is a colimit cocone. -/ def binary_cofan.is_colimit_mk {W : C} {inl : X ⟶ W} {inr : Y ⟶ W} (desc : Π (s : binary_cofan X Y), W ⟶ s.X) (fac_left : ∀ (s : binary_cofan X Y), inl ≫ desc s = s.inl) (fac_right : ∀ (s : binary_cofan X Y), inr ≫ desc s = s.inr) (uniq : ∀ (s : binary_cofan X Y) (m : W ⟶ s.X) (w_inl : inl ≫ m = s.inl) (w_inr : inr ≫ m = s.inr), m = desc s) : is_colimit (binary_cofan.mk inl inr) := { desc := desc, fac' := λ s j, by { rcases j with ⟨⟨⟩⟩, exacts [fac_left s, fac_right s], }, uniq' := λ s m w, uniq s m (w ⟨walking_pair.left⟩) (w ⟨walking_pair.right⟩) } /-- If `s` is a limit binary fan over `X` and `Y`, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `l : W ⟶ s.X` satisfying `l ≫ s.fst = f` and `l ≫ s.snd = g`. -/ @[simps] def binary_fan.is_limit.lift' {W X Y : C} {s : binary_fan X Y} (h : is_limit s) (f : W ⟶ X) (g : W ⟶ Y) : {l : W ⟶ s.X // l ≫ s.fst = f ∧ l ≫ s.snd = g} := ⟨h.lift $ binary_fan.mk f g, h.fac _ _, h.fac _ _⟩ /-- If `s` is a colimit binary cofan over `X` and `Y`,, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `l : s.X ⟶ W` satisfying `s.inl ≫ l = f` and `s.inr ≫ l = g`. -/ @[simps] def binary_cofan.is_colimit.desc' {W X Y : C} {s : binary_cofan X Y} (h : is_colimit s) (f : X ⟶ W) (g : Y ⟶ W) : {l : s.X ⟶ W // s.inl ≫ l = f ∧ s.inr ≫ l = g} := ⟨h.desc $ binary_cofan.mk f g, h.fac _ _, h.fac _ _⟩ /-- Binary products are symmetric. -/ def binary_fan.is_limit_flip {X Y : C} {c : binary_fan X Y} (hc : is_limit c) : is_limit (binary_fan.mk c.snd c.fst) := binary_fan.is_limit_mk (λ s, hc.lift (binary_fan.mk s.snd s.fst)) (λ s, hc.fac _ _) (λ s, hc.fac _ _) (λ s m e₁ e₂, binary_fan.is_limit.hom_ext hc (e₂.trans (hc.fac (binary_fan.mk s.snd s.fst) ⟨walking_pair.left⟩).symm) (e₁.trans (hc.fac (binary_fan.mk s.snd s.fst) ⟨walking_pair.right⟩).symm)) lemma binary_fan.is_limit_iff_is_iso_fst {X Y : C} (h : is_terminal Y) (c : binary_fan X Y) : nonempty (is_limit c) ↔ is_iso c.fst := begin split, { rintro ⟨H⟩, obtain ⟨l, hl, -⟩ := binary_fan.is_limit.lift' H (𝟙 X) (h.from X), exact ⟨⟨l, binary_fan.is_limit.hom_ext H (by simpa [hl, -category.comp_id] using category.comp_id _) (h.hom_ext _ _), hl⟩⟩ }, { introI, exact ⟨binary_fan.is_limit.mk _ (λ _ f _, f ≫ inv c.fst) (λ _ _ _, by simp) (λ _ _ _, h.hom_ext _ _) (λ _ _ _ _ e _, by simp [← e])⟩ } end lemma binary_fan.is_limit_iff_is_iso_snd {X Y : C} (h : is_terminal X) (c : binary_fan X Y) : nonempty (is_limit c) ↔ is_iso c.snd := begin refine iff.trans _ (binary_fan.is_limit_iff_is_iso_fst h (binary_fan.mk c.snd c.fst)), exact ⟨λ h, ⟨binary_fan.is_limit_flip h.some⟩, λ h, ⟨(binary_fan.is_limit_flip h.some).of_iso_limit (iso_binary_fan_mk c).symm⟩⟩, end /-- If `X' ≅ X`, then `X × Y` also is the product of `X'` and `Y`. -/ noncomputable def binary_fan.is_limit_comp_left_iso {X Y X' : C} (c : binary_fan X Y) (f : X ⟶ X') [is_iso f] (h : is_limit c) : is_limit (binary_fan.mk (c.fst ≫ f) c.snd) := begin fapply binary_fan.is_limit_mk, { exact λ s, h.lift (binary_fan.mk (s.fst ≫ inv f) s.snd) }, { intro s, simp }, { intro s, simp }, { intros s m e₁ e₂, apply binary_fan.is_limit.hom_ext h; simpa } end /-- If `Y' ≅ Y`, then `X x Y` also is the product of `X` and `Y'`. -/ noncomputable def binary_fan.is_limit_comp_right_iso {X Y Y' : C} (c : binary_fan X Y) (f : Y ⟶ Y') [is_iso f] (h : is_limit c) : is_limit (binary_fan.mk c.fst (c.snd ≫ f)) := binary_fan.is_limit_flip $ binary_fan.is_limit_comp_left_iso _ f (binary_fan.is_limit_flip h) /-- Binary coproducts are symmetric. -/ def binary_cofan.is_colimit_flip {X Y : C} {c : binary_cofan X Y} (hc : is_colimit c) : is_colimit (binary_cofan.mk c.inr c.inl) := binary_cofan.is_colimit_mk (λ s, hc.desc (binary_cofan.mk s.inr s.inl)) (λ s, hc.fac _ _) (λ s, hc.fac _ _) (λ s m e₁ e₂, binary_cofan.is_colimit.hom_ext hc (e₂.trans (hc.fac (binary_cofan.mk s.inr s.inl) ⟨walking_pair.left⟩).symm) (e₁.trans (hc.fac (binary_cofan.mk s.inr s.inl) ⟨walking_pair.right⟩).symm)) lemma binary_cofan.is_colimit_iff_is_iso_inl {X Y : C} (h : is_initial Y) (c : binary_cofan X Y) : nonempty (is_colimit c) ↔ is_iso c.inl := begin split, { rintro ⟨H⟩, obtain ⟨l, hl, -⟩ := binary_cofan.is_colimit.desc' H (𝟙 X) (h.to X), exact ⟨⟨l, hl, binary_cofan.is_colimit.hom_ext H (by simp [reassoc_of hl]) (h.hom_ext _ _)⟩⟩ }, { introI, exact ⟨binary_cofan.is_colimit.mk _ (λ _ f _, inv c.inl ≫ f) (λ _ _ _, is_iso.hom_inv_id_assoc _ _) (λ _ _ _, h.hom_ext _ _) (λ _ _ _ _ e _, (is_iso.eq_inv_comp _).mpr e)⟩ } end lemma binary_cofan.is_colimit_iff_is_iso_inr {X Y : C} (h : is_initial X) (c : binary_cofan X Y) : nonempty (is_colimit c) ↔ is_iso c.inr := begin refine iff.trans _ (binary_cofan.is_colimit_iff_is_iso_inl h (binary_cofan.mk c.inr c.inl)), exact ⟨λ h, ⟨binary_cofan.is_colimit_flip h.some⟩, λ h, ⟨(binary_cofan.is_colimit_flip h.some).of_iso_colimit (iso_binary_cofan_mk c).symm⟩⟩, end /-- If `X' ≅ X`, then `X ⨿ Y` also is the coproduct of `X'` and `Y`. -/ noncomputable def binary_cofan.is_colimit_comp_left_iso {X Y X' : C} (c : binary_cofan X Y) (f : X' ⟶ X) [is_iso f] (h : is_colimit c) : is_colimit (binary_cofan.mk (f ≫ c.inl) c.inr) := begin fapply binary_cofan.is_colimit_mk, { exact λ s, h.desc (binary_cofan.mk (inv f ≫ s.inl) s.inr) }, { intro s, simp }, { intro s, simp }, { intros s m e₁ e₂, apply binary_cofan.is_colimit.hom_ext h, { rw ← cancel_epi f, simpa using e₁ }, { simpa } } end /-- If `Y' ≅ Y`, then `X ⨿ Y` also is the coproduct of `X` and `Y'`. -/ noncomputable def binary_cofan.is_colimit_comp_right_iso {X Y Y' : C} (c : binary_cofan X Y) (f : Y' ⟶ Y) [is_iso f] (h : is_colimit c) : is_colimit (binary_cofan.mk c.inl (f ≫ c.inr)) := binary_cofan.is_colimit_flip $ binary_cofan.is_colimit_comp_left_iso _ f (binary_cofan.is_colimit_flip h) /-- An abbreviation for `has_limit (pair X Y)`. -/ abbreviation has_binary_product (X Y : C) := has_limit (pair X Y) /-- An abbreviation for `has_colimit (pair X Y)`. -/ abbreviation has_binary_coproduct (X Y : C) := has_colimit (pair X Y) /-- If we have a product of `X` and `Y`, we can access it using `prod X Y` or `X ⨯ Y`. -/ abbreviation prod (X Y : C) [has_binary_product X Y] := limit (pair X Y) /-- If we have a coproduct of `X` and `Y`, we can access it using `coprod X Y ` or `X ⨿ Y`. -/ abbreviation coprod (X Y : C) [has_binary_coproduct X Y] := colimit (pair X Y) notation X ` ⨯ `:20 Y:20 := prod X Y notation X ` ⨿ `:20 Y:20 := coprod X Y /-- The projection map to the first component of the product. -/ abbreviation prod.fst {X Y : C} [has_binary_product X Y] : X ⨯ Y ⟶ X := limit.π (pair X Y) ⟨walking_pair.left⟩ /-- The projecton map to the second component of the product. -/ abbreviation prod.snd {X Y : C} [has_binary_product X Y] : X ⨯ Y ⟶ Y := limit.π (pair X Y) ⟨walking_pair.right⟩ /-- The inclusion map from the first component of the coproduct. -/ abbreviation coprod.inl {X Y : C} [has_binary_coproduct X Y] : X ⟶ X ⨿ Y := colimit.ι (pair X Y) ⟨walking_pair.left⟩ /-- The inclusion map from the second component of the coproduct. -/ abbreviation coprod.inr {X Y : C} [has_binary_coproduct X Y] : Y ⟶ X ⨿ Y := colimit.ι (pair X Y) ⟨walking_pair.right⟩ /-- The binary fan constructed from the projection maps is a limit. -/ def prod_is_prod (X Y : C) [has_binary_product X Y] : is_limit (binary_fan.mk (prod.fst : X ⨯ Y ⟶ X) prod.snd) := (limit.is_limit _).of_iso_limit (cones.ext (iso.refl _) (by { rintro (_ | _), tidy })) /-- The binary cofan constructed from the coprojection maps is a colimit. -/ def coprod_is_coprod (X Y : C) [has_binary_coproduct X Y] : is_colimit (binary_cofan.mk (coprod.inl : X ⟶ X ⨿ Y) coprod.inr) := (colimit.is_colimit _).of_iso_colimit (cocones.ext (iso.refl _) (by { rintro (_ | _), tidy })) @[ext] lemma prod.hom_ext {W X Y : C} [has_binary_product X Y] {f g : W ⟶ X ⨯ Y} (h₁ : f ≫ prod.fst = g ≫ prod.fst) (h₂ : f ≫ prod.snd = g ≫ prod.snd) : f = g := binary_fan.is_limit.hom_ext (limit.is_limit _) h₁ h₂ @[ext] lemma coprod.hom_ext {W X Y : C} [has_binary_coproduct X Y] {f g : X ⨿ Y ⟶ W} (h₁ : coprod.inl ≫ f = coprod.inl ≫ g) (h₂ : coprod.inr ≫ f = coprod.inr ≫ g) : f = g := binary_cofan.is_colimit.hom_ext (colimit.is_colimit _) h₁ h₂ /-- If the product of `X` and `Y` exists, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `prod.lift f g : W ⟶ X ⨯ Y`. -/ abbreviation prod.lift {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) : W ⟶ X ⨯ Y := limit.lift _ (binary_fan.mk f g) /-- diagonal arrow of the binary product in the category `fam I` -/ abbreviation diag (X : C) [has_binary_product X X] : X ⟶ X ⨯ X := prod.lift (𝟙 _) (𝟙 _) /-- If the coproduct of `X` and `Y` exists, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `coprod.desc f g : X ⨿ Y ⟶ W`. -/ abbreviation coprod.desc {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : X ⨿ Y ⟶ W := colimit.desc _ (binary_cofan.mk f g) /-- codiagonal arrow of the binary coproduct -/ abbreviation codiag (X : C) [has_binary_coproduct X X] : X ⨿ X ⟶ X := coprod.desc (𝟙 _) (𝟙 _) @[simp, reassoc] lemma prod.lift_fst {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) : prod.lift f g ≫ prod.fst = f := limit.lift_π _ _ @[simp, reassoc] lemma prod.lift_snd {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) : prod.lift f g ≫ prod.snd = g := limit.lift_π _ _ -- The simp linter says simp can prove the reassoc version of this lemma. @[reassoc, simp] lemma coprod.inl_desc {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : coprod.inl ≫ coprod.desc f g = f := colimit.ι_desc _ _ -- The simp linter says simp can prove the reassoc version of this lemma. @[reassoc, simp] lemma coprod.inr_desc {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : coprod.inr ≫ coprod.desc f g = g := colimit.ι_desc _ _ instance prod.mono_lift_of_mono_left {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) [mono f] : mono (prod.lift f g) := mono_of_mono_fac $ prod.lift_fst _ _ instance prod.mono_lift_of_mono_right {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) [mono g] : mono (prod.lift f g) := mono_of_mono_fac $ prod.lift_snd _ _ instance coprod.epi_desc_of_epi_left {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) [epi f] : epi (coprod.desc f g) := epi_of_epi_fac $ coprod.inl_desc _ _ instance coprod.epi_desc_of_epi_right {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) [epi g] : epi (coprod.desc f g) := epi_of_epi_fac $ coprod.inr_desc _ _ /-- If the product of `X` and `Y` exists, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `l : W ⟶ X ⨯ Y` satisfying `l ≫ prod.fst = f` and `l ≫ prod.snd = g`. -/ def prod.lift' {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) : {l : W ⟶ X ⨯ Y // l ≫ prod.fst = f ∧ l ≫ prod.snd = g} := ⟨prod.lift f g, prod.lift_fst _ _, prod.lift_snd _ _⟩ /-- If the coproduct of `X` and `Y` exists, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `l : X ⨿ Y ⟶ W` satisfying `coprod.inl ≫ l = f` and `coprod.inr ≫ l = g`. -/ def coprod.desc' {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : {l : X ⨿ Y ⟶ W // coprod.inl ≫ l = f ∧ coprod.inr ≫ l = g} := ⟨coprod.desc f g, coprod.inl_desc _ _, coprod.inr_desc _ _⟩ /-- If the products `W ⨯ X` and `Y ⨯ Z` exist, then every pair of morphisms `f : W ⟶ Y` and `g : X ⟶ Z` induces a morphism `prod.map f g : W ⨯ X ⟶ Y ⨯ Z`. -/ def prod.map {W X Y Z : C} [has_binary_product W X] [has_binary_product Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨯ X ⟶ Y ⨯ Z := lim_map (map_pair f g) /-- If the coproducts `W ⨿ X` and `Y ⨿ Z` exist, then every pair of morphisms `f : W ⟶ Y` and `g : W ⟶ Z` induces a morphism `coprod.map f g : W ⨿ X ⟶ Y ⨿ Z`. -/ def coprod.map {W X Y Z : C} [has_binary_coproduct W X] [has_binary_coproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨿ X ⟶ Y ⨿ Z := colim_map (map_pair f g) section prod_lemmas -- Making the reassoc version of this a simp lemma seems to be more harmful than helpful. @[reassoc, simp] lemma prod.comp_lift {V W X Y : C} [has_binary_product X Y] (f : V ⟶ W) (g : W ⟶ X) (h : W ⟶ Y) : f ≫ prod.lift g h = prod.lift (f ≫ g) (f ≫ h) := by { ext; simp } lemma prod.comp_diag {X Y : C} [has_binary_product Y Y] (f : X ⟶ Y) : f ≫ diag Y = prod.lift f f := by simp @[simp, reassoc] lemma prod.map_fst {W X Y Z : C} [has_binary_product W X] [has_binary_product Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : prod.map f g ≫ prod.fst = prod.fst ≫ f := lim_map_π _ _ @[simp, reassoc] lemma prod.map_snd {W X Y Z : C} [has_binary_product W X] [has_binary_product Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : prod.map f g ≫ prod.snd = prod.snd ≫ g := lim_map_π _ _ @[simp] lemma prod.map_id_id {X Y : C} [has_binary_product X Y] : prod.map (𝟙 X) (𝟙 Y) = 𝟙 _ := by { ext; simp } @[simp] lemma prod.lift_fst_snd {X Y : C} [has_binary_product X Y] : prod.lift prod.fst prod.snd = 𝟙 (X ⨯ Y) := by { ext; simp } @[simp, reassoc] lemma prod.lift_map {V W X Y Z : C} [has_binary_product W X] [has_binary_product Y Z] (f : V ⟶ W) (g : V ⟶ X) (h : W ⟶ Y) (k : X ⟶ Z) : prod.lift f g ≫ prod.map h k = prod.lift (f ≫ h) (g ≫ k) := by { ext; simp } @[simp] lemma prod.lift_fst_comp_snd_comp {W X Y Z : C} [has_binary_product W Y] [has_binary_product X Z] (g : W ⟶ X) (g' : Y ⟶ Z) : prod.lift (prod.fst ≫ g) (prod.snd ≫ g') = prod.map g g' := by { rw ← prod.lift_map, simp } -- We take the right hand side here to be simp normal form, as this way composition lemmas for -- `f ≫ h` and `g ≫ k` can fire (eg `id_comp`) , while `map_fst` and `map_snd` can still work just -- as well. @[simp, reassoc] lemma prod.map_map {A₁ A₂ A₃ B₁ B₂ B₃ : C} [has_binary_product A₁ B₁] [has_binary_product A₂ B₂] [has_binary_product A₃ B₃] (f : A₁ ⟶ A₂) (g : B₁ ⟶ B₂) (h : A₂ ⟶ A₃) (k : B₂ ⟶ B₃) : prod.map f g ≫ prod.map h k = prod.map (f ≫ h) (g ≫ k) := by { ext; simp } -- TODO: is it necessary to weaken the assumption here? @[reassoc] lemma prod.map_swap {A B X Y : C} (f : A ⟶ B) (g : X ⟶ Y) [has_limits_of_shape (discrete walking_pair) C] : prod.map (𝟙 X) f ≫ prod.map g (𝟙 B) = prod.map g (𝟙 A) ≫ prod.map (𝟙 Y) f := by simp @[reassoc] lemma prod.map_comp_id {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_binary_product X W] [has_binary_product Z W] [has_binary_product Y W] : prod.map (f ≫ g) (𝟙 W) = prod.map f (𝟙 W) ≫ prod.map g (𝟙 W) := by simp @[reassoc] lemma prod.map_id_comp {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_binary_product W X] [has_binary_product W Y] [has_binary_product W Z] : prod.map (𝟙 W) (f ≫ g) = prod.map (𝟙 W) f ≫ prod.map (𝟙 W) g := by simp /-- If the products `W ⨯ X` and `Y ⨯ Z` exist, then every pair of isomorphisms `f : W ≅ Y` and `g : X ≅ Z` induces an isomorphism `prod.map_iso f g : W ⨯ X ≅ Y ⨯ Z`. -/ @[simps] def prod.map_iso {W X Y Z : C} [has_binary_product W X] [has_binary_product Y Z] (f : W ≅ Y) (g : X ≅ Z) : W ⨯ X ≅ Y ⨯ Z := { hom := prod.map f.hom g.hom, inv := prod.map f.inv g.inv } instance is_iso_prod {W X Y Z : C} [has_binary_product W X] [has_binary_product Y Z] (f : W ⟶ Y) (g : X ⟶ Z) [is_iso f] [is_iso g] : is_iso (prod.map f g) := is_iso.of_iso (prod.map_iso (as_iso f) (as_iso g)) instance prod.map_mono {C : Type*} [category C] {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) [mono f] [mono g] [has_binary_product W X] [has_binary_product Y Z] : mono (prod.map f g) := ⟨λ A i₁ i₂ h, begin ext, { rw ← cancel_mono f, simpa using congr_arg (λ f, f ≫ prod.fst) h }, { rw ← cancel_mono g, simpa using congr_arg (λ f, f ≫ prod.snd) h } end⟩ @[simp, reassoc] lemma prod.diag_map {X Y : C} (f : X ⟶ Y) [has_binary_product X X] [has_binary_product Y Y] : diag X ≫ prod.map f f = f ≫ diag Y := by simp @[simp, reassoc] lemma prod.diag_map_fst_snd {X Y : C} [has_binary_product X Y] [has_binary_product (X ⨯ Y) (X ⨯ Y)] : diag (X ⨯ Y) ≫ prod.map prod.fst prod.snd = 𝟙 (X ⨯ Y) := by simp @[simp, reassoc] lemma prod.diag_map_fst_snd_comp [has_limits_of_shape (discrete walking_pair) C] {X X' Y Y' : C} (g : X ⟶ Y) (g' : X' ⟶ Y') : diag (X ⨯ X') ≫ prod.map (prod.fst ≫ g) (prod.snd ≫ g') = prod.map g g' := by simp instance {X : C} [has_binary_product X X] : is_split_mono (diag X) := is_split_mono.mk' { retraction := prod.fst } end prod_lemmas section coprod_lemmas @[simp, reassoc] lemma coprod.desc_comp {V W X Y : C} [has_binary_coproduct X Y] (f : V ⟶ W) (g : X ⟶ V) (h : Y ⟶ V) : coprod.desc g h ≫ f = coprod.desc (g ≫ f) (h ≫ f) := by { ext; simp } lemma coprod.diag_comp {X Y : C} [has_binary_coproduct X X] (f : X ⟶ Y) : codiag X ≫ f = coprod.desc f f := by simp @[simp, reassoc] lemma coprod.inl_map {W X Y Z : C} [has_binary_coproduct W X] [has_binary_coproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : coprod.inl ≫ coprod.map f g = f ≫ coprod.inl := ι_colim_map _ _ @[simp, reassoc] lemma coprod.inr_map {W X Y Z : C} [has_binary_coproduct W X] [has_binary_coproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : coprod.inr ≫ coprod.map f g = g ≫ coprod.inr := ι_colim_map _ _ @[simp] lemma coprod.map_id_id {X Y : C} [has_binary_coproduct X Y] : coprod.map (𝟙 X) (𝟙 Y) = 𝟙 _ := by { ext; simp } @[simp] lemma coprod.desc_inl_inr {X Y : C} [has_binary_coproduct X Y] : coprod.desc coprod.inl coprod.inr = 𝟙 (X ⨿ Y) := by { ext; simp } -- The simp linter says simp can prove the reassoc version of this lemma. @[reassoc, simp] lemma coprod.map_desc {S T U V W : C} [has_binary_coproduct U W] [has_binary_coproduct T V] (f : U ⟶ S) (g : W ⟶ S) (h : T ⟶ U) (k : V ⟶ W) : coprod.map h k ≫ coprod.desc f g = coprod.desc (h ≫ f) (k ≫ g) := by { ext; simp } @[simp] lemma coprod.desc_comp_inl_comp_inr {W X Y Z : C} [has_binary_coproduct W Y] [has_binary_coproduct X Z] (g : W ⟶ X) (g' : Y ⟶ Z) : coprod.desc (g ≫ coprod.inl) (g' ≫ coprod.inr) = coprod.map g g' := by { rw ← coprod.map_desc, simp } -- We take the right hand side here to be simp normal form, as this way composition lemmas for -- `f ≫ h` and `g ≫ k` can fire (eg `id_comp`) , while `inl_map` and `inr_map` can still work just -- as well. @[simp, reassoc] lemma coprod.map_map {A₁ A₂ A₃ B₁ B₂ B₃ : C} [has_binary_coproduct A₁ B₁] [has_binary_coproduct A₂ B₂] [has_binary_coproduct A₃ B₃] (f : A₁ ⟶ A₂) (g : B₁ ⟶ B₂) (h : A₂ ⟶ A₃) (k : B₂ ⟶ B₃) : coprod.map f g ≫ coprod.map h k = coprod.map (f ≫ h) (g ≫ k) := by { ext; simp } -- I don't think it's a good idea to make any of the following three simp lemmas. @[reassoc] lemma coprod.map_swap {A B X Y : C} (f : A ⟶ B) (g : X ⟶ Y) [has_colimits_of_shape (discrete walking_pair) C] : coprod.map (𝟙 X) f ≫ coprod.map g (𝟙 B) = coprod.map g (𝟙 A) ≫ coprod.map (𝟙 Y) f := by simp @[reassoc] lemma coprod.map_comp_id {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_binary_coproduct Z W] [has_binary_coproduct Y W] [has_binary_coproduct X W] : coprod.map (f ≫ g) (𝟙 W) = coprod.map f (𝟙 W) ≫ coprod.map g (𝟙 W) := by simp @[reassoc] lemma coprod.map_id_comp {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_binary_coproduct W X] [has_binary_coproduct W Y] [has_binary_coproduct W Z] : coprod.map (𝟙 W) (f ≫ g) = coprod.map (𝟙 W) f ≫ coprod.map (𝟙 W) g := by simp /-- If the coproducts `W ⨿ X` and `Y ⨿ Z` exist, then every pair of isomorphisms `f : W ≅ Y` and `g : W ≅ Z` induces a isomorphism `coprod.map_iso f g : W ⨿ X ≅ Y ⨿ Z`. -/ @[simps] def coprod.map_iso {W X Y Z : C} [has_binary_coproduct W X] [has_binary_coproduct Y Z] (f : W ≅ Y) (g : X ≅ Z) : W ⨿ X ≅ Y ⨿ Z := { hom := coprod.map f.hom g.hom, inv := coprod.map f.inv g.inv } instance is_iso_coprod {W X Y Z : C} [has_binary_coproduct W X] [has_binary_coproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) [is_iso f] [is_iso g] : is_iso (coprod.map f g) := is_iso.of_iso (coprod.map_iso (as_iso f) (as_iso g)) instance coprod.map_epi {C : Type*} [category C] {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) [epi f] [epi g] [has_binary_coproduct W X] [has_binary_coproduct Y Z] : epi (coprod.map f g) := ⟨λ A i₁ i₂ h, begin ext, { rw ← cancel_epi f, simpa using congr_arg (λ f, coprod.inl ≫ f) h }, { rw ← cancel_epi g, simpa using congr_arg (λ f, coprod.inr ≫ f) h } end⟩ -- The simp linter says simp can prove the reassoc version of this lemma. @[reassoc, simp] lemma coprod.map_codiag {X Y : C} (f : X ⟶ Y) [has_binary_coproduct X X] [has_binary_coproduct Y Y] : coprod.map f f ≫ codiag Y = codiag X ≫ f := by simp -- The simp linter says simp can prove the reassoc version of this lemma. @[reassoc, simp] lemma coprod.map_inl_inr_codiag {X Y : C} [has_binary_coproduct X Y] [has_binary_coproduct (X ⨿ Y) (X ⨿ Y)] : coprod.map coprod.inl coprod.inr ≫ codiag (X ⨿ Y) = 𝟙 (X ⨿ Y) := by simp -- The simp linter says simp can prove the reassoc version of this lemma. @[reassoc, simp] lemma coprod.map_comp_inl_inr_codiag [has_colimits_of_shape (discrete walking_pair) C] {X X' Y Y' : C} (g : X ⟶ Y) (g' : X' ⟶ Y') : coprod.map (g ≫ coprod.inl) (g' ≫ coprod.inr) ≫ codiag (Y ⨿ Y') = coprod.map g g' := by simp end coprod_lemmas variables (C) /-- `has_binary_products` represents a choice of product for every pair of objects. See <https://stacks.math.columbia.edu/tag/001T>. -/ abbreviation has_binary_products := has_limits_of_shape (discrete walking_pair) C /-- `has_binary_coproducts` represents a choice of coproduct for every pair of objects. See <https://stacks.math.columbia.edu/tag/04AP>. -/ abbreviation has_binary_coproducts := has_colimits_of_shape (discrete walking_pair) C /-- If `C` has all limits of diagrams `pair X Y`, then it has all binary products -/ lemma has_binary_products_of_has_limit_pair [Π {X Y : C}, has_limit (pair X Y)] : has_binary_products C := { has_limit := λ F, has_limit_of_iso (diagram_iso_pair F).symm } /-- If `C` has all colimits of diagrams `pair X Y`, then it has all binary coproducts -/ lemma has_binary_coproducts_of_has_colimit_pair [Π {X Y : C}, has_colimit (pair X Y)] : has_binary_coproducts C := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_pair F) } section variables {C} /-- The braiding isomorphism which swaps a binary product. -/ @[simps] def prod.braiding (P Q : C) [has_binary_product P Q] [has_binary_product Q P] : P ⨯ Q ≅ Q ⨯ P := { hom := prod.lift prod.snd prod.fst, inv := prod.lift prod.snd prod.fst } /-- The braiding isomorphism can be passed through a map by swapping the order. -/ @[reassoc] lemma braid_natural [has_binary_products C] {W X Y Z : C} (f : X ⟶ Y) (g : Z ⟶ W) : prod.map f g ≫ (prod.braiding _ _).hom = (prod.braiding _ _).hom ≫ prod.map g f := by simp @[reassoc] lemma prod.symmetry' (P Q : C) [has_binary_product P Q] [has_binary_product Q P] : prod.lift prod.snd prod.fst ≫ prod.lift prod.snd prod.fst = 𝟙 (P ⨯ Q) := (prod.braiding _ _).hom_inv_id /-- The braiding isomorphism is symmetric. -/ @[reassoc] lemma prod.symmetry (P Q : C) [has_binary_product P Q] [has_binary_product Q P] : (prod.braiding P Q).hom ≫ (prod.braiding Q P).hom = 𝟙 _ := (prod.braiding _ _).hom_inv_id /-- The associator isomorphism for binary products. -/ @[simps] def prod.associator [has_binary_products C] (P Q R : C) : (P ⨯ Q) ⨯ R ≅ P ⨯ (Q ⨯ R) := { hom := prod.lift (prod.fst ≫ prod.fst) (prod.lift (prod.fst ≫ prod.snd) prod.snd), inv := prod.lift (prod.lift prod.fst (prod.snd ≫ prod.fst)) (prod.snd ≫ prod.snd) } @[reassoc] lemma prod.pentagon [has_binary_products C] (W X Y Z : C) : prod.map ((prod.associator W X Y).hom) (𝟙 Z) ≫ (prod.associator W (X ⨯ Y) Z).hom ≫ prod.map (𝟙 W) ((prod.associator X Y Z).hom) = (prod.associator (W ⨯ X) Y Z).hom ≫ (prod.associator W X (Y ⨯ Z)).hom := by simp @[reassoc] lemma prod.associator_naturality [has_binary_products C] {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : prod.map (prod.map f₁ f₂) f₃ ≫ (prod.associator Y₁ Y₂ Y₃).hom = (prod.associator X₁ X₂ X₃).hom ≫ prod.map f₁ (prod.map f₂ f₃) := by simp variables [has_terminal C] /-- The left unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.left_unitor (P : C) [has_binary_product (⊤_ C) P] : ⊤_ C ⨯ P ≅ P := { hom := prod.snd, inv := prod.lift (terminal.from P) (𝟙 _) } /-- The right unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.right_unitor (P : C) [has_binary_product P (⊤_ C)] : P ⨯ ⊤_ C ≅ P := { hom := prod.fst, inv := prod.lift (𝟙 _) (terminal.from P) } @[reassoc] lemma prod.left_unitor_hom_naturality [has_binary_products C] (f : X ⟶ Y) : prod.map (𝟙 _) f ≫ (prod.left_unitor Y).hom = (prod.left_unitor X).hom ≫ f := prod.map_snd _ _ @[reassoc] lemma prod.left_unitor_inv_naturality [has_binary_products C] (f : X ⟶ Y) : (prod.left_unitor X).inv ≫ prod.map (𝟙 _) f = f ≫ (prod.left_unitor Y).inv := by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, prod.left_unitor_hom_naturality] @[reassoc] lemma prod.right_unitor_hom_naturality [has_binary_products C] (f : X ⟶ Y) : prod.map f (𝟙 _) ≫ (prod.right_unitor Y).hom = (prod.right_unitor X).hom ≫ f := prod.map_fst _ _ @[reassoc] lemma prod_right_unitor_inv_naturality [has_binary_products C] (f : X ⟶ Y) : (prod.right_unitor X).inv ≫ prod.map f (𝟙 _) = f ≫ (prod.right_unitor Y).inv := by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, prod.right_unitor_hom_naturality] lemma prod.triangle [has_binary_products C] (X Y : C) : (prod.associator X (⊤_ C) Y).hom ≫ prod.map (𝟙 X) ((prod.left_unitor Y).hom) = prod.map ((prod.right_unitor X).hom) (𝟙 Y) := by tidy end section variables {C} [has_binary_coproducts C] /-- The braiding isomorphism which swaps a binary coproduct. -/ @[simps] def coprod.braiding (P Q : C) : P ⨿ Q ≅ Q ⨿ P := { hom := coprod.desc coprod.inr coprod.inl, inv := coprod.desc coprod.inr coprod.inl } @[reassoc] lemma coprod.symmetry' (P Q : C) : coprod.desc coprod.inr coprod.inl ≫ coprod.desc coprod.inr coprod.inl = 𝟙 (P ⨿ Q) := (coprod.braiding _ _).hom_inv_id /-- The braiding isomorphism is symmetric. -/ lemma coprod.symmetry (P Q : C) : (coprod.braiding P Q).hom ≫ (coprod.braiding Q P).hom = 𝟙 _ := coprod.symmetry' _ _ /-- The associator isomorphism for binary coproducts. -/ @[simps] def coprod.associator (P Q R : C) : (P ⨿ Q) ⨿ R ≅ P ⨿ (Q ⨿ R) := { hom := coprod.desc (coprod.desc coprod.inl (coprod.inl ≫ coprod.inr)) (coprod.inr ≫ coprod.inr), inv := coprod.desc (coprod.inl ≫ coprod.inl) (coprod.desc (coprod.inr ≫ coprod.inl) coprod.inr) } lemma coprod.pentagon (W X Y Z : C) : coprod.map ((coprod.associator W X Y).hom) (𝟙 Z) ≫ (coprod.associator W (X ⨿ Y) Z).hom ≫ coprod.map (𝟙 W) ((coprod.associator X Y Z).hom) = (coprod.associator (W ⨿ X) Y Z).hom ≫ (coprod.associator W X (Y ⨿ Z)).hom := by simp lemma coprod.associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : coprod.map (coprod.map f₁ f₂) f₃ ≫ (coprod.associator Y₁ Y₂ Y₃).hom = (coprod.associator X₁ X₂ X₃).hom ≫ coprod.map f₁ (coprod.map f₂ f₃) := by simp variables [has_initial C] /-- The left unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.left_unitor (P : C) : ⊥_ C ⨿ P ≅ P := { hom := coprod.desc (initial.to P) (𝟙 _), inv := coprod.inr } /-- The right unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.right_unitor (P : C) : P ⨿ ⊥_ C ≅ P := { hom := coprod.desc (𝟙 _) (initial.to P), inv := coprod.inl } lemma coprod.triangle (X Y : C) : (coprod.associator X (⊥_ C) Y).hom ≫ coprod.map (𝟙 X) ((coprod.left_unitor Y).hom) = coprod.map ((coprod.right_unitor X).hom) (𝟙 Y) := by tidy end section prod_functor variables {C} [has_binary_products C] /-- The binary product functor. -/ @[simps] def prod.functor : C ⥤ C ⥤ C := { obj := λ X, { obj := λ Y, X ⨯ Y, map := λ Y Z, prod.map (𝟙 X) }, map := λ Y Z f, { app := λ T, prod.map f (𝟙 T) }} /-- The product functor can be decomposed. -/ def prod.functor_left_comp (X Y : C) : prod.functor.obj (X ⨯ Y) ≅ prod.functor.obj Y ⋙ prod.functor.obj X := nat_iso.of_components (prod.associator _ _) (by tidy) end prod_functor section coprod_functor variables {C} [has_binary_coproducts C] /-- The binary coproduct functor. -/ @[simps] def coprod.functor : C ⥤ C ⥤ C := { obj := λ X, { obj := λ Y, X ⨿ Y, map := λ Y Z, coprod.map (𝟙 X) }, map := λ Y Z f, { app := λ T, coprod.map f (𝟙 T) }} /-- The coproduct functor can be decomposed. -/ def coprod.functor_left_comp (X Y : C) : coprod.functor.obj (X ⨿ Y) ≅ coprod.functor.obj Y ⋙ coprod.functor.obj X := nat_iso.of_components (coprod.associator _ _) (by tidy) end coprod_functor section prod_comparison universe w variables {C} {D : Type u₂} [category.{w} D] variables (F : C ⥤ D) {A A' B B' : C} variables [has_binary_product A B] [has_binary_product A' B'] variables [has_binary_product (F.obj A) (F.obj B)] [has_binary_product (F.obj A') (F.obj B')] /-- The product comparison morphism. In `category_theory/limits/preserves` we show this is always an iso iff F preserves binary products. -/ def prod_comparison (F : C ⥤ D) (A B : C) [has_binary_product A B] [has_binary_product (F.obj A) (F.obj B)] : F.obj (A ⨯ B) ⟶ F.obj A ⨯ F.obj B := prod.lift (F.map prod.fst) (F.map prod.snd) @[simp, reassoc] lemma prod_comparison_fst : prod_comparison F A B ≫ prod.fst = F.map prod.fst := prod.lift_fst _ _ @[simp, reassoc] lemma prod_comparison_snd : prod_comparison F A B ≫ prod.snd = F.map prod.snd := prod.lift_snd _ _ /-- Naturality of the prod_comparison morphism in both arguments. -/ @[reassoc] lemma prod_comparison_natural (f : A ⟶ A') (g : B ⟶ B') : F.map (prod.map f g) ≫ prod_comparison F A' B' = prod_comparison F A B ≫ prod.map (F.map f) (F.map g) := begin rw [prod_comparison, prod_comparison, prod.lift_map, ← F.map_comp, ← F.map_comp, prod.comp_lift, ← F.map_comp, prod.map_fst, ← F.map_comp, prod.map_snd] end /-- The product comparison morphism from `F(A ⨯ -)` to `FA ⨯ F-`, whose components are given by `prod_comparison`. -/ @[simps] def prod_comparison_nat_trans [has_binary_products C] [has_binary_products D] (F : C ⥤ D) (A : C) : prod.functor.obj A ⋙ F ⟶ F ⋙ prod.functor.obj (F.obj A) := { app := λ B, prod_comparison F A B, naturality' := λ B B' f, by simp [prod_comparison_natural] } @[reassoc] lemma inv_prod_comparison_map_fst [is_iso (prod_comparison F A B)] : inv (prod_comparison F A B) ≫ F.map prod.fst = prod.fst := by simp [is_iso.inv_comp_eq] @[reassoc] lemma inv_prod_comparison_map_snd [is_iso (prod_comparison F A B)] : inv (prod_comparison F A B) ≫ F.map prod.snd = prod.snd := by simp [is_iso.inv_comp_eq] /-- If the product comparison morphism is an iso, its inverse is natural. -/ @[reassoc] lemma prod_comparison_inv_natural (f : A ⟶ A') (g : B ⟶ B') [is_iso (prod_comparison F A B)] [is_iso (prod_comparison F A' B')] : inv (prod_comparison F A B) ≫ F.map (prod.map f g) = prod.map (F.map f) (F.map g) ≫ inv (prod_comparison F A' B') := by rw [is_iso.eq_comp_inv, category.assoc, is_iso.inv_comp_eq, prod_comparison_natural] /-- The natural isomorphism `F(A ⨯ -) ≅ FA ⨯ F-`, provided each `prod_comparison F A B` is an isomorphism (as `B` changes). -/ @[simps {rhs_md := semireducible}] def prod_comparison_nat_iso [has_binary_products C] [has_binary_products D] (A : C) [∀ B, is_iso (prod_comparison F A B)] : prod.functor.obj A ⋙ F ≅ F ⋙ prod.functor.obj (F.obj A) := { hom := prod_comparison_nat_trans F A ..(@as_iso _ _ _ _ _ (nat_iso.is_iso_of_is_iso_app ⟨_, _⟩)) } end prod_comparison section coprod_comparison universe w variables {C} {D : Type u₂} [category.{w} D] variables (F : C ⥤ D) {A A' B B' : C} variables [has_binary_coproduct A B] [has_binary_coproduct A' B'] variables [has_binary_coproduct (F.obj A) (F.obj B)] [has_binary_coproduct (F.obj A') (F.obj B')] /-- The coproduct comparison morphism. In `category_theory/limits/preserves` we show this is always an iso iff F preserves binary coproducts. -/ def coprod_comparison (F : C ⥤ D) (A B : C) [has_binary_coproduct A B] [has_binary_coproduct (F.obj A) (F.obj B)] : F.obj A ⨿ F.obj B ⟶ F.obj (A ⨿ B) := coprod.desc (F.map coprod.inl) (F.map coprod.inr) @[simp, reassoc] lemma coprod_comparison_inl : coprod.inl ≫ coprod_comparison F A B = F.map coprod.inl := coprod.inl_desc _ _ @[simp, reassoc] lemma coprod_comparison_inr : coprod.inr ≫ coprod_comparison F A B = F.map coprod.inr := coprod.inr_desc _ _ /-- Naturality of the coprod_comparison morphism in both arguments. -/ @[reassoc] lemma coprod_comparison_natural (f : A ⟶ A') (g : B ⟶ B') : coprod_comparison F A B ≫ F.map (coprod.map f g) = coprod.map (F.map f) (F.map g) ≫ coprod_comparison F A' B' := begin rw [coprod_comparison, coprod_comparison, coprod.map_desc, ← F.map_comp, ← F.map_comp, coprod.desc_comp, ← F.map_comp, coprod.inl_map, ← F.map_comp, coprod.inr_map] end /-- The coproduct comparison morphism from `FA ⨿ F-` to `F(A ⨿ -)`, whose components are given by `coprod_comparison`. -/ @[simps] def coprod_comparison_nat_trans [has_binary_coproducts C] [has_binary_coproducts D] (F : C ⥤ D) (A : C) : F ⋙ coprod.functor.obj (F.obj A) ⟶ coprod.functor.obj A ⋙ F := { app := λ B, coprod_comparison F A B, naturality' := λ B B' f, by simp [coprod_comparison_natural] } @[reassoc] lemma map_inl_inv_coprod_comparison [is_iso (coprod_comparison F A B)] : F.map coprod.inl ≫ inv (coprod_comparison F A B) = coprod.inl := by simp [is_iso.inv_comp_eq] @[reassoc] lemma map_inr_inv_coprod_comparison [is_iso (coprod_comparison F A B)] : F.map coprod.inr ≫ inv (coprod_comparison F A B) = coprod.inr := by simp [is_iso.inv_comp_eq] /-- If the coproduct comparison morphism is an iso, its inverse is natural. -/ @[reassoc] lemma coprod_comparison_inv_natural (f : A ⟶ A') (g : B ⟶ B') [is_iso (coprod_comparison F A B)] [is_iso (coprod_comparison F A' B')] : inv (coprod_comparison F A B) ≫ coprod.map (F.map f) (F.map g) = F.map (coprod.map f g) ≫ inv (coprod_comparison F A' B') := by rw [is_iso.eq_comp_inv, category.assoc, is_iso.inv_comp_eq, coprod_comparison_natural] /-- The natural isomorphism `FA ⨿ F- ≅ F(A ⨿ -)`, provided each `coprod_comparison F A B` is an isomorphism (as `B` changes). -/ @[simps {rhs_md := semireducible}] def coprod_comparison_nat_iso [has_binary_coproducts C] [has_binary_coproducts D] (A : C) [∀ B, is_iso (coprod_comparison F A B)] : F ⋙ coprod.functor.obj (F.obj A) ≅ coprod.functor.obj A ⋙ F := { hom := coprod_comparison_nat_trans F A ..(@as_iso _ _ _ _ _ (nat_iso.is_iso_of_is_iso_app ⟨_, _⟩)) } end coprod_comparison end category_theory.limits open category_theory.limits namespace category_theory variables {C : Type u} [category.{v} C] /-- Auxiliary definition for `over.coprod`. -/ @[simps] def over.coprod_obj [has_binary_coproducts C] {A : C} : over A → over A ⥤ over A := λ f, { obj := λ g, over.mk (coprod.desc f.hom g.hom), map := λ g₁ g₂ k, over.hom_mk (coprod.map (𝟙 _) k.left) } /-- A category with binary coproducts has a functorial `sup` operation on over categories. -/ @[simps] def over.coprod [has_binary_coproducts C] {A : C} : over A ⥤ over A ⥤ over A := { obj := λ f, over.coprod_obj f, map := λ f₁ f₂ k, { app := λ g, over.hom_mk (coprod.map k.left (𝟙 _)) (by { dsimp, rw [coprod.map_desc, category.id_comp, over.w k] }), naturality' := λ f g k, by ext; { dsimp, simp, }, }, map_id' := λ X, by ext; { dsimp, simp, }, map_comp' := λ X Y Z f g, by ext; { dsimp, simp, }, }. end category_theory
14d6a84e4c7671b08e01e0c0dbb22d7c76f27b8a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/2161.lean
7330d12a6115f658aa88516ba86b0c2a240edeb7
[ "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
617
lean
structure Foo where num : Nat deriving DecidableEq namespace Foo instance : OfNat Foo n := ⟨⟨n⟩⟩ /-! # Example 1 -/ @[irreducible] def mul (a b : Foo) : Foo := let d := Nat.gcd a.num 1 ⟨(a.num.div d) * (b.num.div d)⟩ -- should fail fast; exact heartbeat count at time of writing is 31 set_option maxHeartbeats 310 example : ((Foo.mul 4 1).mul 1).mul 1 = 4 := by decide /-! # Example 2 -/ @[irreducible] def add (a b : Foo) : Foo := ⟨a.num * b.num⟩ -- should not succeed (and fail fast); exact heartbeat count at time of writing is 21 example : ((Foo.add 4 1).add 1).add 1 = 4 := by decide
fefe27b5f0406015555fa80dad0aa2b9739f6d4d
aa5a655c05e5359a70646b7154e7cac59f0b4132
/stage0/src/Lean/Elab/Structure.lean
3c21c569acc75bcdfe90ac12971c74534d642c09
[ "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
27,364
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Command import Lean.Meta.Closure import Lean.Meta.SizeOf import Lean.Elab.Command import Lean.Elab.DeclModifiers import Lean.Elab.DeclUtil import Lean.Elab.Inductive import Lean.Elab.DeclarationRange namespace Lean.Elab.Command open Meta /- Recall that the `structure command syntax is ``` parser! (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> optional (" := " >> optional structCtor >> structFields) ``` -/ structure StructCtorView where ref : Syntax modifiers : Modifiers inferMod : Bool -- true if `{}` is used in the constructor declaration name : Name declName : Name structure StructFieldView where ref : Syntax modifiers : Modifiers binderInfo : BinderInfo inferMod : Bool declName : Name name : Name binders : Syntax type? : Option Syntax value? : Option Syntax structure StructView where ref : Syntax modifiers : Modifiers scopeLevelNames : List Name -- All `universe` declarations in the current scope allUserLevelNames : List Name -- `scopeLevelNames` ++ explicit universe parameters provided in the `structure` command isClass : Bool declName : Name scopeVars : Array Expr -- All `variable` declaration in the current scope params : Array Expr -- Explicit parameters provided in the `structure` command parents : Array Syntax type : Syntax ctor : StructCtorView fields : Array StructFieldView inductive StructFieldKind where | newField | fromParent | subobject deriving Inhabited structure StructFieldInfo where name : Name declName : Name -- Remark: this field value doesn't matter for fromParent fields. fvar : Expr kind : StructFieldKind inferMod : Bool := false value? : Option Expr := none deriving Inhabited def StructFieldInfo.isFromParent (info : StructFieldInfo) : Bool := match info.kind with | StructFieldKind.fromParent => true | _ => false def StructFieldInfo.isSubobject (info : StructFieldInfo) : Bool := match info.kind with | StructFieldKind.subobject => true | _ => false /- Auxiliary declaration for `mkProjections` -/ structure ProjectionInfo where declName : Name inferMod : Bool structure ElabStructResult where decl : Declaration projInfos : List ProjectionInfo projInstances : List Name -- projections (to parent classes) that must be marked as instances. mctx : MetavarContext lctx : LocalContext localInsts : LocalInstances defaultAuxDecls : Array (Name × Expr × Expr) private def defaultCtorName := `mk /- The structure constructor syntax is ``` parser! try (declModifiers >> ident >> optional inferMod >> " :: ") ``` -/ private def expandCtor (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM StructCtorView := do let useDefault := do let declName := structDeclName ++ defaultCtorName addAuxDeclarationRanges declName structStx[2] structStx[2] pure { ref := structStx, modifiers := {}, inferMod := false, name := defaultCtorName, declName := declName } if structStx[5].isNone then useDefault else let optCtor := structStx[5][1] if optCtor.isNone then useDefault else let ctor := optCtor[0] withRef ctor do let ctorModifiers ← elabModifiers ctor[0] checkValidCtorModifier ctorModifiers if ctorModifiers.isPrivate && structModifiers.isPrivate then throwError "invalid 'private' constructor in a 'private' structure" if ctorModifiers.isProtected && structModifiers.isPrivate then throwError "invalid 'protected' constructor in a 'private' structure" let inferMod := !ctor[2].isNone let name := ctor[1].getId let declName := structDeclName ++ name let declName ← applyVisibility ctorModifiers.visibility declName addDocString' declName ctorModifiers.docString? addAuxDeclarationRanges declName ctor[1] ctor[1] pure { ref := ctor, name := name, modifiers := ctorModifiers, inferMod := inferMod, declName := declName } def checkValidFieldModifier (modifiers : Modifiers) : TermElabM Unit := do if modifiers.isNoncomputable then throwError "invalid use of 'noncomputable' in field declaration" if modifiers.isPartial then throwError "invalid use of 'partial' in field declaration" if modifiers.isUnsafe then throwError "invalid use of 'unsafe' in field declaration" if modifiers.attrs.size != 0 then throwError "invalid use of attributes in field declaration" if modifiers.isPrivate then throwError "private fields are not supported yet" /- ``` def structExplicitBinder := parser! atomic (declModifiers true >> "(") >> many1 ident >> optional inferMod >> optDeclSig >> optional Term.binderDefault >> ")" def structImplicitBinder := parser! atomic (declModifiers true >> "{") >> many1 ident >> optional inferMod >> declSig >> "}" def structInstBinder := parser! atomic (declModifiers true >> "[") >> many1 ident >> optional inferMod >> declSig >> "]" def structSimpleBinder := parser! atomic (declModifiers true >> ident) >> optional inferMod >> optDeclSig >> optional Term.binderDefault def structFields := parser! many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder) ``` -/ private def expandFields (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM (Array StructFieldView) := let fieldBinders := if structStx[5].isNone then #[] else structStx[5][2][0].getArgs fieldBinders.foldlM (init := #[]) fun (views : Array StructFieldView) fieldBinder => withRef fieldBinder do let mut fieldBinder := fieldBinder if fieldBinder.getKind == ``Parser.Command.structSimpleBinder then fieldBinder := Syntax.node ``Parser.Command.structExplicitBinder #[ fieldBinder[0], mkAtomFrom fieldBinder "(", mkNullNode #[ fieldBinder[1] ], fieldBinder[2], fieldBinder[3], fieldBinder[4], mkAtomFrom fieldBinder ")" ] let k := fieldBinder.getKind let binfo ← if k == ``Parser.Command.structExplicitBinder then pure BinderInfo.default else if k == ``Parser.Command.structImplicitBinder then pure BinderInfo.implicit else if k == ``Parser.Command.structInstBinder then pure BinderInfo.instImplicit else throwError "unexpected kind of structure field" let fieldModifiers ← elabModifiers fieldBinder[0] checkValidFieldModifier fieldModifiers if fieldModifiers.isPrivate && structModifiers.isPrivate then throwError "invalid 'private' field in a 'private' structure" if fieldModifiers.isProtected && structModifiers.isPrivate then throwError "invalid 'protected' field in a 'private' structure" let inferMod := !fieldBinder[3].isNone let (binders, type?) := if binfo == BinderInfo.default then expandOptDeclSig fieldBinder[4] else let (binders, type) := expandDeclSig fieldBinder[4] (binders, some type) let value? := if binfo != BinderInfo.default then none else let optBinderDefault := fieldBinder[5] if optBinderDefault.isNone then none else -- binderDefault := parser! " := " >> termParser some optBinderDefault[0][1] let idents := fieldBinder[2].getArgs idents.foldlM (init := views) fun (views : Array StructFieldView) ident => withRef ident do let name := ident.getId if isInternalSubobjectFieldName name then throwError! "invalid field name '{name}', identifiers starting with '_' are reserved to the system" let declName := structDeclName ++ name let declName ← applyVisibility fieldModifiers.visibility declName addDocString' declName fieldModifiers.docString? return views.push { ref := ident, modifiers := fieldModifiers, binderInfo := binfo, inferMod := inferMod, declName := declName, name := name, binders := binders, type? := type?, value? := value? } private def validStructType (type : Expr) : Bool := match type with | Expr.sort .. => true | _ => false private def checkParentIsStructure (parent : Expr) : TermElabM Name := match parent.getAppFn with | Expr.const c _ _ => do unless isStructure (← getEnv) c do throwError! "'{c}' is not a structure" pure c | _ => throwError "expected structure" private def findFieldInfo? (infos : Array StructFieldInfo) (fieldName : Name) : Option StructFieldInfo := infos.find? fun info => info.name == fieldName private def containsFieldName (infos : Array StructFieldInfo) (fieldName : Name) : Bool := (findFieldInfo? infos fieldName).isSome private partial def processSubfields (structDeclName : Name) (parentFVar : Expr) (parentStructName : Name) (subfieldNames : Array Name) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := let rec loop (i : Nat) (infos : Array StructFieldInfo) := do if h : i < subfieldNames.size then let subfieldName := subfieldNames.get ⟨i, h⟩ if containsFieldName infos subfieldName then throwError! "field '{subfieldName}' from '{parentStructName}' has already been declared" let val ← mkProjection parentFVar subfieldName let type ← inferType val withLetDecl subfieldName type val fun subfieldFVar => /- The following `declName` is only used for creating the `_default` auxiliary declaration name when its default value is overwritten in the structure. -/ let declName := structDeclName ++ subfieldName let infos := infos.push { name := subfieldName, declName := declName, fvar := subfieldFVar, kind := StructFieldKind.fromParent } loop (i+1) infos else k infos loop 0 infos private partial def withParents (view : StructView) (i : Nat) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do if h : i < view.parents.size then let parentStx := view.parents.get ⟨i, h⟩ withRef parentStx do let parent ← Term.elabType parentStx let parentName ← checkParentIsStructure parent let toParentName := Name.mkSimple $ "to" ++ parentName.eraseMacroScopes.getString! -- erase macro scopes? if containsFieldName infos toParentName then throwErrorAt! parentStx "field '{toParentName}' has already been declared" let env ← getEnv let binfo := if view.isClass && isClass env parentName then BinderInfo.instImplicit else BinderInfo.default withLocalDecl toParentName binfo parent fun parentFVar => let infos := infos.push { name := toParentName, declName := view.declName ++ toParentName, fvar := parentFVar, kind := StructFieldKind.subobject } let subfieldNames := getStructureFieldsFlattened env parentName processSubfields view.declName parentFVar parentName subfieldNames infos fun infos => withParents view (i+1) infos k else k infos private def elabFieldTypeValue (view : StructFieldView) (params : Array Expr) : TermElabM (Option Expr × Option Expr) := do match view.type? with | none => match view.value? with | none => pure (none, none) | some valStx => let value ← Term.elabTerm valStx none let value ← mkLambdaFVars params value pure (none, value) | some typeStx => let type ← Term.elabType typeStx match view.value? with | none => let type ← mkForallFVars params type pure (type, none) | some valStx => let value ← Term.elabTermEnsuringType valStx type let type ← mkForallFVars params type let value ← mkLambdaFVars params value pure (type, value) private partial def withFields (views : Array StructFieldView) (i : Nat) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do if h : i < views.size then let view := views.get ⟨i, h⟩ withRef view.ref $ match findFieldInfo? infos view.name with | none => do let (type?, value?) ← Term.elabBinders view.binders.getArgs fun params => elabFieldTypeValue view params match type?, value? with | none, none => throwError "invalid field, type expected" | some type, _ => withLocalDecl view.name view.binderInfo type fun fieldFVar => let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value?, kind := StructFieldKind.newField, inferMod := view.inferMod } withFields views (i+1) infos k | none, some value => let type ← inferType value withLocalDecl view.name view.binderInfo type fun fieldFVar => let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value, kind := StructFieldKind.newField, inferMod := view.inferMod } withFields views (i+1) infos k | some info => match info.kind with | StructFieldKind.newField => throwError! "field '{view.name}' has already been declared" | StructFieldKind.fromParent => match view.value? with | none => throwError! "field '{view.name}' has been declared in parent structure" | some valStx => do if let some type := view.type? then throwErrorAt! type "omit field '{view.name}' type to set default value" else let mut valStx := valStx if view.binders.getArgs.size > 0 then valStx ← `(fun $(view.binders.getArgs)* => $valStx:term) let fvarType ← inferType info.fvar let value ← Term.elabTermEnsuringType valStx fvarType let infos := infos.push { info with value? := value } withFields views (i+1) infos k | StructFieldKind.subobject => unreachable! else k infos private def getResultUniverse (type : Expr) : TermElabM Level := do let type ← whnf type match type with | Expr.sort u _ => pure u | _ => throwError "unexpected structure resulting type" private def collectUsed (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT CollectFVars.State TermElabM Unit := do params.forM fun p => do let type ← inferType p Term.collectUsedFVars type fieldInfos.forM fun info => do let fvarType ← inferType info.fvar Term.collectUsedFVars fvarType match info.value? with | none => pure () | some value => Term.collectUsedFVars value private def removeUnused (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (LocalContext × LocalInstances × Array Expr) := do let (_, used) ← (collectUsed params fieldInfos).run {} Term.removeUnused scopeVars used private def withUsed {α} (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) (k : Array Expr → TermElabM α) : TermElabM α := do let (lctx, localInsts, vars) ← removeUnused scopeVars params fieldInfos withLCtx lctx localInsts $ k vars private def levelMVarToParamFVar (fvar : Expr) : StateRefT Nat TermElabM Unit := do let type ← inferType fvar discard <| Term.levelMVarToParam' type private def levelMVarToParamFVars (fvars : Array Expr) : StateRefT Nat TermElabM Unit := fvars.forM levelMVarToParamFVar private def levelMVarToParamAux (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT Nat TermElabM (Array StructFieldInfo) := do levelMVarToParamFVars scopeVars levelMVarToParamFVars params fieldInfos.mapM fun info => do levelMVarToParamFVar info.fvar match info.value? with | none => pure info | some value => let value ← Term.levelMVarToParam' value pure { info with value? := value } private def levelMVarToParam (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (Array StructFieldInfo) := (levelMVarToParamAux scopeVars params fieldInfos).run' 1 private partial def collectUniversesFromFields (r : Level) (rOffset : Nat) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Level) := do fieldInfos.foldlM (init := #[]) fun (us : Array Level) (info : StructFieldInfo) => do let type ← inferType info.fvar let u ← getLevel type let u ← instantiateLevelMVars u accLevelAtCtor u r rOffset us private def updateResultingUniverse (fieldInfos : Array StructFieldInfo) (type : Expr) : TermElabM Expr := do let r ← getResultUniverse type let rOffset : Nat := r.getOffset let r : Level := r.getLevelOffset match r with | Level.mvar mvarId _ => let us ← collectUniversesFromFields r rOffset fieldInfos let rNew := mkResultUniverse us rOffset assignLevelMVar mvarId rNew instantiateMVars type | _ => throwError "failed to compute resulting universe level of structure, provide universe explicitly" private def collectLevelParamsInFVar (s : CollectLevelParams.State) (fvar : Expr) : TermElabM CollectLevelParams.State := do let type ← inferType fvar let type ← instantiateMVars type pure $ collectLevelParams s type private def collectLevelParamsInFVars (fvars : Array Expr) (s : CollectLevelParams.State) : TermElabM CollectLevelParams.State := fvars.foldlM collectLevelParamsInFVar s private def collectLevelParamsInStructure (structType : Expr) (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Name) := do let s := collectLevelParams {} structType let s ← collectLevelParamsInFVars scopeVars s let s ← collectLevelParamsInFVars params s let s ← fieldInfos.foldlM (fun (s : CollectLevelParams.State) info => collectLevelParamsInFVar s info.fvar) s pure s.params private def addCtorFields (fieldInfos : Array StructFieldInfo) : Nat → Expr → TermElabM Expr | 0, type => pure type | i+1, type => do let info := fieldInfos[i] let decl ← Term.getFVarLocalDecl! info.fvar let type ← instantiateMVars type let type := type.abstract #[info.fvar] match info.kind with | StructFieldKind.fromParent => let val := decl.value addCtorFields fieldInfos i (type.instantiate1 val) | StructFieldKind.subobject => let n := mkInternalSubobjectFieldName $ decl.userName addCtorFields fieldInfos i (mkForall n decl.binderInfo decl.type type) | StructFieldKind.newField => addCtorFields fieldInfos i (mkForall decl.userName decl.binderInfo decl.type type) private def mkCtor (view : StructView) (levelParams : List Name) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM Constructor := withRef view.ref do let type := mkAppN (mkConst view.declName (levelParams.map mkLevelParam)) params let type ← addCtorFields fieldInfos fieldInfos.size type let type ← mkForallFVars params type let type ← instantiateMVars type let type := type.inferImplicit params.size !view.ctor.inferMod pure { name := view.ctor.declName, type := type } @[extern "lean_mk_projections"] private constant mkProjections (env : Environment) (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : Except KernelException Environment private def addProjections (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : TermElabM Unit := do let env ← getEnv match mkProjections env structName projs isClass with | Except.ok env => setEnv env | Except.error ex => throwKernelException ex private def mkAuxConstructions (declName : Name) : TermElabM Unit := do let env ← getEnv let hasUnit := env.contains `PUnit let hasEq := env.contains `Eq let hasHEq := env.contains `HEq mkRecOn declName if hasUnit then mkCasesOn declName if hasUnit && hasEq && hasHEq then mkNoConfusion declName private def addDefaults (lctx : LocalContext) (defaultAuxDecls : Array (Name × Expr × Expr)) : TermElabM Unit := do let localInsts ← getLocalInstances withLCtx lctx localInsts do defaultAuxDecls.forM fun (declName, type, value) => do /- The identity function is used as "marker". -/ let value ← mkId value discard <| mkAuxDefinition declName type value (zeta := true) setReducibleAttribute declName private def elabStructureView (view : StructView) : TermElabM Unit := do view.fields.forM fun field => do if field.declName == view.ctor.declName then throwErrorAt! field.ref "invalid field name '{field.name}', it is equal to structure constructor name" addAuxDeclarationRanges field.declName field.ref field.ref let numExplicitParams := view.params.size let type ← Term.elabType view.type unless validStructType type do throwErrorAt view.type "expected Type" withRef view.ref do withParents view 0 #[] fun fieldInfos => withFields view.fields 0 fieldInfos fun fieldInfos => do Term.synthesizeSyntheticMVarsNoPostponing let u ← getResultUniverse type let inferLevel ← shouldInferResultUniverse u withUsed view.scopeVars view.params fieldInfos $ fun scopeVars => do let numParams := scopeVars.size + numExplicitParams let fieldInfos ← levelMVarToParam scopeVars view.params fieldInfos let type ← withRef view.ref do if inferLevel then updateResultingUniverse fieldInfos type else checkResultingUniverse (← getResultUniverse type) pure type trace[Elab.structure]! "type: {type}" let usedLevelNames ← collectLevelParamsInStructure type scopeVars view.params fieldInfos match sortDeclLevelParams view.scopeLevelNames view.allUserLevelNames usedLevelNames with | Except.error msg => withRef view.ref <| throwError msg | Except.ok levelParams => let params := scopeVars ++ view.params let ctor ← mkCtor view levelParams params fieldInfos let type ← mkForallFVars params type let type ← instantiateMVars type let indType := { name := view.declName, type := type, ctors := [ctor] : InductiveType } let decl := Declaration.inductDecl levelParams params.size [indType] view.modifiers.isUnsafe Term.ensureNoUnassignedMVars decl addDecl decl let projInfos := (fieldInfos.filter fun (info : StructFieldInfo) => !info.isFromParent).toList.map fun (info : StructFieldInfo) => { declName := info.declName, inferMod := info.inferMod : ProjectionInfo } addProjections view.declName projInfos view.isClass mkAuxConstructions view.declName let instParents ← fieldInfos.filterM fun info => do let decl ← Term.getFVarLocalDecl! info.fvar pure (info.isSubobject && decl.binderInfo.isInstImplicit) let projInstances := instParents.toList.map fun info => info.declName Term.applyAttributesAt view.declName view.modifiers.attrs AttributeApplicationTime.afterTypeChecking projInstances.forM fun declName => addInstance declName AttributeKind.global (evalPrio! default) let lctx ← getLCtx let fieldsWithDefault := fieldInfos.filter fun info => info.value?.isSome let defaultAuxDecls ← fieldsWithDefault.mapM fun info => do let type ← inferType info.fvar pure (info.declName ++ `_default, type, info.value?.get!) /- The `lctx` and `defaultAuxDecls` are used to create the auxiliary `_default` declarations The parameters `params` for these definitions must be marked as implicit, and all others as explicit. -/ let lctx := params.foldl (init := lctx) fun (lctx : LocalContext) (p : Expr) => lctx.setBinderInfo p.fvarId! BinderInfo.implicit let lctx := fieldInfos.foldl (init := lctx) fun (lctx : LocalContext) (info : StructFieldInfo) => if info.isFromParent then lctx -- `fromParent` fields are elaborated as let-decls, and are zeta-expanded when creating `_default`. else lctx.setBinderInfo info.fvar.fvarId! BinderInfo.default addDefaults lctx defaultAuxDecls /- parser! (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> " := " >> optional structCtor >> structFields >> optDeriving where def «extends» := parser! " extends " >> sepBy1 termParser ", " def typeSpec := parser! " : " >> termParser def optType : Parser := optional typeSpec def structFields := parser! many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder) def structCtor := parser! try (declModifiers >> ident >> optional inferMod >> " :: ") -/ def elabStructure (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do checkValidInductiveModifier modifiers let isClass := stx[0].getKind == ``Parser.Command.classTk let modifiers := if isClass then modifiers.addAttribute { name := `class } else modifiers let declId := stx[1] let params := stx[2].getArgs let exts := stx[3] let parents := if exts.isNone then #[] else exts[0][1].getSepArgs let optType := stx[4] let derivingClassViews ← getOptDerivingClasses stx[6] let type ← if optType.isNone then `(Sort _) else pure optType[0][1] let declName ← runTermElabM none fun scopeVars => do let scopeLevelNames ← Term.getLevelNames let ⟨name, declName, allUserLevelNames⟩ ← Elab.expandDeclId (← getCurrNamespace) scopeLevelNames declId modifiers addDeclarationRanges declName stx Term.withDeclName declName do let ctor ← expandCtor stx modifiers declName let fields ← expandFields stx modifiers declName Term.withLevelNames allUserLevelNames <| Term.withAutoBoundImplicitLocal <| Term.elabBinders params (catchAutoBoundImplicit := true) fun params => do let params ← Term.addAutoBoundImplicits params let allUserLevelNames ← Term.getLevelNames Term.withAutoBoundImplicitLocal (flag := false) do elabStructureView { ref := stx modifiers := modifiers scopeLevelNames := scopeLevelNames allUserLevelNames := allUserLevelNames declName := declName isClass := isClass scopeVars := scopeVars params := params parents := parents type := type ctor := ctor fields := fields } unless isClass do mkSizeOfInstances declName return declName derivingClassViews.forM fun view => view.applyHandlers #[declName] builtin_initialize registerTraceClass `Elab.structure end Lean.Elab.Command
43a98e916fcd02beac3fe4a888c55b7fd0bf10fc
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/category_theory/full_subcategory.lean
eec75206f3146b4b343b06778f7cf3fa19d96468
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
3,852
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Reid Barton -/ import category_theory.fully_faithful import category_theory.groupoid namespace category_theory universes v u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation section induced /- Induced categories. Given a category D and a function F : C → D from a type C to the objects of D, there is an essentially unique way to give C a category structure such that F becomes a fully faithful functor, namely by taking Hom_C(X, Y) = Hom_D(FX, FY). We call this the category induced from D along F. As a special case, if C is a subtype of D, this produces the full subcategory of D on the objects belonging to C. In general the induced category is equivalent to the full subcategory of D on the image of F. -/ /- It looks odd to make D an explicit argument of `induced_category`, when it is determined by the argument F anyways. The reason to make D explicit is in order to control its syntactic form, so that instances like `induced_category.has_forget₂` (elsewhere) refer to the correct form of D. This is used to set up several algebraic categories like def CommMon : Type (u+1) := induced_category Mon (bundled.map @comm_monoid.to_monoid) -- not `induced_category (bundled monoid) (bundled.map @comm_monoid.to_monoid)`, -- even though `Mon = bundled monoid`! -/ variables {C : Type u₁} (D : Type u₂) [category.{v} D] variables (F : C → D) include F /-- `induced_category D F`, where `F : C → D`, is a typeclass synonym for `C`, which provides a category structure so that the morphisms `X ⟶ Y` are the morphisms in `D` from `F X` to `F Y`. -/ @[nolint has_inhabited_instance unused_arguments] def induced_category : Type u₁ := C variables {D} instance induced_category.has_coe_to_sort [has_coe_to_sort D] : has_coe_to_sort (induced_category D F) := ⟨_, λ c, ↥(F c)⟩ instance induced_category.category : category.{v} (induced_category D F) := { hom := λ X Y, F X ⟶ F Y, id := λ X, 𝟙 (F X), comp := λ _ _ _ f g, f ≫ g } /-- The forgetful functor from an induced category to the original category, forgetting the extra data. -/ @[simps] def induced_functor : induced_category D F ⥤ D := { obj := F, map := λ x y f, f } instance induced_category.full : full (induced_functor F) := { preimage := λ x y f, f } instance induced_category.faithful : faithful (induced_functor F) := {} end induced instance induced_category.groupoid {C : Type u₁} (D : Type u₂) [groupoid.{v} D] (F : C → D) : groupoid.{v} (induced_category D F) := { inv := λ X Y f, groupoid.inv f, inv_comp' := λ X Y f, groupoid.inv_comp f, comp_inv' := λ X Y f, groupoid.comp_inv f, .. induced_category.category F } section full_subcategory /- A full subcategory is the special case of an induced category with F = subtype.val. -/ variables {C : Type u₂} [category.{v} C] variables (Z : C → Prop) instance full_subcategory : category.{v} {X : C // Z X} := induced_category.category subtype.val /-- The forgetful functor from a full subcategory into the original category ("forgetting" the condition). -/ def full_subcategory_inclusion : {X : C // Z X} ⥤ C := induced_functor subtype.val @[simp] lemma full_subcategory_inclusion.obj {X} : (full_subcategory_inclusion Z).obj X = X.val := rfl @[simp] lemma full_subcategory_inclusion.map {X Y} {f : X ⟶ Y} : (full_subcategory_inclusion Z).map f = f := rfl instance full_subcategory.full : full (full_subcategory_inclusion Z) := induced_category.full subtype.val instance full_subcategory.faithful : faithful (full_subcategory_inclusion Z) := induced_category.faithful subtype.val end full_subcategory end category_theory
9facdeb8cf3205ed18eb31e4bd858f7541273de8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/hom/iterate.lean
4bd68c2cdae3cfdd7c28c8e5990897d7e2682e0d
[ "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,588
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import algebra.group_power.lemmas import group_theory.group_action.opposite /-! # Iterates of monoid and ring homomorphisms > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Iterate of a monoid/ring homomorphism is a monoid/ring homomorphism but it has a wrong type, so Lean can't apply lemmas like `monoid_hom.map_one` to `f^[n] 1`. Though it is possible to define a monoid structure on the endomorphisms, quite often we do not want to convert from `M →* M` to `monoid.End M` and from `f^[n]` to `f^n` just to apply a simple lemma. So, we restate standard `*_hom.map_*` lemmas under names `*_hom.iterate_map_*`. We also prove formulas for iterates of add/mul left/right. ## Tags homomorphism, iterate -/ open function variables {M : Type*} {N : Type*} {G : Type*} {H : Type*} /-- An auxiliary lemma that can be used to prove `⇑(f ^ n) = (⇑f^[n])`. -/ lemma hom_coe_pow {F : Type*} [monoid F] (c : F → M → M) (h1 : c 1 = id) (hmul : ∀ f g, c (f * g) = c f ∘ c g) (f : F) : ∀ n, c (f ^ n) = (c f^[n]) | 0 := by { rw [pow_zero, h1], refl } | (n + 1) := by rw [pow_succ, iterate_succ', hmul, hom_coe_pow] namespace monoid_hom section variables [mul_one_class M] [mul_one_class N] @[simp, to_additive] theorem iterate_map_one (f : M →* M) (n : ℕ) : f^[n] 1 = 1 := iterate_fixed f.map_one n @[simp, to_additive] theorem iterate_map_mul (f : M →* M) (n : ℕ) (x y) : f^[n] (x * y) = (f^[n] x) * (f^[n] y) := semiconj₂.iterate f.map_mul n x y end variables [monoid M] [monoid N] [group G] [group H] @[simp, to_additive] theorem iterate_map_inv (f : G →* G) (n : ℕ) (x) : f^[n] (x⁻¹) = (f^[n] x)⁻¹ := commute.iterate_left f.map_inv n x @[simp, to_additive] theorem iterate_map_div (f : G →* G) (n : ℕ) (x y) : f^[n] (x / y) = (f^[n] x) / (f^[n] y) := semiconj₂.iterate f.map_div n x y theorem iterate_map_pow (f : M →* M) (n : ℕ) (a) (m : ℕ) : f^[n] (a^m) = (f^[n] a)^m := commute.iterate_left (λ x, f.map_pow x m) n a theorem iterate_map_zpow (f : G →* G) (n : ℕ) (a) (m : ℤ) : f^[n] (a^m) = (f^[n] a)^m := commute.iterate_left (λ x, f.map_zpow x m) n a lemma coe_pow {M} [comm_monoid M] (f : monoid.End M) (n : ℕ) : ⇑(f^n) = (f^[n]) := hom_coe_pow _ rfl (λ f g, rfl) _ _ end monoid_hom lemma monoid.End.coe_pow {M} [monoid M] (f : monoid.End M) (n : ℕ) : ⇑(f^n) = (f^[n]) := hom_coe_pow _ rfl (λ f g, rfl) _ _ -- we define these manually so that we can pick a better argument order namespace add_monoid_hom variables [add_monoid M] [add_group G] theorem iterate_map_smul (f : M →+ M) (n m : ℕ) (x : M) : f^[n] (m • x) = m • (f^[n] x) := f.to_multiplicative.iterate_map_pow n x m attribute [to_additive, to_additive_reorder 5] monoid_hom.iterate_map_pow theorem iterate_map_zsmul (f : G →+ G) (n : ℕ) (m : ℤ) (x : G) : f^[n] (m • x) = m • (f^[n] x) := f.to_multiplicative.iterate_map_zpow n x m attribute [to_additive, to_additive_reorder 5] monoid_hom.iterate_map_zpow end add_monoid_hom lemma add_monoid.End.coe_pow {A} [add_monoid A] (f : add_monoid.End A) (n : ℕ) : ⇑(f^n) = (f^[n]) := hom_coe_pow _ rfl (λ f g, rfl) _ _ namespace ring_hom section semiring variables {R : Type*} [semiring R] (f : R →+* R) (n : ℕ) (x y : R) lemma coe_pow (n : ℕ) : ⇑(f^n) = (f^[n]) := hom_coe_pow _ rfl (λ f g, rfl) f n theorem iterate_map_one : f^[n] 1 = 1 := f.to_monoid_hom.iterate_map_one n theorem iterate_map_zero : f^[n] 0 = 0 := f.to_add_monoid_hom.iterate_map_zero n theorem iterate_map_add : f^[n] (x + y) = (f^[n] x) + (f^[n] y) := f.to_add_monoid_hom.iterate_map_add n x y theorem iterate_map_mul : f^[n] (x * y) = (f^[n] x) * (f^[n] y) := f.to_monoid_hom.iterate_map_mul n x y theorem iterate_map_pow (a) (n m : ℕ) : f^[n] (a^m) = (f^[n] a)^m := f.to_monoid_hom.iterate_map_pow n a m theorem iterate_map_smul (n m : ℕ) (x : R) : f^[n] (m • x) = m • (f^[n] x) := f.to_add_monoid_hom.iterate_map_smul n m x end semiring variables {R : Type*} [ring R] (f : R →+* R) (n : ℕ) (x y : R) theorem iterate_map_sub : f^[n] (x - y) = (f^[n] x) - (f^[n] y) := f.to_add_monoid_hom.iterate_map_sub n x y theorem iterate_map_neg : f^[n] (-x) = -(f^[n] x) := f.to_add_monoid_hom.iterate_map_neg n x theorem iterate_map_zsmul (n : ℕ) (m : ℤ) (x : R) : f^[n] (m • x) = m • (f^[n] x) := f.to_add_monoid_hom.iterate_map_zsmul n m x end ring_hom --what should be the namespace for this section? section monoid variables [monoid G] (a : G) (n : ℕ) @[simp, to_additive] lemma smul_iterate [mul_action G H] : ((•) a : H → H)^[n] = (•) (a^n) := funext (λ b, nat.rec_on n (by rw [iterate_zero, id.def, pow_zero, one_smul]) (λ n ih, by rw [iterate_succ', comp_app, ih, pow_succ, mul_smul])) @[simp, to_additive] lemma mul_left_iterate : ((*) a)^[n] = (*) (a^n) := smul_iterate a n @[simp, to_additive] lemma mul_right_iterate : (* a)^[n] = (* a ^ n) := smul_iterate (mul_opposite.op a) n @[to_additive] lemma mul_right_iterate_apply_one : (* a)^[n] 1 = a ^ n := by simp [mul_right_iterate] @[simp, to_additive] lemma pow_iterate (n : ℕ) (j : ℕ) : ((λ (x : G), x^n)^[j]) = λ x, x^(n^j) := begin letI : mul_action ℕ G := { smul := λ n g, g^n, one_smul := pow_one, mul_smul := λ m n g, pow_mul' g m n }, exact smul_iterate n j, end end monoid section group variables [group G] @[simp, to_additive] lemma zpow_iterate (n : ℤ) (j : ℕ) : ((λ (x : G), x^n)^[j]) = λ x, x^(n^j) := begin letI : mul_action ℤ G := { smul := λ n g, g^n, one_smul := zpow_one, mul_smul := λ m n g, zpow_mul' g m n }, exact smul_iterate n j, end end group section semigroup variables [semigroup G] {a b c : G} @[to_additive] lemma semiconj_by.function_semiconj_mul_left (h : semiconj_by a b c) : function.semiconj ((*)a) ((*)b) ((*)c) := λ j, by rw [← mul_assoc, h.eq, mul_assoc] @[to_additive] lemma commute.function_commute_mul_left (h : commute a b) : function.commute ((*)a) ((*)b) := semiconj_by.function_semiconj_mul_left h @[to_additive] lemma semiconj_by.function_semiconj_mul_right_swap (h : semiconj_by a b c) : function.semiconj (*a) (*c) (*b) := λ j, by simp_rw [mul_assoc, ← h.eq] @[to_additive] lemma commute.function_commute_mul_right (h : commute a b) : function.commute (*a) (*b) := semiconj_by.function_semiconj_mul_right_swap h end semigroup
91da59ba8777fcdc759589aeb46bea96ee18df4d
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/tests/lean/run/newfrontend1.lean
f1d7064b33ebfb965bde237b94f25ae648a32474
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
8,784
lean
def x := 1 #check x variable {α : Type} def f (a : α) : α := a def tst (xs : List Nat) : Nat := xs.foldl (init := 10) (· + ·) #check tst [1, 2, 3] #check fun x y : Nat => x + y #check tst #check (fun stx => if True then let e := stx; Pure.pure e else Pure.pure stx : Nat → Id Nat) #check let x : Nat := 1; x def foo (a : Nat) (b : Nat := 10) (c : Bool := Bool.true) : Nat := a + b set_option pp.all true #check foo 1 #check foo 3 (c := false) def Nat.boo (a : Nat) := succ a -- succ here is resolved as `Nat.succ`. #check Nat.boo #check true -- apply is still a valid identifier name def apply := "hello" #check apply theorem simple1 (x y : Nat) (h : x = y) : x = y := by { assumption } theorem simple2 (x y : Nat) : x = y → x = y := by { intro h; assumption } syntax "intro2" : tactic macro_rules | `(tactic| intro2) => `(tactic| intro; intro ) theorem simple3 (x y : Nat) : x = x → x = y → x = y := by { intro2; assumption } macro "intro3" : tactic => `(intro; intro; intro) macro "check2" x:term : command => `(#check $x #check $x) macro "foo" x:term "," y:term : term => `($x + $y + $x) set_option pp.all false check2 0+1 check2 foo 0,1 theorem simple4 (x y : Nat) : y = y → x = x → x = y → x = y := by { intro3; assumption } theorem simple5 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro _; intro h3; exact Eq.trans h3 h1 } theorem simple6 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro _; intro h3; refine Eq.trans ?_ h1; assumption } theorem simple7 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro _; intro h3; refine' Eq.trans ?pre ?post; exact y; { exact h3 } { exact h1 } } theorem simple8 (x y z : Nat) : y = z → x = x → x = y → x = z := by intro h1; intro _; intro h3 refine' Eq.trans ?pre ?post case post => exact h1 case pre => exact h3 theorem simple9 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 traceState focus refine' Eq.trans ?pre ?post first | exact h1 assumption | exact y exact h3 assumption theorem simple9b (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 traceState focus refine' Eq.trans ?pre ?post first | exact h1 | exact y; exact h3 assumption theorem simple9c (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 solve | exact h1 | refine' Eq.trans ?pre ?post; exact y; exact h3; assumption | exact h3 theorem simple9d (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 refine' Eq.trans ?pre ?post solve | exact h1 | exact y | exact h3 solve | exact h1 | exact h3 solve | exact h1 | assumption namespace Foo def Prod.mk := 1 #check (⟨2, 3⟩ : Prod _ _) end Foo theorem simple10 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro h2; intro h3; skip; apply Eq.trans; exact h3; assumption } theorem simple11 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro h2; intro h3; apply @Eq.trans; traceState; exact h3; assumption } theorem simple12 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro h2; intro h3; apply @Eq.trans; try exact h1; -- `exact h1` fails traceState; try exact h3; traceState; try exact h1; } theorem simple13 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 h2 h3 traceState apply @Eq.trans case b => exact y traceState repeat assumption theorem simple13b (x y z : Nat) : y = z → x = x → x = y → x = z := by { intros h1 h2 h3; traceState; apply @Eq.trans; case b => exact y; traceState; repeat assumption } theorem simple14 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros apply @Eq.trans case b => exact y repeat assumption theorem simple15 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intros h1 h2 h3; revert y; intros y h1 h3; apply Eq.trans; exact h3; exact h1 } theorem simple16 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intros h1 h2 h3; try clear x; -- should fail clear h2; traceState; apply Eq.trans; exact h3; exact h1 } macro "blabla" : tactic => `(assumption) -- Tactic head symbols do not become reserved words def blabla := 100 #check blabla theorem simple17 (x : Nat) (h : x = 0) : x = 0 := by blabla theorem simple18 (x : Nat) (h : x = 0) : x = 0 := by blabla theorem simple19 (x y : Nat) (h₁ : x = 0) (h₂ : x = y) : y = 0 := by subst x; subst y; exact rfl theorem tstprec1 (x y z : Nat) : x + y * z = x + (y * z) := rfl theorem tstprec2 (x y z : Nat) : y * z + x = (y * z) + x := rfl set_option pp.all true #check fun {α} (a : α) => a #check @(fun α (a : α) => a) #check let myid := fun {α} (a : α) => a; myid [myid 1] -- In the following example, we need `@` otherwise we will try to insert mvars for α and [Add α], -- and will fail to generate instance for [Add α] #check @(fun α (s : Add α) (a : α) => a + a) def g1 {α} (a₁ a₂ : α) {β} (b : β) : α × α × β := (a₁, a₂, b) def id1 : {α : Type} → α → α := fun x => x def listId : List ({α : Type} → α → α) := (fun x => x) :: [] def id2 : {α : Type} → α → α := @(fun α (x : α) => id1 x) def id3 : {α : Type} → α → α := @(fun α x => id1 x) def id4 : {α : Type} → α → α := fun x => id1 x def id5 : {α : Type} → α → α := fun {α} x => id1 x def id6 : {α : Type} → α → α := @(fun {α} x => id1 x) def id7 : {α : Type} → α → α := fun {α} x => @id α x def id8 : {α : Type} → α → α := fun {α} x => id (@id α x) def altTst1 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨StateT.failure, StateT.orElse⟩ def altTst2 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨@(fun α => StateT.failure), @(fun α => StateT.orElse)⟩ def altTst3 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨fun {α} => StateT.failure, fun {α} => StateT.orElse⟩ #check_failure 1 + true /- universes u v /- MonadFunctorT.{u ?M_1 v} (λ (β : Type u), m α) (λ (β : Type u), m' α) n n' -/ set_option pp.raw.maxDepth 100 set_option trace.Elab true def adapt {m m' σ σ'} {n n' : Type → Type} [MonadFunctor m m' n n'] [MonadStateAdapter σ σ' m m'] : MonadStateAdapter σ σ' n n' := ⟨fun split join => monadMap (adaptState split join : m α → m' α)⟩ -/ syntax "fn" (term:max)+ "=>" term : term macro_rules | `(fn $xs* => $b) => `(fun $xs* => $b) set_option pp.all false #check fn x => x+1 #check fn α (a : α) => a def tst1 : {α : Type} → α → α := @(fn α a => a) #check @tst1 syntax ident "==>" term : term syntax "{" ident "}" "==>" term : term macro_rules | `($x:ident ==> $b) => `(fn $x => $b) | `({$x:ident} ==> $b) => `(fun {$x:ident} => $b) #check x ==> x+1 def tst2a : {α : Type} → α → α := @(α ==> a ==> a) def tst2b : {α : Type} → α → α := {α} ==> a ==> a #check @tst2a #check @tst2b def tst3a : {α : Type} → {β : Type} → α → β → α × β := @(α ==> @(β ==> a ==> b ==> (a, b))) def tst3b : {α : Type} → {β : Type} → α → β → α × β := {α} ==> {β} ==> a ==> b ==> (a, b) syntax "function" (term:max)+ "=>" term : term macro_rules | `(function $xs* => $b) => `(@(fun $xs* => $b)) def tst4 : {α : Type} → {β : Type} → α → β → α × β := function α β a b => (a, b) theorem simple20 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 h2 h3; try clear x; -- should fail clear h2; traceState; apply Eq.trans; exact h3; exact h1 theorem simple21 (x y z : Nat) : y = z → x = x → y = x → x = z := fun h1 _ h3 => have : x = y := by { apply Eq.symm; assumption }; Eq.trans this (by assumption) theorem simple22 (x y z : Nat) : y = z → y = x → id (x = z + 0) := fun h1 h2 => show x = z + 0 by apply Eq.trans exact h2.symm assumption skip theorem simple23 (x y z : Nat) : y = z → x = x → y = x → x = z := fun h1 _ h3 => have : x = y := by apply Eq.symm; assumption Eq.trans this (by assumption) theorem simple24 (x y z : Nat) : y = z → x = x → y = x → x = z := fun h1 _ h3 => have h : x = y := by apply Eq.symm; assumption Eq.trans h (by assumption) def f1 (x : Nat) : Nat := let double x := x + x let rec loop x := match x with | 0 => 0 | x+1 => loop x + double x loop x #eval f1 5 def f2 (x : Nat) : String := let bad x : String := toString x bad x def f3 x y := x + y + 1 theorem f3eq x y : f3 x y = x + y + 1 := rfl def f4 (x y : Nat) : String := if x > y + 1 then "hello" else "world"
b5d0acd97521dff115f3b7610e70e92a7549ad0c
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/algebraic_geometry/sheafed_space.lean
301b25c03d23f8e25dcc48a8671aae8f90f82065
[ "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
4,597
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 algebraic_geometry.presheafed_space import topology.sheaves.sheaf /-! # Sheafed spaces Introduces the category of topological spaces equipped with a sheaf (taking values in an arbitrary target category `C`.) We further describe how to apply functors and natural transformations to the values of the presheaves. -/ universes v u open category_theory open Top open topological_space open opposite open category_theory.limits open category_theory.category category_theory.functor variables (C : Type u) [category.{v} C] [limits.has_products C] local attribute [tidy] tactic.op_induction' namespace algebraic_geometry /-- A `SheafedSpace C` is a topological space equipped with a sheaf of `C`s. -/ structure SheafedSpace extends PresheafedSpace C := (sheaf_condition : presheaf.sheaf_condition) variables {C} namespace SheafedSpace instance coe_carrier : has_coe (SheafedSpace C) Top := { coe := λ X, X.carrier } /-- Extract the `sheaf C (X : Top)` from a `SheafedSpace C`. -/ def sheaf (X : SheafedSpace C) : sheaf C (X : Top.{v}) := ⟨X.presheaf, X.sheaf_condition⟩ @[simp] lemma as_coe (X : SheafedSpace C) : X.carrier = (X : Top.{v}) := rfl @[simp] lemma mk_coe (carrier) (presheaf) (h) : (({ carrier := carrier, presheaf := presheaf, sheaf_condition := h } : SheafedSpace.{v} C) : Top.{v}) = carrier := rfl instance (X : SheafedSpace.{v} C) : topological_space X := X.carrier.str /-- The trivial `punit` valued sheaf on any topological space. -/ noncomputable def punit (X : Top) : SheafedSpace (discrete punit) := { sheaf_condition := presheaf.sheaf_condition_punit _, ..@PresheafedSpace.const (discrete punit) _ X punit.star } noncomputable instance : inhabited (SheafedSpace (discrete _root_.punit)) := ⟨punit (Top.of pempty)⟩ instance : category (SheafedSpace C) := show category (induced_category (PresheafedSpace C) SheafedSpace.to_PresheafedSpace), by apply_instance /-- Forgetting the sheaf condition is a functor from `SheafedSpace C` to `PresheafedSpace C`. -/ def forget_to_PresheafedSpace : (SheafedSpace C) ⥤ (PresheafedSpace C) := induced_functor _ variables {C} section local attribute [simp] id comp presheaf.pushforward @[simp] lemma id_base (X : SheafedSpace C) : ((𝟙 X) : X ⟶ X).base = (𝟙 (X : Top.{v})) := rfl lemma id_c (X : SheafedSpace C) : ((𝟙 X) : X ⟶ X).c = (((functor.left_unitor _).inv) ≫ (whisker_right (nat_trans.op (opens.map_id (X.carrier)).hom) _)) := rfl @[simp] lemma id_c_app (X : SheafedSpace C) (U) : ((𝟙 X) : X ⟶ X).c.app U = eq_to_hom (by { op_induction U, cases U, refl }) := by { op_induction U, cases U, simp only [id_c], dsimp, simp, } @[simp] lemma comp_base {X Y Z : SheafedSpace C} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).base = f.base ≫ g.base := rfl @[simp] lemma comp_c_app {X Y Z : SheafedSpace C} (α : X ⟶ Y) (β : Y ⟶ Z) (U) : (α ≫ β).c.app U = (β.c).app U ≫ (α.c).app (op ((opens.map (β.base)).obj (unop U))) ≫ (Top.presheaf.pushforward.comp _ _ _).inv.app U := rfl variables (C) /-- The forgetful functor from `SheafedSpace` to `Top`. -/ def forget : SheafedSpace C ⥤ Top := { obj := λ X, (X : Top.{v}), map := λ X Y f, f.base } end open Top.presheaf /-- The restriction of a sheafed space along an open embedding into the space. -/ noncomputable def restrict {U : Top} (X : SheafedSpace C) (f : U ⟶ (X : Top.{v})) (h : open_embedding f) : SheafedSpace C := { sheaf_condition := λ ι 𝒰, is_limit.of_iso_limit ((is_limit.postcompose_inv_equiv _ _).inv_fun (X.sheaf_condition _)) (sheaf_condition_equalizer_products.fork.iso_of_open_embedding h 𝒰).symm, ..X.to_PresheafedSpace.restrict f h } /-- The global sections, notated Gamma. -/ def Γ : (SheafedSpace C)ᵒᵖ ⥤ C := forget_to_PresheafedSpace.op ⋙ PresheafedSpace.Γ lemma Γ_def : (Γ : _ ⥤ C) = forget_to_PresheafedSpace.op ⋙ PresheafedSpace.Γ := rfl @[simp] lemma Γ_obj (X : (SheafedSpace C)ᵒᵖ) : Γ.obj X = (unop X).presheaf.obj (op ⊤) := rfl lemma Γ_obj_op (X : SheafedSpace C) : Γ.obj (op X) = X.presheaf.obj (op ⊤) := rfl @[simp] lemma Γ_map {X Y : (SheafedSpace C)ᵒᵖ} (f : X ⟶ Y) : Γ.map f = f.unop.c.app (op ⊤) ≫ (unop Y).presheaf.map (opens.le_map_top _ _).op := rfl lemma Γ_map_op {X Y : SheafedSpace C} (f : X ⟶ Y) : Γ.map f.op = f.c.app (op ⊤) ≫ X.presheaf.map (opens.le_map_top _ _).op := rfl end SheafedSpace end algebraic_geometry
541196a681dd018f046bdb4d3ab84d719d4251c2
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/extern.lean
9e36419b29b240f8d8e2ec3687e89545eea10cba
[ "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
310
lean
@[extern] def foo (x : Nat) := x @[extern "bla"] def foo2 (x : Nat) := x @[extern 2 "boo"] def foo3 (x : Nat) := x @[extern cpp "Lean::bla" llvm "lean_bla"] def foo4 (x : Bool) := x @[extern cpp inline "#1 && #2"] def foo5 (x y : Bool) := x -- @[extern cpp adhoc llvm "foo"] -- def foo6 (x y : Bool) := x
bde1efbed4e4e491cd83f684568d8a5f72170cba
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_cc_noconfusion.lean
0e8c51c7402e3c988addb13e669e0677a2722979
[ "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
1,284
lean
import data.list open nat set_option blast.strategy "cc" constant f : nat → nat example (a b c d : nat) : f d = f b → succ a = f b → f d = succ c → a = c := by blast example (a b c d e : nat) : f d = f b → f e = f b → succ a = f b → f e = succ c → a = c := by blast example (a b c d e : nat) : f d = f b → f e = f b → succ a = f b → f e = zero → false := by blast example (a b c d e : nat) : f d = f b → f e = f b → succ a = f b → f e = 0 → false := by blast open list example (a b c d e f : nat) (l1 l2 l3 l4 : list nat) : l1 = l2 → l2 = l3 → l4 = [a, b, succ c] → l1 = [c, d, succ e] → l3 = l4 → c = e := by blast example (a b c d e f : nat) (l1 l2 l3 l4 : list nat) : l4 = [a, b, succ (succ c)] → l1 = [c, d, succ (succ e)] → l3 = l4 → l1 = l2 → l2 = l3 → c = e := by blast example (a b c d e f : nat) (l1 l2 l3 l4 : list nat) : l4 = [a, b, succ c] → l1 = [c, d, 0] → l3 = l4 → l1 = l2 → l2 = l3 → false := by blast example (a b c d e f : nat) (l1 l2 l3 l4 : list nat) : l4 = [a, b, succ c] → l1 = nil → l3 = l4 → l1 = l2 → l2 = l3 → false := by blast example (a b c d e f : nat) (l1 l2 l3 l4 : list nat) : l1 = l2 → l2 = l3 → l4 = [a, b, succ c] → l1 = nil → l3 = l4 → false := by blast
e0a9faac7d835f4d867232dd3430875525238395
4ad6af7525e674c3cdc623c1495472954f3ce34c
/src/03_haskell.lean
ae2ab3d37079fd74813b71e735bbd32dd5a1b590
[]
no_license
alcides/lean3_tutorial
4bf48026f7cfa5ae80e9a75f46ca23364d455810
7a871e00c4fd5cb000929a59e1bd804a626ef277
refs/heads/master
1,663,719,613,974
1,591,141,389,000
1,591,141,389,000
268,600,781
5
0
null
null
null
null
UTF-8
Lean
false
false
4,448
lean
/- In a undergraduate class I have taught the past years, it was frequent to ask students to prove some properties about their programs. Here we follow the exercices students have been typically asked to do in pen and paper. -/ /- This is how you inductively define new types. The haskell version: data List a = Empty | Cons a (List a) Note: Lean provides a convient list structure with a few lemmas available. You should use the default ones as much as possible, as they will save you time and trouble. -/ inductive L (a:Type) : Type | empty : L | cons : a → L → L /- If you want to refer to the empty constructor, you have to use "L.empty". While this allows you to have multiple constructors with the same name in different types, it clutters the code. To overcome it, we bring everything within L to the outer scope with: -/ open L /- length :: [a] -> nat length [] = 0 length (x:xs) = 1 + length xs -/ def length {a:Type} : L a → nat | empty := 0 | (cons head tail) := 1 + length tail /- map :: (a → b) → [a] → [b] map _ [] = [] map f (x:xs) = f x : map f xs -/ def map {a:Type} {b:Type} : (a → b) → L a → L b | _ empty := empty | f (cons head tail) := cons (f head) (map f tail) /- Now that we have defined the computable part, let us move into the second language to prove some properties. In this first example, we will show a particular example, not really a property. As such, we will use example instead of lemma or theorem. -/ example : length (map id (cons 1 (cons 2 empty))) = 2 := begin rewrite map, rw map, rw map, rw length, rw length, rw length, end /- rw stands for rewrite, a new tactic that replaces the ocurrent of that function, using its definition. This is a very useful tactic. The proof is very repetitive — nobody writes code/proofs like this. Let's see how to improve it in this level. -/ /- Next goal: prove that the length of the map of a list is equal to that of the original list. -/ theorem length_map_is_the_same (a b:Type) (f:a→b) (xs:L a) : length (map f xs) = length xs := begin induction xs, { -- Base case: empty rw length, rw map, rw length, }, { -- Recursive case: cons rw map, rw length, rw length, rw xs_ih, } end /- This is our first proof by induction on the structure of the list xs. If you try to rw map or length before doing the induction, it will yield an error. If a function is defined using equations, rewrite is only possible if it is clear which of the equations to use. For that we need to rewrite empty or rewrite cons. By using induction, we can rewrite is knowing its structure. The induction tactic leaves two goals to be solved instead of the original one. Now we need to prove both, but they are hopefully easier. Despite not being necessary, we organize both goals using curly braces. To each goal its block. (begin-end also work, but let us reserve those for the outer scope only. Despite having editor support, it is considered polite to comment what each sub-goal refers to. Typically in the recursive/inductive step, we are looking to advance one side of the equality to contain one side of the inductive hypothisis. The default name in this case is (xs_ih). Always look at the context on the side window and look for it. -/ @[simp] /- Please ignore this line for now. -/ theorem map_id_is_the_same (a:Type) (xs:L a) : map id xs = xs := begin sorry, -- it is your turn again. end /- Let us address the weird @[simp] address before the last theorem. Have you noticed how you have never had to proe that 1+1 = 2 or any of those basic steps. Most tactics try to simplify the result automatically, but you can do it manually using the "simp" tactic. The annotation in the previous theorem is how the user can indicate that whenver Lean tries to simplify a proposition, it can use that theorem automatically. It is how the Lean standard library was written. -/ example : length (map id (cons 1 (cons 2 empty))) == 1 + 1 := begin simp, repeat { rw length, }, end /- The other new tactic in this example is the repeat tactic, that tries to repeat the inside tactics as many times as possible until it fails, even if it fails at the first try. This is how you can avoid the boilerplate in the first example in this file. -/
14bf991342ea66f5bab678ccecee34ab450e372f
037dba89703a79cd4a4aec5e959818147f97635d
/src/2020/peano/peano_practice_questions.lean
c07b204c789aa6acbf229c508d038ff6053aa1a3
[]
no_license
ImperialCollegeLondon/M40001_lean
3a6a09298da395ab51bc220a535035d45bbe919b
62a76fa92654c855af2b2fc2bef8e60acd16ccec
refs/heads/master
1,666,750,403,259
1,665,771,117,000
1,665,771,117,000
209,141,835
115
12
null
1,640,270,596,000
1,568,749,174,000
Lean
UTF-8
Lean
false
false
2,562
lean
/- MATH40001 : Introduction to university mathematics. Peano Axioms - Extra Practice, October 2020. These questions are based on Dr Lawn's Practice Questions on Blackboard. This is a Lean file. It can be read with the Lean theorem prover. You can work on this file online at the following URL: or you can install Lean and its maths library following the instructions at https://leanprover-community.github.io/get_started.html There are advantages to installing Lean on your own computer (for example it's faster), but it's more hassle than just using it online. Replace the sorries for the theorems you think are provable with tactics which prove them. Here, we use the function `succ` instead of `ν`. -/ import data.nat.basic open nat function #check (succ : ℕ → ℕ) #reduce succ 0 #reduce succ 36 theorem exists_succ_true : ∃ (ν : ℕ → ℕ), ν = succ := begin sorry end theorem exists_succ_false : ¬ ∃ (ν : ℕ → ℕ), ν = succ := begin sorry end theorem succ_injective_true : injective succ := begin unfold injective, sorry end theorem succ_injective_false : ¬ injective succ := begin unfold injective, sorry end theorem succ_surjective_true : surjective succ := begin unfold surjective, sorry end theorem succ_surjective_false : ¬ surjective succ := begin unfold surjective, sorry end theorem all_functions_are_succ_true : ∀ (ν : ℕ → ℕ), ν = succ := begin sorry end theorem all_functions_are_succ_false : ¬ ∀ (ν : ℕ → ℕ), ν = succ := begin sorry end theorem exists_unique_zero_true : ∃! n : ℕ, n = 0 := begin sorry end theorem exists_unique_zero_false : ¬ ∃! n : ℕ, n = 0:= begin sorry end /- The lemma `funext_iff` : (f₁ = f₂) ↔ (∀ x, f₁ x = f₂ x) might come in handy somewhere above. Next, try writing down the Peano Axioms as given in the lectures/notes: type `\forall`, `\exists`, `\nu`, `\in`, `\sub` and `\to` and then SPACE or TAB for their respective symbols ∀ ∃ ν ∈ ⊆ → -/ def N : set ℕ := {n | true} -- Let `N` be the set of all natural numbers def Peano_Axiom_1 : Prop := 0 ∈ N -- as an example def Peano_Axiom_2 : Prop := sorry def Peano_Axiom_3 : Prop := sorry def Peano_Axiom_4 : Prop := sorry def Peano_Axiom_5 : Prop := sorry -- Lean Fun Facts! set_option pp.numerals false -- changes lean's pretty printer options #reduce succ 5 #reduce 37 #check 6 #check 37 -- Compare Lean's recursor with (P5) #check (@nat.rec : ∀ {C : ℕ → Sort*}, C 0 → (∀ n, C n → C (succ n)) → ∀ n, C n)
52fb4f53f5db8ce513556904575b10ee99be143c
d0f9af2b0ace5ce352570d61b09019c8ef4a3b96
/hw3/dm_box.lean
4bcf40f5a783fe64b01270ebab166ef22d7688d6
[]
no_license
jngo13/Discrete-Mathematics
8671540ef2da7c75915d32332dd20c02f001474e
bf674a866e61f60e6e6d128df85fa73819091787
refs/heads/master
1,675,615,657,924
1,609,142,011,000
1,609,142,011,000
267,190,341
0
0
null
null
null
null
UTF-8
Lean
false
false
1,280
lean
-- Justin Ngo -- jmn4fms -- 2/3/20 -- Sullivan 2102-001 /- 3. [30 points] Define a polymorphic ADT called dm_box. This type builder takes one type argument. The intuitive idea is that a dm_box contains one value of the type specified by the type argument. Define dm_box to have one constructor, mk, that takes one value of the specified type and that produces a dm_box with that value stored "in" the box. Note: a box is very much like an ordered pair but it contains only one value, not two. Define one "inspector" function, unbox, that takes a dm_box and returns the value "inside" the box. Write unbox, unbox', and unbox'', using respectively lambda, C-style, and cases syntax. Put your definitions in a file, dm_box.lean, and write a few test cases, using values of different types, in dm_box_test.lean. -/ inductive dm_box (value:Type): Type | mk: value → dm_box --first type of dm_box open dm_box --data type has its own namespace --Lamda style def unbox {value: Type}: dm_box value → value := λ (b: dm_box value), match b with | dm_box.mk x := x end -- C style def unbox' {value: Type} (b: dm_box value):= match b with |(dm_box.mk x) := x end -- By case def unbox'' {value: Type}: (dm_box value) → value |(dm_box.mk x) := x
b1f6a9f8040e24084827e8cb231fd805a7b9a4cb
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/record4.lean
9454f3b9dd7817661e6827af4322c467110c24ab
[ "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
185
lean
structure point (A : Type) (B : Type) := mk :: (x : A) (y : B) inductive color | red | green | blue structure color_point (A : Type) (B : Type) extends point A B := mk :: (c : color)
8d9df4687eb5c0f939e1c3ffdf82c02d7f21eff3
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/smt_tests3.lean
7815a0371d6efac4810d0909a73dad2536a973f5
[ "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
680
lean
def f : nat → nat | 0 := 1 | (n+1) := f n + 1 lemma ex(a : nat) : f a ≠ 0 := begin induction a, dsimp [f], intro x, contradiction, dsimp [f], change nat.succ (f a_1) ≠ 0, apply nat.succ_ne_zero end lemma ex2 (a : nat) : f a ≠ 0 := begin [smt] induction a, { intros, ematch_using [f] }, { repeat {ematch_using [f, nat.add_one_eq_succ, nat.succ_ne_zero]}} end lemma ex3 (a : nat) : f (a+1) = f a + 1 := begin [smt] dsimp [f] end lemma ex4 (a : nat) : f (a+1) = f a + 1 := begin [smt] simp [f] end lemma ex5 (a : nat) : f (a+1) = f a + 1 := begin [smt] ematch_using [f] end lemma ex6 (a : nat) : f 0 = 1 := begin [smt] ematch_using [f] end
19a6a9c4898299777c3a6e3cfec401675e37fad1
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/field_theory/fixed.lean
86caf68458c2013073913f3960a1e76ff6c17125
[ "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,171
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.polynomial.group_ring_action import field_theory.normal import field_theory.separable import field_theory.tower /-! # Fixed field under a group action. This is the basis of the Fundamental Theorem of Galois Theory. Given a (finite) group `G` that acts on a field `F`, we define `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of `G`. This subfield is then normal and separable, and in addition (TODO) if `G` acts faithfully on `F` then `finrank (fixed_points G F) F = fintype.card G`. ## Main Definitions - `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of `G`, where `G` is a group that acts on `F`. -/ noncomputable theory open_locale classical big_operators open mul_action finset finite_dimensional universes u v w variables {M : Type u} [monoid M] variables (G : Type u) [group G] variables (F : Type v) [field F] [mul_semiring_action M F] [mul_semiring_action G F] (m : M) /-- The subfield of F fixed by the field endomorphism `m`. -/ def fixed_by.subfield : subfield F := { carrier := fixed_by M F m, zero_mem' := smul_zero m, add_mem' := λ x y hx hy, (smul_add m x y).trans $ congr_arg2 _ hx hy, neg_mem' := λ x hx, (smul_neg m x).trans $ congr_arg _ hx, one_mem' := smul_one m, mul_mem' := λ x y hx hy, (smul_mul' m x y).trans $ congr_arg2 _ hx hy, inv_mem' := λ x hx, (smul_inv'' m x).trans $ congr_arg _ hx } section invariant_subfields variables (M) {F} /-- A typeclass for subrings invariant under a `mul_semiring_action`. -/ class is_invariant_subfield (S : subfield F) : Prop := (smul_mem : ∀ (m : M) {x : F}, x ∈ S → m • x ∈ S) variable (S : subfield F) instance is_invariant_subfield.to_mul_semiring_action [is_invariant_subfield M S] : mul_semiring_action M S := { smul := λ m x, ⟨m • x, is_invariant_subfield.smul_mem m x.2⟩, one_smul := λ s, subtype.eq $ one_smul M s, mul_smul := λ m₁ m₂ s, subtype.eq $ mul_smul m₁ m₂ s, smul_add := λ m s₁ s₂, subtype.eq $ smul_add m s₁ s₂, smul_zero := λ m, subtype.eq $ smul_zero m, smul_one := λ m, subtype.eq $ smul_one m, smul_mul := λ m s₁ s₂, subtype.eq $ smul_mul' m s₁ s₂ } instance [is_invariant_subfield M S] : is_invariant_subring M (S.to_subring) := { smul_mem := is_invariant_subfield.smul_mem } end invariant_subfields namespace fixed_points variable (M) -- we use `subfield.copy` so that the underlying set is `fixed_points M F` /-- The subfield of fixed points by a monoid action. -/ def subfield : subfield F := subfield.copy (⨅ (m : M), fixed_by.subfield F m) (fixed_points M F) (by { ext z, simp [fixed_points, fixed_by.subfield, infi, subfield.mem_Inf] }) instance : is_invariant_subfield M (fixed_points.subfield M F) := { smul_mem := λ g x hx g', by rw [hx, hx] } instance : smul_comm_class M (fixed_points.subfield M F) F := { smul_comm := λ m f f', show m • (↑f * f') = f * (m • f'), by rw [smul_mul', f.prop m] } instance smul_comm_class' : smul_comm_class (fixed_points.subfield M F) M F := smul_comm_class.symm _ _ _ @[simp] theorem smul (m : M) (x : fixed_points.subfield M F) : m • x = x := subtype.eq $ x.2 m -- Why is this so slow? @[simp] theorem smul_polynomial (m : M) (p : polynomial (fixed_points.subfield M F)) : m • p = p := polynomial.induction_on p (λ x, by rw [polynomial.smul_C, smul]) (λ p q ihp ihq, by rw [smul_add, ihp, ihq]) (λ n x ih, by rw [smul_mul', polynomial.smul_C, smul, smul_pow', polynomial.smul_X]) instance : algebra (fixed_points.subfield M F) F := by apply_instance theorem coe_algebra_map : algebra_map (fixed_points.subfield M F) F = subfield.subtype (fixed_points.subfield M F) := rfl lemma linear_independent_smul_of_linear_independent {s : finset F} : linear_independent (fixed_points.subfield G F) (λ i : (s : set F), (i : F)) → linear_independent F (λ i : (s : set F), mul_action.to_fun G F i) := begin haveI : is_empty ((∅ : finset F) : set F) := ⟨subtype.prop⟩, refine finset.induction_on s (λ _, linear_independent_empty_type) (λ a s has ih hs, _), rw coe_insert at hs ⊢, rw linear_independent_insert (mt mem_coe.1 has) at hs, rw linear_independent_insert' (mt mem_coe.1 has), refine ⟨ih hs.1, λ ha, _⟩, rw finsupp.mem_span_image_iff_total at ha, rcases ha with ⟨l, hl, hla⟩, rw [finsupp.total_apply_of_mem_supported F hl] at hla, suffices : ∀ i ∈ s, l i ∈ fixed_points.subfield G F, { replace hla := (sum_apply _ _ (λ i, l i • to_fun G F i)).symm.trans (congr_fun hla 1), simp_rw [pi.smul_apply, to_fun_apply, one_smul] at hla, refine hs.2 (hla ▸ submodule.sum_mem _ (λ c hcs, _)), change (⟨l c, this c hcs⟩ : fixed_points.subfield G F) • c ∈ _, exact submodule.smul_mem _ _ (submodule.subset_span $ mem_coe.2 hcs) }, intros i his g, refine eq_of_sub_eq_zero (linear_independent_iff'.1 (ih hs.1) s.attach (λ i, g • l i - l i) _ ⟨i, his⟩ (mem_attach _ _) : _), refine (@sum_attach _ _ s _ (λ i, (g • l i - l i) • mul_action.to_fun G F i)).trans _, ext g', dsimp only, conv_lhs { rw sum_apply, congr, skip, funext, rw [pi.smul_apply, sub_smul, smul_eq_mul] }, rw [sum_sub_distrib, pi.zero_apply, sub_eq_zero], conv_lhs { congr, skip, funext, rw [to_fun_apply, ← mul_inv_cancel_left g g', mul_smul, ← smul_mul', ← to_fun_apply _ x] }, show ∑ x in s, g • (λ y, l y • mul_action.to_fun G F y) x (g⁻¹ * g') = ∑ x in s, (λ y, l y • mul_action.to_fun G F y) x g', rw [← smul_sum, ← sum_apply _ _ (λ y, l y • to_fun G F y), ← sum_apply _ _ (λ y, l y • to_fun G F y)], dsimp only, rw [hla, to_fun_apply, to_fun_apply, smul_smul, mul_inv_cancel_left] end variables [fintype G] (x : F) /-- `minpoly G F x` is the minimal polynomial of `(x : F)` over `fixed_points G F`. -/ def minpoly : polynomial (fixed_points.subfield G F) := (prod_X_sub_smul G F x).to_subring (fixed_points.subfield G F).to_subring $ λ c hc g, let ⟨n, hc0, hn⟩ := polynomial.mem_frange_iff.1 hc in hn.symm ▸ prod_X_sub_smul.coeff G F x g n namespace minpoly theorem monic : (minpoly G F x).monic := by { simp only [minpoly, polynomial.monic_to_subring], exact prod_X_sub_smul.monic G F x } theorem eval₂ : polynomial.eval₂ (subring.subtype $ (fixed_points.subfield G F).to_subring) x (minpoly G F x) = 0 := begin rw [← prod_X_sub_smul.eval G F x, polynomial.eval₂_eq_eval_map], simp only [minpoly, polynomial.map_to_subring], end theorem eval₂' : polynomial.eval₂ (subfield.subtype $ (fixed_points.subfield G F)) x (minpoly G F x) = 0 := eval₂ G F x theorem ne_one : minpoly G F x ≠ (1 : polynomial (fixed_points.subfield G F)) := λ H, have _ := eval₂ G F x, (one_ne_zero : (1 : F) ≠ 0) $ by rwa [H, polynomial.eval₂_one] at this theorem of_eval₂ (f : polynomial (fixed_points.subfield G F)) (hf : polynomial.eval₂ (subfield.subtype $ fixed_points.subfield G F) x f = 0) : minpoly G F x ∣ f := begin erw [← polynomial.map_dvd_map' (subfield.subtype $ fixed_points.subfield G F), minpoly, polynomial.map_to_subring _ (subfield G F).to_subring, prod_X_sub_smul], refine fintype.prod_dvd_of_coprime (polynomial.pairwise_coprime_X_sub_C $ mul_action.injective_of_quotient_stabilizer G x) (λ y, quotient_group.induction_on y $ λ g, _), rw [polynomial.dvd_iff_is_root, polynomial.is_root.def, mul_action.of_quotient_stabilizer_mk, polynomial.eval_smul', ← subfield.to_subring.subtype_eq_subtype, ← is_invariant_subring.coe_subtype_hom' G (fixed_points.subfield G F).to_subring, ← mul_semiring_action_hom.coe_polynomial, ← mul_semiring_action_hom.map_smul, smul_polynomial, mul_semiring_action_hom.coe_polynomial, is_invariant_subring.coe_subtype_hom', polynomial.eval_map, subfield.to_subring.subtype_eq_subtype, hf, smul_zero] end /- Why is this so slow? -/ theorem irreducible_aux (f g : polynomial (fixed_points.subfield G F)) (hf : f.monic) (hg : g.monic) (hfg : f * g = minpoly G F x) : f = 1 ∨ g = 1 := begin have hf2 : f ∣ minpoly G F x, { rw ← hfg, exact dvd_mul_right _ _ }, have hg2 : g ∣ minpoly G F x, { rw ← hfg, exact dvd_mul_left _ _ }, have := eval₂ G F x, rw [← hfg, polynomial.eval₂_mul, mul_eq_zero] at this, cases this, { right, have hf3 : f = minpoly G F x, { exact polynomial.eq_of_monic_of_associated hf (monic G F x) (associated_of_dvd_dvd hf2 $ @of_eval₂ G _ F _ _ _ x f this) }, rwa [← mul_one (minpoly G F x), hf3, mul_right_inj' (monic G F x).ne_zero] at hfg }, { left, have hg3 : g = minpoly G F x, { exact polynomial.eq_of_monic_of_associated hg (monic G F x) (associated_of_dvd_dvd hg2 $ @of_eval₂ G _ F _ _ _ x g this) }, rwa [← one_mul (minpoly G F x), hg3, mul_left_inj' (monic G F x).ne_zero] at hfg } end theorem irreducible : irreducible (minpoly G F x) := (polynomial.irreducible_of_monic (monic G F x) (ne_one G F x)).2 (irreducible_aux G F x) end minpoly theorem is_integral : is_integral (fixed_points.subfield G F) x := ⟨minpoly G F x, minpoly.monic G F x, minpoly.eval₂ G F x⟩ theorem minpoly_eq_minpoly : minpoly G F x = _root_.minpoly (fixed_points.subfield G F) x := minpoly.eq_of_irreducible_of_monic (minpoly.irreducible G F x) (minpoly.eval₂ G F x) (minpoly.monic G F x) instance normal : normal (fixed_points.subfield G F) F := ⟨λ x, (is_integral G F x).is_algebraic _, λ x, (polynomial.splits_id_iff_splits _).1 $ by { rw [← minpoly_eq_minpoly, minpoly, coe_algebra_map, ← subfield.to_subring.subtype_eq_subtype, polynomial.map_to_subring _ (fixed_points.subfield G F).to_subring, prod_X_sub_smul], exact polynomial.splits_prod _ (λ _ _, polynomial.splits_X_sub_C _) }⟩ instance separable : is_separable (fixed_points.subfield G F) F := ⟨λ x, is_integral G F x, λ x, by { -- this was a plain rw when we were using unbundled subrings erw [← minpoly_eq_minpoly, ← polynomial.separable_map (fixed_points.subfield G F).subtype, minpoly, polynomial.map_to_subring _ ((subfield G F).to_subring) ], exact polynomial.separable_prod_X_sub_C_iff.2 (injective_of_quotient_stabilizer G x) }⟩ lemma dim_le_card : module.rank (fixed_points.subfield G F) F ≤ fintype.card G := dim_le $ λ s hs, by simpa only [dim_fun', cardinal.mk_coe_finset, finset.coe_sort_coe, cardinal.lift_nat_cast, cardinal.nat_cast_le] using cardinal_lift_le_dim_of_linear_independent' (linear_independent_smul_of_linear_independent G F hs) instance : finite_dimensional (fixed_points.subfield G F) F := is_noetherian.iff_fg.1 $ is_noetherian.iff_dim_lt_aleph_0.2 $ lt_of_le_of_lt (dim_le_card G F) (cardinal.nat_lt_aleph_0 _) lemma finrank_le_card : finrank (fixed_points.subfield G F) F ≤ fintype.card G := begin rw [← cardinal.nat_cast_le, finrank_eq_dim], apply dim_le_card, end end fixed_points lemma linear_independent_to_linear_map (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [ring A] [algebra R A] [comm_ring B] [is_domain B] [algebra R B] : linear_independent B (alg_hom.to_linear_map : (A →ₐ[R] B) → (A →ₗ[R] B)) := have linear_independent B (linear_map.lto_fun R A B ∘ alg_hom.to_linear_map), from ((linear_independent_monoid_hom A B).comp (coe : (A →ₐ[R] B) → (A →* B)) (λ f g hfg, alg_hom.ext $ monoid_hom.ext_iff.1 hfg) : _), this.of_comp _ lemma cardinal_mk_alg_hom (K : Type u) (V : Type v) (W : Type w) [field K] [field V] [algebra K V] [finite_dimensional K V] [field W] [algebra K W] [finite_dimensional K W] : cardinal.mk (V →ₐ[K] W) ≤ finrank W (V →ₗ[K] W) := cardinal_mk_le_finrank_of_linear_independent $ linear_independent_to_linear_map K V W section alg_hom_fintype /-- A technical finiteness result. -/ noncomputable def fintype.subtype_prod {E : Type*} {X : set E} (hX : X.finite) {L : Type*} (F : E → multiset L) : fintype (Π x : X, {l : L // l ∈ F x}) := by { classical, letI : fintype X := set.finite.fintype hX, exact pi.fintype} variables (E K : Type*) [field E] [field K] [algebra F E] [algebra F K] [finite_dimensional F E] /-- Function from Hom_K(E,L) to pi type Π (x : basis), roots of min poly of x -/ -- Marked as `noncomputable!` since this definition takes multiple seconds to compile, -- and isn't very computable in practice (since neither `finrank` nor `fin_basis` are). noncomputable! def roots_of_min_poly_pi_type (φ : E →ₐ[F] K) (x : set.range (finite_dimensional.fin_basis F E : _ → E)) : {l : K // l ∈ (((minpoly F x.1).map (algebra_map F K)).roots : multiset K)} := ⟨φ x, begin rw [polynomial.mem_roots_map (minpoly.ne_zero_of_finite_field_extension F x.val), ← polynomial.alg_hom_eval₂_algebra_map, ← φ.map_zero], exact congr_arg φ (minpoly.aeval F (x : E)), end⟩ lemma aux_inj_roots_of_min_poly : function.injective (roots_of_min_poly_pi_type F E K) := begin intros f g h, suffices : (f : E →ₗ[F] K) = g, { rw linear_map.ext_iff at this, ext x, exact this x }, rw function.funext_iff at h, apply linear_map.ext_on (finite_dimensional.fin_basis F E).span_eq, rintro e he, have := (h ⟨e, he⟩), apply_fun subtype.val at this, exact this, end /-- Given field extensions `E/F` and `K/F`, with `E/F` finite, there are finitely many `F`-algebra homomorphisms `E →ₐ[K] K`. -/ noncomputable instance alg_hom.fintype : fintype (E →ₐ[F] K) := let n := finite_dimensional.finrank F E in begin let B : basis (fin n) F E := finite_dimensional.fin_basis F E, let X := set.range (B : fin n → E), have hX : X.finite := set.finite_range ⇑B, refine @fintype.of_injective _ _ (fintype.subtype_prod hX (λ e, ((minpoly F e).map (algebra_map F K)).roots)) _ (aux_inj_roots_of_min_poly F E K), end end alg_hom_fintype noncomputable instance alg_equiv.fintype (K : Type u) (V : Type v) [field K] [field V] [algebra K V] [finite_dimensional K V] : fintype (V ≃ₐ[K] V) := fintype.of_equiv (V →ₐ[K] V) (alg_equiv_equiv_alg_hom K V).symm lemma finrank_alg_hom (K : Type u) (V : Type v) [field K] [field V] [algebra K V] [finite_dimensional K V] : fintype.card (V →ₐ[K] V) ≤ finrank V (V →ₗ[K] V) := fintype_card_le_finrank_of_linear_independent $ linear_independent_to_linear_map K V V namespace fixed_points theorem finrank_eq_card (G : Type u) (F : Type v) [group G] [field F] [fintype G] [mul_semiring_action G F] [has_faithful_smul G F] : finrank (fixed_points.subfield G F) F = fintype.card G := le_antisymm (fixed_points.finrank_le_card G F) $ calc fintype.card G ≤ fintype.card (F →ₐ[fixed_points.subfield G F] F) : fintype.card_le_of_injective _ (mul_semiring_action.to_alg_hom_injective _ F) ... ≤ finrank F (F →ₗ[fixed_points.subfield G F] F) : finrank_alg_hom (fixed_points G F) F ... = finrank (fixed_points.subfield G F) F : finrank_linear_map' _ _ _ /-- `mul_semiring_action.to_alg_hom` is bijective. -/ theorem to_alg_hom_bijective (G : Type u) (F : Type v) [group G] [field F] [fintype G] [mul_semiring_action G F] [has_faithful_smul G F] : function.bijective (mul_semiring_action.to_alg_hom _ _ : G → F →ₐ[subfield G F] F) := begin rw fintype.bijective_iff_injective_and_card, split, { exact mul_semiring_action.to_alg_hom_injective _ F }, { apply le_antisymm, { exact fintype.card_le_of_injective _ (mul_semiring_action.to_alg_hom_injective _ F) }, { rw ← finrank_eq_card G F, exact has_le.le.trans_eq (finrank_alg_hom _ F) (finrank_linear_map' _ _ _) } }, end /-- Bijection between G and algebra homomorphisms that fix the fixed points -/ def to_alg_hom_equiv (G : Type u) (F : Type v) [group G] [field F] [fintype G] [mul_semiring_action G F] [has_faithful_smul G F] : G ≃ (F →ₐ[fixed_points.subfield G F] F) := equiv.of_bijective _ (to_alg_hom_bijective G F) end fixed_points
194c263c7fd81e02d6eb5d6a3af02644c6873707
8eeb99d0fdf8125f5d39a0ce8631653f588ee817
/src/category_theory/category/pairwise.lean
62efab647e67731dcc1af11a9419a5e22e147064
[ "Apache-2.0" ]
permissive
jesse-michael-han/mathlib
a15c58378846011b003669354cbab7062b893cfe
fa6312e4dc971985e6b7708d99a5bc3062485c89
refs/heads/master
1,625,200,760,912
1,602,081,753,000
1,602,081,753,000
181,787,230
0
0
null
1,555,460,682,000
1,555,460,682,000
null
UTF-8
Lean
false
false
4,356
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import topology.sheaves.sheaf import category_theory.limits.preserves.basic /-! # The category of "pairwise intersections". Given `ι : Type v`, we build the diagram category `pairwise ι` with objects `single i` and `pair i j`, for `i j : ι`, whose only non-identity morphisms are `left : single i ⟶ pair i j` and `right : single j ⟶ pair i j`. We use this later in describing the sheaf condition. Given any function `U : ι → α`, where `α` is some complete lattice (e.g. `opens X`), we produce a functor `pairwise ι ⥤ αᵒᵖ` in the obvious way, and show that `supr U` provides a limit cone over this functor. -/ noncomputable theory universes v u open topological_space open Top open opposite open category_theory open category_theory.limits namespace category_theory /-- An inductive type representing either a single term of a type `ι`, or a pair of terms. We use this as the objects of a category to describe the sheaf condition. -/ inductive pairwise (ι : Type v) | single : ι → pairwise | pair : ι → ι → pairwise variables {ι : Type v} namespace pairwise instance pairwise_inhabited [inhabited ι] : inhabited (pairwise ι) := ⟨single (default ι)⟩ /-- Morphisms in the category `pairwise ι`. The only non-identity morphisms are `left i j : single i ⟶ pair i j` and `right i j : single j ⟶ pair i j`. -/ inductive hom : pairwise ι → pairwise ι → Type v | id_single : Π i, hom (single i) (single i) | id_pair : Π i j, hom (pair i j) (pair i j) | left : Π i j, hom (single i) (pair i j) | right : Π i j, hom (single j) (pair i j) open hom instance hom_inhabited [inhabited ι] : inhabited (hom (single (default ι)) (single (default ι))) := ⟨id_single (default ι)⟩ /-- The identity morphism in `pairwise ι`. -/ def id : Π (o : pairwise ι), hom o o | (single i) := id_single i | (pair i j) := id_pair i j /-- Composition of morphisms in `pairwise ι`. -/ def comp : Π {o₁ o₂ o₃ : pairwise ι} (f : hom o₁ o₂) (g : hom o₂ o₃), hom o₁ o₃ | _ _ _ (id_single i) g := g | _ _ _ (id_pair i j) g := g | _ _ _ (left i j) (id_pair _ _) := left i j | _ _ _ (right i j) (id_pair _ _) := right i j section local attribute [tidy] tactic.case_bash instance : category (pairwise ι) := { hom := hom, id := id, comp := λ X Y Z f g, comp f g, } end variables {α : Type v} (U : ι → α) section variables [semilattice_inf α] /-- Auxilliary definition for `diagram`. -/ @[simp] def diagram_obj : pairwise ι → αᵒᵖ | (single i) := op (U i) | (pair i j) := op (U i ⊓ U j) /-- Auxilliary definition for `diagram`. -/ @[simp] def diagram_map : Π {o₁ o₂ : pairwise ι} (f : o₁ ⟶ o₂), diagram_obj U o₁ ⟶ diagram_obj U o₂ | _ _ (id_single i) := 𝟙 _ | _ _ (id_pair i j) := 𝟙 _ | _ _ (left i j) := (hom_of_le inf_le_left).op | _ _ (right i j) := (hom_of_le inf_le_right).op /-- Given a function `U : ι → α` for `[semilattice_inf α]`, we obtain a functor `pairwise ι ⥤ αᵒᵖ`, sending `single i` to `op (U i)` and `pair i j` to `op (U i ⊓ U j)`, and the morphisms to the obvious inequalities. -/ @[simps] def diagram : pairwise ι ⥤ αᵒᵖ := { obj := diagram_obj U, map := λ X Y f, diagram_map U f, } end section -- `complete_lattice` is not really needed, as we only ever use `inf`, -- but the appropriate structure has not been defined. variables [complete_lattice α] /-- Auxilliary definition for `cone`. -/ def cone_π_app : Π (o : pairwise ι), op (supr U) ⟶ diagram_obj U o | (single i) := (hom_of_le (le_supr _ _)).op | (pair i j) := (hom_of_le inf_le_left ≫ hom_of_le (le_supr U i)).op /-- Given a function `U : ι → α` for `[complete_lattice α]`, `supr U` provides a cone over `diagram U`. -/ @[simps] def cone : cone (diagram U) := { X := op (supr U), π := { app := cone_π_app U, } } /-- Given a function `U : ι → α` for `[complete_lattice α]`, `supr U` provides a limit cone over `diagram U`. -/ def cone_is_limit : is_limit (cone U) := { lift := λ s, op_hom_of_le begin apply complete_lattice.Sup_le, rintros _ ⟨j, rfl⟩, exact le_of_op_hom (s.π.app (single j)) end } end end pairwise end category_theory
72abda189abab45befab4dc382765910f5bee5f8
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/Util/Error.lean
5e353ad2fefb5181316015fa13d1d9cb5c1eac23
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,143
lean
/- Copyright (c) 2021 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ namespace Lake class MonadError (m : Type u → Type v) where error {α : Type u} : String → m α export MonadError (error) instance [MonadLift m n] [MonadError m] : MonadError n where error msg := liftM (m := m) <| error msg instance : MonadError IO where error msg := throw <| IO.userError msg instance : MonadError (EIO String) where error msg := throw msg instance : MonadError (Except String) where error msg := throw msg /-- Perform an EIO action. If it throws an error, invoke `error` with its string representation. -/ protected def MonadError.runEIO [Monad m] [MonadError m] [MonadLiftT BaseIO m] [ToString ε] (x : EIO ε α) : m α := do match (← x.toBaseIO) with | Except.ok a => pure a | Except.error e => error (toString e) /-- Perform an IO action. If it throws an error, invoke `error` with its string representation. -/ @[inline] protected def MonadError.runIO [Monad m] [MonadError m] [MonadLiftT BaseIO m] (x : IO α) : m α := MonadError.runEIO x
e1694d45f3f8f2a76c07d43cd57babb464a98a53
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Widget/InteractiveDiagnostic.lean
24d859d4b5b0679ce7c5542ceaef69c5e5ef9d8d
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
8,763
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.Linter.UnusedVariables import Lean.Server.Utils import Lean.Widget.InteractiveGoal namespace Lean.Widget open Lsp Server inductive StrictOrLazy (α β : Type) : Type | strict : α → StrictOrLazy α β | lazy : β → StrictOrLazy α β deriving Inhabited, RpcEncodable structure LazyTraceChildren where indent : Nat children : Array (WithRpcRef MessageData) deriving TypeName inductive MsgEmbed where | expr : CodeWithInfos → MsgEmbed | goal : InteractiveGoal → MsgEmbed | trace (indent : Nat) (cls : Name) (msg : TaggedText MsgEmbed) (collapsed : Bool) (children : StrictOrLazy (Array (TaggedText MsgEmbed)) (WithRpcRef LazyTraceChildren)) deriving Inhabited, RpcEncodable /-- We embed objects in LSP diagnostics by storing them in the tag of an empty subtree (`text ""`). In other words, we terminate the `MsgEmbed`-tagged tree at embedded objects and instead store the pretty-printed embed (which can itself be a `TaggedText`) in the tag. -/ abbrev InteractiveDiagnostic := Lsp.DiagnosticWith (TaggedText MsgEmbed) deriving instance RpcEncodable for Lsp.DiagnosticWith namespace InteractiveDiagnostic open MsgEmbed def toDiagnostic (diag : InteractiveDiagnostic) : Lsp.Diagnostic := { diag with message := prettyTt diag.message } where prettyTt (tt : TaggedText MsgEmbed) : String := let tt : TaggedText MsgEmbed := tt.rewrite fun | .expr tt, _ => .text tt.stripTags | .goal g, _ => .text (toString g.pretty) | .trace .., _ => .text "(trace)" tt.stripTags end InteractiveDiagnostic private def mkPPContext (nCtx : NamingContext) (ctx : MessageDataContext) : PPContext := { env := ctx.env, mctx := ctx.mctx, lctx := ctx.lctx, opts := ctx.opts, currNamespace := nCtx.currNamespace, openDecls := nCtx.openDecls } private inductive EmbedFmt /-- Tags denote `Info` objects. -/ | expr (ctx : Elab.ContextInfo) (infos : RBMap Nat Elab.Info compare) | goal (ctx : Elab.ContextInfo) (lctx : LocalContext) (g : MVarId) /-- Some messages (in particular, traces) are too costly to print eagerly. Instead, we allow the user to expand sub-traces interactively. -/ | trace (cls : Name) (msg : Format) (collapsed : Bool) (children : StrictOrLazy (Array Format) (Array MessageData)) /-- Ignore any tags in this subtree. -/ | ignoreTags deriving Inhabited private abbrev MsgFmtM := StateT (Array EmbedFmt) IO open MessageData in /-- We first build a `Nat`-tagged `Format` with the most shallow tag, if any, in every branch indexing into the array of embedded objects. -/ private partial def msgToInteractiveAux (msgData : MessageData) : IO (Format × Array EmbedFmt) := go { currNamespace := Name.anonymous, openDecls := [] } none msgData #[] where pushEmbed (e : EmbedFmt) : MsgFmtM Nat := modifyGet fun es => (es.size, es.push e) withIgnoreTags (x : MsgFmtM Format) : MsgFmtM Format := do let fmt ← x let t ← pushEmbed EmbedFmt.ignoreTags return Format.tag t fmt mkContextInfo (nCtx : NamingContext) (ctx : MessageDataContext) : Elab.ContextInfo := { env := ctx.env mctx := ctx.mctx fileMap := default options := ctx.opts currNamespace := nCtx.currNamespace openDecls := nCtx.openDecls -- Hack: to make sure unique ids created at `ppExprWithInfos` do not collide with ones in `ctx.mctx` ngen := { namePrefix := `_diag } } go : NamingContext → Option MessageDataContext → MessageData → MsgFmtM Format | _, _, ofFormat fmt => withIgnoreTags (pure fmt) | _, _, ofLevel u => return format u | _, _, ofName n => return format n | nCtx, some ctx, ofSyntax s => withIgnoreTags (ppTerm (mkPPContext nCtx ctx) ⟨s⟩) -- HACK: might not be a term | _, none, ofSyntax s => withIgnoreTags (pure s.formatStx) | _, none, ofExpr e => return format (toString e) | nCtx, some ctx, ofExpr e => do let ci := mkContextInfo nCtx ctx let (fmt, infos) ← ci.runMetaM ctx.lctx <| PrettyPrinter.ppExprWithInfos e let t ← pushEmbed <| EmbedFmt.expr ci infos return Format.tag t fmt | _, none, ofGoal mvarId => pure $ "goal " ++ format (mkMVar mvarId) | nCtx, some ctx, ofGoal mvarId => return .tag (← pushEmbed (.goal (mkContextInfo nCtx ctx) ctx.lctx mvarId)) "\n" | nCtx, _, withContext ctx d => go nCtx ctx d | _, ctx, withNamingContext nCtx d => go nCtx ctx d | nCtx, ctx, tagged _ d => go nCtx ctx d | nCtx, ctx, nest n d => Format.nest n <$> go nCtx ctx d | nCtx, ctx, compose d₁ d₂ => do let d₁ ← go nCtx ctx d₁; let d₂ ← go nCtx ctx d₂; pure $ d₁ ++ d₂ | nCtx, ctx, group d => Format.group <$> go nCtx ctx d | nCtx, ctx, .trace cls header children collapsed => do let header := (← go nCtx ctx header).nest 4 let nodes ← if collapsed && !children.isEmpty then let children := children.map fun child => MessageData.withNamingContext nCtx <| match ctx with | some ctx => MessageData.withContext ctx child | none => child pure (.lazy children) else pure (.strict (← children.mapM (go nCtx ctx))) let e := .trace cls header collapsed nodes pure (.tag (← pushEmbed e) ".\n") partial def msgToInteractive (msgData : MessageData) (hasWidgets : Bool) (indent : Nat := 0) : IO (TaggedText MsgEmbed) := do if !hasWidgets then return (TaggedText.prettyTagged (← msgData.format)).rewrite fun _ tt => .text tt.stripTags let (fmt, embeds) ← msgToInteractiveAux msgData /- Here we rewrite a `TaggedText Nat` corresponding to a whole `MessageData` into one where the tags are `TaggedText MsgEmbed`s corresponding to embedded objects with their subtree empty (`text ""`). In other words, we terminate the `MsgEmbed`-tagged -tree at embedded objects and store the pretty-printed embed (which can itself be a `TaggedText`) in the tag. -/ let rec fmtToTT (fmt : Format) (indent : Nat) : IO (TaggedText MsgEmbed) := (TaggedText.prettyTagged fmt indent).rewriteM fun (n, col) tt => match embeds[n]! with | .expr ctx infos => return .tag (.expr (tagExprInfos ctx infos tt)) default | .goal ctx lctx g => ctx.runMetaM lctx do return .tag (.goal (← goalToInteractive g)) default | .trace cls msg collapsed children => do let col := col + tt.stripTags.length - 2 let children ← match children with | .lazy children => pure <| .lazy ⟨{indent := col+2, children := children.map .mk}⟩ | .strict children => pure <| .strict (← children.mapM (fmtToTT · (col+2))) return .tag (.trace indent cls (← fmtToTT msg col) collapsed children) default | .ignoreTags => return .text tt.stripTags fmtToTT fmt indent /-- Transform a Lean Message concerning the given text into an LSP Diagnostic. -/ def msgToInteractiveDiagnostic (text : FileMap) (m : Message) (hasWidgets : Bool) : IO InteractiveDiagnostic := do let low : Lsp.Position := text.leanPosToLspPos m.pos let fullHigh := text.leanPosToLspPos <| m.endPos.getD m.pos let high : Lsp.Position := match m.endPos with | some endPos => /- Truncate messages that are more than one line long. This is a workaround to avoid big blocks of "red squiggly lines" on VS Code. TODO: should it be a parameter? -/ let endPos := if endPos.line > m.pos.line then { line := m.pos.line + 1, column := 0 } else endPos text.leanPosToLspPos endPos | none => low let range : Range := ⟨low, high⟩ let fullRange : Range := ⟨low, fullHigh⟩ let severity? := some <| match m.severity with | .information => .information | .warning => .warning | .error => .error let source? := some "Lean 4" let tags? := if m.data.isDeprecationWarning then some #[.deprecated] else if m.data.isUnusedVariableWarning then some #[.unnecessary] else none let message ← try msgToInteractive m.data hasWidgets catch ex => pure <| TaggedText.text s!"[error when printing message: {ex.toString}]" pure { range, fullRange? := some fullRange, severity?, source?, message, tags? } end Lean.Widget
8cbd35b5dc5d6eeb5c068ca64ab42c937f5ba570
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/order/filter/bases.lean
3263a60f1b22ffe99ff59a28ddd1f7fc1f3359e2
[ "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
37,231
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import order.filter.basic import data.set.countable /-! # Filter bases A filter basis `B : filter_basis α` on a type `α` is a nonempty collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. Compared to filters, filter bases do not require that any set containing an element of `B` belongs to `B`. A filter basis `B` can be used to construct `B.filter : filter α` such that a set belongs to `B.filter` if and only if it contains an element of `B`. Given an indexing type `ι`, a predicate `p : ι → Prop`, and a map `s : ι → set α`, the proposition `h : filter.is_basis p s` makes sure the range of `s` bounded by `p` (ie. `s '' set_of p`) defines a filter basis `h.filter_basis`. If one already has a filter `l` on `α`, `filter.has_basis l p s` (where `p : ι → Prop` and `s : ι → set α` as above) means that a set belongs to `l` if and only if it contains some `s i` with `p i`. It implies `h : filter.is_basis p s`, and `l = h.filter_basis.filter`. The point of this definition is that checking statements involving elements of `l` often reduces to checking them on the basis elements. We define a function `has_basis.index (h : filter.has_basis l p s) (t) (ht : t ∈ l)` that returns some index `i` such that `p i` and `s i ⊆ t`. This function can be useful to avoid manual destruction of `h.mem_iff.mpr ht` using `cases` or `let`. This file also introduces more restricted classes of bases, involving monotonicity or countability. In particular, for `l : filter α`, `l.is_countably_generated` means there is a countable set of sets which generates `s`. This is reformulated in term of bases, and consequences are derived. ## Main statements * `has_basis.mem_iff`, `has_basis.mem_of_superset`, `has_basis.mem_of_mem` : restate `t ∈ f` in terms of a basis; * `basis_sets` : all sets of a filter form a basis; * `has_basis.inf`, `has_basis.inf_principal`, `has_basis.prod`, `has_basis.prod_self`, `has_basis.map`, `has_basis.comap` : combinators to construct filters of `l ⊓ l'`, `l ⊓ 𝓟 t`, `l ×ᶠ l'`, `l ×ᶠ l`, `l.map f`, `l.comap f` respectively; * `has_basis.le_iff`, `has_basis.ge_iff`, has_basis.le_basis_iff` : restate `l ≤ l'` in terms of bases. * `has_basis.tendsto_right_iff`, `has_basis.tendsto_left_iff`, `has_basis.tendsto_iff` : restate `tendsto f l l'` in terms of bases. * `is_countably_generated_iff_exists_antimono_basis` : proves a filter is countably generated if and only if it admis a basis parametrized by a decreasing sequence of sets indexed by `ℕ`. * `tendsto_iff_seq_tendsto ` : an abstract version of "sequentially continuous implies continuous". ## Implementation notes As with `Union`/`bUnion`/`sUnion`, there are three different approaches to filter bases: * `has_basis l s`, `s : set (set α)`; * `has_basis l s`, `s : ι → set α`; * `has_basis l p s`, `p : ι → Prop`, `s : ι → set α`. We use the latter one because, e.g., `𝓝 x` in an `emetric_space` or in a `metric_space` has a basis of this form. The other two can be emulated using `s = id` or `p = λ _, true`. With this approach sometimes one needs to `simp` the statement provided by the `has_basis` machinery, e.g., `simp only [exists_prop, true_and]` or `simp only [forall_const]` can help with the case `p = λ _, true`. -/ open set filter open_locale filter classical variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} {ι' : Type*} /-- A filter basis `B` on a type `α` is a nonempty collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. -/ structure filter_basis (α : Type*) := (sets : set (set α)) (nonempty : sets.nonempty) (inter_sets {x y} : x ∈ sets → y ∈ sets → ∃ z ∈ sets, z ⊆ x ∩ y) instance filter_basis.nonempty_sets (B : filter_basis α) : nonempty B.sets := B.nonempty.to_subtype /-- If `B` is a filter basis on `α`, and `U` a subset of `α` then we can write `U ∈ B` as on paper. -/ @[reducible] instance {α : Type*}: has_mem (set α) (filter_basis α) := ⟨λ U B, U ∈ B.sets⟩ -- For illustration purposes, the filter basis defining (at_top : filter ℕ) instance : inhabited (filter_basis ℕ) := ⟨{ sets := range Ici, nonempty := ⟨Ici 0, mem_range_self 0⟩, inter_sets := begin rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, refine ⟨Ici (max n m), mem_range_self _, _⟩, rintros p p_in, split ; rw mem_Ici at *, exact le_of_max_le_left p_in, exact le_of_max_le_right p_in, end }⟩ /-- `is_basis p s` means the image of `s` bounded by `p` is a filter basis. -/ protected structure filter.is_basis (p : ι → Prop) (s : ι → set α) : Prop := (nonempty : ∃ i, p i) (inter : ∀ {i j}, p i → p j → ∃ k, p k ∧ s k ⊆ s i ∩ s j) namespace filter namespace is_basis /-- Constructs a filter basis from an indexed family of sets satisfying `is_basis`. -/ protected def filter_basis {p : ι → Prop} {s : ι → set α} (h : is_basis p s) : filter_basis α := { sets := s '' set_of p, nonempty := let ⟨i, hi⟩ := h.nonempty in ⟨s i, mem_image_of_mem s hi⟩, inter_sets := by { rintros _ _ ⟨i, hi, rfl⟩ ⟨j, hj, rfl⟩, rcases h.inter hi hj with ⟨k, hk, hk'⟩, exact ⟨_, mem_image_of_mem s hk, hk'⟩ } } variables {p : ι → Prop} {s : ι → set α} (h : is_basis p s) lemma mem_filter_basis_iff {U : set α} : U ∈ h.filter_basis ↔ ∃ i, p i ∧ s i = U := iff.rfl end is_basis end filter namespace filter_basis /-- The filter associated to a filter basis. -/ protected def filter (B : filter_basis α) : filter α := { sets := {s | ∃ t ∈ B, t ⊆ s}, univ_sets := let ⟨s, s_in⟩ := B.nonempty in ⟨s, s_in, s.subset_univ⟩, sets_of_superset := λ x y ⟨s, s_in, h⟩ hxy, ⟨s, s_in, set.subset.trans h hxy⟩, inter_sets := λ x y ⟨s, s_in, hs⟩ ⟨t, t_in, ht⟩, let ⟨u, u_in, u_sub⟩ := B.inter_sets s_in t_in in ⟨u, u_in, set.subset.trans u_sub $ set.inter_subset_inter hs ht⟩ } lemma mem_filter_iff (B : filter_basis α) {U : set α} : U ∈ B.filter ↔ ∃ s ∈ B, s ⊆ U := iff.rfl lemma mem_filter_of_mem (B : filter_basis α) {U : set α} : U ∈ B → U ∈ B.filter:= λ U_in, ⟨U, U_in, subset.refl _⟩ lemma eq_infi_principal (B : filter_basis α) : B.filter = ⨅ s : B.sets, 𝓟 s := begin have : directed (≥) (λ (s : B.sets), 𝓟 (s : set α)), { rintros ⟨U, U_in⟩ ⟨V, V_in⟩, rcases B.inter_sets U_in V_in with ⟨W, W_in, W_sub⟩, use [W, W_in], finish }, ext U, simp [mem_filter_iff, mem_infi this] end protected lemma generate (B : filter_basis α) : generate B.sets = B.filter := begin apply le_antisymm, { intros U U_in, rcases B.mem_filter_iff.mp U_in with ⟨V, V_in, h⟩, exact generate_sets.superset (generate_sets.basic V_in) h }, { rw sets_iff_generate, apply mem_filter_of_mem } end end filter_basis namespace filter namespace is_basis variables {p : ι → Prop} {s : ι → set α} /-- Constructs a filter from an indexed family of sets satisfying `is_basis`. -/ protected def filter (h : is_basis p s) : filter α := h.filter_basis.filter protected lemma mem_filter_iff (h : is_basis p s) {U : set α} : U ∈ h.filter ↔ ∃ i, p i ∧ s i ⊆ U := begin erw [h.filter_basis.mem_filter_iff], simp only [mem_filter_basis_iff h, exists_prop], split, { rintros ⟨_, ⟨i, pi, rfl⟩, h⟩, tauto }, { tauto } end lemma filter_eq_generate (h : is_basis p s) : h.filter = generate {U | ∃ i, p i ∧ s i = U} := by erw h.filter_basis.generate ; refl end is_basis /-- We say that a filter `l` has a basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`. -/ protected structure has_basis (l : filter α) (p : ι → Prop) (s : ι → set α) : Prop := (mem_iff' : ∀ (t : set α), t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t) section same_type variables {l l' : filter α} {p : ι → Prop} {s : ι → set α} {t : set α} {i : ι} {p' : ι' → Prop} {s' : ι' → set α} {i' : ι'} lemma has_basis_generate (s : set (set α)) : (generate s).has_basis (λ t, finite t ∧ t ⊆ s) (λ t, ⋂₀ t) := ⟨begin intro U, rw mem_generate_iff, apply exists_congr, tauto end⟩ /-- The smallest filter basis containing a given collection of sets. -/ def filter_basis.of_sets (s : set (set α)) : filter_basis α := { sets := sInter '' { t | finite t ∧ t ⊆ s}, nonempty := ⟨univ, ∅, ⟨⟨finite_empty, empty_subset s⟩, sInter_empty⟩⟩, inter_sets := begin rintros _ _ ⟨a, ⟨fina, suba⟩, rfl⟩ ⟨b, ⟨finb, subb⟩, rfl⟩, exact ⟨⋂₀ (a ∪ b), mem_image_of_mem _ ⟨fina.union finb, union_subset suba subb⟩, by rw sInter_union⟩, end } /-- Definition of `has_basis` unfolded with implicit set argument. -/ lemma has_basis.mem_iff (hl : l.has_basis p s) : t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t := hl.mem_iff' t lemma has_basis.eq_of_same_basis (hl : l.has_basis p s) (hl' : l'.has_basis p s) : l = l' := begin ext t, rw [hl.mem_iff, hl'.mem_iff] end lemma has_basis_iff : l.has_basis p s ↔ ∀ t, t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t := ⟨λ ⟨h⟩, h, λ h, ⟨h⟩⟩ lemma has_basis.ex_mem (h : l.has_basis p s) : ∃ i, p i := let ⟨i, pi, h⟩ := h.mem_iff.mp univ_mem_sets in ⟨i, pi⟩ protected lemma has_basis.nonempty (h : l.has_basis p s) : nonempty ι := nonempty_of_exists h.ex_mem protected lemma is_basis.has_basis (h : is_basis p s) : has_basis h.filter p s := ⟨λ t, by simp only [h.mem_filter_iff, exists_prop]⟩ lemma has_basis.mem_of_superset (hl : l.has_basis p s) (hi : p i) (ht : s i ⊆ t) : t ∈ l := (hl.mem_iff).2 ⟨i, hi, ht⟩ lemma has_basis.mem_of_mem (hl : l.has_basis p s) (hi : p i) : s i ∈ l := hl.mem_of_superset hi $ subset.refl _ /-- Index of a basis set such that `s i ⊆ t` as an element of `subtype p`. -/ noncomputable def has_basis.index (h : l.has_basis p s) (t : set α) (ht : t ∈ l) : {i : ι // p i} := ⟨(h.mem_iff.1 ht).some, (h.mem_iff.1 ht).some_spec.fst⟩ lemma has_basis.property_index (h : l.has_basis p s) (ht : t ∈ l) : p (h.index t ht) := (h.index t ht).2 lemma has_basis.set_index_mem (h : l.has_basis p s) (ht : t ∈ l) : s (h.index t ht) ∈ l := h.mem_of_mem $ h.property_index _ lemma has_basis.set_index_subset (h : l.has_basis p s) (ht : t ∈ l) : s (h.index t ht) ⊆ t := (h.mem_iff.1 ht).some_spec.snd lemma has_basis.is_basis (h : l.has_basis p s) : is_basis p s := { nonempty := let ⟨i, hi, H⟩ := h.mem_iff.mp univ_mem_sets in ⟨i, hi⟩, inter := λ i j hi hj, by simpa [h.mem_iff] using l.inter_sets (h.mem_of_mem hi) (h.mem_of_mem hj) } lemma has_basis.filter_eq (h : l.has_basis p s) : h.is_basis.filter = l := by { ext U, simp [h.mem_iff, is_basis.mem_filter_iff] } lemma has_basis.eq_generate (h : l.has_basis p s) : l = generate { U | ∃ i, p i ∧ s i = U } := by rw [← h.is_basis.filter_eq_generate, h.filter_eq] lemma generate_eq_generate_inter (s : set (set α)) : generate s = generate (sInter '' { t | finite t ∧ t ⊆ s}) := by erw [(filter_basis.of_sets s).generate, ← (has_basis_generate s).filter_eq] ; refl lemma of_sets_filter_eq_generate (s : set (set α)) : (filter_basis.of_sets s).filter = generate s := by rw [← (filter_basis.of_sets s).generate, generate_eq_generate_inter s] ; refl lemma has_basis.to_has_basis' (hl : l.has_basis p s) (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → s' i' ∈ l) : l.has_basis p' s' := begin refine ⟨λ t, ⟨λ ht, _, λ ⟨i', hi', ht⟩, mem_sets_of_superset (h' i' hi') ht⟩⟩, rcases hl.mem_iff.1 ht with ⟨i, hi, ht⟩, rcases h i hi with ⟨i', hi', hs's⟩, exact ⟨i', hi', subset.trans hs's ht⟩ end lemma has_basis.to_has_basis (hl : l.has_basis p s) (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l.has_basis p' s' := hl.to_has_basis' h $ λ i' hi', let ⟨i, hi, hss'⟩ := h' i' hi' in hl.mem_iff.2 ⟨i, hi, hss'⟩ lemma has_basis.to_subset (hl : l.has_basis p s) {t : ι → set α} (h : ∀ i, p i → t i ⊆ s i) (ht : ∀ i, p i → t i ∈ l) : l.has_basis p t := hl.to_has_basis' (λ i hi, ⟨i, hi, h i hi⟩) ht lemma has_basis.eventually_iff (hl : l.has_basis p s) {q : α → Prop} : (∀ᶠ x in l, q x) ↔ ∃ i, p i ∧ ∀ ⦃x⦄, x ∈ s i → q x := by simpa using hl.mem_iff lemma has_basis.frequently_iff (hl : l.has_basis p s) {q : α → Prop} : (∃ᶠ x in l, q x) ↔ ∀ i, p i → ∃ x ∈ s i, q x := by simp [filter.frequently, hl.eventually_iff] lemma has_basis.exists_iff (hl : l.has_basis p s) {P : set α → Prop} (mono : ∀ ⦃s t⦄, s ⊆ t → P t → P s) : (∃ s ∈ l, P s) ↔ ∃ (i) (hi : p i), P (s i) := ⟨λ ⟨s, hs, hP⟩, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in ⟨i, hi, mono his hP⟩, λ ⟨i, hi, hP⟩, ⟨s i, hl.mem_of_mem hi, hP⟩⟩ lemma has_basis.forall_iff (hl : l.has_basis p s) {P : set α → Prop} (mono : ∀ ⦃s t⦄, s ⊆ t → P s → P t) : (∀ s ∈ l, P s) ↔ ∀ i, p i → P (s i) := ⟨λ H i hi, H (s i) $ hl.mem_of_mem hi, λ H s hs, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in mono his (H i hi)⟩ lemma has_basis.ne_bot_iff (hl : l.has_basis p s) : ne_bot l ↔ (∀ {i}, p i → (s i).nonempty) := forall_sets_nonempty_iff_ne_bot.symm.trans $ hl.forall_iff $ λ _ _, nonempty.mono lemma has_basis.eq_bot_iff (hl : l.has_basis p s) : l = ⊥ ↔ ∃ i, p i ∧ s i = ∅ := not_iff_not.1 $ ne_bot_iff.symm.trans $ hl.ne_bot_iff.trans $ by simp only [not_exists, not_and, ← ne_empty_iff_nonempty] lemma basis_sets (l : filter α) : l.has_basis (λ s : set α, s ∈ l) id := ⟨λ t, exists_sets_subset_iff.symm⟩ lemma has_basis_self {l : filter α} {P : set α → Prop} : has_basis l (λ s, s ∈ l ∧ P s) id ↔ ∀ t ∈ l, ∃ r ∈ l, P r ∧ r ⊆ t := begin simp only [has_basis_iff, exists_prop, id, and_assoc], exact forall_congr (λ s, ⟨λ h, h.1, λ h, ⟨h, λ ⟨t, hl, hP, hts⟩, mem_sets_of_superset hl hts⟩⟩) end /-- If `{s i | p i}` is a basis of a filter `l` and each `s i` includes `s j` such that `p j ∧ q j`, then `{s j | p j ∧ q j}` is a basis of `l`. -/ lemma has_basis.restrict (h : l.has_basis p s) {q : ι → Prop} (hq : ∀ i, p i → ∃ j, p j ∧ q j ∧ s j ⊆ s i) : l.has_basis (λ i, p i ∧ q i) s := begin refine ⟨λ t, ⟨λ ht, _, λ ⟨i, hpi, hti⟩, h.mem_iff.2 ⟨i, hpi.1, hti⟩⟩⟩, rcases h.mem_iff.1 ht with ⟨i, hpi, hti⟩, rcases hq i hpi with ⟨j, hpj, hqj, hji⟩, exact ⟨j, ⟨hpj, hqj⟩, subset.trans hji hti⟩ end /-- If `{s i | p i}` is a basis of a filter `l` and `V ∈ l`, then `{s i | p i ∧ s i ⊆ V}` is a basis of `l`. -/ lemma has_basis.restrict_subset (h : l.has_basis p s) {V : set α} (hV : V ∈ l) : l.has_basis (λ i, p i ∧ s i ⊆ V) s := h.restrict $ λ i hi, (h.mem_iff.1 (inter_mem_sets hV (h.mem_of_mem hi))).imp $ λ j hj, ⟨hj.fst, subset_inter_iff.1 hj.snd⟩ lemma has_basis.has_basis_self_subset {p : set α → Prop} (h : l.has_basis (λ s, s ∈ l ∧ p s) id) {V : set α} (hV : V ∈ l) : l.has_basis (λ s, s ∈ l ∧ p s ∧ s ⊆ V) id := by simpa only [and_assoc] using h.restrict_subset hV theorem has_basis.ge_iff (hl' : l'.has_basis p' s') : l ≤ l' ↔ ∀ i', p' i' → s' i' ∈ l := ⟨λ h i' hi', h $ hl'.mem_of_mem hi', λ h s hs, let ⟨i', hi', hs⟩ := hl'.mem_iff.1 hs in mem_sets_of_superset (h _ hi') hs⟩ theorem has_basis.le_iff (hl : l.has_basis p s) : l ≤ l' ↔ ∀ t ∈ l', ∃ i (hi : p i), s i ⊆ t := by simp only [le_def, hl.mem_iff] theorem has_basis.le_basis_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : l ≤ l' ↔ ∀ i', p' i' → ∃ i (hi : p i), s i ⊆ s' i' := by simp only [hl'.ge_iff, hl.mem_iff] lemma has_basis.ext (hl : l.has_basis p s) (hl' : l'.has_basis p' s') (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l = l' := begin apply le_antisymm, { rw hl.le_basis_iff hl', simpa using h' }, { rw hl'.le_basis_iff hl, simpa using h }, end lemma has_basis.inf (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊓ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∩ s' i.2) := ⟨begin intro t, simp only [mem_inf_sets, exists_prop, hl.mem_iff, hl'.mem_iff], split, { rintros ⟨t, ⟨i, hi, ht⟩, t', ⟨i', hi', ht'⟩, H⟩, use [(i, i'), ⟨hi, hi'⟩, subset.trans (inter_subset_inter ht ht') H] }, { rintros ⟨⟨i, i'⟩, ⟨hi, hi'⟩, H⟩, use [s i, i, hi, subset.refl _, s' i', i', hi', subset.refl _, H] } end⟩ lemma has_basis_principal (t : set α) : (𝓟 t).has_basis (λ i : unit, true) (λ i, t) := ⟨λ U, by simp⟩ lemma has_basis.sup (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊔ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∪ s' i.2) := ⟨begin intros t, simp only [mem_sup_sets, hl.mem_iff, hl'.mem_iff, prod.exists, union_subset_iff, exists_prop, and_assoc, exists_and_distrib_left], simp only [← and_assoc, exists_and_distrib_right, and_comm] end⟩ lemma has_basis.inf_principal (hl : l.has_basis p s) (s' : set α) : (l ⊓ 𝓟 s').has_basis p (λ i, s i ∩ s') := ⟨λ t, by simp only [mem_inf_principal, hl.mem_iff, subset_def, mem_set_of_eq, mem_inter_iff, and_imp]⟩ lemma has_basis.inf_basis_ne_bot_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : ne_bot (l ⊓ l') ↔ ∀ ⦃i⦄ (hi : p i) ⦃i'⦄ (hi' : p' i'), (s i ∩ s' i').nonempty := (hl.inf hl').ne_bot_iff.trans $ by simp [@forall_swap _ ι'] lemma has_basis.inf_ne_bot_iff (hl : l.has_basis p s) : ne_bot (l ⊓ l') ↔ ∀ ⦃i⦄ (hi : p i) ⦃s'⦄ (hs' : s' ∈ l'), (s i ∩ s').nonempty := hl.inf_basis_ne_bot_iff l'.basis_sets lemma has_basis.inf_principal_ne_bot_iff (hl : l.has_basis p s) {t : set α} : ne_bot (l ⊓ 𝓟 t) ↔ ∀ ⦃i⦄ (hi : p i), (s i ∩ t).nonempty := (hl.inf_principal t).ne_bot_iff lemma inf_ne_bot_iff : ne_bot (l ⊓ l') ↔ ∀ ⦃s : set α⦄ (hs : s ∈ l) ⦃s'⦄ (hs' : s' ∈ l'), (s ∩ s').nonempty := l.basis_sets.inf_ne_bot_iff lemma inf_principal_ne_bot_iff {s : set α} : ne_bot (l ⊓ 𝓟 s) ↔ ∀ U ∈ l, (U ∩ s).nonempty := l.basis_sets.inf_principal_ne_bot_iff lemma inf_eq_bot_iff {f g : filter α} : f ⊓ g = ⊥ ↔ ∃ (U ∈ f) (V ∈ g), U ∩ V = ∅ := not_iff_not.1 $ ne_bot_iff.symm.trans $ inf_ne_bot_iff.trans $ by simp [← ne_empty_iff_nonempty] protected lemma disjoint_iff {f g : filter α} : disjoint f g ↔ ∃ (U ∈ f) (V ∈ g), U ∩ V = ∅ := disjoint_iff.trans inf_eq_bot_iff lemma mem_iff_inf_principal_compl {f : filter α} {s : set α} : s ∈ f ↔ f ⊓ 𝓟 sᶜ = ⊥ := begin refine not_iff_not.1 ((inf_principal_ne_bot_iff.trans _).symm.trans ne_bot_iff), exact ⟨λ h hs, by simpa [empty_not_nonempty] using h s hs, λ hs t ht, inter_compl_nonempty_iff.2 $ λ hts, hs $ mem_sets_of_superset ht hts⟩, end lemma not_mem_iff_inf_principal_compl {f : filter α} {s : set α} : s ∉ f ↔ ne_bot (f ⊓ 𝓟 sᶜ) := (not_congr mem_iff_inf_principal_compl).trans ne_bot_iff.symm lemma mem_iff_disjoint_principal_compl {f : filter α} {s : set α} : s ∈ f ↔ disjoint f (𝓟 sᶜ) := mem_iff_inf_principal_compl.trans disjoint_iff.symm lemma le_iff_forall_disjoint_principal_compl {f g : filter α} : f ≤ g ↔ ∀ V ∈ g, disjoint f (𝓟 Vᶜ) := forall_congr $ λ _, forall_congr $ λ _, mem_iff_disjoint_principal_compl lemma le_iff_forall_inf_principal_compl {f g : filter α} : f ≤ g ↔ ∀ V ∈ g, f ⊓ 𝓟 Vᶜ = ⊥ := forall_congr $ λ _, forall_congr $ λ _, mem_iff_inf_principal_compl lemma inf_ne_bot_iff_frequently_left {f g : filter α} : ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in f, p x) → ∃ᶠ x in g, p x := by simpa only [inf_ne_bot_iff, frequently_iff, exists_prop, and_comm] lemma inf_ne_bot_iff_frequently_right {f g : filter α} : ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in g, p x) → ∃ᶠ x in f, p x := by { rw inf_comm, exact inf_ne_bot_iff_frequently_left } lemma has_basis.eq_binfi (h : l.has_basis p s) : l = ⨅ i (_ : p i), 𝓟 (s i) := eq_binfi_of_mem_sets_iff_exists_mem $ λ t, by simp only [h.mem_iff, mem_principal_sets] lemma has_basis.eq_infi (h : l.has_basis (λ _, true) s) : l = ⨅ i, 𝓟 (s i) := by simpa only [infi_true] using h.eq_binfi lemma has_basis_infi_principal {s : ι → set α} (h : directed (≥) s) [nonempty ι] : (⨅ i, 𝓟 (s i)).has_basis (λ _, true) s := ⟨begin refine λ t, (mem_infi (h.mono_comp _ _) t).trans $ by simp only [exists_prop, true_and, mem_principal_sets], exact λ _ _, principal_mono.2 end⟩ /-- If `s : ι → set α` is an indexed family of sets, then finite intersections of `s i` form a basis of `⨅ i, 𝓟 (s i)`. -/ lemma has_basis_infi_principal_finite (s : ι → set α) : (⨅ i, 𝓟 (s i)).has_basis (λ t : set ι, finite t) (λ t, ⋂ i ∈ t, s i) := begin refine ⟨λ U, (mem_infi_finite _).trans _⟩, simp only [infi_principal_finset, mem_Union, mem_principal_sets, exists_prop, exists_finite_iff_finset, finset.set_bInter_coe] end lemma has_basis_binfi_principal {s : β → set α} {S : set β} (h : directed_on (s ⁻¹'o (≥)) S) (ne : S.nonempty) : (⨅ i ∈ S, 𝓟 (s i)).has_basis (λ i, i ∈ S) s := ⟨begin refine λ t, (mem_binfi _ ne).trans $ by simp only [mem_principal_sets], rw [directed_on_iff_directed, ← directed_comp, (∘)] at h ⊢, apply h.mono_comp _ _, exact λ _ _, principal_mono.2 end⟩ lemma has_basis_binfi_principal' (h : ∀ i, p i → ∀ j, p j → ∃ k (h : p k), s k ⊆ s i ∧ s k ⊆ s j) (ne : ∃ i, p i) : (⨅ i (h : p i), 𝓟 (s i)).has_basis p s := filter.has_basis_binfi_principal h ne lemma has_basis.map (f : α → β) (hl : l.has_basis p s) : (l.map f).has_basis p (λ i, f '' (s i)) := ⟨λ t, by simp only [mem_map, image_subset_iff, hl.mem_iff, preimage]⟩ lemma has_basis.comap (f : β → α) (hl : l.has_basis p s) : (l.comap f).has_basis p (λ i, f ⁻¹' (s i)) := ⟨begin intro t, simp only [mem_comap_sets, exists_prop, hl.mem_iff], split, { rintros ⟨t', ⟨i, hi, ht'⟩, H⟩, exact ⟨i, hi, subset.trans (preimage_mono ht') H⟩ }, { rintros ⟨i, hi, H⟩, exact ⟨s i, ⟨i, hi, subset.refl _⟩, H⟩ } end⟩ lemma comap_has_basis (f : α → β) (l : filter β) : has_basis (comap f l) (λ s : set β, s ∈ l) (λ s, f ⁻¹' s) := ⟨λ t, mem_comap_sets⟩ lemma has_basis.prod_self (hl : l.has_basis p s) : (l ×ᶠ l).has_basis p (λ i, (s i).prod (s i)) := ⟨begin intro t, apply mem_prod_iff.trans, split, { rintros ⟨t₁, ht₁, t₂, ht₂, H⟩, rcases hl.mem_iff.1 (inter_mem_sets ht₁ ht₂) with ⟨i, hi, ht⟩, exact ⟨i, hi, λ p ⟨hp₁, hp₂⟩, H ⟨(ht hp₁).1, (ht hp₂).2⟩⟩ }, { rintros ⟨i, hi, H⟩, exact ⟨s i, hl.mem_of_mem hi, s i, hl.mem_of_mem hi, H⟩ } end⟩ lemma mem_prod_self_iff {s} : s ∈ l ×ᶠ l ↔ ∃ t ∈ l, set.prod t t ⊆ s := l.basis_sets.prod_self.mem_iff lemma has_basis.sInter_sets (h : has_basis l p s) : ⋂₀ l.sets = ⋂ i ∈ set_of p, s i := begin ext x, suffices : (∀ t ∈ l, x ∈ t) ↔ ∀ i, p i → x ∈ s i, by simpa only [mem_Inter, mem_set_of_eq, mem_sInter], simp_rw h.mem_iff, split, { intros h i hi, exact h (s i) ⟨i, hi, subset.refl _⟩ }, { rintros h _ ⟨i, hi, sub⟩, exact sub (h i hi) }, end variables [preorder ι] (l p s) /-- `is_antimono_basis p s` means the image of `s` bounded by `p` is a filter basis such that `s` is decreasing and `p` is increasing, ie `i ≤ j → p i → p j`. -/ structure is_antimono_basis extends is_basis p s : Prop := (decreasing : ∀ {i j}, p i → p j → i ≤ j → s j ⊆ s i) (mono : monotone p) /-- We say that a filter `l` has a antimono basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`, and `s` is decreasing and `p` is increasing, ie `i ≤ j → p i → p j`. -/ structure has_antimono_basis [preorder ι] (l : filter α) (p : ι → Prop) (s : ι → set α) extends has_basis l p s : Prop := (decreasing : ∀ {i j}, p i → p j → i ≤ j → s j ⊆ s i) (mono : monotone p) end same_type section two_types variables {la : filter α} {pa : ι → Prop} {sa : ι → set α} {lb : filter β} {pb : ι' → Prop} {sb : ι' → set β} {f : α → β} lemma has_basis.tendsto_left_iff (hla : la.has_basis pa sa) : tendsto f la lb ↔ ∀ t ∈ lb, ∃ i (hi : pa i), ∀ x ∈ sa i, f x ∈ t := by { simp only [tendsto, (hla.map f).le_iff, image_subset_iff], refl } lemma has_basis.tendsto_right_iff (hlb : lb.has_basis pb sb) : tendsto f la lb ↔ ∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i := by simp only [tendsto, hlb.ge_iff, mem_map, filter.eventually] lemma has_basis.tendsto_iff (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : tendsto f la lb ↔ ∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib := by simp [hlb.tendsto_right_iff, hla.eventually_iff] lemma tendsto.basis_left (H : tendsto f la lb) (hla : la.has_basis pa sa) : ∀ t ∈ lb, ∃ i (hi : pa i), ∀ x ∈ sa i, f x ∈ t := hla.tendsto_left_iff.1 H lemma tendsto.basis_right (H : tendsto f la lb) (hlb : lb.has_basis pb sb) : ∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i := hlb.tendsto_right_iff.1 H lemma tendsto.basis_both (H : tendsto f la lb) (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : ∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib := (hla.tendsto_iff hlb).1 H lemma has_basis.prod (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : (la ×ᶠ lb).has_basis (λ i : ι × ι', pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) := (hla.comap prod.fst).inf (hlb.comap prod.snd) lemma has_basis.prod' {la : filter α} {lb : filter β} {ι : Type*} {p : ι → Prop} {sa : ι → set α} {sb : ι → set β} (hla : la.has_basis p sa) (hlb : lb.has_basis p sb) (h_dir : ∀ {i j}, p i → p j → ∃ k, p k ∧ sa k ⊆ sa i ∧ sb k ⊆ sb j) : (la ×ᶠ lb).has_basis p (λ i, (sa i).prod (sb i)) := ⟨begin intros t, rw mem_prod_iff, split, { rintros ⟨u, u_in, v, v_in, huv⟩, rcases hla.mem_iff.mp u_in with ⟨i, hi, si⟩, rcases hlb.mem_iff.mp v_in with ⟨j, hj, sj⟩, rcases h_dir hi hj with ⟨k, hk, ki, kj⟩, use [k, hk], calc (sa k).prod (sb k) ⊆ (sa i).prod (sb j) : set.prod_mono ki kj ... ⊆ u.prod v : set.prod_mono si sj ... ⊆ t : huv, }, { rintro ⟨i, hi, h⟩, exact ⟨sa i, hla.mem_of_mem hi, sb i, hlb.mem_of_mem hi, h⟩ }, end⟩ end two_types /-- `is_countably_generated f` means `f = generate s` for some countable `s`. -/ def is_countably_generated (f : filter α) : Prop := ∃ s : set (set α), countable s ∧ f = generate s /-- `is_countable_basis p s` means the image of `s` bounded by `p` is a countable filter basis. -/ structure is_countable_basis (p : ι → Prop) (s : ι → set α) extends is_basis p s : Prop := (countable : countable $ set_of p) /-- We say that a filter `l` has a countable basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`, and the set defined by `p` is countable. -/ structure has_countable_basis (l : filter α) (p : ι → Prop) (s : ι → set α) extends has_basis l p s : Prop := (countable : countable $ set_of p) /-- A countable filter basis `B` on a type `α` is a nonempty countable collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. -/ structure countable_filter_basis (α : Type*) extends filter_basis α := (countable : countable sets) -- For illustration purposes, the countable filter basis defining (at_top : filter ℕ) instance nat.inhabited_countable_filter_basis : inhabited (countable_filter_basis ℕ) := ⟨{ countable := countable_range (λ n, Ici n), ..(default $ filter_basis ℕ),}⟩ lemma antimono_seq_of_seq (s : ℕ → set α) : ∃ t : ℕ → set α, (∀ i j, i ≤ j → t j ⊆ t i) ∧ (⨅ i, 𝓟 $ s i) = ⨅ i, 𝓟 (t i) := begin use λ n, ⋂ m ≤ n, s m, split, { exact λ i j hij, bInter_mono' (Iic_subset_Iic.2 hij) (λ n hn, subset.refl _) }, apply le_antisymm; rw le_infi_iff; intro i, { rw le_principal_iff, refine (bInter_mem_sets (finite_le_nat _)).2 (λ j hji, _), rw ← le_principal_iff, apply infi_le_of_le j _, apply le_refl _ }, { apply infi_le_of_le i _, rw principal_mono, intro a, simp, intro h, apply h, refl }, end lemma countable_binfi_eq_infi_seq [complete_lattice α] {B : set ι} (Bcbl : countable B) (Bne : B.nonempty) (f : ι → α) : ∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) := begin rw countable_iff_exists_surjective_to_subtype Bne at Bcbl, rcases Bcbl with ⟨g, gsurj⟩, rw infi_subtype', use (λ n, g n), apply le_antisymm; rw le_infi_iff, { intro i, apply infi_le_of_le (g i) _, apply le_refl _ }, { intros a, rcases gsurj a with ⟨i, rfl⟩, apply infi_le } end lemma countable_binfi_eq_infi_seq' [complete_lattice α] {B : set ι} (Bcbl : countable B) (f : ι → α) {i₀ : ι} (h : f i₀ = ⊤) : ∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) := begin cases B.eq_empty_or_nonempty with hB Bnonempty, { rw [hB, infi_emptyset], use λ n, i₀, simp [h] }, { exact countable_binfi_eq_infi_seq Bcbl Bnonempty f } end lemma countable_binfi_principal_eq_seq_infi {B : set (set α)} (Bcbl : countable B) : ∃ (x : ℕ → set α), (⨅ t ∈ B, 𝓟 t) = ⨅ i, 𝓟 (x i) := countable_binfi_eq_infi_seq' Bcbl 𝓟 principal_univ namespace is_countably_generated /-- A set generating a countably generated filter. -/ def generating_set {f : filter α} (h : is_countably_generated f) := classical.some h lemma countable_generating_set {f : filter α} (h : is_countably_generated f) : countable h.generating_set := (classical.some_spec h).1 lemma eq_generate {f : filter α} (h : is_countably_generated f) : f = generate h.generating_set := (classical.some_spec h).2 /-- A countable filter basis for a countably generated filter. -/ def countable_filter_basis {l : filter α} (h : is_countably_generated l) : countable_filter_basis α := { countable := (countable_set_of_finite_subset h.countable_generating_set).image _, ..filter_basis.of_sets (h.generating_set) } lemma filter_basis_filter {l : filter α} (h : is_countably_generated l) : h.countable_filter_basis.to_filter_basis.filter = l := begin conv_rhs { rw h.eq_generate }, apply of_sets_filter_eq_generate, end lemma has_countable_basis {l : filter α} (h : is_countably_generated l) : l.has_countable_basis (λ t, finite t ∧ t ⊆ h.generating_set) (λ t, ⋂₀ t) := ⟨by convert has_basis_generate _ ; exact h.eq_generate, countable_set_of_finite_subset h.countable_generating_set⟩ lemma exists_countable_infi_principal {f : filter α} (h : f.is_countably_generated) : ∃ s : set (set α), countable s ∧ f = ⨅ t ∈ s, 𝓟 t := begin let B := h.countable_filter_basis, use [B.sets, B.countable], rw ← h.filter_basis_filter, rw B.to_filter_basis.eq_infi_principal, rw infi_subtype'' end lemma exists_seq {f : filter α} (cblb : f.is_countably_generated) : ∃ x : ℕ → set α, f = ⨅ i, 𝓟 (x i) := begin rcases cblb.exists_countable_infi_principal with ⟨B, Bcbl, rfl⟩, exact countable_binfi_principal_eq_seq_infi Bcbl, end /-- If `f` is countably generated and `f.has_basis p s`, then `f` admits a decreasing basis enumerated by natural numbers such that all sets have the form `s i`. More precisely, there is a sequence `i n` such that `p (i n)` for all `n` and `s (i n)` is a decreasing sequence of sets which forms a basis of `f`-/ lemma exists_antimono_subbasis {f : filter α} (cblb : f.is_countably_generated) {p : ι → Prop} {s : ι → set α} (hs : f.has_basis p s) : ∃ x : ℕ → ι, (∀ i, p (x i)) ∧ f.has_antimono_basis (λ _, true) (λ i, s (x i)) := begin rcases cblb.exists_seq with ⟨x', hx'⟩, have : ∀ i, x' i ∈ f := λ i, hx'.symm ▸ (infi_le (λ i, 𝓟 (x' i)) i) (mem_principal_self _), let x : ℕ → {i : ι // p i} := λ n, nat.rec_on n (hs.index _ $ this 0) (λ n xn, (hs.index _ $ inter_mem_sets (this $ n + 1) (hs.mem_of_mem xn.coe_prop))), have x_mono : ∀ n : ℕ, s (x n.succ) ⊆ s (x n) := λ n, subset.trans (hs.set_index_subset _) (inter_subset_right _ _), replace x_mono : ∀ ⦃i j⦄, i ≤ j → s (x j) ≤ s (x i), { refine @monotone_of_monotone_nat (order_dual $ set α) _ _ _, exact x_mono }, have x_subset : ∀ i, s (x i) ⊆ x' i, { rintro (_|i), exacts [hs.set_index_subset _, subset.trans (hs.set_index_subset _) (inter_subset_left _ _)] }, refine ⟨λ i, x i, λ i, (x i).2, _⟩, have : (⨅ i, 𝓟 (s (x i))).has_antimono_basis (λ _, true) (λ i, s (x i)) := ⟨has_basis_infi_principal (directed_of_sup x_mono), λ i j _ _ hij, x_mono hij, monotone_const⟩, convert this, exact le_antisymm (le_infi $ λ i, le_principal_iff.2 $ by cases i; apply hs.set_index_mem) (hx'.symm ▸ le_infi (λ i, le_principal_iff.2 $ this.to_has_basis.mem_iff.2 ⟨i, trivial, x_subset i⟩)) end /-- A countably generated filter admits a basis formed by a monotonically decreasing sequence of sets. -/ lemma exists_antimono_basis {f : filter α} (cblb : f.is_countably_generated) : ∃ x : ℕ → set α, f.has_antimono_basis (λ _, true) x := let ⟨x, hxf, hx⟩ := cblb.exists_antimono_subbasis f.basis_sets in ⟨x, hx⟩ end is_countably_generated lemma has_countable_basis.is_countably_generated {f : filter α} {p : ι → Prop} {s : ι → set α} (h : f.has_countable_basis p s) : f.is_countably_generated := ⟨{t | ∃ i, p i ∧ s i = t}, h.countable.image s, h.to_has_basis.eq_generate⟩ lemma is_countably_generated_seq (x : ℕ → set α) : is_countably_generated (⨅ i, 𝓟 $ x i) := begin rcases antimono_seq_of_seq x with ⟨y, am, h⟩, rw h, use [range y, countable_range _], rw (has_basis_infi_principal _).eq_generate, { simp [range] }, { exact directed_of_sup am }, { use 0 }, end lemma is_countably_generated_of_seq {f : filter α} (h : ∃ x : ℕ → set α, f = ⨅ i, 𝓟 $ x i) : f.is_countably_generated := let ⟨x, h⟩ := h in by rw h ; apply is_countably_generated_seq lemma is_countably_generated_binfi_principal {B : set $ set α} (h : countable B) : is_countably_generated (⨅ (s ∈ B), 𝓟 s) := is_countably_generated_of_seq (countable_binfi_principal_eq_seq_infi h) lemma is_countably_generated_iff_exists_antimono_basis {f : filter α} : is_countably_generated f ↔ ∃ x : ℕ → set α, f.has_antimono_basis (λ _, true) x := begin split, { exact λ h, h.exists_antimono_basis }, { rintros ⟨x, h⟩, rw h.to_has_basis.eq_infi, exact is_countably_generated_seq x }, end lemma is_countably_generated_principal (s : set α) : is_countably_generated (𝓟 s) := begin rw show 𝓟 s = ⨅ i : ℕ, 𝓟 s, by simp, apply is_countably_generated_seq end namespace is_countably_generated lemma inf {f g : filter α} (hf : is_countably_generated f) (hg : is_countably_generated g) : is_countably_generated (f ⊓ g) := begin rw is_countably_generated_iff_exists_antimono_basis at hf hg, rcases hf with ⟨s, hs⟩, rcases hg with ⟨t, ht⟩, exact has_countable_basis.is_countably_generated ⟨hs.to_has_basis.inf ht.to_has_basis, set.countable_encodable _⟩ end lemma inf_principal {f : filter α} (h : is_countably_generated f) (s : set α) : is_countably_generated (f ⊓ 𝓟 s) := h.inf (filter.is_countably_generated_principal s) lemma exists_antimono_seq' {f : filter α} (cblb : f.is_countably_generated) : ∃ x : ℕ → set α, (∀ i j, i ≤ j → x j ⊆ x i) ∧ ∀ {s}, (s ∈ f ↔ ∃ i, x i ⊆ s) := let ⟨x, hx⟩ := is_countably_generated_iff_exists_antimono_basis.mp cblb in ⟨x, λ i j, hx.decreasing trivial trivial, λ s, by simp [hx.to_has_basis.mem_iff]⟩ protected lemma comap {l : filter β} (h : l.is_countably_generated) (f : α → β) : (comap f l).is_countably_generated := let ⟨x, hx_mono⟩ := h.exists_antimono_basis in is_countably_generated_of_seq ⟨_, (hx_mono.to_has_basis.comap _).eq_infi⟩ end is_countably_generated end filter
1465636578eaba1a0d9bedc33a54c0b268ce19a6
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/GeneralizeVars.lean
4ee1322c6cd2ac69a912928622a1cfcd2abe7c3c
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
2,748
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Basic import Lean.Util.CollectFVars namespace Lean.Meta /-- Add to `forbidden` all a set of `FVarId`s containing `targets` and all variables they depend on. -/ partial def mkGeneralizationForbiddenSet (targets : Array Expr) (forbidden : FVarIdSet := {}) : MetaM FVarIdSet := do let mut s := { fvarSet := forbidden } let mut todo := #[] for target in targets do if target.isFVar then todo := todo.push target.fvarId! else s := collectFVars s (← instantiateMVars (← inferType target)) loop todo.toList s.fvarSet where visit (fvarId : FVarId) (todo : List FVarId) (s : FVarIdSet) : MetaM (List FVarId × FVarIdSet) := do let localDecl ← getLocalDecl fvarId let mut s' := collectFVars {} (← instantiateMVars localDecl.type) if let some val := localDecl.value? then s' := collectFVars s' (← instantiateMVars val) let mut todo := todo let mut s := s for fvarId in s'.fvarSet do unless s.contains fvarId do todo := fvarId :: todo s := s.insert fvarId return (todo, s) loop (todo : List FVarId) (s : FVarIdSet) : MetaM FVarIdSet := do match todo with | [] => return s | fvarId::todo => if s.contains fvarId then loop todo s else let (todo, s) ← visit fvarId todo <| s.insert fvarId loop todo s /-- Collect variables to be generalized. It uses the following heuristic - Collect forward dependencies that are not in the forbidden set, and depend on some variable in `targets`. - We use `mkForbiddenSet` to compute `forbidden`. Remark: we *not* collect instance implicit arguments nor auxiliary declarations for compiling recursive declarations. -/ def getFVarSetToGeneralize (targets : Array Expr) (forbidden : FVarIdSet) : MetaM FVarIdSet := do let mut s : FVarIdSet := targets.foldl (init := {}) fun s target => if target.isFVar then s.insert target.fvarId! else s let mut r : FVarIdSet := {} for localDecl in (← getLCtx) do unless forbidden.contains localDecl.fvarId do unless localDecl.isAuxDecl || localDecl.binderInfo.isInstImplicit do if (← getMCtx).findLocalDeclDependsOn localDecl fun fvarId => s.contains fvarId then r := r.insert localDecl.fvarId s := s.insert localDecl.fvarId return r def getFVarsToGeneralize (targets : Array Expr) (forbidden : FVarIdSet := {}) : MetaM (Array FVarId) := do let forbidden ← mkGeneralizationForbiddenSet targets forbidden let s ← getFVarSetToGeneralize targets forbidden sortFVarIds s.toArray end Lean.Meta
f63a270d56a1044466062a27b7748ca2dae2a9d6
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/extra/616b.hlean
15cb89434be185461743518a0fc946b33910ad94
[ "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
249
hlean
import .f616a open eq definition my_elim {A P : Type*} {R : A → A → Type*} (Pc : A → P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') (x : quotient R) : P := begin induction x, exact (Pc a), refine (pathover_of_eq (Pp H)) end
4660162df34a48b00bead920ad30fa76c2af7794
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/index.lean
79b83b7e5edc44938243d32e16299aed9dcddf4c
[ "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
11,214
lean
/- Copyright (c) 2021 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import group_theory.quotient_group import set_theory.cardinal.finite /-! # Index of a Subgroup In this file we define the index of a subgroup, and prove several divisibility properties. Several theorems proved in this file are known as Lagrange's theorem. ## Main definitions - `H.index` : the index of `H : subgroup G` as a natural number, and returns 0 if the index is infinite. - `H.relindex K` : the relative index of `H : subgroup G` in `K : subgroup G` as a natural number, and returns 0 if the relative index is infinite. # Main results - `card_mul_index` : `nat.card H * H.index = nat.card G` - `index_mul_card` : `H.index * fintype.card H = fintype.card G` - `index_dvd_card` : `H.index ∣ fintype.card G` - `index_eq_mul_of_le` : If `H ≤ K`, then `H.index = K.index * (H.subgroup_of K).index` - `index_dvd_of_le` : If `H ≤ K`, then `K.index ∣ H.index` - `relindex_mul_relindex` : `relindex` is multiplicative in towers -/ namespace subgroup open_locale cardinal variables {G : Type*} [group G] (H K L : subgroup G) /-- The index of a subgroup as a natural number, and returns 0 if the index is infinite. -/ @[to_additive "The index of a subgroup as a natural number, and returns 0 if the index is infinite."] noncomputable def index : ℕ := nat.card (G ⧸ H) /-- The relative index of a subgroup as a natural number, and returns 0 if the relative index is infinite. -/ @[to_additive "The relative index of a subgroup as a natural number, and returns 0 if the relative index is infinite."] noncomputable def relindex : ℕ := (H.subgroup_of K).index @[to_additive] lemma index_comap_of_surjective {G' : Type*} [group G'] {f : G' →* G} (hf : function.surjective f) : (H.comap f).index = H.index := begin letI := quotient_group.left_rel H, letI := quotient_group.left_rel (H.comap f), have key : ∀ x y : G', setoid.r x y ↔ setoid.r (f x) (f y) := λ x y, iff_of_eq (congr_arg (∈ H) (by rw [f.map_mul, f.map_inv])), refine cardinal.to_nat_congr (equiv.of_bijective (quotient.map' f (λ x y, (key x y).mp)) ⟨_, _⟩), { simp_rw [←quotient.eq'] at key, refine quotient.ind' (λ x, _), refine quotient.ind' (λ y, _), exact (key x y).mpr }, { refine quotient.ind' (λ x, _), obtain ⟨y, hy⟩ := hf x, exact ⟨y, (quotient.map'_mk' f _ y).trans (congr_arg quotient.mk' hy)⟩ }, end @[to_additive] lemma index_comap {G' : Type*} [group G'] (f : G' →* G) : (H.comap f).index = H.relindex f.range := eq.trans (congr_arg index (by refl)) ((H.subgroup_of f.range).index_comap_of_surjective f.range_restrict_surjective) variables {H K L} @[to_additive relindex_mul_index] lemma relindex_mul_index (h : H ≤ K) : H.relindex K * K.index = H.index := ((mul_comm _ _).trans (cardinal.to_nat_mul _ _).symm).trans (congr_arg cardinal.to_nat (equiv.cardinal_eq (quotient_equiv_prod_of_le h))).symm @[to_additive] lemma index_dvd_of_le (h : H ≤ K) : K.index ∣ H.index := dvd_of_mul_left_eq (H.relindex K) (relindex_mul_index h) @[to_additive] lemma relindex_subgroup_of (hKL : K ≤ L) : (H.subgroup_of L).relindex (K.subgroup_of L) = H.relindex K := ((index_comap (H.subgroup_of L) (inclusion hKL)).trans (congr_arg _ (inclusion_range hKL))).symm variables (H K L) @[to_additive relindex_mul_relindex] lemma relindex_mul_relindex (hHK : H ≤ K) (hKL : K ≤ L) : H.relindex K * K.relindex L = H.relindex L := begin rw [←relindex_subgroup_of hKL], exact relindex_mul_index (λ x hx, hHK hx), end @[to_additive] lemma inf_relindex_right : (H ⊓ K).relindex K = H.relindex K := begin rw [←subgroup_of_map_subtype, relindex, relindex, subgroup_of, comap_map_eq_self_of_injective], exact subtype.coe_injective, end @[to_additive] lemma inf_relindex_left : (H ⊓ K).relindex H = K.relindex H := by rw [inf_comm, inf_relindex_right] @[to_additive relindex_inf_mul_relindex] lemma relindex_inf_mul_relindex : H.relindex (K ⊓ L) * K.relindex L = (H ⊓ K).relindex L := by rw [←inf_relindex_right H (K ⊓ L), ←inf_relindex_right K L, ←inf_relindex_right (H ⊓ K) L, inf_assoc, relindex_mul_relindex (H ⊓ (K ⊓ L)) (K ⊓ L) L inf_le_right inf_le_right] @[to_additive] lemma inf_relindex_eq_relindex_sup [K.normal] : (H ⊓ K).relindex H = K.relindex (H ⊔ K) := cardinal.to_nat_congr (quotient_group.quotient_inf_equiv_prod_normal_quotient H K).to_equiv @[to_additive] lemma relindex_eq_relindex_sup [K.normal] : K.relindex H = K.relindex (H ⊔ K) := by rw [←inf_relindex_left, inf_relindex_eq_relindex_sup] variables {H K} @[to_additive] lemma relindex_dvd_of_le_left (hHK : H ≤ K) : K.relindex L ∣ H.relindex L := begin apply dvd_of_mul_left_eq ((H ⊓ L).relindex (K ⊓ L)), rw [←inf_relindex_right H L, ←inf_relindex_right K L], exact relindex_mul_relindex (H ⊓ L) (K ⊓ L) L (inf_le_inf_right L hHK) inf_le_right, end variables (H K) @[simp, to_additive] lemma index_top : (⊤ : subgroup G).index = 1 := cardinal.to_nat_eq_one_iff_unique.mpr ⟨quotient_group.subsingleton_quotient_top, ⟨1⟩⟩ @[simp, to_additive] lemma index_bot : (⊥ : subgroup G).index = nat.card G := cardinal.to_nat_congr (quotient_group.quotient_bot.to_equiv) @[to_additive] lemma index_bot_eq_card [fintype G] : (⊥ : subgroup G).index = fintype.card G := index_bot.trans nat.card_eq_fintype_card @[simp, to_additive] lemma relindex_top_left : (⊤ : subgroup G).relindex H = 1 := index_top @[simp, to_additive] lemma relindex_top_right : H.relindex ⊤ = H.index := by rw [←relindex_mul_index (show H ≤ ⊤, from le_top), index_top, mul_one] @[simp, to_additive] lemma relindex_bot_left : (⊥ : subgroup G).relindex H = nat.card H := by rw [relindex, bot_subgroup_of, index_bot] @[to_additive] lemma relindex_bot_left_eq_card [fintype H] : (⊥ : subgroup G).relindex H = fintype.card H := H.relindex_bot_left.trans nat.card_eq_fintype_card @[simp, to_additive] lemma relindex_bot_right : H.relindex ⊥ = 1 := by rw [relindex, subgroup_of_bot_eq_top, index_top] @[simp, to_additive] lemma relindex_self : H.relindex H = 1 := by rw [relindex, subgroup_of_self, index_top] @[simp, to_additive card_mul_index] lemma card_mul_index : nat.card H * H.index = nat.card G := by { rw [←relindex_bot_left, ←index_bot], exact relindex_mul_index bot_le } @[to_additive] lemma index_map {G' : Type*} [group G'] (f : G →* G') : (H.map f).index = (H ⊔ f.ker).index * f.range.index := by rw [←comap_map_eq, index_comap, relindex_mul_index (H.map_le_range f)] @[to_additive] lemma index_map_dvd {G' : Type*} [group G'] {f : G →* G'} (hf : function.surjective f) : (H.map f).index ∣ H.index := begin rw [index_map, f.range_top_of_surjective hf, index_top, mul_one], exact index_dvd_of_le le_sup_left, end @[to_additive] lemma dvd_index_map {G' : Type*} [group G'] {f : G →* G'} (hf : f.ker ≤ H) : H.index ∣ (H.map f).index := begin rw [index_map, sup_of_le_left hf], apply dvd_mul_right, end @[to_additive] lemma index_map_eq {G' : Type*} [group G'] {f : G →* G'} (hf1 : function.surjective f) (hf2 : f.ker ≤ H) : (H.map f).index = H.index := nat.dvd_antisymm (H.index_map_dvd hf1) (H.dvd_index_map hf2) @[to_additive] lemma index_eq_card [fintype (G ⧸ H)] : H.index = fintype.card (G ⧸ H) := nat.card_eq_fintype_card @[to_additive index_mul_card] lemma index_mul_card [fintype G] [hH : fintype H] : H.index * fintype.card H = fintype.card G := by rw [←relindex_bot_left_eq_card, ←index_bot_eq_card, mul_comm]; exact relindex_mul_index bot_le @[to_additive] lemma index_dvd_card [fintype G] : H.index ∣ fintype.card G := begin classical, exact ⟨fintype.card H, H.index_mul_card.symm⟩, end variables {H K L} @[to_additive] lemma relindex_eq_zero_of_le_left (hHK : H ≤ K) (hKL : K.relindex L = 0) : H.relindex L = 0 := eq_zero_of_zero_dvd (hKL ▸ (relindex_dvd_of_le_left L hHK)) @[to_additive] lemma relindex_eq_zero_of_le_right (hKL : K ≤ L) (hHK : H.relindex K = 0) : H.relindex L = 0 := cardinal.to_nat_apply_of_omega_le (le_trans (le_of_not_lt (λ h, cardinal.mk_ne_zero _ ((cardinal.cast_to_nat_of_lt_omega h).symm.trans (cardinal.nat_cast_inj.mpr hHK)))) (quotient_subgroup_of_embedding_of_le H hKL).cardinal_le) @[to_additive] lemma relindex_le_of_le_left (hHK : H ≤ K) (hHL : H.relindex L ≠ 0) : K.relindex L ≤ H.relindex L := nat.le_of_dvd (nat.pos_of_ne_zero hHL) (relindex_dvd_of_le_left L hHK) @[to_additive] lemma relindex_le_of_le_right (hKL : K ≤ L) (hHL : H.relindex L ≠ 0) : H.relindex K ≤ H.relindex L := cardinal.to_nat_le_of_le_of_lt_omega (lt_of_not_ge (mt cardinal.to_nat_apply_of_omega_le hHL)) (cardinal.mk_le_of_injective (quotient_subgroup_of_embedding_of_le H hKL).2) @[to_additive] lemma relindex_ne_zero_trans (hHK : H.relindex K ≠ 0) (hKL : K.relindex L ≠ 0) : H.relindex L ≠ 0 := λ h, mul_ne_zero (mt (relindex_eq_zero_of_le_right (show K ⊓ L ≤ K, from inf_le_left)) hHK) hKL ((relindex_inf_mul_relindex H K L).trans (relindex_eq_zero_of_le_left inf_le_left h)) @[to_additive] lemma relindex_inf_ne_zero (hH : H.relindex L ≠ 0) (hK : K.relindex L ≠ 0) : (H ⊓ K).relindex L ≠ 0 := begin replace hH : H.relindex (K ⊓ L) ≠ 0 := mt (relindex_eq_zero_of_le_right inf_le_right) hH, rw ← inf_relindex_right at hH hK ⊢, rw inf_assoc, exact relindex_ne_zero_trans hH hK, end @[to_additive] lemma index_inf_ne_zero (hH : H.index ≠ 0) (hK : K.index ≠ 0) : (H ⊓ K).index ≠ 0 := begin rw ← relindex_top_right at hH hK ⊢, exact relindex_inf_ne_zero hH hK, end @[to_additive] lemma relindex_inf_le : (H ⊓ K).relindex L ≤ H.relindex L * K.relindex L := begin by_cases h : H.relindex L = 0, { exact (le_of_eq (relindex_eq_zero_of_le_left (by exact inf_le_left) h)).trans (zero_le _) }, rw [←inf_relindex_right, inf_assoc, ←relindex_mul_relindex _ _ L inf_le_right inf_le_right, inf_relindex_right, inf_relindex_right], exact mul_le_mul_right' (relindex_le_of_le_right inf_le_right h) (K.relindex L), end @[to_additive] lemma index_inf_le : (H ⊓ K).index ≤ H.index * K.index := by simp_rw [←relindex_top_right, relindex_inf_le] @[simp, to_additive index_eq_one] lemma index_eq_one : H.index = 1 ↔ H = ⊤ := ⟨λ h, quotient_group.subgroup_eq_top_of_subsingleton H (cardinal.to_nat_eq_one_iff_unique.mp h).1, λ h, (congr_arg index h).trans index_top⟩ @[to_additive] lemma index_ne_zero_of_fintype [hH : fintype (G ⧸ H)] : H.index ≠ 0 := by { rw index_eq_card, exact fintype.card_ne_zero } /-- Finite index implies finite quotient. -/ @[to_additive "Finite index implies finite quotient."] noncomputable def fintype_of_index_ne_zero (hH : H.index ≠ 0) : fintype (G ⧸ H) := (cardinal.lt_omega_iff_fintype.mp (lt_of_not_ge (mt cardinal.to_nat_apply_of_omega_le hH))).some @[to_additive one_lt_index_of_ne_top] lemma one_lt_index_of_ne_top [fintype (G ⧸ H)] (hH : H ≠ ⊤) : 1 < H.index := nat.one_lt_iff_ne_zero_and_ne_one.mpr ⟨index_ne_zero_of_fintype, mt index_eq_one.mp hH⟩ end subgroup
b4ec897b5eb4324e3741e31942db711e08ca0ab1
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/char_lits.lean
110961ef5f20eb1eebefeaa3e3f9bee64400d391
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
199
lean
import system.io check #"a" vm_eval #"a" vm_eval #"\n" vm_eval #"\\" vm_eval put_str (list.cons #"\\" "aaa") vm_eval put_str [#"\n"] vm_eval put_str [#"\n"] vm_eval put_str (list.cons #"\'" "aaa")
e9d66f1becfc811b6185596e8f4e7a4cb908c33c
07c6143268cfb72beccd1cc35735d424ebcb187b
/test/library_search/basic.lean
1a8320069cd66ba02c9f078dc11f730fe22bbec7
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
2,871
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 data.nat.basic /- Turn off trace messages so they don't pollute the test build: -/ set_option trace.silence_library_search true /- For debugging purposes, we can display the list of lemmas: -/ -- set_option trace.suggest true namespace test.library_search -- Check that `library_search` fails if there are no goals. example : true := begin trivial, success_if_fail { library_search }, end -- Verify that `library_search` solves goals via `solve_by_elim` when the library isn't -- even needed. example (P : Prop) (p : P) : P := by library_search example (P : Prop) (p : P) (np : ¬P) : false := by library_search example (X : Type) (P : Prop) (x : X) (h : Π x : X, x = x → P) : P := by library_search def lt_one (n : ℕ) := n < 1 lemma zero_lt_one (n : ℕ) (h : n = 0) : lt_one n := by subst h; dsimp [lt_one]; simp -- Verify that calls to solve_by_elim to discharge subgoals use `rfl` example : lt_one 0 := by library_search example (α : Prop) : α → α := by library_search -- says: `exact id` example (p : Prop) [decidable p] : (¬¬p) → p := by library_search -- says: `exact not_not.mp` example (a b : Prop) (h : a ∧ b) : a := by library_search -- says: `exact h.left` example (P Q : Prop) [decidable P] [decidable Q]: (¬ Q → ¬ P) → (P → Q) := by library_search -- says: `exact not_imp_not.mp` example (a b : ℕ) : a + b = b + a := by library_search -- says: `exact add_comm a b` example {a b : ℕ} : a ≤ a + b := by library_search -- says: `exact nat.le.intro rfl` example (n m k : ℕ) : n * (m - k) = n * m - n * k := by library_search -- says: `exact nat.mul_sub_left_distrib n m k` example (n m k : ℕ) : n * m - n * k = n * (m - k) := by library_search -- says: `exact eq.symm (nat.mul_sub_left_distrib n m k)` example {n m : ℕ} (h : m < n) : m ≤ n - 1 := by library_search -- says: `exact nat.le_pred_of_lt h` example {α : Type} (x y : α) : x = y ↔ y = x := by library_search -- says: `exact eq_comm` example (a b : ℕ) (ha : 0 < a) (hb : 0 < b) : 0 < a + b := by library_search -- says: `exact add_pos ha hb` example (a b : ℕ) : 0 < a → 0 < b → 0 < a + b := by library_search -- says: `exact add_pos` example (a b : ℕ) (h : a ∣ b) (w : b > 0) : a ≤ b := by library_search -- says: `exact nat.le_of_dvd w h` -- We even find `iff` results: example : ∀ P : Prop, ¬(P ↔ ¬P) := by library_search -- says: `λ (a : Prop), (iff_not_self a).mp` example {a b c : ℕ} (ha : a > 0) (w : b ∣ c) : a * b ∣ a * c := by library_search -- exact mul_dvd_mul_left a w example {a b c : ℕ} (h₁ : a ∣ c) (h₂ : a ∣ b + c) : a ∣ b := by library_search -- says `exact (nat.dvd_add_left h₁).mp h₂` end test.library_search
823cf48c12a6492b0f83b172d13a363e919a41e8
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/computability/partrec_code.lean
126327b13f4f3a3972583d61c617db2ff566022c
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,586
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Godel numbering for partial recursive functions. -/ import computability.partrec open encodable denumerable namespace nat.partrec open nat (mkpair) theorem rfind' {f} (hf : nat.partrec f) : nat.partrec (nat.unpaired (λ a m, (nat.rfind (λ n, (λ m, m = 0) <$> f (mkpair a (n + m)))).map (+ m))) := partrec₂.unpaired'.2 $ begin refine partrec.map ((@partrec₂.unpaired' (λ (a b : ℕ), nat.rfind (λ n, (λ m, m = 0) <$> f (mkpair a (n + b))))).1 _) (primrec.nat_add.comp primrec.snd $ primrec.snd.comp primrec.fst).to_comp.to₂, have := rfind (partrec₂.unpaired'.2 ((partrec.nat_iff.2 hf).comp (primrec₂.mkpair.comp (primrec.fst.comp $ primrec.unpair.comp primrec.fst) (primrec.nat_add.comp primrec.snd (primrec.snd.comp $ primrec.unpair.comp primrec.fst))).to_comp).to₂), simp at this, exact this end inductive code : Type | zero : code | succ : code | left : code | right : code | pair : code → code → code | comp : code → code → code | prec : code → code → code | rfind' : code → code end nat.partrec namespace nat.partrec.code open nat (mkpair unpair) open nat.partrec (code) instance : inhabited code := ⟨zero⟩ protected def const : ℕ → code | 0 := zero | (n+1) := comp succ (const n) theorem const_inj : Π {n₁ n₂}, nat.partrec.code.const n₁ = nat.partrec.code.const n₂ → n₁ = n₂ | 0 0 h := by simp | (n₁+1) (n₂+1) h := by { dsimp [nat.partrec.code.const] at h, injection h with h₁ h₂, simp only [const_inj h₂] } protected def id : code := pair left right def curry (c : code) (n : ℕ) : code := comp c (pair (code.const n) code.id) def encode_code : code → ℕ | zero := 0 | succ := 1 | left := 2 | right := 3 | (pair cf cg) := bit0 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (comp cf cg) := bit0 (bit1 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (prec cf cg) := bit1 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (rfind' cf) := bit1 (bit1 $ encode_code cf) + 4 def of_nat_code : ℕ → code | 0 := zero | 1 := succ | 2 := left | 3 := right | (n+4) := let m := n.div2.div2 in have hm : m < n + 4, by simp [m, nat.div2_val]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, match n.bodd, n.div2.bodd with | ff, ff := pair (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | ff, tt := comp (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | tt, ff := prec (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | tt, tt := rfind' (of_nat_code m) end private theorem encode_of_nat_code : ∀ n, encode_code (of_nat_code n) = n | 0 := rfl | 1 := rfl | 2 := rfl | 3 := rfl | (n+4) := let m := n.div2.div2 in have hm : m < n + 4, by simp [m, nat.div2_val]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, have IH : _ := encode_of_nat_code m, have IH1 : _ := encode_of_nat_code m.unpair.1, have IH2 : _ := encode_of_nat_code m.unpair.2, begin transitivity, swap, rw [← nat.bit_decomp n, ← nat.bit_decomp n.div2], simp [encode_code, of_nat_code, -add_comm], cases n.bodd; cases n.div2.bodd; simp [encode_code, of_nat_code, -add_comm, IH, IH1, IH2, m, nat.bit] end instance : denumerable code := mk' ⟨encode_code, of_nat_code, λ c, by induction c; try {refl}; simp [ encode_code, of_nat_code, -add_comm, *], encode_of_nat_code⟩ theorem encode_code_eq : encode = encode_code := rfl theorem of_nat_code_eq : of_nat code = of_nat_code := rfl theorem encode_lt_pair (cf cg) : encode cf < encode (pair cf cg) ∧ encode cg < encode (pair cf cg) := begin simp [encode_code_eq, encode_code, -add_comm], have := nat.mul_le_mul_right _ (dec_trivial : 1 ≤ 2*2), rw [one_mul, mul_assoc, ← bit0_eq_two_mul, ← bit0_eq_two_mul] at this, have := lt_of_le_of_lt this (lt_add_of_pos_right _ (dec_trivial:0<4)), exact ⟨ lt_of_le_of_lt (nat.le_mkpair_left _ _) this, lt_of_le_of_lt (nat.le_mkpair_right _ _) this⟩ end theorem encode_lt_comp (cf cg) : encode cf < encode (comp cf cg) ∧ encode cg < encode (comp cf cg) := begin suffices, exact (encode_lt_pair cf cg).imp (λ h, lt_trans h this) (λ h, lt_trans h this), change _, simp [encode_code_eq, encode_code] end theorem encode_lt_prec (cf cg) : encode cf < encode (prec cf cg) ∧ encode cg < encode (prec cf cg) := begin suffices, exact (encode_lt_pair cf cg).imp (λ h, lt_trans h this) (λ h, lt_trans h this), change _, simp [encode_code_eq, encode_code], end theorem encode_lt_rfind' (cf) : encode cf < encode (rfind' cf) := begin simp [encode_code_eq, encode_code, -add_comm], have := nat.mul_le_mul_right _ (dec_trivial : 1 ≤ 2*2), rw [one_mul, mul_assoc, ← bit0_eq_two_mul, ← bit0_eq_two_mul] at this, refine lt_of_le_of_lt (le_trans this _) (lt_add_of_pos_right _ (dec_trivial:0<4)), exact le_of_lt (nat.bit0_lt_bit1 $ le_of_lt $ nat.bit0_lt_bit1 $ le_refl _), end section open primrec theorem pair_prim : primrec₂ pair := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit0.comp $ nat_bit0.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem comp_prim : primrec₂ comp := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit0.comp $ nat_bit1.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem prec_prim : primrec₂ prec := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit1.comp $ nat_bit0.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem rfind_prim : primrec rfind' := of_nat_iff.2 $ encode_iff.1 $ nat_add.comp (nat_bit1.comp $ nat_bit1.comp $ encode_iff.2 $ primrec.of_nat code) (const 4) theorem rec_prim' {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : primrec c) {z : α → σ} (hz : primrec z) {s : α → σ} (hs : primrec s) {l : α → σ} (hl : primrec l) {r : α → σ} (hr : primrec r) {pr : α → code × code × σ × σ → σ} (hpr : primrec₂ pr) {co : α → code × code × σ × σ → σ} (hco : primrec₂ co) {pc : α → code × code × σ × σ → σ} (hpc : primrec₂ pc) {rf : α → code × σ → σ} (hrf : primrec₂ rf) : let PR (a) := λ cf cg hf hg, pr a (cf, cg, hf, hg), CO (a) := λ cf cg hf hg, co a (cf, cg, hf, hg), PC (a) := λ cf cg hf hg, pc a (cf, cg, hf, hg), RF (a) := λ cf hf, rf a (cf, hf), F (a c) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in primrec (λ a, F a (c a)) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m, s)) (pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))) (cond n.div2.bodd (co a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂)) (pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))), have : primrec G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (primrec.unpair.comp m), have m₂ := snd.comp (primrec.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp a (((primrec.of_nat code).comp m).pair s)) (hpc.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) (primrec.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : primrec₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp primrec.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end theorem rec_prim {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : primrec c) {z : α → σ} (hz : primrec z) {s : α → σ} (hs : primrec s) {l : α → σ} (hl : primrec l) {r : α → σ} (hr : primrec r) {pr : α → code → code → σ → σ → σ} (hpr : primrec (λ a : α × code × code × σ × σ, pr a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {co : α → code → code → σ → σ → σ} (hco : primrec (λ a : α × code × code × σ × σ, co a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {pc : α → code → code → σ → σ → σ} (hpc : primrec (λ a : α × code × code × σ × σ, pc a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {rf : α → code → σ → σ} (hrf : primrec (λ a : α × code × σ, rf a.1 a.2.1 a.2.2)) : let F (a c) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (pr a) (co a) (pc a) (rf a) in primrec (λ a, F a (c a)) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m) s) (pc a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂)) (cond n.div2.bodd (co a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂) (pr a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂)), have : primrec G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (primrec.unpair.comp m), have m₂ := snd.comp (primrec.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp $ a.pair (((primrec.of_nat code).comp m).pair s)) (hpc.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) (primrec.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : primrec₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp primrec.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end end section open computable /- TODO(Mario): less copy-paste from previous proof -/ theorem rec_computable {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : computable c) {z : α → σ} (hz : computable z) {s : α → σ} (hs : computable s) {l : α → σ} (hl : computable l) {r : α → σ} (hr : computable r) {pr : α → code × code × σ × σ → σ} (hpr : computable₂ pr) {co : α → code × code × σ × σ → σ} (hco : computable₂ co) {pc : α → code × code × σ × σ → σ} (hpc : computable₂ pc) {rf : α → code × σ → σ} (hrf : computable₂ rf) : let PR (a) := λ cf cg hf hg, pr a (cf, cg, hf, hg), CO (a) := λ cf cg hf hg, co a (cf, cg, hf, hg), PC (a) := λ cf cg hf hg, pc a (cf, cg, hf, hg), RF (a) := λ cf hf, rf a (cf, hf), F (a c) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in computable (λ a, F a (c a)) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m, s)) (pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))) (cond n.div2.bodd (co a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂)) (pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))), have : computable G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ computable.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ computable.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (computable.unpair.comp m), have m₂ := snd.comp (computable.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp a (((computable.of_nat code).comp m).pair s)) (hpc.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂))) (computable.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : computable₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp computable.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_le_left hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_le_right hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end end def eval : code → ℕ →. ℕ | zero := pure 0 | succ := nat.succ | left := ↑(λ n : ℕ, n.unpair.1) | right := ↑(λ n : ℕ, n.unpair.2) | (pair cf cg) := λ n, mkpair <$> eval cf n <*> eval cg n | (comp cf cg) := λ n, eval cg n >>= eval cf | (prec cf cg) := nat.unpaired (λ a n, n.elim (eval cf a) (λ y IH, do i ← IH, eval cg (mkpair a (mkpair y i)))) | (rfind' cf) := nat.unpaired (λ a m, (nat.rfind (λ n, (λ m, m = 0) <$> eval cf (mkpair a (n + m)))).map (+ m)) instance : has_mem (ℕ →. ℕ) code := ⟨λ f c, eval c = f⟩ @[simp] theorem eval_const : ∀ n m, eval (code.const n) m = roption.some n | 0 m := rfl | (n+1) m := by simp! * @[simp] theorem eval_id (n) : eval code.id n = roption.some n := by simp! [(<*>)] @[simp] theorem eval_curry (c n x) : eval (curry c n) x = eval c (mkpair n x) := by simp! [(<*>)] theorem const_prim : primrec code.const := (primrec.id.nat_iterate (primrec.const zero) (comp_prim.comp (primrec.const succ) primrec.snd).to₂).of_eq $ λ n, by simp; induction n; simp [*, code.const, function.iterate_succ'] theorem curry_prim : primrec₂ curry := comp_prim.comp primrec.fst $ pair_prim.comp (const_prim.comp primrec.snd) (primrec.const code.id) theorem curry_inj {c₁ c₂ n₁ n₂} (h : curry c₁ n₁ = curry c₂ n₂) : c₁ = c₂ ∧ n₁ = n₂ := ⟨by injection h, by { injection h, injection h with h₁ h₂, injection h₂ with h₃ h₄, exact const_inj h₃ }⟩ theorem smn : ∃ f : code → ℕ → code, computable₂ f ∧ ∀ c n x, eval (f c n) x = eval c (mkpair n x) := ⟨curry, primrec₂.to_comp curry_prim, eval_curry⟩ theorem exists_code {f : ℕ →. ℕ} : nat.partrec f ↔ ∃ c : code, eval c = f := ⟨λ h, begin induction h, case nat.partrec.zero { exact ⟨zero, rfl⟩ }, case nat.partrec.succ { exact ⟨succ, rfl⟩ }, case nat.partrec.left { exact ⟨left, rfl⟩ }, case nat.partrec.right { exact ⟨right, rfl⟩ }, case nat.partrec.pair : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨pair cf cg, rfl⟩ }, case nat.partrec.comp : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨comp cf cg, rfl⟩ }, case nat.partrec.prec : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨prec cf cg, rfl⟩ }, case nat.partrec.rfind : f pf hf { rcases hf with ⟨cf, rfl⟩, refine ⟨comp (rfind' cf) (pair code.id zero), _⟩, simp [eval, (<*>), pure, pfun.pure, roption.map_id'] }, end, λ h, begin rcases h with ⟨c, rfl⟩, induction c, case nat.partrec.code.zero { exact nat.partrec.zero }, case nat.partrec.code.succ { exact nat.partrec.succ }, case nat.partrec.code.left { exact nat.partrec.left }, case nat.partrec.code.right { exact nat.partrec.right }, case nat.partrec.code.pair : cf cg pf pg { exact pf.pair pg }, case nat.partrec.code.comp : cf cg pf pg { exact pf.comp pg }, case nat.partrec.code.prec : cf cg pf pg { exact pf.prec pg }, case nat.partrec.code.rfind' : cf pf { exact pf.rfind' }, end⟩ def evaln : ∀ k : ℕ, code → ℕ → option ℕ | 0 _ := λ m, none | (k+1) zero := λ n, guard (n ≤ k) >> pure 0 | (k+1) succ := λ n, guard (n ≤ k) >> pure (nat.succ n) | (k+1) left := λ n, guard (n ≤ k) >> pure n.unpair.1 | (k+1) right := λ n, guard (n ≤ k) >> pure n.unpair.2 | (k+1) (pair cf cg) := λ n, guard (n ≤ k) >> mkpair <$> evaln (k+1) cf n <*> evaln (k+1) cg n | (k+1) (comp cf cg) := λ n, guard (n ≤ k) >> do x ← evaln (k+1) cg n, evaln (k+1) cf x | (k+1) (prec cf cg) := λ n, guard (n ≤ k) >> n.unpaired (λ a n, n.cases (evaln (k+1) cf a) $ λ y, do i ← evaln k (prec cf cg) (mkpair a y), evaln (k+1) cg (mkpair a (mkpair y i))) | (k+1) (rfind' cf) := λ n, guard (n ≤ k) >> n.unpaired (λ a m, do x ← evaln (k+1) cf (mkpair a m), if x = 0 then pure m else evaln k (rfind' cf) (mkpair a (m+1))) theorem evaln_bound : ∀ {k c n x}, x ∈ evaln k c n → n < k | 0 c n x h := by simp [evaln] at h; cases h | (k+1) c n x h := begin suffices : ∀ {o : option ℕ}, x ∈ guard (n ≤ k) >> o → n < k + 1, { cases c; rw [evaln] at h; exact this h }, simpa [(>>)] using nat.lt_succ_of_le end theorem evaln_mono : ∀ {k₁ k₂ c n x}, k₁ ≤ k₂ → x ∈ evaln k₁ c n → x ∈ evaln k₂ c n | 0 k₂ c n x hl h := by simp [evaln] at h; cases h | (k+1) (k₂+1) c n x hl h := begin have hl' := nat.le_of_succ_le_succ hl, have : ∀ {k k₂ n x : ℕ} {o₁ o₂ : option ℕ}, k ≤ k₂ → (x ∈ o₁ → x ∈ o₂) → x ∈ guard (n ≤ k) >> o₁ → x ∈ guard (n ≤ k₂) >> o₂, { simp [(>>)], introv h h₁ h₂ h₃, exact ⟨le_trans h₂ h, h₁ h₃⟩ }, simp at h ⊢, induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n; rw [evaln] at h ⊢; refine this hl' (λ h, _) h, iterate 4 {exact h}, { -- pair cf cg simp [(<*>)] at h ⊢, exact h.imp (λ a, and.imp (hf _ _) $ Exists.imp $ λ b, and.imp_left (hg _ _)) }, { -- comp cf cg simp at h ⊢, exact h.imp (λ a, and.imp (hg _ _) (hf _ _)) }, { -- prec cf cg revert h, simp, induction n.unpair.2; simp, { apply hf }, { exact λ y h₁ h₂, ⟨y, evaln_mono hl' h₁, hg _ _ h₂⟩ } }, { -- rfind' cf simp at h ⊢, refine h.imp (λ x, and.imp (hf _ _) _), by_cases x0 : x = 0; simp [x0], exact evaln_mono hl' } end theorem evaln_sound : ∀ {k c n x}, x ∈ evaln k c n → x ∈ eval c n | 0 _ n x h := by simp [evaln] at h; cases h | (k+1) c n x h := begin induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n; simp [eval, evaln, (>>), (<*>)] at h ⊢; cases h with _ h, iterate 4 {simpa [pure, pfun.pure, eq_comm] using h}, { -- pair cf cg rcases h with ⟨y, ef, z, eg, rfl⟩, exact ⟨_, hf _ _ ef, _, hg _ _ eg, rfl⟩ }, { --comp hf hg rcases h with ⟨y, eg, ef⟩, exact ⟨_, hg _ _ eg, hf _ _ ef⟩ }, { -- prec cf cg revert h, induction n.unpair.2 with m IH generalizing x; simp, { apply hf }, { refine λ y h₁ h₂, ⟨y, IH _ _, _⟩, { have := evaln_mono k.le_succ h₁, simp [evaln, (>>)] at this, exact this.2 }, { exact hg _ _ h₂ } } }, { -- rfind' cf rcases h with ⟨m, h₁, h₂⟩, by_cases m0 : m = 0; simp [m0] at h₂, { exact ⟨0, ⟨by simpa [m0] using hf _ _ h₁, λ m, (nat.not_lt_zero _).elim⟩, by injection h₂ with h₂; simp [h₂]⟩ }, { have := evaln_sound h₂, simp [eval] at this, rcases this with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩, refine ⟨ y+1, ⟨by simpa [add_comm, add_left_comm] using hy₁, λ i im, _⟩, by simp [add_comm, add_left_comm] ⟩, cases i with i, { exact ⟨m, by simpa using hf _ _ h₁, m0⟩ }, { rcases hy₂ (nat.lt_of_succ_lt_succ im) with ⟨z, hz, z0⟩, exact ⟨z, by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hz, z0⟩ } } } end theorem evaln_complete {c n x} : x ∈ eval c n ↔ ∃ k, x ∈ evaln k c n := ⟨λ h, begin suffices : ∃ k, x ∈ evaln (k+1) c n, { exact let ⟨k, h⟩ := this in ⟨k+1, h⟩ }, induction c generalizing n x; simp [eval, evaln, pure, pfun.pure, (<*>), (>>)] at h ⊢, iterate 4 { exact ⟨⟨_, le_refl _⟩, h.symm⟩ }, case nat.partrec.code.pair : cf cg hf hg { rcases h with ⟨x, hx, y, hy, rfl⟩, rcases hf hx with ⟨k₁, hk₁⟩, rcases hg hy with ⟨k₂, hk₂⟩, refine ⟨max k₁ k₂, _⟩, refine ⟨le_max_left_of_le $ nat.le_of_lt_succ $ evaln_bound hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_left _ _) hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂, rfl⟩ }, case nat.partrec.code.comp : cf cg hf hg { rcases h with ⟨y, hy, hx⟩, rcases hg hy with ⟨k₁, hk₁⟩, rcases hf hx with ⟨k₂, hk₂⟩, refine ⟨max k₁ k₂, _⟩, exact ⟨le_max_left_of_le $ nat.le_of_lt_succ $ evaln_bound hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_left _ _) hk₁, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂⟩ }, case nat.partrec.code.prec : cf cg hf hg { revert h, generalize : n.unpair.1 = n₁, generalize : n.unpair.2 = n₂, induction n₂ with m IH generalizing x n; simp, { intro, rcases hf h with ⟨k, hk⟩, exact ⟨_, le_max_left _ _, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk⟩ }, { intros y hy hx, rcases IH hy with ⟨k₁, nk₁, hk₁⟩, rcases hg hx with ⟨k₂, hk₂⟩, refine ⟨(max k₁ k₂).succ, nat.le_succ_of_le $ le_max_left_of_le $ le_trans (le_max_left _ (mkpair n₁ m)) nk₁, y, evaln_mono (nat.succ_le_succ $ le_max_left _ _) _, evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_right _ _) hk₂⟩, simp [evaln, (>>)], exact ⟨le_trans (le_max_right _ _) nk₁, hk₁⟩ } }, case nat.partrec.code.rfind' : cf hf { rcases h with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩, suffices : ∃ k, y + n.unpair.2 ∈ evaln (k+1) (rfind' cf) (mkpair n.unpair.1 n.unpair.2), {simpa [evaln, (>>)]}, revert hy₁ hy₂, generalize : n.unpair.2 = m, intros, induction y with y IH generalizing m; simp [evaln, (>>)], { simp at hy₁, rcases hf hy₁ with ⟨k, hk⟩, exact ⟨_, nat.le_of_lt_succ $ evaln_bound hk, _, hk, by simp; refl⟩ }, { rcases hy₂ (nat.succ_pos _) with ⟨a, ha, a0⟩, rcases hf ha with ⟨k₁, hk₁⟩, rcases IH m.succ (by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hy₁) (λ i hi, by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hy₂ (nat.succ_lt_succ hi)) with ⟨k₂, hk₂⟩, use (max k₁ k₂).succ, rw [zero_add] at hk₁, use (nat.le_succ_of_le $ le_max_left_of_le $ nat.le_of_lt_succ $ evaln_bound hk₁), use a, use evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_left _ _) hk₁, simpa [nat.succ_eq_add_one, a0, -max_eq_left, -max_eq_right, add_comm, add_left_comm] using evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂ } } end, λ ⟨k, h⟩, evaln_sound h⟩ section open primrec private def lup (L : list (list (option ℕ))) (p : ℕ × code) (n : ℕ) := do l ← L.nth (encode p), o ← l.nth n, o private lemma hlup : primrec (λ p:_×(_×_)×_, lup p.1 p.2.1 p.2.2) := option_bind (list_nth.comp fst (primrec.encode.comp $ fst.comp snd)) (option_bind (list_nth.comp snd $ snd.comp $ snd.comp fst) snd) private def G (L : list (list (option ℕ))) : option (list (option ℕ)) := option.some $ let a := of_nat (ℕ × code) L.length, k := a.1, c := a.2 in (list.range k).map (λ n, k.cases none $ λ k', nat.partrec.code.rec_on c (some 0) -- zero (some (nat.succ n)) (some n.unpair.1) (some n.unpair.2) (λ cf cg _ _, do x ← lup L (k, cf) n, y ← lup L (k, cg) n, some (mkpair x y)) (λ cf cg _ _, do x ← lup L (k, cg) n, lup L (k, cf) x) (λ cf cg _ _, let z := n.unpair.1 in n.unpair.2.cases (lup L (k, cf) z) (λ y, do i ← lup L (k', c) (mkpair z y), lup L (k, cg) (mkpair z (mkpair y i)))) (λ cf _, let z := n.unpair.1, m := n.unpair.2 in do x ← lup L (k, cf) (mkpair z m), x.cases (some m) (λ _, lup L (k', c) (mkpair z (m+1))))) private lemma hG : primrec G := begin have a := (primrec.of_nat (ℕ × code)).comp list_length, have k := fst.comp a, refine option_some.comp (list_map (list_range.comp k) (_ : primrec _)), replace k := k.comp fst, have n := snd, refine nat_cases k (const none) (_ : primrec _), have k := k.comp fst, have n := n.comp fst, have k' := snd, have c := snd.comp (a.comp $ fst.comp fst), apply rec_prim c (const (some 0)) (option_some.comp (primrec.succ.comp n)) (option_some.comp (fst.comp $ primrec.unpair.comp n)) (option_some.comp (snd.comp $ primrec.unpair.comp n)), { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, exact option_bind (hlup.comp $ L.pair $ (k.pair cf).pair n) (option_map ((hlup.comp $ L.pair $ (k.pair cg).pair n).comp fst) (primrec₂.mkpair.comp (snd.comp fst) snd)) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, exact option_bind (hlup.comp $ L.pair $ (k.pair cg).pair n) (hlup.comp ((L.comp fst).pair $ ((k.pair cf).comp fst).pair snd)) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, have z := fst.comp (primrec.unpair.comp n), refine nat_cases (snd.comp (primrec.unpair.comp n)) (hlup.comp $ L.pair $ (k.pair cf).pair z) (_ : primrec _), have L := L.comp fst, have z := z.comp fst, have y := snd, refine option_bind (hlup.comp $ L.pair $ (((k'.pair c).comp fst).comp fst).pair (primrec₂.mkpair.comp z y)) (_ : primrec _), have z := z.comp fst, have y := y.comp fst, have i := snd, exact hlup.comp ((L.comp fst).pair $ ((k.pair cg).comp $ fst.comp fst).pair $ primrec₂.mkpair.comp z $ primrec₂.mkpair.comp y i) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have z := fst.comp (primrec.unpair.comp n), have m := snd.comp (primrec.unpair.comp n), refine option_bind (hlup.comp $ L.pair $ (k.pair cf).pair (primrec₂.mkpair.comp z m)) (_ : primrec _), have m := m.comp fst, exact nat_cases snd (option_some.comp m) ((hlup.comp ((L.comp fst).pair $ ((k'.pair c).comp $ fst.comp fst).pair (primrec₂.mkpair.comp (z.comp fst) (primrec.succ.comp m)))).comp fst) } end private lemma evaln_map (k c n) : (((list.range k).nth n).map (evaln k c)).bind (λ b, b) = evaln k c n := begin by_cases kn : n < k, { simp [list.nth_range kn] }, { rw list.nth_len_le, { cases e : evaln k c n, {refl}, exact kn.elim (evaln_bound e) }, simpa using kn } end theorem evaln_prim : primrec (λ (a : (ℕ × code) × ℕ), evaln a.1.1 a.1.2 a.2) := have primrec₂ (λ (_:unit) (n : ℕ), let a := of_nat (ℕ × code) n in (list.range a.1).map (evaln a.1 a.2)), from primrec.nat_strong_rec _ (hG.comp snd).to₂ $ λ _ p, begin simp [G], rw (_ : (of_nat (ℕ × code) _).snd = of_nat code p.unpair.2), swap, {simp}, apply list.map_congr (λ n, _), rw (by simp : list.range p = list.range (mkpair p.unpair.1 (encode (of_nat code p.unpair.2)))), generalize : p.unpair.1 = k, generalize : of_nat code p.unpair.2 = c, intro nk, cases k with k', {simp [evaln]}, let k := k'+1, change k'.succ with k, simp [nat.lt_succ_iff] at nk, have hg : ∀ {k' c' n}, mkpair k' (encode c') < mkpair k (encode c) → lup ((list.range (mkpair k (encode c))).map (λ n, (list.range n.unpair.1).map (evaln n.unpair.1 (of_nat code n.unpair.2)))) (k', c') n = evaln k' c' n, { intros k₁ c₁ n₁ hl, simp [lup, list.nth_range hl, evaln_map, (>>=)] }, cases c with cf cg cf cg cf cg cf; simp [evaln, nk, (>>), (>>=), (<$>), (<*>), pure], { cases encode_lt_pair cf cg with lf lg, rw [hg (nat.mkpair_lt_mkpair_right _ lf), hg (nat.mkpair_lt_mkpair_right _ lg)], cases evaln k cf n, {refl}, cases evaln k cg n; refl }, { cases encode_lt_comp cf cg with lf lg, rw hg (nat.mkpair_lt_mkpair_right _ lg), cases evaln k cg n, {refl}, simp [hg (nat.mkpair_lt_mkpair_right _ lf)] }, { cases encode_lt_prec cf cg with lf lg, rw hg (nat.mkpair_lt_mkpair_right _ lf), cases n.unpair.2, {refl}, simp, rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self), cases evaln k' _ _, {refl}, simp [hg (nat.mkpair_lt_mkpair_right _ lg)] }, { have lf := encode_lt_rfind' cf, rw hg (nat.mkpair_lt_mkpair_right _ lf), cases evaln k cf n with x, {refl}, simp, cases x; simp [nat.succ_ne_zero], rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self) } end, (option_bind (list_nth.comp (this.comp (const ()) (encode_iff.2 fst)) snd) snd.to₂).of_eq $ λ ⟨⟨k, c⟩, n⟩, by simp [evaln_map] end section open partrec computable theorem eval_eq_rfind_opt (c n) : eval c n = nat.rfind_opt (λ k, evaln k c n) := roption.ext $ λ x, begin refine evaln_complete.trans (nat.rfind_opt_mono _).symm, intros a m n hl, apply evaln_mono hl, end theorem eval_part : partrec₂ eval := (rfind_opt (evaln_prim.to_comp.comp ((snd.pair (fst.comp fst)).pair (snd.comp fst))).to₂).of_eq $ λ a, by simp [eval_eq_rfind_opt] theorem fixed_point {f : code → code} (hf : computable f) : ∃ c : code, eval (f c) = eval c := let g (x y : ℕ) : roption ℕ := eval (of_nat code x) x >>= λ b, eval (of_nat code b) y in have partrec₂ g := (eval_part.comp ((computable.of_nat _).comp fst) fst).bind (eval_part.comp ((computable.of_nat _).comp snd) (snd.comp fst)).to₂, let ⟨cg, eg⟩ := exists_code.1 this in have eg' : ∀ a n, eval cg (mkpair a n) = roption.map encode (g a n) := by simp [eg], let F (x : ℕ) : code := f (curry cg x) in have computable F := hf.comp (curry_prim.comp (primrec.const cg) primrec.id).to_comp, let ⟨cF, eF⟩ := exists_code.1 this in have eF' : eval cF (encode cF) = roption.some (encode (F (encode cF))), by simp [eF], ⟨curry cg (encode cF), funext (λ n, show eval (f (curry cg (encode cF))) n = eval (curry cg (encode cF)) n, by simp [eg', eF', roption.map_id', g])⟩ theorem fixed_point₂ {f : code → ℕ →. ℕ} (hf : partrec₂ f) : ∃ c : code, eval c = f c := let ⟨cf, ef⟩ := exists_code.1 hf in (fixed_point (curry_prim.comp (primrec.const cf) primrec.encode).to_comp).imp $ λ c e, funext $ λ n, by simp [e.symm, ef, roption.map_id'] end end nat.partrec.code
86f1cdc18581bb10820673dfc16698111c7e7007
d450724ba99f5b50b57d244eb41fef9f6789db81
/src/Submissions/hw7.lean
2fe2fb61969bc07ec71deba5cfd4a41b4f08229f
[]
no_license
jakekauff/CS2120F21
4f009adeb4ce4a148442b562196d66cc6c04530c
e69529ec6f5d47a554291c4241a3d8ec4fe8f5ad
refs/heads/main
1,693,841,880,030
1,637,604,848,000
1,637,604,848,000
399,946,698
0
0
null
null
null
null
UTF-8
Lean
false
false
11,138
lean
import data.set import tactic.ring namespace relation -- Jakob Kauffmann (jgk2qq); github: jakekauff13 -- Collaborated with: Jumi Hall (jah5py) & -- Connor McCaffrey (cam7qp) -- PRELIMINARY SETUP /- Preliminary set up. For the rest of this file, we specify an arbitrary binary relation, r, on an arbitrary type, β, as a two-place predicate, with infix notation x ≺ y for (r x y). One can pronounce these expressions in English as "x is related to y". -/ variables {α β : Type} (r : β → β → Prop) local infix `≺` : 50 := r /- The default Lean libraries are missing definitions for the assympetric property of relations and for the notion of a powerset. We define these terms for use in the rest of this file. -/ def asymmetric := ∀ ⦃x y⦄, x ≺ y → ¬ y ≺ x def powerset (s : set β) := { s' | s' ⊆ s} -- PROBLEMS /- #1: Give both a formal and an English-language proof. Then answer the question, is the proposition true if you remove the first condition, that β is inhabited? Briefly explain your answer (in English). -/ example : (∃ (b : β), true) → asymmetric r → ¬reflexive r := begin assume e, assume a, assume x, unfold asymmetric at a, unfold reflexive at x, cases e with w pf, have rww := x w, have c := a rww, contradiction, end -- English-Language Proof: /- Proof: Suppose β is inhabited and r is asymmetric. We now show r is not reflexive. We will prove by negation, assuming that r is reflexive and then we will show that this assumption leads to a contradiction from which we can conclude r is not reflexive. To derive the contradiction, we first expand the definitions of asymmetric and reflexive. We will now show that the following assumptions contradict one another: β: Type r: β → β → Prop e: ∃ (b : β), true a: ∀ ⦃x y : β⦄, r x y → ¬r y x x: ∀ (x : β), r x x To show this by exists elimination we first infer that there is a an object, w : β, of which we have a proof of existence. Applying reflexivity (x), to w, we deduce w ≺ w (r w w). Next, by applying asymmetry (a), to w ≺ w we derive w ⊀ w, thus deriving the aforementioned contradiction. QED. -/ /- #2. Logic, like programming, is subtle. It's very easy for humans to miss subtle corner cases. As an example, today I ran across a problem in a textbook by Paul Traiger, a professor emeritus of philosophy and cognitive science at Occidental College. He asks students to prove that if a relation is both transitive and reflexive that it cannot be anti-symmetric. See the question at the very bottom of the page here: https://sites.oxy.edu/traiger/logic/exercises/chapter13/properties_of_relations_exercise.html Is the conjecture actually logically valid? If not, what condition needs to be added to make it so? Try prove this/his version of the conjecture, as articulated slightly differently below. If you get stuck, then you need to figure out an additional condition that needs to be added as a premise to make the proposition true. In that case, add the premise and then show that the updated conjecture is true. -/ example : (∃ (b : β), true) → transitive r → reflexive r → ¬ asymmetric r := begin assume h, unfold transitive reflexive asymmetric, assume t r a, cases h with b True, have b_refl := r b, have b_not_refl := a b_refl, contradiction, end /- #3: Prove that the subset relation on the powerset of any set, s, is antisymmetric. Formally state and prove, and then give an informal proof of, this proposition. -/ example : ∀ (s : set β) (s1 s2 ∈ powerset s), s1 ⊆ s2 → s2 ⊆ s1 → s1 = s2 := begin assume s s1 s2 s1ins s2ins s1ins2 s2ins1, apply set.ext, assume x, split, assume xins1, exact s1ins2 xins1, assume xins2, exact s2ins1 xins2, end /- Proof: Suppose that s is a set of type β and that s1 and s2 are in the powerset of s. We will prove that s1 = s2, assuming the following: s1 ⊆ s2 and s2 ⊆ s1. First, we equate the equals sign to an if and only if statement under set extensionality. By application of our assumptions on one another, we derive that s1 = s2. QED. -/ /- Given two natural numbers, n and m, we will say that m divides n if there is a natural number, k, such that n = k*m. Here's a formal definition of this relation. -/ def divides (m n : ℕ) := ∃ k, n = k * m /- #4: Formally and informally state and prove each of the following propositions. Remember that the ring tactic is useful for producing proofs of simple algebraic equalities involving + and *. You can use the phrase, "by basic algebra" when translating the use of this tactic into English. (Or if you wanted to be truly Hobbit-like you could say "by the ring axioms!") -/ -- A: For any n, 1 divides n. example : ∀ n, divides 1 n := begin assume n, unfold divides, cases n with p, apply exists.intro 0, refl, apply exists.intro p.succ, have mulone := mul_one p.succ, rw mulone, end /- Proof: We provide a proof that for any n, 1 divides n. In order to provide this proof, we first assume n of type ℕ. Next, we expand the definition of divides. We will then perform case analysis on n to prove that there exists a k such that n = k * 1. Case analysis yields two cases which we will prove, thus proving that 1 divides n. The first case is that in which n = 0. After application of the exists introduction rule with the value 0, we now prove by simple algebra that 0 = 0 * 1. The second case is that is which n > 0. Similarly, we show that there exists a k such that n = k * 1, and that k is again equal to n. QED. -/ -- B. For any n, n divides n example : ∀ n, divides n n := begin assume n, unfold divides, apply exists.intro 1, have mulone := one_mul n, rw mulone, end /- Proof: We provide a proof that for any n, n divides n. We first assume n is of type ℕ, then we expand the definition of divides. After applying the exists introduction rule with a value of 1, we must prove that n = 1 * n, which is done by simple algebra. QED. -/ -- #C. prove that divides is reflexive example : reflexive divides := begin unfold reflexive divides, assume n, apply exists.intro 1, have mulone := (one_mul n), rw mulone, end /- Proof: We will provide a proof that divides is reflexive. We first assume n is of type ℕ, and then we expand the definition of divides and reflexive. After applying the exists introduction rule with a value of 1, we must prove that n = 1 * n, which is done by simple algebra. -/ -- #D. prove that divides is transitive example : transitive divides := begin unfold transitive divides, assume a b c, assume ab bc, cases ab with a1 p1, cases bc with a2 p2, apply exists.intro(a2*a1), rw p2, rw p1, have mulassoc := mul_assoc a2 a1 a, rw mulassoc, end /- Proof: We will provide a proof that divides is transitive. We first expand the definition of transitive and divides. We will then make the following assumptions: a b c : ℕ ab : ∃ (k : ℕ), b = k * a bc : ∃ (k : ℕ), c = k * b Under these assumptions, we will prove that there exists a k such that c = k * a, showing that divides is transitive. We begin by performing case analysis on both ab and bc, yielding the following assumptions: a b c a1 a2 : ℕ p1 : b = a1 * a p2 : c = a2 * b We will use these assumptions to rewrite the final proposition c = k * a to now be a2 * a1 * a = a2 * a1 * a. We do this by applying the exists introduction rule for the value a2 * a1, converting the proposition into c = a2 * a1 * a. Next, we have the proofs that c = a2 * b and b = a1 * a. Using these, we can rewrite the final proposition as a2 * a1 * a = a2 * a1 * a, which is true by reflexivity of equality. QED. -/ /- E. Is divides symmetric? if yes, give a proof, otherwise give a counterexample and a brief explanation to show that it's not. -/ example: symmetric divides := begin end -- Divides is NOT symmetric, as shown by the cases where 2 divides 4 -- (k = 2, which is a natural number), but 4 does not divide 2 -- (k = 1/2, which is not a natural number). -- In order for a relation to be symmetric, the relation -- must hold between the two values in both directions. However, with divides, -- a natural number does not exist such that a number divides a larger number, -- and that larger number divides the smaller number. /- #F. Prove that divides is antisymmetric. -/ example : anti_symmetric divides := begin unfold anti_symmetric divides, assume x y xy yx, apply exists.elim xy, apply exists.elim yx, assume a b c d, rw b, have : a = 1 := sorry, rw this, have mulone := one_mul y, exact mulone, end /- Proof: We will prove that divides is antisymmetric. First, we expand the definitions of antisymmetric and divides. Then we perform case analysis on our assumed exists statements, leaving us to rewrite the cases. It is obvious that the value of a must be 1 by simple deduction from already present proofs, leaving us again to simply rewrite our goal, giving us a new goal that 1 * y = y, which is true by simple algebra. QED. -/ /- #5 Prove the following propositions. Remember that throughout this file, each definition implicitly includes β as a type and r as an arbitrary binary relation on β. In addition to formal proofs, give an English language proof of the last of the three problems. -/ -- A example : asymmetric r → irreflexive r := begin assume h x k, have nk := h k, contradiction, end /- Proof: We will provide a proof that a relation is irreflexive, given that the relation is asymmetric, by negation. We do this by assuming that r x x is true and showing that ¬ r x x is true by applying the proof that the relation is asymmetric to r x x, thus deriving a contradiction. QED. -/ -- B example : irreflexive r → transitive r → asymmetric r := begin unfold irreflexive transitive, assume i t x y, assume rxy, assume nryx, have f := t rxy nryx, have nrxx := i x, contradiction, end /- Proof: We will provide a proof by negation that a relation is asymmetric, given that the relation is irreflexive and transitive. We first expand the definitions of irreflexive and transitive. Then we make the assumptions that the relation r is irreflexive and transitive. Next, we assume r x y and ¬ r y x. After this, we apply transitive to r x y and ¬ r y x to derive a proof of r x x. Finally, we show a contradiction by applying irreflexive to x, which gives us ¬ r x x. QED. -/ -- C example : transitive r → ¬ symmetric r → ¬ irreflexive r := begin unfold transitive symmetric irreflexive, assume trans symm irrefl, end /- We do not believe that the proposition is provable or fixable. We tried to add that β is inhabited, but this effort was futile. We were unable to find a counter-example of a relation that shows the invalidity of the proposition. -/ end relation
1920c4de2eba0c24f88a9bed36d4555afdec1856
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/coe_univ_bug.lean
bd2a219d406fe7af17b2b15be7e000e50a6d249b
[ "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
425
lean
open nat def below (n : nat) : nat → Prop := λ i, i < n def f {n : nat} (v : subtype (below n)) : nat := v + 1 universe variable u instance pred2subtype {A : Type u} : has_coe_to_sort (A → Prop) _ := ⟨(λ p : A → Prop, subtype p)⟩ instance coesubtype {A : Type u} {p : A → Prop} : has_coe (@coe_sort _ _ pred2subtype p) A := ⟨λ s, subtype.val s⟩ def g {n : nat} (v : below n) : nat := v + 1 #print g
d57a7b65f94690dc7f089f622a1aefbd59db81ed
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Lean/Parser/Tactic.lean
1f377b7e5584ed44ecf7faf61adb19589b0e6c36
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,397
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Lean.Parser.Term namespace Lean namespace Parser namespace Tactic def underscoreFn : ParserFn := fun c s => let s := symbolFn "_" c s; let stx := s.stxStack.back; let s := s.popSyntax; s.pushSyntax $ mkIdentFrom stx `_ @[inline] def underscore : Parser := { fn := underscoreFn, info := mkAtomicInfo "ident" } def ident' : Parser := ident <|> underscore @[builtinTacticParser] def «intro» := parser! nonReservedSymbol "intro " >> optional ident' @[builtinTacticParser] def «intros» := parser! nonReservedSymbol "intros " >> many ident' @[builtinTacticParser] def «revert» := parser! nonReservedSymbol "revert " >> many1 ident @[builtinTacticParser] def «clear» := parser! nonReservedSymbol "clear " >> many1 ident @[builtinTacticParser] def «subst» := parser! nonReservedSymbol "subst " >> many1 ident @[builtinTacticParser] def «assumption» := parser! nonReservedSymbol "assumption" @[builtinTacticParser] def «apply» := parser! nonReservedSymbol "apply " >> termParser @[builtinTacticParser] def «exact» := parser! nonReservedSymbol "exact " >> termParser @[builtinTacticParser] def «refine» := parser! nonReservedSymbol "refine " >> termParser @[builtinTacticParser] def «case» := parser! nonReservedSymbol "case " >> ident >> tacticParser @[builtinTacticParser] def «allGoals» := parser! nonReservedSymbol "allGoals " >> tacticParser @[builtinTacticParser] def «skip» := parser! nonReservedSymbol "skip" @[builtinTacticParser] def «traceState» := parser! nonReservedSymbol "traceState" @[builtinTacticParser] def «failIfSuccess» := parser! nonReservedSymbol "failIfSuccess " >> tacticParser @[builtinTacticParser] def «generalize» := parser! nonReservedSymbol "generalize" >> optional (try (ident >> " : ")) >> termParser 50 >> " = " >> ident def majorPremise := parser! optional (try (ident >> " : ")) >> termParser def inductionAlt : Parser := nodeWithAntiquot "inductionAlt" `Lean.Parser.Tactic.inductionAlt $ ident' >> many ident' >> darrow >> (Term.hole <|> Term.namedHole <|> tacticParser) def inductionAlts : Parser := withPosition $ fun pos => "|" >> sepBy1 inductionAlt (checkColGe pos.column "alternatives must be indented" >> "|") def withAlts : Parser := optional (" with " >> inductionAlts) def usingRec : Parser := optional (" using " >> ident) def generalizingVars := optional (" generalizing " >> many1 ident) @[builtinTacticParser] def «induction» := parser! nonReservedSymbol "induction " >> majorPremise >> usingRec >> generalizingVars >> withAlts @[builtinTacticParser] def «cases» := parser! nonReservedSymbol "cases " >> majorPremise >> withAlts def withIds : Parser := optional (" with " >> many1 ident') @[builtinTacticParser] def «injection» := parser! nonReservedSymbol "injection " >> termParser >> withIds @[builtinTacticParser] def paren := parser! "(" >> nonEmptySeq >> ")" @[builtinTacticParser] def nestedTacticBlock := parser! "begin " >> seq >> "end" @[builtinTacticParser] def nestedTacticBlockCurly := parser! "{" >> seq >> "}" @[builtinTacticParser] def orelse := tparser! " <|> " >> tacticParser 1 end Tactic end Parser end Lean
a3bf8a4287c8cd131921fa5e2fbb70b07247acba
f1b175e38ffc5cc1c7c5551a72d0dbaf70786f83
/analysis/topology/uniform_space.lean
4f2e00da544166ce956aed70716d580de6c51b66
[ "Apache-2.0" ]
permissive
mjendrusch/mathlib
df3ae884dd5ce38c7edf452bcbfd3baf4e3a6214
5c209edb7eb616a26f64efe3500f2b1ba95b8d55
refs/heads/master
1,585,663,284,800
1,539,062,055,000
1,539,062,055,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
85,522
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot Theory of uniform spaces. Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * completeness * completion (on Cauchy filters instead of Cauchy sequences) * extension of uniform continuous functions to complete spaces * uniform contiunuity & embedding * totally bounded * totally bounded ∧ complete → compact One reason to directly formalize uniform spaces is foundational: we define ℝ as a completion of ℚ. The central concept of uniform spaces is its uniformity: a filter relating two elements of the space. This filter is reflexive, symmetric and transitive. So a set (i.e. a relation) in this filter represents a 'distance': it is reflexive, symmetric and the uniformity contains a set for which the `triangular` rule holds. The formalization is mostly based on the books: N. Bourbaki: General Topology I. M. James: Topologies and Uniformities A major difference is that this formalization is heavily based on the filter library. -/ import order.filter data.quot analysis.topology.topological_space analysis.topology.continuity open set lattice filter classical local attribute [instance] prop_decidable set_option eqn_compiler.zeta true universes u section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type*} := {p : α × α | p.1 = p.2} @[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s := by simp only [subset_def, prod.forall, mem_id_rel]; exact forall_congr (λ _, forall_eq') /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} @[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)} {x y : α} : (x, y) ∈ comp_rel r₁ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by rw [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, comp_rel (f x) (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ comp_rel s t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : comp_rel id_rel r = r := set.ext $ assume ⟨a, b⟩, by simp only [mem_comp_rel, mem_id_rel, exists_eq_left'] lemma comp_rel_assoc {r s t : set (α×α)} : comp_rel (comp_rel r s) t = comp_rel r (comp_rel s t) := by ext p; cases p; simp only [mem_comp_rel]; tauto /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : principal id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, comp_rel s s) ≤ uniformity) def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r ∈ U.sets) x, (x, x) ∈ r) (symm : ∀ r ∈ U.sets, {p | prod.swap p ∈ r} ∈ U.sets) (comp : ∀ r ∈ U.sets, ∃ t ∈ U.sets, comp_rel t t ⊆ r) : uniform_space.core α := ⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm, begin intros r ru, rw [mem_lift'_sets], exact comp _ ru, apply monotone_comp_rel; exact monotone_id, end⟩ /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity.sets, is_open_univ := λ _ _, by simp only [set.mem_univ, forall_true_iff]; exact univ_mem_sets, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt] assume ⟨a, b⟩ ih1 ih2 h, ⟨ih1 h, ih2 h⟩, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ rfl := rfl /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity.sets)) @[pattern] def uniform_space.mk' {α} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀s:set α, t.is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity.sets)) : uniform_space α := ⟨c, is_open_uniformity⟩ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.refl _ } def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.refl _ } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] @[extensionality] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h := have hu : u₁ = u₂, from uniform_space.core_eq h, have ht : t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂, hu], by substs hu ht lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl section uniform_space variables [uniform_space α] /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity : filter (α × α) := (@uniform_space.to_core α _).uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ (@uniformity α _).sets) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : principal id_rel ≤ @uniformity α _ := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ (@uniformity α _).sets) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) uniformity ≤ uniformity := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : uniformity.lift' (λs:set (α×α), comp_rel s s) ≤ uniformity := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto prod.swap (@uniformity α _) uniformity := symm_le_uniformity lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ_, (a, a)) f uniformity := assume s hs, show {x | (a, a) ∈ s} ∈ f.sets, from univ_mem_sets' $ assume b, refl_mem_uniformity hs lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, comp_rel t t ⊆ s := have s ∈ (uniformity.lift' (λt:set (α×α), comp_rel t t)).sets, from comp_le_uniformity hs, (mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ (@uniformity α _).sets, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem_sets hs this, assume a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ comp_rel t t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : uniformity ≤ (@prod.swap α α) <$> uniformity := by rw [map_swap_eq_comap_swap]; from map_le_iff_le_comap.1 tendsto_swap_uniformity lemma uniformity_eq_symm : uniformity = (@prod.swap α α) <$> uniformity := le_antisymm uniformity_le_symm symm_le_uniformity theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : uniformity.lift (λs, g (preimage prod.swap s)) ≤ f) : uniformity.lift g ≤ f := calc uniformity.lift g ≤ (filter.map prod.swap (@uniformity α _)).lift g : lift_mono uniformity_le_symm (le_refl _) ... ≤ _ : by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f): uniformity.lift (λs, f (comp_rel s s)) ≤ uniformity.lift f := calc uniformity.lift (λs, f (comp_rel s s)) = (uniformity.lift' (λs:set (α×α), comp_rel s s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ uniformity.lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s)) ≤ uniformity := calc uniformity.lift' (λd, comp_rel d (comp_rel d d)) = uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s (comp_rel t t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (principal ∘ comp_rel s) $ monotone_comp (monotone_comp_rel monotone_const monotone_id) monotone_principal ... = uniformity.lift' (λs:set(α×α), comp_rel s s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ uniformity : comp_le_uniformity lemma mem_nhds_uniformity_iff {x : α} {s : set α} : (s ∈ (nhds x).sets) ↔ ({p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets) := ⟨ begin simp only [mem_nhds_sets_iff, is_open_uniformity], rintro ⟨t, ts, ht, xt⟩, filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_sets_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets}, assume x' hx', refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'), by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b), have hp : (x', b) ∈ t, from hax' ▸ hp', have (b, b') ∈ t, from hab ▸ hp'', have (x', b') ∈ comp_rel t t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma nhds_eq_comap_uniformity {x : α} : nhds x = uniformity.comap (prod.mk x) := by ext s; rw [mem_nhds_uniformity_iff, mem_comap_sets]; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, uniformity.sets_of_superset h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by rwa h at hp) lemma nhds_eq_uniformity {x : α} : nhds x = uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ s}) := begin ext s, rw [mem_lift'_sets], tactic.swap, apply monotone_preimage, rw [mem_nhds_uniformity_iff], exact ⟨assume h, ⟨_, h, assume y h, h rfl⟩, assume ⟨t, h₁, h₂⟩, uniformity.sets_of_superset h₁ $ assume ⟨x', y⟩ hp (eq : x' = x), h₂ $ show (x, y) ∈ t, from eq ▸ hp⟩ end lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) : {y : α | (x, y) ∈ s} ∈ (nhds x).sets := have nhds x ≤ principal {y : α | (x, y) ∈ s}, by rw [nhds_eq_uniformity]; exact infi_le_of_le s (infi_le _ h), le_principal_iff.1 this lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) : {x : α | (x, y) ∈ s} ∈ (nhds y).sets := mem_nhds_left _ (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (nhds a) uniformity := assume s, mem_nhds_right a lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (nhds a) uniformity := assume s, mem_nhds_left a lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_comp monotone_preimage $ monotone_comp monotone_preimage monotone_principal) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> uniformity).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ monotone_comp monotone_preimage hg ... = _ : by rw [image_swap_eq_preimage_swap]; refl lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : filter.prod (nhds a) (nhds b) = uniformity.lift (λs:set (α×α), uniformity.lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := begin rw [prod_def], show (nhds a).lift (λs:set α, (nhds b).lift (λt:set α, principal (set.prod s t))) = _, rw [lift_nhds_right], apply congr_arg, funext s, rw [lift_nhds_left], refl, exact monotone_comp (monotone_prod monotone_const monotone_id) monotone_principal, exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : nhds (a, b) = uniformity.lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ (@uniformity α _).sets) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $ show cl_d ∈ (nhds (x, y)).sets, begin rw [nhds_eq_uniformity_prod, mem_lift'_sets], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simpa only [exists_prop, classical.skolem] using this, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp only [mem_Union]; exact ⟨(a, b), hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d∈(@uniformity α _).sets, comp_rel d (comp_rel t d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (nhds (a, b) ⊓ principal t ≠ ⊥) : by rw [closure_eq_nhds]; refl ... ↔ (((@prod.swap α α) <$> uniformity).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) uniformity).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by refl ... ↔ (uniformity.lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ principal t ≠ ⊥) : begin rw [map_lift'_eq2], simp only [image_swap_eq_preimage_swap]; refl, exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s∈(@uniformity α _).sets, ∃x, x ∈ set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t) : begin rw [lift'_inf_principal_eq, lift'_neq_bot_iff], apply forall_congr, intro s, rw [ne_empty_iff_exists_mem], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀s∈(@uniformity α _).sets, (a, b) ∈ comp_rel s (comp_rel t s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp only [mem_bInter_iff] lemma uniformity_eq_uniformity_closure : (@uniformity α _) = uniformity.lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, le_principal_iff.2 $ by filter_upwards [hs] subset_closure) (calc uniformity.lift' closure ≤ uniformity.lift' (λd, comp_rel d (comp_rel d d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ uniformity : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : (@uniformity α _) = uniformity.lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ assume x, assume : x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ (@uniformity α _).sets, by filter_upwards [hs] this, le_principal_iff.2 this) (assume s hs, (uniformity.lift' interior).sets_of_superset (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : interior s ∈ (@uniformity α _).sets := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed [uniform_space α] {s : set (α×α)} (h : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, is_closed t ∧ t ⊆ s := have s ∈ ((@uniformity α _).lift' closure).sets, by rwa [uniformity_eq_uniformity_closure] at h, have ∃t∈(@uniformity α _).sets, closure t ⊆ s, by rwa [mem_lift'_sets] at this; apply closure_mono, let ⟨t, ht, hst⟩ := this in ⟨closure t, uniformity.sets_of_superset ht subset_closure, is_closed_closure, hst⟩ /- uniform continuity -/ def uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) uniformity uniformity theorem uniform_continuous_def [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ (@uniformity β _).sets, {x : α × α | (f x.1, f x.2) ∈ r} ∈ (@uniformity α _).sets := iff.rfl lemma uniform_continuous_id : uniform_continuous (@id α) := show tendsto (λ x:α×α, (x.1, x.2)) _ _, by simp only [prod.mk.eta]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := @tendsto_const_uniformity _ _ _ b uniformity lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (g ∘ f) := hf.comp hg def uniform_embedding [uniform_space β] (f : α → β) := function.injective f ∧ comap (λx:α×α, (f x.1, f x.2)) uniformity = uniformity theorem uniform_embedding_def [uniform_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ ∀ s, s ∈ (@uniformity α _).sets ↔ ∃ t ∈ (@uniformity β _).sets, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s := by rw [uniform_embedding, eq_comm, filter.ext_iff]; simp only [filter.mem_comap_sets, subset_def, prod.forall]; refl theorem uniform_embedding_def' [uniform_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ s, s ∈ (@uniformity α _).sets → ∃ t ∈ (@uniformity β _).sets, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s := by simp only [uniform_embedding_def]; exact ⟨λ ⟨I, H⟩, ⟨I, λ s su, (H _).2 ⟨s, su, λ x y, id⟩, λ s, (H s).1⟩, λ ⟨I, H₁, H₂⟩, ⟨I, λ s, ⟨H₂ s, λ ⟨t, tu, h⟩, sets_of_superset _ (H₁ tu) (λ ⟨a, b⟩, h a b)⟩⟩⟩ lemma uniform_embedding.uniform_continuous [uniform_space β] {f : α → β} (hf : uniform_embedding f) : uniform_continuous f := (uniform_embedding_def'.1 hf).2.1 lemma uniform_embedding.uniform_continuous_iff [uniform_space β] [uniform_space γ] {f : α → β} {g : β → γ} (hg : uniform_embedding g) : uniform_continuous f ↔ uniform_continuous (g ∘ f) := by unfold uniform_continuous tendsto; rw [← hg.2, ← map_le_iff_le_comap, filter.map_map] lemma uniform_embedding.dense_embedding [uniform_space β] {f : α → β} (h : uniform_embedding f) (hd : ∀x, x ∈ closure (range f)) : dense_embedding f := { dense := hd, inj := h.left, induced := begin intro a, simp only [nhds_eq_uniformity], rw [← h.2, comap_lift'_eq, comap_lift'_eq2], refl, exact monotone_preimage, exact monotone_preimage end } lemma uniform_continuous.continuous [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_tendsto.mpr $ assume a, calc map f (nhds a) ≤ (map (λp:α×α, (f p.1, f p.2)) uniformity).lift' (λs:set (β×β), {y | (f a, y) ∈ s}) : begin rw [nhds_eq_uniformity, map_lift'_eq, map_lift'_eq2], exact (lift'_mono' $ assume s hs b ⟨a', (ha' : (_, a') ∈ s), a'_eq⟩, ⟨(a, a'), ha', show (f a, f a') = (f a, b), from a'_eq ▸ rfl⟩), exact monotone_preimage, exact monotone_preimage end ... ≤ nhds (f a) : by rw [nhds_eq_uniformity]; exact lift'_mono hf (le_refl _) lemma closure_image_mem_nhds_of_uniform_embedding [uniform_space α] [uniform_space β] {s : set (α×α)} {e : α → β} (b : β) (he₁ : uniform_embedding e) (he₂ : dense_embedding e) (hs : s ∈ (@uniformity α _).sets) : ∃a, closure (e '' {a' | (a, a') ∈ s}) ∈ (nhds b).sets := have s ∈ (comap (λp:α×α, (e p.1, e p.2)) $ uniformity).sets, from he₁.right.symm ▸ hs, let ⟨t₁, ht₁u, ht₁⟩ := this in have ht₁ : ∀p:α×α, (e p.1, e p.2) ∈ t₁ → p ∈ s, from ht₁, let ⟨t₂, ht₂u, ht₂s, ht₂c⟩ := comp_symm_of_uniformity ht₁u in let ⟨t, htu, hts, htc⟩ := comp_symm_of_uniformity ht₂u in have preimage e {b' | (b, b') ∈ t₂} ∈ (comap e $ nhds b).sets, from preimage_mem_comap $ mem_nhds_left b ht₂u, let ⟨a, (ha : (b, e a) ∈ t₂)⟩ := inhabited_of_mem_sets (he₂.comap_nhds_neq_bot) this in have ∀b' (s' : set (β × β)), (b, b') ∈ t → s' ∈ (@uniformity β _).sets → {y : β | (b', y) ∈ s'} ∩ e '' {a' : α | (a, a') ∈ s} ≠ ∅, from assume b' s' hb' hs', have preimage e {b'' | (b', b'') ∈ s' ∩ t} ∈ (comap e $ nhds b').sets, from preimage_mem_comap $ mem_nhds_left b' $ inter_mem_sets hs' htu, let ⟨a₂, ha₂s', ha₂t⟩ := inhabited_of_mem_sets (he₂.comap_nhds_neq_bot) this in have (e a, e a₂) ∈ t₁, from ht₂c $ prod_mk_mem_comp_rel (ht₂s ha) $ htc $ prod_mk_mem_comp_rel hb' ha₂t, have e a₂ ∈ {b'':β | (b', b'') ∈ s'} ∩ e '' {a' | (a, a') ∈ s}, from ⟨ha₂s', mem_image_of_mem _ $ ht₁ (a, a₂) this⟩, ne_empty_of_mem this, have ∀b', (b, b') ∈ t → nhds b' ⊓ principal (e '' {a' | (a, a') ∈ s}) ≠ ⊥, begin intros b' hb', rw [nhds_eq_uniformity, lift'_inf_principal_eq, lift'_neq_bot_iff], exact assume s, this b' s hb', exact monotone_inter monotone_preimage monotone_const end, have ∀b', (b, b') ∈ t → b' ∈ closure (e '' {a' | (a, a') ∈ s}), from assume b' hb', by rw [closure_eq_nhds]; exact this b' hb', ⟨a, (nhds b).sets_of_superset (mem_nhds_left b htu) this⟩ /-- A filter `f` is Cauchy if for every entourage `r`, there exists an `s ∈ f` such that `s × s ⊆ r`. This is a generalization of Cauchy sequences, because if `a : ℕ → α` then the filter of sets containing cofinitely many of the `a n` is Cauchy iff `a` is a Cauchy sequence. -/ def cauchy (f : filter α) := f ≠ ⊥ ∧ filter.prod f f ≤ uniformity lemma cauchy_iff [uniform_space α] {f : filter α} : cauchy f ↔ (f ≠ ⊥ ∧ (∀s∈(@uniformity α _).sets, ∃t∈f.sets, set.prod t t ⊆ s)) := and_congr (iff.refl _) $ forall_congr $ assume s, forall_congr $ assume hs, mem_prod_same_iff lemma cauchy_downwards {f g : filter α} (h_c : cauchy f) (hg : g ≠ ⊥) (h_le : g ≤ f) : cauchy g := ⟨hg, le_trans (filter.prod_mono h_le h_le) h_c.right⟩ lemma cauchy_nhds {a : α} : cauchy (nhds a) := ⟨nhds_neq_bot, calc filter.prod (nhds a) (nhds a) = uniformity.lift (λs:set (α×α), uniformity.lift' (λt:set(α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (a, y) ∈ t})) : nhds_nhds_eq_uniformity_uniformity_prod ... ≤ uniformity.lift' (λs:set (α×α), comp_rel s s) : le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le_of_le hs $ principal_mono.mpr $ assume ⟨x, y⟩ ⟨(hx : (x, a) ∈ s), (hy : (a, y) ∈ s)⟩, ⟨a, hx, hy⟩ ... ≤ uniformity : comp_le_uniformity⟩ lemma cauchy_pure {a : α} : cauchy (pure a) := cauchy_downwards cauchy_nhds (show principal {a} ≠ ⊥, from mt principal_eq_bot_iff.1 (singleton_ne_empty a)) (pure_le_nhds a) lemma le_nhds_of_cauchy_adhp {f : filter α} {x : α} (hf : cauchy f) (adhs : f ⊓ nhds x ≠ ⊥) : f ≤ nhds x := have ∀s∈f.sets, x ∈ closure s, begin intros s hs, simp only [closure_eq_nhds, inf_comm], exact assume h', adhs $ bot_unique $ h' ▸ inf_le_inf (le_principal_iff.2 hs) (le_refl _) end, calc f ≤ f.lift' (λs:set α, {y | x ∈ closure s ∧ y ∈ closure s}) : le_infi $ assume s, le_infi $ assume hs, begin rw [←forall_sets_neq_empty_iff_neq_bot] at adhs, exact le_principal_iff.2 (mem_sets_of_superset hs (λ _ H, ⟨this s hs, subset_closure H⟩)) end ... ≤ f.lift' (λs:set α, {y | (x, y) ∈ closure (set.prod s s)}) : by simp only [closure_prod_eq]; exact le_refl _ ... = (filter.prod f f).lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : begin rw [prod_same_eq], rw [lift'_lift'_assoc], exact monotone_prod monotone_id monotone_id, exact monotone_comp (assume s t h x h', closure_mono h h') monotone_preimage end ... ≤ uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : lift'_mono hf.right (le_refl _) ... = (uniformity.lift' closure).lift' (λs:set (α×α), {y | (x, y) ∈ s}) : begin rw [lift'_lift'_assoc], exact assume s t h, closure_mono h, exact monotone_preimage end ... = uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ s}) : by rw [←uniformity_eq_uniformity_closure] ... = nhds x : by rw [nhds_eq_uniformity] lemma le_nhds_iff_adhp_of_cauchy {f : filter α} {x : α} (hf : cauchy f) : f ≤ nhds x ↔ f ⊓ nhds x ≠ ⊥ := ⟨assume h, (inf_of_le_left h).symm ▸ hf.left, le_nhds_of_cauchy_adhp hf⟩ lemma cauchy_map [uniform_space β] {f : filter α} {m : α → β} (hm : uniform_continuous m) (hf : cauchy f) : cauchy (map m f) := ⟨have f ≠ ⊥, from hf.left, by simp; assumption, calc filter.prod (map m f) (map m f) = map (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_map_map_eq ... ≤ map (λp:α×α, (m p.1, m p.2)) uniformity : map_mono hf.right ... ≤ uniformity : hm⟩ lemma cauchy_comap [uniform_space β] {f : filter β} {m : α → β} (hm : comap (λp:α×α, (m p.1, m p.2)) uniformity ≤ uniformity) (hf : cauchy f) (hb : comap m f ≠ ⊥) : cauchy (comap m f) := ⟨hb, calc filter.prod (comap m f) (comap m f) = comap (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_comap_comap_eq ... ≤ comap (λp:α×α, (m p.1, m p.2)) uniformity : comap_mono hf.right ... ≤ uniformity : hm⟩ /- separated uniformity -/ /-- The separation relation is the intersection of all entourages. Two points which are related by the separation relation are "indistinguishable" according to the uniform structure. -/ protected def separation_rel (α : Type u) [u : uniform_space α] := ⋂₀ (@uniformity α _).sets lemma separated_equiv : equivalence (λx y, (x, y) ∈ separation_rel α) := ⟨assume x, assume s, refl_mem_uniformity, assume x y, assume h (s : set (α×α)) hs, have preimage prod.swap s ∈ (@uniformity α _).sets, from symm_le_uniformity hs, h _ this, assume x y z (hxy : (x, y) ∈ separation_rel α) (hyz : (y, z) ∈ separation_rel α) s (hs : s ∈ (@uniformity α _).sets), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ protected def separation_setoid (α : Type u) [u : uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ separation_rel α, separated_equiv⟩ @[class] def separated (α : Type u) [uniform_space α] := separation_rel α = id_rel theorem separated_def {α : Type u} [uniform_space α] : separated α ↔ ∀ x y, (∀ r ∈ (@uniformity α _).sets, (x, y) ∈ r) → x = y := by simp only [separated, id_rel_subset.2 separated_equiv.1, subset.antisymm_iff, and_true]; simp only [subset_def, separation_rel, set.mem_sInter, prod.forall, mem_id_rel] theorem separated_def' {α : Type u} [uniform_space α] : separated α ↔ ∀ x y, x ≠ y → ∃ r ∈ (@uniformity α _).sets, (x, y) ∉ r := separated_def.trans $ forall_congr $ λ x, forall_congr $ λ y, by rw ← not_imp_not; simp only [classical.not_forall] instance separated_t2 [s : separated α] : t2_space α := ⟨assume x y, assume h : x ≠ y, let ⟨d, hd, (hxy : (x, y) ∉ d)⟩ := separated_def'.1 s x y h in let ⟨d', hd', (hd'd' : comp_rel d' d' ⊆ d)⟩ := comp_mem_uniformity_sets hd in have {y | (x, y) ∈ d'} ∈ (nhds x).sets, from mem_nhds_left x hd', let ⟨u, hu₁, hu₂, hu₃⟩ := mem_nhds_sets_iff.mp this in have {x | (x, y) ∈ d'} ∈ (nhds y).sets, from mem_nhds_right y hd', let ⟨v, hv₁, hv₂, hv₃⟩ := mem_nhds_sets_iff.mp this in have u ∩ v = ∅, from eq_empty_of_subset_empty $ assume z ⟨(h₁ : z ∈ u), (h₂ : z ∈ v)⟩, have (x, y) ∈ comp_rel d' d', from ⟨z, hu₁ h₁, hv₁ h₂⟩, hxy $ hd'd' this, ⟨u, v, hu₂, hv₂, hu₃, hv₃, this⟩⟩ instance separated_regular [separated α] : regular_space α := { regular := λs a hs ha, have -s ∈ (nhds a).sets, from mem_nhds_sets hs ha, have {p : α × α | p.1 = a → p.2 ∈ -s} ∈ uniformity.sets, from mem_nhds_uniformity_iff.mp this, let ⟨d, hd, h⟩ := comp_mem_uniformity_sets this in let e := {y:α| (a, y) ∈ d} in have hae : a ∈ closure e, from subset_closure $ refl_mem_uniformity hd, have set.prod (closure e) (closure e) ⊆ comp_rel d (comp_rel (set.prod e e) d), begin rw [←closure_prod_eq, closure_eq_inter_uniformity], change (⨅d' ∈ uniformity.sets, _) ≤ comp_rel d (comp_rel _ d), exact (infi_le_of_le d $ infi_le_of_le hd $ le_refl _) end, have e_subset : closure e ⊆ -s, from assume a' ha', let ⟨x, (hx : (a, x) ∈ d), y, ⟨hx₁, hx₂⟩, (hy : (y, _) ∈ d)⟩ := @this ⟨a, a'⟩ ⟨hae, ha'⟩ in have (a, a') ∈ comp_rel d d, from ⟨y, hx₂, hy⟩, h this rfl, have closure e ∈ (nhds a).sets, from (nhds a).sets_of_superset (mem_nhds_left a hd) subset_closure, have nhds a ⊓ principal (-closure e) = ⊥, from (@inf_eq_bot_iff_le_compl _ _ _ (principal (- closure e)) (principal (closure e)) (by simp only [union_compl_self, sup_principal, principal_univ, union_comm]) (by simp only [compl_inter_self, inf_principal, principal_eq_bot_iff])).mpr (le_principal_iff.2 this), ⟨- closure e, is_closed_closure, assume x h₁ h₂, @e_subset x h₂ h₁, this⟩, ..separated_t2 } /-- A set `s` is totally bounded if for every entourage `d` there is a finite set of points `t` such that every element of `s` is `d`-near to some element of `t`. -/ def totally_bounded (s : set α) : Prop := ∀d ∈ (@uniformity α _).sets, ∃t : set α, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) theorem totally_bounded_iff_subset {s : set α} : totally_bounded s ↔ ∀d ∈ (@uniformity α _).sets, ∃t ⊆ s, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) := ⟨λ H d hd, begin rcases comp_symm_of_uniformity hd with ⟨r, hr, rs, rd⟩, rcases H r hr with ⟨k, fk, ks⟩, let u := {y ∈ k | ∃ x, x ∈ s ∧ (x, y) ∈ r}, choose f this using assume x:u, x.2.2, refine ⟨range f, _, _, _⟩, { exact range_subset_iff.2 (λ x, (this x).1) }, { have : finite u := finite_subset fk (λ x h, h.1), exact ⟨@set.fintype_range _ _ _ _ this.fintype⟩ }, { intros x xs, rcases mem_Union.1 (ks xs) with ⟨y, hy⟩, rcases mem_Union.1 hy with ⟨hy, xy⟩, let z : coe_sort u := ⟨y, hy, x, xs, xy⟩, refine mem_Union.2 ⟨f z, mem_Union.2 ⟨mem_range_self z, _⟩⟩, exact rd (mem_comp_rel.2 ⟨_, xy, rs (this z).2⟩) } end, λ H d hd, let ⟨t, _, ht⟩ := H d hd in ⟨t, ht⟩⟩ lemma totally_bounded_subset [uniform_space α] {s₁ s₂ : set α} (hs : s₁ ⊆ s₂) (h : totally_bounded s₂) : totally_bounded s₁ := assume d hd, let ⟨t, ht₁, ht₂⟩ := h d hd in ⟨t, ht₁, subset.trans hs ht₂⟩ lemma totally_bounded_closure [uniform_space α] {s : set α} (h : totally_bounded s) : totally_bounded (closure s) := assume t ht, let ⟨t', ht', hct', htt'⟩ := mem_uniformity_is_closed ht, ⟨c, hcf, hc⟩ := h t' ht' in ⟨c, hcf, calc closure s ⊆ closure (⋃ (y : α) (H : y ∈ c), {x : α | (x, y) ∈ t'}) : closure_mono hc ... = _ : closure_eq_of_is_closed $ is_closed_Union hcf $ assume i hi, continuous_iff_is_closed.mp (continuous_id.prod_mk continuous_const) _ hct' ... ⊆ _ : bUnion_subset $ assume i hi, subset.trans (assume x, @htt' (x, i)) (subset_bUnion_of_mem hi)⟩ lemma totally_bounded_image [uniform_space α] [uniform_space β] {f : α → β} {s : set α} (hf : uniform_continuous f) (hs : totally_bounded s) : totally_bounded (f '' s) := assume t ht, have {p:α×α | (f p.1, f p.2) ∈ t} ∈ (@uniformity α _).sets, from hf ht, let ⟨c, hfc, hct⟩ := hs _ this in ⟨f '' c, finite_image f hfc, image_subset_iff.2 $ λ x hx, let ⟨i, hi, ht⟩ := mem_bUnion_iff.1 (hct hx) in mem_bUnion ⟨i, hi, rfl⟩ ht⟩ lemma totally_bounded_preimage [uniform_space α] [uniform_space β] {f : α → β} {s : set β} (hf : uniform_embedding f) (hs : totally_bounded s) : totally_bounded (f ⁻¹' s) := λ t ht, begin rw ← hf.2 at ht, rcases mem_comap_sets.2 ht with ⟨t', ht', ts⟩, rcases totally_bounded_iff_subset.1 (totally_bounded_subset (image_preimage_subset f s) hs) _ ht' with ⟨c, cs, hfc, hct⟩, refine ⟨f ⁻¹' c, finite_preimage hf.1 hfc, λ x h, _⟩, have := hct (mem_image_of_mem f h), rw [mem_bUnion_iff] at this ⊢, rcases this with ⟨z, zc, zt⟩, rcases cs zc with ⟨y, yc, rfl⟩, exact ⟨y, zc, ts (by exact zt)⟩ end lemma cauchy_of_totally_bounded_of_ultrafilter {s : set α} {f : filter α} (hs : totally_bounded s) (hf : ultrafilter f) (h : f ≤ principal s) : cauchy f := ⟨hf.left, assume t ht, let ⟨t', ht'₁, ht'_symm, ht'_t⟩ := comp_symm_of_uniformity ht in let ⟨i, hi, hs_union⟩ := hs t' ht'₁ in have (⋃y∈i, {x | (x,y) ∈ t'}) ∈ f.sets, from mem_sets_of_superset (le_principal_iff.mp h) hs_union, have ∃y∈i, {x | (x,y) ∈ t'} ∈ f.sets, from mem_of_finite_Union_ultrafilter hf hi this, let ⟨y, hy, hif⟩ := this in have set.prod {x | (x,y) ∈ t'} {x | (x,y) ∈ t'} ⊆ comp_rel t' t', from assume ⟨x₁, x₂⟩ ⟨(h₁ : (x₁, y) ∈ t'), (h₂ : (x₂, y) ∈ t')⟩, ⟨y, h₁, ht'_symm h₂⟩, (filter.prod f f).sets_of_superset (prod_mem_prod hif hif) (subset.trans this ht'_t)⟩ lemma totally_bounded_iff_filter {s : set α} : totally_bounded s ↔ (∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c) := ⟨assume : totally_bounded s, assume f hf hs, ⟨ultrafilter_of f, ultrafilter_of_le, cauchy_of_totally_bounded_of_ultrafilter this (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hs)⟩, assume h : ∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c, assume d hd, classical.by_contradiction $ assume hs, have hd_cover : ∀{t:set α}, finite t → ¬ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}), by simpa only [not_exists, not_and] using hs, let f := ⨅t:{t : set α // finite t}, principal (s \ (⋃y∈t.val, {x | (x,y) ∈ d})), ⟨a, ha⟩ := @exists_mem_of_ne_empty α s (assume h, hd_cover finite_empty $ h.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩ (assume ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, ⟨⟨t₁ ∪ t₂, finite_union ht₁ ht₂⟩, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inl, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inr⟩) (assume ⟨t, ht⟩, mt (diff_eq_empty.1 ∘ principal_eq_bot_iff.1) (hd_cover ht)), have f ≤ principal s, from infi_le_of_le ⟨∅, finite_empty⟩ $ le_principal_iff.2 (diff_subset _ _), let ⟨c, (hc₁ : c ≤ f), (hc₂ : cauchy c)⟩ := h f ‹f ≠ ⊥› this, ⟨m, hm, (hmd : set.prod m m ⊆ d)⟩ := (@mem_prod_same_iff α c d).mp $ hc₂.right hd in have c ≤ principal s, from le_trans ‹c ≤ f› this, have m ∩ s ∈ c.sets, from inter_mem_sets hm $ le_principal_iff.mp this, let ⟨y, hym, hys⟩ := inhabited_of_mem_sets hc₂.left this in let ys := (⋃y'∈({y}:set α), {x | (x, y') ∈ d}) in have m ⊆ ys, from assume y' hy', show y' ∈ (⋃y'∈({y}:set α), {x | (x, y') ∈ d}), by rw bUnion_singleton; exact @hmd (y', y) ⟨hy', hym⟩, have c ≤ principal (s - ys), from le_trans hc₁ $ infi_le_of_le ⟨{y}, finite_singleton _⟩ $ le_refl _, have (s - ys) ∩ (m ∩ s) ∈ c.sets, from inter_mem_sets (le_principal_iff.mp this) ‹m ∩ s ∈ c.sets›, have ∅ ∈ c.sets, from c.sets_of_superset this $ assume x ⟨⟨hxs, hxys⟩, hxm, _⟩, hxys $ ‹m ⊆ ys› hxm, hc₂.left $ empty_in_sets_eq_bot.mp this⟩ lemma totally_bounded_iff_ultrafilter {s : set α} : totally_bounded s ↔ (∀f, ultrafilter f → f ≤ principal s → cauchy f) := ⟨assume hs f, cauchy_of_totally_bounded_of_ultrafilter hs, assume h, totally_bounded_iff_filter.mpr $ assume f hf hfs, have cauchy (ultrafilter_of f), from h (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs), ⟨ultrafilter_of f, ultrafilter_of_le, this⟩⟩ lemma compact_of_totally_bounded_complete {s : set α} (ht : totally_bounded s) (hc : ∀{f:filter α}, cauchy f → f ≤ principal s → ∃x∈s, f ≤ nhds x) : compact s := begin rw [compact_iff_ultrafilter_le_nhds], rw [totally_bounded_iff_ultrafilter] at ht, exact assume f hf hfs, hc (ht _ hf hfs) hfs end /-- A complete space is defined here using uniformities. A uniform space is complete if every Cauchy filter converges. -/ class complete_space (α : Type u) [uniform_space α] : Prop := (complete : ∀{f:filter α}, cauchy f → ∃x, f ≤ nhds x) theorem le_nhds_lim_of_cauchy {α} [uniform_space α] [complete_space α] [inhabited α] {f : filter α} (hf : cauchy f) : f ≤ nhds (lim f) := lim_spec (complete_space.complete hf) lemma complete_of_is_closed [complete_space α] {s : set α} {f : filter α} (h : is_closed s) (hf : cauchy f) (hfs : f ≤ principal s) : ∃x∈s, f ≤ nhds x := let ⟨x, hx⟩ := complete_space.complete hf in have x ∈ s, from is_closed_iff_nhds.mp h x $ neq_bot_of_le_neq_bot hf.left $ le_inf hx hfs, ⟨x, this, hx⟩ lemma compact_of_totally_bounded_is_closed [complete_space α] {s : set α} (ht : totally_bounded s) (hc : is_closed s) : compact s := @compact_of_totally_bounded_complete α _ s ht $ assume f, complete_of_is_closed hc lemma complete_space_extension [uniform_space β] {m : β → α} (hm : uniform_embedding m) (dense : ∀x, x ∈ closure (range m)) (h : ∀f:filter β, cauchy f → ∃x:α, map m f ≤ nhds x) : complete_space α := ⟨assume (f : filter α), assume hf : cauchy f, let p : set (α × α) → set α → set α := λs t, {y : α| ∃x:α, x ∈ t ∧ (x, y) ∈ s}, g := uniformity.lift (λs, f.lift' (p s)) in have mp₀ : monotone p, from assume a b h t s ⟨x, xs, xa⟩, ⟨x, xs, h xa⟩, have mp₁ : ∀{s}, monotone (p s), from assume s a b h x ⟨y, ya, yxs⟩, ⟨y, h ya, yxs⟩, have f ≤ g, from le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, le_principal_iff.mpr $ mem_sets_of_superset ht $ assume x hx, ⟨x, hx, refl_mem_uniformity hs⟩, have g ≠ ⊥, from neq_bot_of_le_neq_bot hf.left this, have comap m g ≠ ⊥, from comap_neq_bot $ assume t ht, let ⟨t', ht', ht_mem⟩ := (mem_lift_sets $ monotone_lift' monotone_const mp₀).mp ht in let ⟨t'', ht'', ht'_sub⟩ := (mem_lift'_sets mp₁).mp ht_mem in let ⟨x, (hx : x ∈ t'')⟩ := inhabited_of_mem_sets hf.left ht'' in have h₀ : nhds x ⊓ principal (range m) ≠ ⊥, by rw [closure_eq_nhds] at dense; exact dense x, have h₁ : {y | (x, y) ∈ t'} ∈ (nhds x ⊓ principal (range m)).sets, from @mem_inf_sets_of_left α (nhds x) (principal (range m)) _ $ mem_nhds_left x ht', have h₂ : range m ∈ (nhds x ⊓ principal (range m)).sets, from @mem_inf_sets_of_right α (nhds x) (principal (range m)) _ $ subset.refl _, have {y | (x, y) ∈ t'} ∩ range m ∈ (nhds x ⊓ principal (range m)).sets, from @inter_mem_sets α (nhds x ⊓ principal (range m)) _ _ h₁ h₂, let ⟨y, xyt', b, b_eq⟩ := inhabited_of_mem_sets h₀ this in ⟨b, b_eq.symm ▸ ht'_sub ⟨x, hx, xyt'⟩⟩, have cauchy g, from ⟨‹g ≠ ⊥›, assume s hs, let ⟨s₁, hs₁, (comp_s₁ : comp_rel s₁ s₁ ⊆ s)⟩ := comp_mem_uniformity_sets hs, ⟨s₂, hs₂, (comp_s₂ : comp_rel s₂ s₂ ⊆ s₁)⟩ := comp_mem_uniformity_sets hs₁, ⟨t, ht, (prod_t : set.prod t t ⊆ s₂)⟩ := mem_prod_same_iff.mp (hf.right hs₂) in have hg₁ : p (preimage prod.swap s₁) t ∈ g.sets, from mem_lift (symm_le_uniformity hs₁) $ @mem_lift' α α f _ t ht, have hg₂ : p s₂ t ∈ g.sets, from mem_lift hs₂ $ @mem_lift' α α f _ t ht, have hg : set.prod (p (preimage prod.swap s₁) t) (p s₂ t) ∈ (filter.prod g g).sets, from @prod_mem_prod α α _ _ g g hg₁ hg₂, (filter.prod g g).sets_of_superset hg (assume ⟨a, b⟩ ⟨⟨c₁, c₁t, hc₁⟩, ⟨c₂, c₂t, hc₂⟩⟩, have (c₁, c₂) ∈ set.prod t t, from ⟨c₁t, c₂t⟩, comp_s₁ $ prod_mk_mem_comp_rel hc₁ $ comp_s₂ $ prod_mk_mem_comp_rel (prod_t this) hc₂)⟩, have cauchy (filter.comap m g), from cauchy_comap (le_of_eq hm.right) ‹cauchy g› (by assumption), let ⟨x, (hx : map m (filter.comap m g) ≤ nhds x)⟩ := h _ this in have map m (filter.comap m g) ⊓ nhds x ≠ ⊥, from (le_nhds_iff_adhp_of_cauchy (cauchy_map hm.uniform_continuous this)).mp hx, have g ⊓ nhds x ≠ ⊥, from neq_bot_of_le_neq_bot this (inf_le_inf (assume s hs, ⟨s, hs, subset.refl _⟩) (le_refl _)), ⟨x, calc f ≤ g : by assumption ... ≤ nhds x : le_nhds_of_cauchy_adhp ‹cauchy g› this⟩⟩ /- separation space -/ section separation_space local attribute [instance] separation_setoid instance {α : Type u} [u : uniform_space α] : uniform_space (quotient (separation_setoid α)) := { to_topological_space := u.to_topological_space.coinduced (λx, ⟦x⟧), uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity, refl := assume s hs ⟨a, b⟩ (h : a = b), have ∀a:α, (a, a) ∈ preimage (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) s, from assume a, refl_mem_uniformity hs, h ▸ quotient.induction_on a this, symm := tendsto_map' $ tendsto_swap_uniformity.comp tendsto_map, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity).lift' (λs, comp_rel s s) = uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ assume s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin clear_, cases a_eq, injection b_eq with h₁ h₂, simp only at h₂, subst h₂, have h : (a₂, b₁) ∈ separation_rel α := quotient.exact h₁.symm, exact ⟨(a₁, b₂), ⟨_, ha, ⟨_, h s hs, hb⟩⟩, rfl⟩ end ... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity : map_mono comp_le_uniformity3, is_open_uniformity := assume s, have ∀a, ⟦a⟧ ∈ s → ({p:α×α | p.1 = a → ⟦p.2⟧ ∈ s} ∈ (@uniformity α _).sets ↔ {p:α×α | p.1 ≈ a → ⟦p.2⟧ ∈ s} ∈ (@uniformity α _).sets), from assume a ha, ⟨assume h, let ⟨t, ht, hts⟩ := comp_mem_uniformity_sets h in have hts : ∀{a₁ a₂}, (a, a₁) ∈ t → (a₁, a₂) ∈ t → ⟦a₂⟧ ∈ s, from assume a₁ a₂ ha₁ ha₂, @hts (a, a₂) ⟨a₁, ha₁, ha₂⟩ rfl, have ht' : ∀{a₁ a₂}, a₁ ≈ a₂ → (a₁, a₂) ∈ t, from assume a₁ a₂ h, sInter_subset_of_mem ht h, uniformity.sets_of_superset ht $ assume ⟨a₁, a₂⟩ h₁ h₂, hts (ht' $ setoid.symm h₂) h₁, assume h, uniformity.sets_of_superset h $ λ p hp1 hp2, hp1 (hp2 ▸ setoid.refl _)⟩, begin simp only [topological_space.coinduced, u.is_open_uniformity, uniformity, forall_quotient_iff, mem_map, mem_set_of_eq, quotient.eq], exact ⟨λh a ha, (this a ha).mp $ h a ha, λh a ha, (this a ha).mpr $ h a ha⟩ end } lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_refl _ lemma comap_quotient_le_uniformity : comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity ≤ uniformity := assume t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (@uniformity α _).sets_of_superset hs $ assume x hx, ⟨x, hx, rfl⟩, assume ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma comap_quotient_eq_uniformity : comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity = uniformity := le_antisymm comap_quotient_le_uniformity le_comap_map lemma complete_space_separation [h : complete_space α] : complete_space (quotient (separation_setoid α)) := ⟨assume f, assume hf : cauchy f, have cauchy (comap (λx, ⟦x⟧) f), from cauchy_comap comap_quotient_le_uniformity hf $ comap_neq_bot_of_surj hf.left $ assume b, quotient.exists_rep _, let ⟨x, (hx : comap (λx, ⟦x⟧) f ≤ nhds x)⟩ := complete_space.complete this in ⟨⟦x⟧, calc f ≤ map (λx, ⟦x⟧) (comap (λx, ⟦x⟧) f) : le_map_comap $ assume b, quotient.exists_rep _ ... ≤ map (λx, ⟦x⟧) (nhds x) : map_mono hx ... ≤ _ : continuous_iff_tendsto.mp uniform_continuous_quotient_mk.continuous _⟩⟩ lemma separated_separation [h : complete_space α] : separated (quotient (separation_setoid α)) := set.ext $ assume ⟨a, b⟩, quotient.induction_on₂ a b $ assume a b, ⟨assume h, have a ≈ b, from assume s hs, have s ∈ (comap (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity).sets, from comap_quotient_le_uniformity hs, let ⟨t, ht, hts⟩ := this in @hts (a, b) (h t ht), show ⟦a⟧ = ⟦b⟧, from quotient.sound this, assume heq : ⟦a⟧ = ⟦b⟧, assume h hs, heq ▸ refl_mem_uniformity hs⟩ variables [uniform_space β] [uniform_space γ] lemma uniform_continuous_quotient {f : quotient (separation_setoid α) → β} (hf : uniform_continuous (λx, f ⟦x⟧)) : uniform_continuous f := hf lemma uniform_continuous_quotient_lift {f : α → β} {h : ∀a b, (a, b) ∈ separation_rel α → f a = f b} (hf : uniform_continuous f) : uniform_continuous (λa, quotient.lift f h a) := uniform_continuous_quotient hf lemma uniformity_quotient : @uniformity (quotient (separation_setoid α)) _ = uniformity.map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) := rfl lemma separated_of_uniform_continuous {f : α → β} (H : uniform_continuous f) {x y : α} (h : x ≈ y) : f x ≈ f y := assume _ h', h _ (H h') lemma eq_of_separated_of_uniform_continuous [separated β] {f : α → β} (H : uniform_continuous f) {x y : α} (h : x ≈ y) : f x = f y := separated_def.1 (by apply_instance) _ _ $ separated_of_uniform_continuous H h end separation_space section uniform_extension variables [uniform_space β] [uniform_space γ] {e : β → α} (h_e : uniform_embedding e) (h_dense : ∀x, x ∈ closure (range e)) {f : β → γ} (h_f : uniform_continuous f) local notation `ψ` := (h_e.dense_embedding h_dense).extend f lemma uniformly_extend_of_emb [cγ : complete_space γ] [sγ : separated γ] {b : β} : ψ (e b) = f b := dense_embedding.extend_e_eq _ $ continuous_iff_tendsto.mp h_f.continuous b lemma uniformly_extend_exists [complete_space γ] [sγ : separated γ] {a : α} : ∃c, tendsto f (comap e (nhds a)) (nhds c) := let de := (h_e.dense_embedding h_dense) in have cauchy (nhds a), from cauchy_nhds, have cauchy (comap e (nhds a)), from cauchy_comap (le_of_eq h_e.right) this de.comap_nhds_neq_bot, have cauchy (map f (comap e (nhds a))), from cauchy_map h_f this, complete_space.complete this lemma uniformly_extend_spec [complete_space γ] [sγ : separated γ] {a : α} : tendsto f (comap e (nhds a)) (nhds (ψ a)) := @lim_spec _ (id _) _ _ $ uniformly_extend_exists h_e h_dense h_f lemma uniform_continuous_uniformly_extend [cγ : complete_space γ] [sγ : separated γ] : uniform_continuous ψ := assume d hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in have h_pnt : ∀{a m}, m ∈ (nhds a).sets → ∃c, c ∈ f '' preimage e m ∧ (c, ψ a) ∈ s ∧ (ψ a, c) ∈ s, from assume a m hm, have nb : map f (comap e (nhds a)) ≠ ⊥, from map_ne_bot (h_e.dense_embedding h_dense).comap_nhds_neq_bot, have (f '' preimage e m) ∩ ({c | (c, ψ a) ∈ s } ∩ {c | (ψ a, c) ∈ s }) ∈ (map f (comap e (nhds a))).sets, from inter_mem_sets (image_mem_map $ preimage_mem_comap $ hm) (uniformly_extend_spec h_e h_dense h_f $ inter_mem_sets (mem_nhds_right _ hs) (mem_nhds_left _ hs)), inhabited_of_mem_sets nb this, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ (@uniformity β _).sets, from h_f hs, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ (comap (λx:β×β, (e x.1, e x.2)) uniformity).sets, by rwa [h_e.right.symm] at this, let ⟨t, ht, ts⟩ := this in show preimage (λp:(α×α), (ψ p.1, ψ p.2)) d ∈ uniformity.sets, from (@uniformity α _).sets_of_superset (interior_mem_uniformity ht) $ assume ⟨x₁, x₂⟩ hx_t, have nhds (x₁, x₂) ≤ principal (interior t), from is_open_iff_nhds.mp is_open_interior (x₁, x₂) hx_t, have interior t ∈ (filter.prod (nhds x₁) (nhds x₂)).sets, by rwa [nhds_prod_eq, le_principal_iff] at this, let ⟨m₁, hm₁, m₂, hm₂, (hm : set.prod m₁ m₂ ⊆ interior t)⟩ := mem_prod_iff.mp this in let ⟨a, ha₁, _, ha₂⟩ := h_pnt hm₁ in let ⟨b, hb₁, hb₂, _⟩ := h_pnt hm₂ in have set.prod (preimage e m₁) (preimage e m₂) ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s, from calc _ ⊆ preimage (λp:(β×β), (e p.1, e p.2)) (interior t) : preimage_mono hm ... ⊆ preimage (λp:(β×β), (e p.1, e p.2)) t : preimage_mono interior_subset ... ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s : ts, have set.prod (f '' preimage e m₁) (f '' preimage e m₂) ⊆ s, from calc set.prod (f '' preimage e m₁) (f '' preimage e m₂) = (λp:(β×β), (f p.1, f p.2)) '' (set.prod (preimage e m₁) (preimage e m₂)) : prod_image_image_eq ... ⊆ (λp:(β×β), (f p.1, f p.2)) '' preimage (λp:(β×β), (f p.1, f p.2)) s : mono_image this ... ⊆ s : image_subset_iff.mpr $ subset.refl _, have (a, b) ∈ s, from @this (a, b) ⟨ha₁, hb₁⟩, hs_comp $ show (ψ x₁, ψ x₂) ∈ comp_rel s (comp_rel s s), from ⟨a, ha₂, ⟨b, this, hb₂⟩⟩ end uniform_extension end uniform_space end /-- Space of Cauchy filters This is essentially the completion of a uniform space. The embeddings are the neighbourhood filters. This space is not minimal, the separated uniform space (i.e. quotiented on the intersection of all entourages) is necessary for this. -/ def Cauchy (α : Type u) [uniform_space α] : Type u := { f : filter α // cauchy f } namespace Cauchy section parameters {α : Type u} [uniform_space α] def gen (s : set (α × α)) : set (Cauchy α × Cauchy α) := {p | s ∈ (filter.prod (p.1.val) (p.2.val)).sets } lemma monotone_gen : monotone gen := monotone_set_of $ assume p, @monotone_mem_sets (α×α) (filter.prod (p.1.val) (p.2.val)) private lemma symm_gen : map prod.swap (uniformity.lift' gen) ≤ uniformity.lift' gen := calc map prod.swap (uniformity.lift' gen) = uniformity.lift' (λs:set (α×α), {p | s ∈ (filter.prod (p.2.val) (p.1.val)).sets }) : begin delta gen, rw map_lift'_eq (monotone_set_of (λ _, _)), { simp only [image_swap_eq_preimage_swap]; refl }, exact monotone_mem_sets end ... ≤ uniformity.lift' gen : uniformity_lift_le_swap (monotone_comp (monotone_set_of $ assume p, @monotone_mem_sets (α×α) ((filter.prod ((p.2).val) ((p.1).val)))) monotone_principal) begin have h := λ(p:Cauchy α×Cauchy α), @filter.prod_comm _ _ (p.2.val) (p.1.val), simp only [h, mem_map, (∘), mem_preimage_eq, prod.swap_prod_mk, prod.mk.eta, set_of_mem], exact le_refl _ end private lemma comp_rel_gen_gen_subset_gen_comp_rel {s t : set (α×α)} : comp_rel (gen s) (gen t) ⊆ (gen (comp_rel s t) : set (Cauchy α × Cauchy α)) := assume ⟨f, g⟩ ⟨h, h₁, h₂⟩, let ⟨t₁, (ht₁ : t₁ ∈ f.val.sets), t₂, (ht₂ : t₂ ∈ h.val.sets), (h₁ : set.prod t₁ t₂ ⊆ s)⟩ := mem_prod_iff.mp h₁ in let ⟨t₃, (ht₃ : t₃ ∈ h.val.sets), t₄, (ht₄ : t₄ ∈ g.val.sets), (h₂ : set.prod t₃ t₄ ⊆ t)⟩ := mem_prod_iff.mp h₂ in have t₂ ∩ t₃ ∈ h.val.sets, from inter_mem_sets ht₂ ht₃, let ⟨x, xt₂, xt₃⟩ := inhabited_of_mem_sets (h.property.left) this in (filter.prod f.val g.val).sets_of_superset (prod_mem_prod ht₁ ht₄) (assume ⟨a, b⟩ ⟨(ha : a ∈ t₁), (hb : b ∈ t₄)⟩, ⟨x, h₁ (show (a, x) ∈ set.prod t₁ t₂, from ⟨ha, xt₂⟩), h₂ (show (x, b) ∈ set.prod t₃ t₄, from ⟨xt₃, hb⟩)⟩) private lemma comp_gen : (uniformity.lift' gen).lift' (λs, comp_rel s s) ≤ uniformity.lift' gen := calc (uniformity.lift' gen).lift' (λs, comp_rel s s) = uniformity.lift' (λs, comp_rel (gen s) (gen s)) : begin rw [lift'_lift'_assoc], exact monotone_gen, exact (monotone_comp_rel monotone_id monotone_id) end ... ≤ uniformity.lift' (λs, gen $ comp_rel s s) : lift'_mono' $ assume s hs, comp_rel_gen_gen_subset_gen_comp_rel ... = (uniformity.lift' $ λs:set(α×α), comp_rel s s).lift' gen : begin rw [lift'_lift'_assoc], exact (monotone_comp_rel monotone_id monotone_id), exact monotone_gen end ... ≤ uniformity.lift' gen : lift'_mono comp_le_uniformity (le_refl _) instance completion_space : uniform_space (Cauchy α) := uniform_space.of_core { uniformity := uniformity.lift' gen, refl := principal_le_lift' $ assume s hs ⟨a, b⟩ (a_eq_b : a = b), a_eq_b ▸ a.property.right hs, symm := symm_gen, comp := comp_gen } theorem mem_uniformity {s : set (Cauchy α × Cauchy α)} : s ∈ (@uniformity (Cauchy α) _).sets ↔ ∃ t ∈ (@uniformity α _).sets, gen t ⊆ s := mem_lift'_sets monotone_gen theorem mem_uniformity' {s : set (Cauchy α × Cauchy α)} : s ∈ (@uniformity (Cauchy α) _).sets ↔ ∃ t ∈ (@uniformity α _).sets, ∀ f g : Cauchy α, t ∈ (filter.prod f.1 g.1).sets → (f, g) ∈ s := mem_uniformity.trans $ bex_congr $ λ t h, prod.forall /-- Embedding of `α` into its completion -/ def pure_cauchy (a : α) : Cauchy α := ⟨pure a, cauchy_pure⟩ lemma uniform_embedding_pure_cauchy : uniform_embedding (pure_cauchy : α → Cauchy α) := ⟨assume a₁ a₂ h, have (pure_cauchy a₁).val = (pure_cauchy a₂).val, from congr_arg _ h, have {a₁} = ({a₂} : set α), from principal_eq_iff_eq.mp this, singleton_eq_singleton_iff.1 this, have (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) = id, from funext $ assume s, set.ext $ assume ⟨a₁, a₂⟩, by simp only [pure_cauchy, mem_preimage_eq, gen, mem_set_of_eq, filter.pure_def, prod_principal_principal, mem_principal_sets, prod_singleton_singleton, singleton_subset_iff, id], calc comap (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) (uniformity.lift' gen) = uniformity.lift' (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) : comap_lift'_eq monotone_gen ... = uniformity : by rw [this, lift'_id]⟩ lemma pure_cauchy_dense : ∀x, x ∈ closure (range pure_cauchy) := assume f, have h_ex : ∀s∈(@uniformity (Cauchy α) _).sets, ∃y:α, (f, pure_cauchy y) ∈ s, from assume s hs, let ⟨t'', ht''₁, (ht''₂ : gen t'' ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht'₁, ht'₂⟩ := comp_mem_uniformity_sets ht''₁ in have t' ∈ (filter.prod (f.val) (f.val)).sets, from f.property.right ht'₁, let ⟨t, ht, (h : set.prod t t ⊆ t')⟩ := mem_prod_same_iff.mp this in let ⟨x, (hx : x ∈ t)⟩ := inhabited_of_mem_sets f.property.left ht in have t'' ∈ (filter.prod f.val (pure x)).sets, from mem_prod_iff.mpr ⟨t, ht, {y:α | (x, y) ∈ t'}, assume y, begin rw mem_singleton_iff, rintro rfl, exact refl_mem_uniformity ht'₁ end, assume ⟨a, b⟩ ⟨(h₁ : a ∈ t), (h₂ : (x, b) ∈ t')⟩, ht'₂ $ prod_mk_mem_comp_rel (@h (a, x) ⟨h₁, hx⟩) h₂⟩, ⟨x, ht''₂ $ by exact this⟩, begin simp only [closure_eq_nhds, nhds_eq_uniformity, lift'_inf_principal_eq, set.inter_comm], exact (lift'_neq_bot_iff $ monotone_inter monotone_const monotone_preimage).mpr (assume s hs, let ⟨y, hy⟩ := h_ex s hs in have pure_cauchy y ∈ range pure_cauchy ∩ {y : Cauchy α | (f, y) ∈ s}, from ⟨mem_range_self y, hy⟩, ne_empty_of_mem this) end instance : complete_space (Cauchy α) := complete_space_extension uniform_embedding_pure_cauchy pure_cauchy_dense $ assume f hf, let f' : Cauchy α := ⟨f, hf⟩ in have map pure_cauchy f ≤ uniformity.lift' (preimage (prod.mk f')), from le_lift' $ assume s hs, let ⟨t, ht₁, (ht₂ : gen t ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht', (h : set.prod t' t' ⊆ t)⟩ := mem_prod_same_iff.mp (hf.right ht₁) in have t' ⊆ { y : α | (f', pure_cauchy y) ∈ gen t }, from assume x hx, (filter.prod f (pure x)).sets_of_superset (prod_mem_prod ht' $ mem_pure hx) h, f.sets_of_superset ht' $ subset.trans this (preimage_mono ht₂), ⟨f', by rwa [nhds_eq_uniformity]⟩ end section local attribute [instance] separation_setoid lemma injective_separated_pure_cauchy {α : Type*} [uniform_space α] [s : separated α] : function.injective (λa:α, ⟦pure_cauchy a⟧) | a b h := separated_def.1 s _ _ $ assume s hs, let ⟨t, ht, hts⟩ := by rw [← (@uniform_embedding_pure_cauchy α _).right, filter.mem_comap_sets] at hs; exact hs in have (pure_cauchy a, pure_cauchy b) ∈ t, from quotient.exact h t ht, @hts (a, b) this end end Cauchy instance nonempty_Cauchy {α : Type u} [h : nonempty α] [uniform_space α] : nonempty (Cauchy α) := h.rec_on $ assume a, nonempty.intro $ Cauchy.pure_cauchy a instance inhabited_Cauchy {α : Type u} [inhabited α] [uniform_space α] : inhabited (Cauchy α) := ⟨Cauchy.pure_cauchy $ default α⟩ section constructions variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} instance : partial_order (uniform_space α) := { le := λt s, s.uniformity ≤ t.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₂ h₁, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, @le_trans _ _ c.uniformity b.uniformity a.uniformity h₂ h₁ } instance : has_Sup (uniform_space α) := ⟨assume s, uniform_space.of_core { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma le_Sup {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : t ≤ Sup tt := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma Sup_le {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t' ≤ t) : Sup tt ≤ t := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_bot (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_top (uniform_space α) := ⟨{ to_topological_space := ⊤, uniformity := principal id_rel, refl := le_refl _, symm := by simp only [tendsto, map_principal, swap_id_rel, le_principal_iff]; apply subset.refl, comp := begin rw [lift'_principal], {simp only [id_comp_rel, le_principal_iff, mem_principal_sets]}, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := λ s, by simp only [is_open_fold, is_open_top, true_iff]; intros x hx; simp only [mem_principal_sets]; rintro ⟨a,b⟩ h rfl; cases h; exact hx } ⟩ instance : complete_lattice (uniform_space α) := { sup := λa b, Sup {a, b}, le_sup_left := assume a b, le_Sup $ or.inr $ or.inl rfl, le_sup_right := assume a b, le_Sup $ or.inl rfl, sup_le := assume a b c h₁ h₂, Sup_le $ assume t' ht', or.cases_on ht' (λ h, h.symm ▸ h₂) (λ ht', or.cases_on ht' (λ h, h.symm ▸ h₁) false.elim), inf := λa b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := assume a b c h₁ h₂, le_Sup ⟨h₁, h₂⟩, inf_le_left := assume a b, Sup_le $ assume x ⟨ha, hb⟩, ha, inf_le_right := assume a b, Sup_le $ assume x ⟨ha, hb⟩, hb, top := ⊤, le_top := assume u, u.refl, bot := ⊥, bot_le := assume a, show a.uniformity ≤ ⊤, from le_top, Sup := Sup, le_Sup := assume s u, le_Sup, Sup_le := assume s u, Sup_le, Inf := λtt, Sup {t | ∀t'∈tt, t ≤ t'}, le_Inf := assume s a hs, le_Sup hs, Inf_le := assume s a ha, Sup_le $ assume u hs, hs _ ha, ..uniform_space.partial_order } lemma supr_uniformity {ι : Sort*} {u : ι → uniform_space α} : (supr u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, a = u i), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : a = u i)⟩, ha.symm ▸ infi_le _ _) lemma sup_uniformity {u v : uniform_space α} : (u ⊔ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊔ v) = (⨆i (h : i = u ∨ i = v), i), by simp only [supr_or, supr_sup_eq, supr_supr_eq_left], calc (u ⊔ v).uniformity = ((⨆i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp only [supr_uniformity, infi_or, infi_inf_eq, infi_infi_eq_left] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊤⟩ /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by rw [comap_principal]; exact le_principal_iff.2 (assume ⟨a, b⟩ (h : a = b), h ▸ rfl)) (comap_mono u.refl), symm := by simp only [tendsto_comap_iff, prod.swap, (∘)]; exact tendsto_comap.comp tendsto_swap_uniformity, comp := le_trans begin rw [comap_lift'_eq, comap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (comap_mono u.comp), is_open_uniformity := λ s, begin change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp only [is_open_iff_nhds, nhds_induced_eq_comap, mem_nhds_uniformity_iff, comap, and_comm, exists_prop, le_principal_iff], refine ball_congr (λ x hx, ⟨_, _⟩), { rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩, rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) }, { rintro ⟨t, ht, hts⟩, exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl, mem_nhds_uniformity_iff.1 $ mem_nhds_left _ ht⟩ } end } lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id := by ext u s; show s ∈ (comap (λ p:α×α, (p.1, p.2)) _).sets ↔ _; rw [prod.id_prod, filter.comap_id] lemma uniform_space.comap_comap_comp {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} : uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) := by ext s; show _ ↔ s ∈ (comap _ (comap _ _)).sets; rw filter.comap_comap_comp; refl lemma uniform_continuous_iff {α β} [uα : uniform_space α] [uβ : uniform_space β] (f : α → β) : uniform_continuous f ↔ uβ.comap f ≤ uα := filter.map_le_iff_le_comap lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.comap f u) u f := tendsto_comap theorem to_topological_space_comap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.comap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := eq_of_nhds_eq_nhds $ assume a, begin simp only [nhds_induced_eq_comap, nhds_eq_uniformity, nhds_eq_uniformity], change comap f (uniformity.lift' (preimage (λb, (f a, b)))) = (u.uniformity.comap (λp:α×α, (f p.1, f p.2))).lift' (preimage (λa', (a, a'))), rw [comap_lift'_eq monotone_preimage, comap_lift'_eq2 monotone_preimage], exact rfl end lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g := tendsto_comap_iff.2 h lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ assume a, by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _) lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := rfl lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := bot_unique $ assume s hs, classical.by_cases (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊥) (assume : s ≠ ∅, let ⟨x, hx⟩ := exists_mem_of_ne_empty this in have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl, this.symm ▸ @is_open_univ _ ⊥) lemma to_topological_space_supr {ι : Sort*} {u : ι → uniform_space α} : @uniform_space.to_topological_space α (supr u) = (⨆i, @uniform_space.to_topological_space α (u i)) := classical.by_cases (assume h : nonempty ι, eq_of_nhds_eq_nhds $ assume a, begin rw [nhds_supr, nhds_eq_uniformity], change _ = (supr u).uniformity.lift' (preimage $ prod.mk a), begin rw [supr_uniformity, lift'_infi], exact (congr_arg _ $ funext $ assume i, @nhds_eq_uniformity α (u i) a), exact h, exact assume a b, rfl end end) (assume : ¬ nonempty ι, le_antisymm (have supr u = ⊥, from bot_unique $ supr_le $ assume i, (this ⟨i⟩).elim, have @uniform_space.to_topological_space _ (supr u) = ⊥, from this.symm ▸ to_topological_space_bot, this.symm ▸ bot_le) (supr_le $ assume i, to_topological_space_mono $ le_supr _ _)) lemma to_topological_space_Sup {s : set (uniform_space α)} : @uniform_space.to_topological_space α (Sup s) = (⨆i∈s, @uniform_space.to_topological_space α i) := begin rw [Sup_eq_supr, to_topological_space_supr], apply congr rfl, funext x, exact to_topological_space_supr end lemma to_topological_space_sup {u v : uniform_space α} : @uniform_space.to_topological_space α (u ⊔ v) = @uniform_space.to_topological_space α u ⊔ @uniform_space.to_topological_space α v := ord_continuous_sup $ assume s, to_topological_space_Sup instance : uniform_space empty := ⊤ instance : uniform_space unit := ⊤ instance : uniform_space bool := ⊤ instance : uniform_space ℕ := ⊤ instance : uniform_space ℤ := ⊤ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.comap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : (@uniformity (subtype p) _) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) uniformity := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_comap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_comap' hf lemma tendsto_of_uniform_continuous_subtype [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ (nhds a).sets) : tendsto f (nhds a) (nhds (f a)) := by rw [(@map_nhds_subtype_val_eq α _ s a (mem_of_nhds ha) ha).symm]; exact tendsto_map' (continuous_iff_tendsto.mp hf.continuous _) instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.comap prod.fst ⊔ u₂.comap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.comap prod.fst ⊔ u₂.comap prod.snd).to_topological_space : by rw [to_topological_space_sup, to_topological_space_comap, to_topological_space_comap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) theorem uniformity_prod [uniform_space α] [uniform_space β] : @uniformity (α × β) _ = uniformity.comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓ uniformity.comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) := sup_uniformity lemma uniform_embedding_subtype_emb {α : Type*} {β : Type*} [uniform_space α] [uniform_space β] (p : α → Prop) {e : α → β} (ue : uniform_embedding e) (de : dense_embedding e) : uniform_embedding (de.subtype_emb p) := ⟨(de.subtype p).inj, by simp only [comap_comap_comp, (∘), dense_embedding.subtype_emb, uniformity_subtype, ue.right.symm]⟩ lemma uniform_extend_subtype {α : Type*} {β : Type*} {γ : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [complete_space γ] [inhabited γ] [separated γ] {p : α → Prop} {e : α → β} {f : α → γ} {b : β} {s : set α} (hf : uniform_continuous (λx:subtype p, f x.val)) (he : uniform_embedding e) (hd : ∀x:β, x ∈ closure (range e)) (hb : closure (e '' s) ∈ (nhds b).sets) (hs : is_closed s) (hp : ∀x∈s, p x) : ∃c, tendsto f (comap e (nhds b)) (nhds c) := have de : dense_embedding e, from he.dense_embedding hd, have de' : dense_embedding (de.subtype_emb p), by exact de.subtype p, have ue' : uniform_embedding (de.subtype_emb p), from uniform_embedding_subtype_emb _ he de, have b ∈ closure (e '' {x | p x}), from (closure_mono $ mono_image $ hp) (mem_of_nhds hb), let ⟨c, (hc : tendsto (f ∘ subtype.val) (comap (de.subtype_emb p) (nhds ⟨b, this⟩)) (nhds c))⟩ := uniformly_extend_exists ue' de'.dense hf in begin rw [nhds_subtype_eq_comap, comap_comap_comp] at hc, change (tendsto (f ∘ @subtype.val α p) (comap (e ∘ @subtype.val α p) (nhds b)) (nhds c)) at hc, rw [←comap_comap_comp] at hc, existsi c, apply tendsto_comap'' s _ _ hc, exact ⟨_, hb, assume x, begin change e x ∈ (closure (e '' s)) → x ∈ s, rw [←closure_induced, closure_eq_nhds], simp only [nhds_induced_eq_comap, de.induced], change x ∈ {x | nhds x ⊓ principal s ≠ ⊥} → x ∈ s, rw [←closure_eq_nhds, closure_eq_of_is_closed hs], exact id, exact de.inj end⟩, exact (assume x hx, ⟨⟨x, hp x hx⟩, rfl⟩) end /- 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 -/ lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : @uniformity (α×β) _ = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (filter.prod uniformity uniformity) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_comap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap_comp, comap_comap_comp] lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ (@uniformity α _).sets) (hb : b ∈ (@uniformity β _).sets) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _).sets := by rw [uniformity_prod]; exact inter_mem_inf_sets (preimage_mem_comap ha) (preimage_mem_comap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) uniformity uniformity := le_trans (map_mono (@le_sup_left (uniform_space (α×β)) _ _ _)) map_comap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) uniformity uniformity := le_trans (map_mono (@le_sup_right (uniform_space (α×β)) _ _ _)) map_comap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd variables [uniform_space α] [uniform_space β] [uniform_space γ] lemma uniform_continuous.prod_mk {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) : uniform_continuous (λ a, f (a,b)) := uniform_continuous.comp (uniform_continuous.prod_mk uniform_continuous_id uniform_continuous_const) h lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) : uniform_continuous (λ b, f (a,b)) := uniform_continuous.comp (uniform_continuous.prod_mk uniform_continuous_const uniform_continuous_id) h instance complete_space.prod [complete_space α] [complete_space β] : complete_space (α × β) := { complete := λ f hf, let ⟨x1, hx1⟩ := complete_space.complete $ cauchy_map uniform_continuous_fst hf in let ⟨x2, hx2⟩ := complete_space.complete $ cauchy_map uniform_continuous_snd hf in ⟨(x1, x2), by rw [nhds_prod_eq, filter.prod_def]; from filter.le_lift (λ s hs, filter.le_lift' $ λ t ht, have H1 : prod.fst ⁻¹' s ∈ f.sets := hx1 hs, have H2 : prod.snd ⁻¹' t ∈ f.sets := hx2 ht, filter.inter_mem_sets H1 H2)⟩ } lemma uniform_embedding.prod {α' : Type*} {β' : Type*} [uniform_space α] [uniform_space β] [uniform_space α'] [uniform_space β'] {e₁ : α → α'} {e₂ : β → β'} (h₁ : uniform_embedding e₁) (h₂ : uniform_embedding e₂) : uniform_embedding (λp:α×β, (e₁ p.1, e₂ p.2)) := ⟨assume ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, λ h, prod.ext (h₁.left (prod.mk.inj h).1) (h₂.left (prod.mk.inj h).2), by simp only [(∘), uniformity_prod, h₁.right.symm, h₂.right.symm, comap_inf, comap_comap_comp]⟩ lemma to_topological_space_prod [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl section separation_space local attribute [instance] separation_setoid lemma uniform_continuous_quotient_lift₂ [uniform_space γ] {f : α → β → γ} {h : ∀a c b d, (a, b) ∈ separation_rel α → (c, d) ∈ separation_rel β → f a c = f b d} (hf : uniform_continuous (λp:α×β, f p.1 p.2)) : uniform_continuous (λp:_×_, quotient.lift₂ f h p.1 p.2) := begin rw [uniform_continuous, uniformity_prod_eq_prod, uniformity_quotient, uniformity_quotient, filter.prod_map_map_eq, filter.tendsto_map'_iff, filter.tendsto_map'_iff], rwa [uniform_continuous, uniformity_prod_eq_prod, filter.tendsto_map'_iff] at hf end lemma separation_prod {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) ≈ (a₂, b₂) ↔ a₁ ≈ a₂ ∧ b₁ ≈ b₂ := begin split ; intro h, { exact ⟨separated_of_uniform_continuous uniform_continuous_fst h, separated_of_uniform_continuous uniform_continuous_snd h⟩ }, { rcases h with ⟨eqv_α, eqv_β⟩, intros r r_in, rw uniformity_prod at r_in, rcases r_in with ⟨t_α, ⟨r_α, r_α_in, h_α⟩, t_β, ⟨r_β, r_β_in, h_β⟩, H⟩, let p_α := λ (p : (α × β) × α × β), ((p.fst).fst, (p.snd).fst), let p_β := λ (p : (α × β) × α × β), ((p.fst).snd, (p.snd).snd), have key_α : p_α ((a₁, b₁), (a₂, b₂)) ∈ r_α, by simp only [p_α, eqv_α r_α r_α_in], have key_β : p_β ((a₁, b₁), (a₂, b₂)) ∈ r_β, by simp only [p_β, eqv_β r_β r_β_in], exact H ⟨h_α key_α, h_β key_β⟩ }, end instance separated.prod [separated α] [separated β] : separated (α × β) := separated_def.2 $ assume x y H, prod.ext (eq_of_separated_of_uniform_continuous uniform_continuous_fst H) (eq_of_separated_of_uniform_continuous uniform_continuous_snd H) end separation_space end constructions lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α} (hs : compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ n ∈ (@uniformity α _).sets, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i := begin let u := λ n, {x | ∃ i (m ∈ (@uniformity α _).sets), {y | (x, y) ∈ comp_rel m n} ⊆ c i}, have hu₁ : ∀ n ∈ (@uniformity α _).sets, is_open (u n), { refine λ n hn, is_open_uniformity.2 _, rintro x ⟨i, m, hm, h⟩, rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩, apply uniformity.sets_of_superset hm', rintros ⟨x, y⟩ hp rfl, refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩, change (x, z) ∈ comp_rel (comp_rel m' m') n, rw comp_rel_assoc, exact ⟨y, hp, hz⟩ }, have hu₂ : s ⊆ ⋃ n ∈ (@uniformity α _).sets, u n, { intros x hx, rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩, rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩, exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ }, rcases compact_elim_finite_subcover_image hs hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩, refine ⟨_, Inter_mem_sets b_fin bu, λ x hx, _⟩, rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩, refine ⟨i, λ y hy, h _⟩, exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy) end lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ n ∈ (@uniformity α _).sets, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t := by rw sUnion_eq_Union at hc₂; simpa only [set_coe.exists, exists_prop] using lebesgue_number_lemma hs (by simpa only [set_coe.forall]) hc₂
cc2aab30842f43f566675f32b85aea79b1469706
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/continued_fractions/computation/translations.lean
90b9179c315121617a98bafe0b00b1659305b6ef
[ "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
10,459
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.computation.basic import algebra.continued_fractions.translations /-! # Basic Translation Lemmas Between Structures Defined for Computing Continued Fractions ## Summary This is a collection of simple lemmas between the different structures used for the computation of continued fractions defined in `algebra.continued_fractions.computation.basic`. The file consists of three sections: 1. Recurrences and inversion lemmas for `int_fract_pair.stream`: these lemmas give us inversion rules and recurrences for the computation of the stream of integer and fractional parts of a value. 2. Translation lemmas for the head term: these lemmas show us that the head term of the computed continued fraction of a value `v` is `⌊v⌋` and how this head term is moved along the structures used in the computation process. 3. Translation lemmas for the sequence: these lemmas show how the sequences of the involved structures (`int_fract_pair.stream`, `int_fract_pair.seq1`, and `generalized_continued_fraction.of`) are connected, i.e. how the values are moved along the structures and the termination of one sequence implies the termination of another sequence. ## Main Theorems - `succ_nth_stream_eq_some_iff` gives as a recurrence to compute the `n + 1`th value of the sequence of integer and fractional parts of a value in case of non-termination. - `succ_nth_stream_eq_none_iff` gives as a recurrence to compute the `n + 1`th value of the sequence of integer and fractional parts of a value in case of termination. - `nth_of_eq_some_of_succ_nth_int_fract_pair_stream` and `nth_of_eq_some_of_nth_int_fract_pair_stream_fr_ne_zero` show how the entries of the sequence of the computed continued fraction can be obtained from the stream of integer and fractional parts. -/ namespace generalized_continued_fraction open generalized_continued_fraction (of) /- Fix a discrete linear ordered floor field and a value `v`. -/ variables {K : Type*} [linear_ordered_field K] [floor_ring K] {v : K} namespace int_fract_pair /-! ### Recurrences and Inversion Lemmas for `int_fract_pair.stream` Here we state some lemmas that give us inversion rules and recurrences for the computation of the stream of integer and fractional parts of a value. -/ variable {n : ℕ} lemma stream_eq_none_of_fr_eq_zero {ifp_n : int_fract_pair K} (stream_nth_eq : int_fract_pair.stream v n = some ifp_n) (nth_fr_eq_zero : ifp_n.fr = 0) : int_fract_pair.stream v (n + 1) = none := begin cases ifp_n with _ fr, change fr = 0 at nth_fr_eq_zero, simp [int_fract_pair.stream, stream_nth_eq, nth_fr_eq_zero] end /-- Gives a recurrence to compute the `n + 1`th value of the sequence of integer and fractional parts of a value in case of termination. -/ lemma succ_nth_stream_eq_none_iff : int_fract_pair.stream v (n + 1) = none ↔ (int_fract_pair.stream v n = none ∨ ∃ ifp, int_fract_pair.stream v n = some ifp ∧ ifp.fr = 0) := begin cases stream_nth_eq : (int_fract_pair.stream v n) with ifp, case option.none : { simp [stream_nth_eq, int_fract_pair.stream] }, case option.some : { cases ifp with _ fr, cases decidable.em (fr = 0); finish [int_fract_pair.stream] } end /-- Gives a recurrence to compute the `n + 1`th value of the sequence of integer and fractional parts of a value in case of non-termination. -/ lemma succ_nth_stream_eq_some_iff {ifp_succ_n : int_fract_pair K} : int_fract_pair.stream v (n + 1) = some ifp_succ_n ↔ ∃ (ifp_n : int_fract_pair K), int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr ≠ 0 ∧ int_fract_pair.of ifp_n.fr⁻¹ = ifp_succ_n := begin split, { assume stream_succ_nth_eq, have : int_fract_pair.stream v (n + 1) ≠ none, by simp [stream_succ_nth_eq], have : ¬int_fract_pair.stream v n = none ∧ ¬(∃ ifp, int_fract_pair.stream v n = some ifp ∧ ifp.fr = 0), by { have not_none_not_fract_zero, from (not_iff_not_of_iff succ_nth_stream_eq_none_iff).elim_left this, exact (not_or_distrib.elim_left not_none_not_fract_zero) }, cases this with stream_nth_ne_none nth_fr_ne_zero, replace nth_fr_ne_zero : ∀ ifp, int_fract_pair.stream v n = some ifp → ifp.fr ≠ 0, by simpa using nth_fr_ne_zero, obtain ⟨ifp_n, stream_nth_eq⟩ : ∃ ifp_n, int_fract_pair.stream v n = some ifp_n, from option.ne_none_iff_exists'.mp stream_nth_ne_none, existsi ifp_n, have ifp_n_fr_ne_zero : ifp_n.fr ≠ 0, from nth_fr_ne_zero ifp_n stream_nth_eq, cases ifp_n with _ ifp_n_fr, suffices : int_fract_pair.of ifp_n_fr⁻¹ = ifp_succ_n, by simpa [stream_nth_eq, ifp_n_fr_ne_zero], simp only [int_fract_pair.stream, stream_nth_eq, ifp_n_fr_ne_zero, option.some_bind, if_false] at stream_succ_nth_eq, injection stream_succ_nth_eq }, { rintro ⟨⟨_⟩, ifp_n_props⟩, finish [int_fract_pair.stream, ifp_n_props] } end lemma exists_succ_nth_stream_of_fr_zero {ifp_succ_n : int_fract_pair K} (stream_succ_nth_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) (succ_nth_fr_eq_zero : ifp_succ_n.fr = 0) : ∃ ifp_n : int_fract_pair K, int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr⁻¹ = ⌊ifp_n.fr⁻¹⌋ := begin -- get the witness from `succ_nth_stream_eq_some_iff` and prove that it has the additional -- properties rcases (succ_nth_stream_eq_some_iff.elim_left stream_succ_nth_eq) with ⟨ifp_n, stream_nth_eq, nth_fr_ne_zero, _⟩, existsi ifp_n, cases ifp_n with _ ifp_n_fr, suffices : ifp_n_fr⁻¹ = ⌊ifp_n_fr⁻¹⌋, by simpa [stream_nth_eq], have : int_fract_pair.of ifp_n_fr⁻¹ = ifp_succ_n, by finish, cases ifp_succ_n with _ ifp_succ_n_fr, change ifp_succ_n_fr = 0 at succ_nth_fr_eq_zero, have : int.fract ifp_n_fr⁻¹ = ifp_succ_n_fr, by injection this, have : int.fract ifp_n_fr⁻¹ = 0, by rwa [succ_nth_fr_eq_zero] at this, calc ifp_n_fr⁻¹ = int.fract ifp_n_fr⁻¹ + ⌊ifp_n_fr⁻¹⌋ : by rw (int.fract_add_floor ifp_n_fr⁻¹) ... = ⌊ifp_n_fr⁻¹⌋ : by simp [‹int.fract ifp_n_fr⁻¹ = 0›] end end int_fract_pair section head /-! ### Translation of the Head Term Here we state some lemmas that show us that the head term of the computed continued fraction of a value `v` is `⌊v⌋` and how this head term is moved along the structures used in the computation process. -/ /-- The head term of the sequence with head of `v` is just the integer part of `v`. -/ @[simp] lemma int_fract_pair.seq1_fst_eq_of : (int_fract_pair.seq1 v).fst = int_fract_pair.of v := rfl lemma of_h_eq_int_fract_pair_seq1_fst_b : (of v).h = (int_fract_pair.seq1 v).fst.b := by { cases aux_seq_eq : (int_fract_pair.seq1 v), simp [of, aux_seq_eq] } /-- The head term of the gcf of `v` is `⌊v⌋`. -/ @[simp] lemma of_h_eq_floor : (of v).h = ⌊v⌋ := by simp [of_h_eq_int_fract_pair_seq1_fst_b, int_fract_pair.of] end head section sequence /-! ### Translation of the Sequences Here we state some lemmas that show how the sequences of the involved structures (`int_fract_pair.stream`, `int_fract_pair.seq1`, and `generalized_continued_fraction.of`) are connected, i.e. how the values are moved along the structures and how the termination of one sequence implies the termination of another sequence. -/ variable {n : ℕ} lemma int_fract_pair.nth_seq1_eq_succ_nth_stream : (int_fract_pair.seq1 v).snd.nth n = (int_fract_pair.stream v) (n + 1) := rfl section termination /-! #### Translation of the Termination of the Sequences Let's first show how the termination of one sequence implies the termination of another sequence. -/ lemma of_terminated_at_iff_int_fract_pair_seq1_terminated_at : (of v).terminated_at n ↔ (int_fract_pair.seq1 v).snd.terminated_at n := begin rw [terminated_at_iff_s_none, of], rcases (int_fract_pair.seq1 v) with ⟨head, ⟨st⟩⟩, cases st_n_eq : st n; simp [of, st_n_eq, seq.map, seq.nth, stream.map, seq.terminated_at, stream.nth] end lemma of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none : (of v).terminated_at n ↔ int_fract_pair.stream v (n + 1) = none := by rw [of_terminated_at_iff_int_fract_pair_seq1_terminated_at, seq.terminated_at, int_fract_pair.nth_seq1_eq_succ_nth_stream] end termination section values /-! #### Translation of the Values of the Sequence Now let's show how the values of the sequences correspond to one another. -/ lemma int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some {gp_n : pair K} (s_nth_eq : (of v).s.nth n = some gp_n) : ∃ (ifp : int_fract_pair K), int_fract_pair.stream v (n + 1) = some ifp ∧ (ifp.b : K) = gp_n.b := begin obtain ⟨ifp, stream_succ_nth_eq, gp_n_eq⟩ : ∃ ifp, int_fract_pair.stream v (n + 1) = some ifp ∧ pair.mk 1 (ifp.b : K) = gp_n, by { unfold of int_fract_pair.seq1 at s_nth_eq, rwa [seq.map_tail, seq.nth_tail, seq.map_nth, option.map_eq_some'] at s_nth_eq }, cases gp_n_eq, injection gp_n_eq with _ ifp_b_eq_gp_n_b, existsi ifp, exact ⟨stream_succ_nth_eq, ifp_b_eq_gp_n_b⟩ end /-- Shows how the entries of the sequence of the computed continued fraction can be obtained by the integer parts of the stream of integer and fractional parts. -/ lemma nth_of_eq_some_of_succ_nth_int_fract_pair_stream {ifp_succ_n : int_fract_pair K} (stream_succ_nth_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) : (of v).s.nth n = some ⟨1, ifp_succ_n.b⟩ := begin unfold of int_fract_pair.seq1, rw [seq.map_tail, seq.nth_tail, seq.map_nth], simp [seq.nth, stream_succ_nth_eq] end /-- Shows how the entries of the sequence of the computed continued fraction can be obtained by the fractional parts of the stream of integer and fractional parts. -/ lemma nth_of_eq_some_of_nth_int_fract_pair_stream_fr_ne_zero {ifp_n : int_fract_pair K} (stream_nth_eq : int_fract_pair.stream v n = some ifp_n) (nth_fr_ne_zero : ifp_n.fr ≠ 0) : (of v).s.nth n = some ⟨1, (int_fract_pair.of ifp_n.fr⁻¹).b⟩ := have int_fract_pair.stream v (n + 1) = some (int_fract_pair.of ifp_n.fr⁻¹), by { cases ifp_n, simp [int_fract_pair.stream, stream_nth_eq, nth_fr_ne_zero], refl }, nth_of_eq_some_of_succ_nth_int_fract_pair_stream this end values end sequence end generalized_continued_fraction
974cdb6fceb9ac51b8baf0f27383dfca55039879
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/group_action/sigma.lean
a7947d7f13176914fd4754379f87bb612827d846
[ "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
2,272
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import group_theory.group_action.defs /-! # Sigma instances for additive and multiplicative actions This file defines instances for arbitrary sum of additive and multiplicative actions. ## See also * `group_theory.group_action.pi` * `group_theory.group_action.prod` * `group_theory.group_action.sum` -/ variables {ι : Type*} {M N : Type*} {α : ι → Type*} namespace sigma section has_smul variables [Π i, has_smul M (α i)] [Π i, has_smul N (α i)] (a : M) (i : ι) (b : α i) (x : Σ i, α i) @[to_additive sigma.has_vadd] instance : has_smul M (Σ i, α i) := ⟨λ a, sigma.map id $ λ i, (•) a⟩ @[to_additive] lemma smul_def : a • x = x.map id (λ i, (•) a) := rfl @[simp, to_additive] lemma smul_mk : a • mk i b = ⟨i, a • b⟩ := rfl @[to_additive] instance [has_smul M N] [Π i, is_scalar_tower M N (α i)] : is_scalar_tower M N (Σ i, α i) := ⟨λ a b x, by { cases x, rw [smul_mk, smul_mk, smul_mk, smul_assoc] }⟩ @[to_additive] instance [Π i, smul_comm_class M N (α i)] : smul_comm_class M N (Σ i, α i) := ⟨λ a b x, by { cases x, rw [smul_mk, smul_mk, smul_mk, smul_mk, smul_comm] }⟩ @[to_additive] instance [Π i, has_smul Mᵐᵒᵖ (α i)] [Π i, is_central_scalar M (α i)] : is_central_scalar M (Σ i, α i) := ⟨λ a x, by { cases x, rw [smul_mk, smul_mk, op_smul_eq_smul] }⟩ /-- This is not an instance because `i` becomes a metavariable. -/ @[to_additive "This is not an instance because `i` becomes a metavariable."] protected lemma has_faithful_smul' [has_faithful_smul M (α i)] : has_faithful_smul M (Σ i, α i) := ⟨λ x y h, eq_of_smul_eq_smul $ λ a : α i, heq_iff_eq.1 (ext_iff.1 $ h $ mk i a).2⟩ @[to_additive] instance [nonempty ι] [Π i, has_faithful_smul M (α i)] : has_faithful_smul M (Σ i, α i) := nonempty.elim ‹_› $ λ i, sigma.has_faithful_smul' i end has_smul @[to_additive] instance {m : monoid M} [Π i, mul_action M (α i)] : mul_action M (Σ i, α i) := { mul_smul := λ a b x, by { cases x, rw [smul_mk, smul_mk, smul_mk, mul_smul] }, one_smul := λ x, by { cases x, rw [smul_mk, one_smul] } } end sigma
4893f75988fb143e7ca12c0f8e6a8960e58cae23
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/Data/Position.lean
3e1a0106e8b5cd2a91cfd459d104a0422b5cc3a4
[ "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
2,500
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, Sebastian Ullrich -/ import Lean.Data.Format namespace Lean structure Position where line : Nat column : Nat deriving Inhabited, DecidableEq, Repr namespace Position protected def lt : Position → Position → Bool | ⟨l₁, c₁⟩, ⟨l₂, c₂⟩ => (l₁, c₁) < (l₂, c₂) instance : ToFormat Position := ⟨fun ⟨l, c⟩ => "⟨" ++ format l ++ ", " ++ format c ++ "⟩"⟩ instance : ToString Position := ⟨fun ⟨l, c⟩ => "⟨" ++ toString l ++ ", " ++ toString c ++ "⟩"⟩ end Position structure FileMap where source : String positions : Array String.Pos lines : Array Nat deriving Inhabited class MonadFileMap (m : Type → Type) where getFileMap : m FileMap export MonadFileMap (getFileMap) namespace FileMap partial def ofString (s : String) : FileMap := let rec loop (i : String.Pos) (line : Nat) (ps : Array String.Pos) (lines : Array Nat) : FileMap := if s.atEnd i then { source := s, positions := ps.push i, lines := lines.push line } else let c := s.get i; let i := s.next i; if c == '\n' then loop i (line+1) (ps.push i) (lines.push (line+1)) else loop i line ps lines loop 0 1 (#[0]) (#[1]) partial def toPosition (fmap : FileMap) (pos : String.Pos) : Position := match fmap with | { source := str, positions := ps, lines := lines } => if ps.size >= 2 && pos <= ps.back then let rec toColumn (i : String.Pos) (c : Nat) : Nat := if i == pos || str.atEnd i then c else toColumn (str.next i) (c+1) let rec loop (b e : Nat) := let posB := ps[b] if e == b + 1 then { line := lines.get! b, column := toColumn posB 0 } else let m := (b + e) / 2; let posM := ps.get! m; if pos == posM then { line := lines.get! m, column := 0 } else if pos > posM then loop m e else loop b m loop 0 (ps.size -1) else if lines.isEmpty then ⟨0, 0⟩ else -- Some systems like the delaborator use synthetic positions without an input file, -- which would violate `toPositionAux`'s invariant. -- Can also happen with EOF errors, which are not strictly inside the file. ⟨lines.back, pos - ps.back⟩ end FileMap end Lean def String.toFileMap (s : String) : Lean.FileMap := Lean.FileMap.ofString s
1012bb6b41be2014e3c7ed47787ba4ef51e48650
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/congrThm.lean
b9934fd94652eb5f82afba6fa9010fdbf449bec7
[ "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
339
lean
import Lean open Lean open Lean.Meta def test (f : Expr) : MetaM Unit := do let some thm ← mkCongrSimp? f | unreachable! check thm.type check thm.proof assert! (← isDefEq thm.type (← inferType thm.proof)) IO.println (← Meta.ppExpr thm.type) #eval test (mkConst ``decide) #eval test (mkConst ``Array.uget [levelZero])
62faf94a43fd84ed095c6185c4335fc54e03fd34
e39f04f6ff425fe3b3f5e26a8998b817d1dba80f
/data/option.lean
ff0c53ce8a04e86bbf8fd96ac7c11a7c54beb9ba
[ "Apache-2.0" ]
permissive
kristychoi/mathlib
c504b5e8f84e272ea1d8966693c42de7523bf0ec
257fd84fe98927ff4a5ffe044f68c4e9d235cc75
refs/heads/master
1,586,520,722,896
1,544,030,145,000
1,544,031,933,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,735
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 logic.basic data.bool init.data.option.instances tactic.interactive namespace option variables {α : Type*} {β : Type*} instance has_mem : has_mem α (option α) := ⟨λ a b, b = some a⟩ @[simp] theorem mem_def {a : α} {b : option α} : a ∈ b ↔ b = some a := iff.rfl @[simp] theorem get_mem : ∀ {o : option α} (h : is_some o), option.get h ∈ o | (some a) _ := rfl theorem get_of_mem {a : α} : ∀ {o : option α} (h : is_some o), a ∈ o → option.get h = a | _ _ rfl := rfl theorem mem_unique {o : option α} {a b : α} (ha : a ∈ o) (hb : b ∈ o) : a = b := option.some.inj $ ha.symm.trans hb theorem some_inj {a b : α} : some a = some b ↔ a = b := by simp theorem injective_some (α : Type*) : function.injective (@some α) := λ _ _, some_inj.mp @[extensionality] theorem ext : ∀ {o₁ o₂ : option α}, (∀ a, a ∈ o₁ ↔ a ∈ o₂) → o₁ = o₂ | none none H := rfl | (some a) o H := ((H _).1 rfl).symm | o (some b) H := (H _).2 rfl theorem eq_none_iff_forall_not_mem {o : option α} : o = none ↔ (∀ a, a ∉ o) := ⟨λ e a h, by rw e at h; cases h, λ h, ext $ by simpa⟩ @[simp] theorem none_bind {α β} (f : α → option β) : none >>= f = none := rfl @[simp] theorem some_bind {α β} (a : α) (f : α → option β) : some a >>= f = f a := rfl @[simp] theorem none_bind' (f : α → option β) : none.bind f = none := rfl @[simp] theorem some_bind' (a : α) (f : α → option β) : (some a).bind f = f a := rfl @[simp] theorem bind_some : ∀ x : option α, x >>= some = x := @bind_pure α option _ _ @[simp] theorem bind_eq_some {α β} {x : option α} {f : α → option β} {b : β} : x >>= f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem bind_eq_some' {x : option α} {f : α → option β} {b : β} : x.bind f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp lemma bind_comm {α β γ} {f : α → β → option γ} (a : option α) (b : option β) : a.bind (λx, b.bind (f x)) = b.bind (λy, a.bind (λx, f x y)) := by cases a; cases b; refl @[simp] theorem map_none {α β} {f : α → β} : f <$> none = none := rfl @[simp] theorem map_some {α β} {a : α} {f : α → β} : f <$> some a = some (f a) := rfl @[simp] theorem map_none' {f : α → β} : option.map f none = none := rfl @[simp] theorem map_some' {a : α} {f : α → β} : option.map f (some a) = some (f a) := rfl @[simp] theorem map_eq_some {α β} {x : option α} {f : α → β} {b : β} : f <$> x = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_eq_some' {x : option α} {f : α → β} {b : β} : x.map f = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_id' : option.map (@id α) = id := map_id @[simp] theorem seq_some {α β} {a : α} {f : α → β} : some f <*> some a = some (f a) := rfl @[simp] theorem some_orelse' (a : α) (x : option α) : (some a).orelse x = some a := rfl @[simp] theorem some_orelse (a : α) (x : option α) : (some a <|> x) = some a := rfl @[simp] theorem none_orelse' (x : option α) : none.orelse x = x := by cases x; refl @[simp] theorem none_orelse (x : option α) : (none <|> x) = x := none_orelse' x @[simp] theorem orelse_none' (x : option α) : x.orelse none = x := by cases x; refl @[simp] theorem orelse_none (x : option α) : (x <|> none) = x := orelse_none' x @[simp] theorem is_some_none : @is_some α none = ff := rfl @[simp] theorem is_some_some {a : α} : is_some (some a) = tt := rfl theorem is_some_iff_exists {x : option α} : is_some x ↔ ∃ a, x = some a := by cases x; simp [is_some]; exact ⟨_, rfl⟩ @[simp] theorem is_none_none : @is_none α none = tt := rfl @[simp] theorem is_none_some {a : α} : is_none (some a) = ff := rfl @[simp] theorem not_is_some {a : option α} : is_some a = ff ↔ a.is_none = tt := by cases a; simp theorem is_none_iff_eq_none {o : option α} : o.is_none = tt ↔ o = none := ⟨option.eq_none_of_is_none, λ e, e.symm ▸ rfl⟩ instance decidable_eq_none {o : option α} : decidable (o = none) := decidable_of_bool _ is_none_iff_eq_none instance decidable_forall_mem {p : α → Prop} [decidable_pred p] : ∀ o : option α, decidable (∀ a ∈ o, p a) | none := is_true (by simp) | (some a) := decidable_of_iff (p a) (by simp) instance decidable_exists_mem {p : α → Prop} [decidable_pred p] : ∀ o : option α, decidable (∃ a ∈ o, p a) | none := is_false (by simp) | (some a) := decidable_of_iff (p a) (by simp) /-- inhabited `get` function. Returns `a` if the input is `some a`, otherwise returns `default`. -/ @[reducible] def iget [inhabited α] : option α → α | (some x) := x | none := default α @[simp] theorem iget_some [inhabited α] {a : α} : (some a).iget = a := rfl theorem iget_mem [inhabited α] : ∀ {o : option α}, is_some o → o.iget ∈ o | (some a) _ := rfl theorem iget_of_mem [inhabited α] {a : α} : ∀ {o : option α}, a ∈ o → o.iget = a | _ rfl := rfl @[simp] theorem guard_eq_some' {p : Prop} [decidable p] : ∀ u, guard p = some u ↔ p | () := by by_cases p; simp [guard, h, pure]; intro; contradiction /-- `guard p a` returns `some a` if `p a` holds, otherwise `none`. -/ def guard (p : α → Prop) [decidable_pred p] (a : α) : option α := if p a then some a else none /-- `filter p o` returns `some a` if `o` is `some a` and `p a` holds, otherwise `none`. -/ def filter (p : α → Prop) [decidable_pred p] (o : option α) : option α := o.bind (guard p) @[simp] theorem guard_eq_some {p : α → Prop} [decidable_pred p] {a b : α} : guard p a = some b ↔ a = b ∧ p a := by by_cases p a; simp [option.guard, h]; intro; contradiction def to_list : option α → list α | none := [] | (some a) := [a] @[simp] theorem mem_to_list {a : α} {o : option α} : a ∈ to_list o ↔ a ∈ o := by cases o; simp [to_list, eq_comm] def lift_or_get (f : α → α → α) : option α → option α → option α | none none := none | (some a) none := some a -- get a | none (some b) := some b -- get b | (some a) (some b) := some (f a b) -- lift f instance lift_or_get_comm (f : α → α → α) [h : is_commutative α f] : is_commutative (option α) (lift_or_get f) := ⟨λ a b, by cases a; cases b; simp [lift_or_get, h.comm]⟩ instance lift_or_get_assoc (f : α → α → α) [h : is_associative α f] : is_associative (option α) (lift_or_get f) := ⟨λ a b c, by cases a; cases b; cases c; simp [lift_or_get, h.assoc]⟩ instance lift_or_get_idem (f : α → α → α) [h : is_idempotent α f] : is_idempotent (option α) (lift_or_get f) := ⟨λ a, by cases a; simp [lift_or_get, h.idempotent]⟩ instance lift_or_get_is_left_id (f : α → α → α) : is_left_id (option α) (lift_or_get f) none := ⟨λ a, by cases a; simp [lift_or_get]⟩ instance lift_or_get_is_right_id (f : α → α → α) : is_right_id (option α) (lift_or_get f) none := ⟨λ a, by cases a; simp [lift_or_get]⟩ theorem lift_or_get_choice {f : α → α → α} (h : ∀ a b, f a b = a ∨ f a b = b) : ∀ o₁ o₂, lift_or_get f o₁ o₂ = o₁ ∨ lift_or_get f o₁ o₂ = o₂ | none none := or.inl rfl | (some a) none := or.inl rfl | none (some b) := or.inr rfl | (some a) (some b) := by simpa [lift_or_get] using h a b section rel inductive rel (r : α → β → Prop) : option α → option β → Prop | some {a b} : r a b → rel (some a) (some b) | none {} : rel none none end rel end option
dde06eac810c4340ee32a6da4e940d6b78f750ad
ebf7140a9ea507409ff4c994124fa36e79b4ae35
/src/hints/category_theory/exercise3/hint4.lean
4b5b895ac374ab671c9729c3313f7ec424e7cb22
[]
no_license
fundou/lftcm2020
3e88d58a92755ea5dd49f19c36239c35286ecf5e
99d11bf3bcd71ffeaef0250caa08ecc46e69b55b
refs/heads/master
1,685,610,799,304
1,624,070,416,000
1,624,070,416,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
430
lean
import category_theory.equivalence open category_theory variables {C : Type*} [category C] variables {D : Type*} [category D] lemma equiv_reflects_mono {X Y : C} (f : X ⟶ Y) (e : C ≌ D) (hef : mono (e.functor.map f)) : mono f := begin split, intros Z g h w, apply e.functor.map_injective, rw ← cancel_mono (e.functor.map f), -- Now we're ready to push eveything back to `C`, using the same trick. sorry end
77df42cac3e0bdaa2479f20da040ba485e18f64d
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Init/System/IO.lean
18e7a7f9693e6a12a94f0c49fb46fabc3eec6023
[ "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
19,636
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, Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Control.EState import Init.Control.Reader import Init.Data.String import Init.Data.ByteArray import Init.System.IOError import Init.System.FilePath import Init.System.ST import Init.Data.ToString.Macro /-- Like https://hackage.haskell.org/package/ghc-Prim-0.5.2.0/docs/GHC-Prim.html#t:RealWorld. Makes sure we never reorder `IO` operations. TODO: mark opaque -/ def IO.RealWorld : Type := Unit /- TODO(Leo): mark it as an opaque definition. Reason: prevent functions defined in other modules from accessing `IO.RealWorld`. We don't want action such as ``` def getWorld : IO (IO.RealWorld) := get ``` -/ def EIO (ε : Type) : Type → Type := EStateM ε IO.RealWorld @[inline] def EIO.catchExceptions (x : EIO ε α) (h : ε → EIO Empty α) : EIO Empty α := fun s => match x s with | EStateM.Result.ok a s => EStateM.Result.ok a s | EStateM.Result.error ex s => h ex s instance : Monad (EIO ε) := inferInstanceAs (Monad (EStateM ε IO.RealWorld)) instance : MonadFinally (EIO ε) := inferInstanceAs (MonadFinally (EStateM ε IO.RealWorld)) instance : MonadExceptOf ε (EIO ε) := inferInstanceAs (MonadExceptOf ε (EStateM ε IO.RealWorld)) instance : OrElse (EIO ε α) := ⟨MonadExcept.orelse⟩ instance [Inhabited ε] : Inhabited (EIO ε α) := inferInstanceAs (Inhabited (EStateM ε IO.RealWorld α)) open IO (Error) in abbrev IO : Type → Type := EIO Error @[inline] def EIO.toIO (f : ε → IO.Error) (x : EIO ε α) : IO α := x.adaptExcept f @[inline] def EIO.toIO' (x : EIO ε α) : IO (Except ε α) := EIO.toIO (fun _ => unreachable!) (observing x) @[inline] def IO.toEIO (f : IO.Error → ε) (x : IO α) : EIO ε α := x.adaptExcept f /- After we inline `EState.run'`, the closed term `((), ())` is generated, where the second `()` represents the "initial world". We don't want to cache this closed term. So, we disable the "extract closed terms" optimization. -/ set_option compiler.extract_closed false in @[inline] unsafe def unsafeEIO (fn : EIO ε α) : Except ε α := match fn.run () with | EStateM.Result.ok a _ => Except.ok a | EStateM.Result.error e _ => Except.error e @[inline] unsafe def unsafeIO (fn : IO α) : Except IO.Error α := unsafeEIO fn @[extern "lean_io_timeit"] constant timeit (msg : @& String) (fn : IO α) : IO α @[extern "lean_io_allocprof"] constant allocprof (msg : @& String) (fn : IO α) : IO α /- Programs can execute IO actions during initialization that occurs before the `main` function is executed. The attribute `[init <action>]` specifies which IO action is executed to set the value of an opaque constant. The action `initializing` returns `true` iff it is invoked during initialization. -/ @[extern "lean_io_initializing"] constant IO.initializing : IO Bool namespace IO def ofExcept [ToString ε] (e : Except ε α) : IO α := match e with | Except.ok a => pure a | Except.error e => throw (IO.userError (toString e)) def lazyPure (fn : Unit → α) : IO α := pure (fn ()) /-- Monotonically increasing time since an unspecified past point in milliseconds. No relation to wall clock time. -/ @[extern "lean_io_mono_ms_now"] constant monoMsNow : IO Nat def sleep (ms : UInt32) : IO Unit := -- TODO: add a proper primitive for IO.sleep fun s => dbgSleep ms fun _ => EStateM.Result.ok () s /-- Run `act` in a separate `Task`. This is similar to Haskell's [`unsafeInterleaveIO`](http://hackage.haskell.org/package/base-4.14.0.0/docs/System-IO-Unsafe.html#v:unsafeInterleaveIO), except that the `Task` is started eagerly as usual. Thus pure accesses to the `Task` do not influence the impure `act` computation. Unlike with pure tasks created by `Task.mk`, tasks created by this function will be run even if the last reference to the task is dropped. `act` should manually check for cancellation via `IO.checkCanceled` if it wants to react to that. -/ @[extern "lean_io_as_task"] constant asTask (act : IO α) (prio := Task.Priority.default) : IO (Task (Except IO.Error α)) /-- See `IO.asTask`. -/ @[extern "lean_io_map_task"] constant mapTask (f : α → IO β) (t : Task α) (prio := Task.Priority.default) : IO (Task (Except IO.Error β)) /-- See `IO.asTask`. -/ @[extern "lean_io_bind_task"] constant bindTask (t : Task α) (f : α → IO (Task (Except IO.Error β))) (prio := Task.Priority.default) : IO (Task (Except IO.Error β)) /-- Check if the task's cancellation flag has been set by calling `IO.cancel` or dropping the last reference to the task. -/ @[extern "lean_io_check_canceled"] constant checkCanceled : IO Bool /-- Request cooperative cancellation of the task. The task must explicitly call `IO.checkCanceled` to react to the cancellation. -/ @[extern "lean_io_cancel"] constant cancel : @& Task α → IO Unit /-- Check if the task has finished execution, at which point calling `Task.get` will return immediately. -/ @[extern "lean_io_has_finished"] constant hasFinished : @& Task α → IO Bool /-- Wait for the task to finish, then return its result. -/ @[extern "lean_io_wait"] constant wait : Task α → IO α /-- Wait until any of the tasks in the given list has finished, then return its result. -/ @[extern "lean_io_wait_any"] constant waitAny : @& List (Task α) → IO α /-- Helper method for implementing "deterministic" timeouts. It is the numbe of "small" memory allocations performed by the current execution thread. -/ @[extern "lean_io_get_num_heartbeats"] constant getNumHeartbeats : EIO ε Nat inductive FS.Mode where | read | write | readWrite | append constant FS.Handle : Type := Unit /-- A pure-Lean abstraction of POSIX streams. We use `Stream`s for the standard streams stdin/stdout/stderr so we can capture output of `#eval` commands into memory. -/ structure FS.Stream where isEof : IO Bool flush : IO Unit read : USize → IO ByteArray write : ByteArray → IO Unit getLine : IO String putStr : String → IO Unit namespace Prim open FS @[extern "lean_get_stdin"] constant getStdin : IO FS.Stream @[extern "lean_get_stdout"] constant getStdout : IO FS.Stream @[extern "lean_get_stderr"] constant getStderr : IO FS.Stream @[extern "lean_get_set_stdin"] constant setStdin : FS.Stream → IO FS.Stream @[extern "lean_get_set_stdout"] constant setStdout : FS.Stream → IO FS.Stream @[extern "lean_get_set_stderr"] constant setStderr : FS.Stream → IO FS.Stream @[specialize] partial def iterate (a : α) (f : α → IO (Sum α β)) : IO β := do let v ← f a match v with | Sum.inl a => iterate a f | Sum.inr b => pure b -- @[export lean_fopen_flags] def fopenFlags (m : FS.Mode) (b : Bool) : String := let mode := match m with | FS.Mode.read => "r" | FS.Mode.write => "w" | FS.Mode.readWrite => "r+" | FS.Mode.append => "a" ; let bin := if b then "b" else "t" mode ++ bin @[extern "lean_io_prim_handle_mk"] constant Handle.mk (s : @& String) (mode : @& String) : IO Handle @[extern "lean_io_prim_handle_is_eof"] constant Handle.isEof (h : @& Handle) : IO Bool @[extern "lean_io_prim_handle_flush"] constant Handle.flush (h : @& Handle) : IO Unit @[extern "lean_io_prim_handle_read"] constant Handle.read (h : @& Handle) (bytes : USize) : IO ByteArray @[extern "lean_io_prim_handle_write"] constant Handle.write (h : @& Handle) (buffer : @& ByteArray) : IO Unit @[extern "lean_io_prim_handle_get_line"] constant Handle.getLine (h : @& Handle) : IO String @[extern "lean_io_prim_handle_put_str"] constant Handle.putStr (h : @& Handle) (s : @& String) : IO Unit @[extern "lean_io_getenv"] constant getEnv (var : @& String) : IO (Option String) @[extern "lean_io_realpath"] constant realPath (fname : String) : IO String @[extern "lean_io_is_dir"] constant isDir (fname : @& String) : IO Bool @[extern "lean_io_file_exists"] constant fileExists (fname : @& String) : IO Bool @[extern "lean_io_remove_file"] constant removeFile (fname : @& String) : IO Unit @[extern "lean_io_app_dir"] constant appPath : IO String @[extern "lean_io_current_dir"] constant currentDir : IO String end Prim namespace FS variable [Monad m] [MonadLiftT IO m] def Handle.mk (s : String) (Mode : Mode) (bin : Bool := true) : m Handle := liftM (Prim.Handle.mk s (Prim.fopenFlags Mode bin)) @[inline] def withFile (fn : String) (mode : Mode) (f : Handle → m α) : m α := Handle.mk fn mode >>= f /-- returns whether the end of the file has been reached while reading a file. `h.isEof` returns true /after/ the first attempt at reading past the end of `h`. Once `h.isEof` is true, the reading `h` raises `IO.Error.eof`. -/ def Handle.isEof : Handle → m Bool := liftM ∘ Prim.Handle.isEof def Handle.flush : Handle → m Unit := liftM ∘ Prim.Handle.flush def Handle.read (h : Handle) (bytes : Nat) : m ByteArray := liftM (Prim.Handle.read h (USize.ofNat bytes)) def Handle.write (h : Handle) (s : ByteArray) : m Unit := liftM (Prim.Handle.write h s) def Handle.getLine : Handle → m String := liftM ∘ Prim.Handle.getLine def Handle.putStr (h : Handle) (s : String) : m Unit := liftM <| Prim.Handle.putStr h s def Handle.putStrLn (h : Handle) (s : String) : m Unit := h.putStr (s.push '\n') partial def Handle.readBinToEnd (h : Handle) : m ByteArray := do let rec loop (acc : ByteArray) : m ByteArray := do if ← h.isEof then return acc else let buf ← h.read 1024 loop (acc ++ buf) loop ByteArray.empty partial def Handle.readToEnd (h : Handle) : m String := do let rec read (s : String) := do let line ← h.getLine if line.length == 0 then pure s else read (s ++ line) read "" def readBinFile (fname : String) : m ByteArray := do let h ← Handle.mk fname Mode.read true h.readBinToEnd def readFile (fname : String) : m String := do let h ← Handle.mk fname Mode.read false h.readToEnd partial def lines (fname : String) : m (Array String) := do let h ← Handle.mk fname Mode.read false let rec read (lines : Array String) := do let line ← h.getLine if line.length == 0 then pure lines else if line.back == '\n' then let line := line.dropRight 1 let line := if System.Platform.isWindows && line.back == '\x0d' then line.dropRight 1 else line read <| lines.push line else pure <| lines.push line read #[] def writeBinFile (fname : String) (content : ByteArray) : m Unit := do let h ← Handle.mk fname Mode.write true h.write content def writeFile (fname : String) (content : String) : m Unit := do let h ← Handle.mk fname Mode.write false h.putStr content namespace Stream def putStrLn (strm : FS.Stream) (s : String) : m Unit := liftM (strm.putStr (s.push '\n')) end Stream end FS section variable [Monad m] [MonadLiftT IO m] def getStdin : m FS.Stream := liftM Prim.getStdin def getStdout : m FS.Stream := liftM Prim.getStdout def getStderr : m FS.Stream := liftM Prim.getStderr /-- Replaces the stdin stream of the current thread and returns its previous value. -/ def setStdin : FS.Stream → m FS.Stream := liftM ∘ Prim.setStdin /-- Replaces the stdout stream of the current thread and returns its previous value. -/ def setStdout : FS.Stream → m FS.Stream := liftM ∘ Prim.setStdout /-- Replaces the stderr stream of the current thread and returns its previous value. -/ def setStderr : FS.Stream → m FS.Stream := liftM ∘ Prim.setStderr def withStdin [MonadFinally m] (h : FS.Stream) (x : m α) : m α := do let prev ← setStdin h try x finally discard <| setStdin prev def withStdout [MonadFinally m] (h : FS.Stream) (x : m α) : m α := do let prev ← setStdout h try x finally discard <| setStdout prev def withStderr [MonadFinally m] (h : FS.Stream) (x : m α) : m α := do let prev ← setStderr h try x finally discard <| setStderr prev def print [ToString α] (s : α) : IO Unit := do let out ← getStdout out.putStr <| toString s def println [ToString α] (s : α) : IO Unit := print ((toString s).push '\n') def eprint [ToString α] (s : α) : IO Unit := do let out ← getStderr liftM <| out.putStr <| toString s def eprintln [ToString α] (s : α) : IO Unit := eprint <| toString s |>.push '\n' @[export lean_io_eprintln] private def eprintlnAux (s : String) : IO Unit := eprintln s def getEnv : String → m (Option String) := liftM ∘ Prim.getEnv def realPath : String → m String := liftM ∘ Prim.realPath def isDir : String → m Bool := liftM ∘ Prim.isDir def fileExists : String → m Bool := liftM ∘ Prim.fileExists def removeFile : String → m Unit := liftM ∘ Prim.removeFile def appPath : m String := liftM Prim.appPath def appDir : m String := do let p ← appPath let some p ← pure <| System.FilePath.parent p | liftM (m := IO) <| throw <| IO.userError s!"System.IO.appDir: unexpected filename '{p}'" realPath p def currentDir : m String := liftM Prim.currentDir end namespace Process inductive Stdio where | piped | inherit | null def Stdio.toHandleType : Stdio → Type | Stdio.piped => FS.Handle | Stdio.inherit => Unit | Stdio.null => Unit structure StdioConfig where /- 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 structure SpawnArgs extends StdioConfig where /- Command name. -/ cmd : String /- Arguments for the process -/ args : Array String := #[] /- Working directory for the process. Inherit from current process if `none`. -/ cwd : Option String := none /- Add or remove environment variables for the process. -/ env : Array (String × Option String) := #[] -- TODO(Sebastian): constructor must be private structure Child (cfg : StdioConfig) where stdin : cfg.stdin.toHandleType stdout : cfg.stdout.toHandleType stderr : cfg.stderr.toHandleType @[extern "lean_io_process_spawn"] constant spawn (args : SpawnArgs) : IO (Child args.toStdioConfig) @[extern "lean_io_process_child_wait"] constant Child.wait {cfg : @& StdioConfig} : @& Child cfg → IO UInt32 structure Output where exitCode : UInt32 stdout : String stderr : String /-- Run process to completion and capture output. -/ def output (args : SpawnArgs) : IO Output := do let child ← spawn { args with stdout := Stdio.piped, stderr := Stdio.piped } let stdout ← IO.asTask child.stdout.readToEnd Task.Priority.dedicated let stderr ← child.stderr.readToEnd let exitCode ← child.wait let stdout ← IO.ofExcept stdout.get pure { exitCode := exitCode, stdout := stdout, stderr := stderr } /-- Run process to completion and return stdout on success. -/ def run (args : SpawnArgs) : IO String := do let out ← output args if out.exitCode != 0 then throw <| IO.userError <| "process '" ++ args.cmd ++ "' exited with code " ++ toString out.exitCode; pure out.stdout end Process structure AccessRight where read : Bool := false write : Bool := false execution : Bool := false def AccessRight.flags (acc : AccessRight) : UInt32 := let r : UInt32 := if acc.read then 0x4 else 0 let w : UInt32 := if acc.write then 0x2 else 0 let x : UInt32 := if acc.execution then 0x1 else 0 r.lor <| w.lor x structure FileRight where user : AccessRight := {} group : AccessRight := {} other : AccessRight := {} def FileRight.flags (acc : FileRight) : UInt32 := let u : UInt32 := acc.user.flags.shiftLeft 6 let g : UInt32 := acc.group.flags.shiftLeft 3 let o : UInt32 := acc.other.flags u.lor <| g.lor o @[extern "lean_chmod"] constant Prim.setAccessRights (filename : @& String) (mode : UInt32) : IO Unit def setAccessRights (filename : String) (mode : FileRight) : IO Unit := Prim.setAccessRights filename mode.flags /- References -/ abbrev Ref (α : Type) := ST.Ref IO.RealWorld α instance : MonadLift (ST IO.RealWorld) (EIO ε) := ⟨fun x s => match x s with | EStateM.Result.ok a s => EStateM.Result.ok a s | EStateM.Result.error ex _ => nomatch ex⟩ def mkRef [Monad m] [MonadLiftT (ST IO.RealWorld) m] (a : α) : m (IO.Ref α) := ST.mkRef a namespace FS namespace Stream @[export lean_stream_of_handle] def ofHandle (h : Handle) : Stream := { isEof := Prim.Handle.isEof h, flush := Prim.Handle.flush h, read := Prim.Handle.read h, write := Prim.Handle.write h, getLine := Prim.Handle.getLine h, putStr := Prim.Handle.putStr h, } structure Buffer where data : ByteArray := ByteArray.empty pos : Nat := 0 def ofBuffer (r : Ref Buffer) : Stream := { isEof := do let b ← r.get; pure <| b.pos >= b.data.size, flush := pure (), read := fun n => r.modifyGet fun b => let data := b.data.extract b.pos (b.pos + n.toNat) (data, { b with pos := b.pos + data.size }), write := fun data => r.modify fun b => -- set `exact` to `false` so that repeatedly writing to the stream does not impose quadratic run time { b with data := data.copySlice 0 b.data b.pos data.size false, pos := b.pos + data.size }, getLine := r.modifyGet fun b => let pos := match b.data.findIdx? (start := b.pos) fun u => u == 0 || u = '\n'.toNat.toUInt8 with -- include '\n', but not '\0' | some pos => if b.data.get! pos == 0 then pos else pos + 1 | none => b.data.size (String.fromUTF8Unchecked <| b.data.extract b.pos pos, { b with pos := pos }), putStr := fun s => r.modify fun b => let data := s.toUTF8 { b with data := data.copySlice 0 b.data b.pos data.size false, pos := b.pos + data.size }, } end Stream /-- Run action with `stdin` emptied and `stdout+stderr` captured into a `String`. -/ def withIsolatedStreams (x : IO α) : IO (String × Except IO.Error α) := do let bIn ← mkRef { : Stream.Buffer } let bOut ← mkRef { : Stream.Buffer } let r ← withStdin (Stream.ofBuffer bIn) <| withStdout (Stream.ofBuffer bOut) <| withStderr (Stream.ofBuffer bOut) <| observing x let bOut ← bOut.get let out := String.fromUTF8Unchecked bOut.data pure (out, r) end FS end IO universe u namespace Lean /-- Typeclass used for presenting the output of an `#eval` command. -/ class Eval (α : Type u) where -- We default `hideUnit` to `true`, but set it to `false` in the direct call from `#eval` -- so that `()` output is hidden in chained instances such as for some `m Unit`. -- We take `Unit → α` instead of `α` because ‵α` may contain effectful debugging primitives (e.g., `dbg_trace`) eval : (Unit → α) → forall (hideUnit : optParam Bool true), IO Unit instance [ToString α] : Eval α := ⟨fun a _ => IO.println (toString (a ()))⟩ instance [Repr α] : Eval α := ⟨fun a _ => IO.println (repr (a ()))⟩ instance : Eval Unit := ⟨fun u hideUnit => if hideUnit then pure () else IO.println (repr (u ()))⟩ instance [Eval α] : Eval (IO α) := ⟨fun x _ => do let a ← x (); Eval.eval (fun _ => a)⟩ @[noinline, nospecialize] def runEval [Eval α] (a : Unit → α) : IO (String × Except IO.Error Unit) := IO.FS.withIsolatedStreams (Eval.eval a false) end Lean syntax "println! " (interpolatedStr(term) <|> term) : term macro_rules | `(println! $msg) => if msg.getKind == Lean.interpolatedStrKind then `((IO.println (s! $msg) : IO Unit)) else `((IO.println $msg : IO Unit))
5c12cfd0fdf60c13eaa543c2c2b8ed19a29f9c40
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/int/sqrt.lean
829aa955bb9d2f9f7159b6732bd30f7e33ca1c86
[ "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
1,052
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.nat.sqrt /-! # Square root of integers This file defines the square root function on integers. `int.sqrt z` is the greatest integer `r` such that `r * r ≤ z`. If `z ≤ 0`, then `int.sqrt z = 0`. -/ namespace int /-- `sqrt z` is the square root of an integer `z`. If `z` is positive, it returns the largest integer `r` such that `r * r ≤ n`. If it is negative, it returns `0`. For example, `sqrt (-1) = 0`, `sqrt 1 = 1`, `sqrt 2 = 1` -/ @[pp_nodot] def sqrt (z : ℤ) : ℤ := nat.sqrt $ int.to_nat z theorem sqrt_eq (n : ℤ) : sqrt (n*n) = n.nat_abs := by rw [sqrt, ← nat_abs_mul_self, to_nat_coe_nat, nat.sqrt_eq] theorem exists_mul_self (x : ℤ) : (∃ n, n * n = x) ↔ sqrt x * sqrt x = x := ⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq, ← int.coe_nat_mul, nat_abs_mul_self], λ h, ⟨sqrt x, h⟩⟩ theorem sqrt_nonneg (n : ℤ) : 0 ≤ sqrt n := coe_nat_nonneg _ end int
663aa400f06c0ed9eccb8dad777170220913e6c7
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/lie/universal_enveloping.lean
c8bed4612a51d05c5f16da99bced444f2ce399e3
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,884
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.of_associative import algebra.ring_quot import linear_algebra.tensor_algebra.basic /-! # Universal enveloping algebra Given a commutative ring `R` and a Lie algebra `L` over `R`, we construct the universal enveloping algebra of `L`, together with its universal property. ## Main definitions * `universal_enveloping_algebra`: the universal enveloping algebra, endowed with an `R`-algebra structure. * `universal_enveloping_algebra.ι`: the Lie algebra morphism from `L` to its universal enveloping algebra. * `universal_enveloping_algebra.lift`: given an associative algebra `A`, together with a Lie algebra morphism `f : L →ₗ⁅R⁆ A`, `lift R L f : universal_enveloping_algebra R L →ₐ[R] A` is the unique morphism of algebras through which `f` factors. * `universal_enveloping_algebra.ι_comp_lift`: states that the lift of a morphism is indeed part of a factorisation. * `universal_enveloping_algebra.lift_unique`: states that lifts of morphisms are indeed unique. * `universal_enveloping_algebra.hom_ext`: a restatement of `lift_unique` as an extensionality lemma. ## Tags lie algebra, universal enveloping algebra, tensor algebra -/ universes u₁ u₂ u₃ variables (R : Type u₁) (L : Type u₂) variables [comm_ring R] [lie_ring L] [lie_algebra R L] local notation `ιₜ` := tensor_algebra.ι R namespace universal_enveloping_algebra /-- The quotient by the ideal generated by this relation is the universal enveloping algebra. Note that we have avoided using the more natural expression: | lie_compat (x y : L) : rel (ιₜ ⁅x, y⁆) ⁅ιₜ x, ιₜ y⁆ so that our construction needs only the semiring structure of the tensor algebra. -/ inductive rel : tensor_algebra R L → tensor_algebra R L → Prop | lie_compat (x y : L) : rel (ιₜ ⁅x, y⁆ + (ιₜ y) * (ιₜ x)) ((ιₜ x) * (ιₜ y)) end universal_enveloping_algebra /-- The universal enveloping algebra of a Lie algebra. -/ @[derive [inhabited, ring, algebra R]] def universal_enveloping_algebra := ring_quot (universal_enveloping_algebra.rel R L) namespace universal_enveloping_algebra /-- The quotient map from the tensor algebra to the universal enveloping algebra as a morphism of associative algebras. -/ def mk_alg_hom : tensor_algebra R L →ₐ[R] universal_enveloping_algebra R L := ring_quot.mk_alg_hom R (rel R L) variables {L} /-- The natural Lie algebra morphism from a Lie algebra to its universal enveloping algebra. -/ def ι : L →ₗ⁅R⁆ universal_enveloping_algebra R L := { map_lie' := λ x y, by { suffices : mk_alg_hom R L (ιₜ ⁅x, y⁆ + (ιₜ y) * (ιₜ x)) = mk_alg_hom R L ((ιₜ x) * (ιₜ y)), { rw alg_hom.map_mul at this, simp [lie_ring.of_associative_ring_bracket, ← this], }, exact ring_quot.mk_alg_hom_rel _ (rel.lie_compat x y), }, ..(mk_alg_hom R L).to_linear_map.comp ιₜ } variables {A : Type u₃} [ring A] [algebra R A] (f : L →ₗ⁅R⁆ A) /-- The universal property of the universal enveloping algebra: Lie algebra morphisms into associative algebras lift to associative algebra morphisms from the universal enveloping algebra. -/ def lift : (L →ₗ⁅R⁆ A) ≃ (universal_enveloping_algebra R L →ₐ[R] A) := { to_fun := λ f, ring_quot.lift_alg_hom R ⟨tensor_algebra.lift R (f : L →ₗ[R] A), begin intros a b h, induction h with x y, simp [lie_ring.of_associative_ring_bracket], end⟩, inv_fun := λ F, (F : universal_enveloping_algebra R L →ₗ⁅R⁆ A).comp (ι R), left_inv := λ f, by { ext, simp [ι, mk_alg_hom], }, right_inv := λ F, by { ext, simp [ι, mk_alg_hom], } } @[simp] lemma lift_symm_apply (F : universal_enveloping_algebra R L →ₐ[R] A) : (lift R).symm F = (F : universal_enveloping_algebra R L →ₗ⁅R⁆ A).comp (ι R) := rfl @[simp] lemma ι_comp_lift : (lift R f) ∘ (ι R) = f := funext $ lie_hom.ext_iff.mp $ (lift R).symm_apply_apply f @[simp] lemma lift_ι_apply (x : L) : lift R f (ι R x) = f x := by rw [←function.comp_apply (lift R f) (ι R) x, ι_comp_lift] lemma lift_unique (g : universal_enveloping_algebra R L →ₐ[R] A) : g ∘ (ι R) = f ↔ g = lift R f := begin refine iff.trans _ (lift R).symm_apply_eq, split; {intro h, ext, simp [←h] }, end /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma hom_ext {g₁ g₂ : universal_enveloping_algebra R L →ₐ[R] A} (h : (g₁ : universal_enveloping_algebra R L →ₗ⁅R⁆ A).comp (ι R) = (g₂ : universal_enveloping_algebra R L →ₗ⁅R⁆ A).comp (ι R)) : g₁ = g₂ := have h' : (lift R).symm g₁ = (lift R).symm g₂, { ext, simp [h], }, (lift R).symm.injective h' end universal_enveloping_algebra
425744ad31f8d774e2c446cfa0c933bd3b5027d5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/lie/universal_enveloping.lean
6ada08e97fa4508048863d9d96e3f1a847c81fce
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
5,497
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.lie.basic import Mathlib.algebra.ring_quot import Mathlib.linear_algebra.tensor_algebra import Mathlib.PostPort universes u₁ u₂ u₃ namespace Mathlib /-! # Universal enveloping algebra Given a commutative ring `R` and a Lie algebra `L` over `R`, we construct the universal enveloping algebra of `L`, together with its universal property. ## Main definitions * `universal_enveloping_algebra`: the universal enveloping algebra, endowed with an `R`-algebra structure. * `universal_enveloping_algebra.ι`: the Lie algebra morphism from `L` to its universal enveloping algebra. * `universal_enveloping_algebra.lift`: given an associative algebra `A`, together with a Lie algebra morphism `f : L →ₗ⁅R⁆ A`, `lift R L f : universal_enveloping_algebra R L →ₐ[R] A` is the unique morphism of algebras through which `f` factors. * `universal_enveloping_algebra.ι_comp_lift`: states that the lift of a morphism is indeed part of a factorisation. * `universal_enveloping_algebra.lift_unique`: states that lifts of morphisms are indeed unique. * `universal_enveloping_algebra.hom_ext`: a restatement of `lift_unique` as an extensionality lemma. ## Tags lie algebra, universal enveloping algebra, tensor algebra -/ namespace universal_enveloping_algebra /-- The quotient by the ideal generated by this relation is the universal enveloping algebra. Note that we have avoided using the more natural expression: | lie_compat (x y : L) : rel (ιₜ ⁅x, y⁆) ⁅ιₜ x, ιₜ y⁆ so that our construction needs only the semiring structure of the tensor algebra. -/ inductive rel (R : Type u₁) (L : Type u₂) [comm_ring R] [lie_ring L] [lie_algebra R L] : tensor_algebra R L → tensor_algebra R L → Prop where | lie_compat : ∀ (x y : L), rel R L (coe_fn (tensor_algebra.ι R) (has_bracket.bracket x y) + coe_fn (tensor_algebra.ι R) y * coe_fn (tensor_algebra.ι R) x) (coe_fn (tensor_algebra.ι R) x * coe_fn (tensor_algebra.ι R) y) end universal_enveloping_algebra /-- The universal enveloping algebra of a Lie algebra. -/ def universal_enveloping_algebra (R : Type u₁) (L : Type u₂) [comm_ring R] [lie_ring L] [lie_algebra R L] := ring_quot sorry namespace universal_enveloping_algebra /-- The quotient map from the tensor algebra to the universal enveloping algebra as a morphism of associative algebras. -/ def mk_alg_hom (R : Type u₁) (L : Type u₂) [comm_ring R] [lie_ring L] [lie_algebra R L] : alg_hom R (tensor_algebra R L) (universal_enveloping_algebra R L) := ring_quot.mk_alg_hom R (rel R L) /-- The natural Lie algebra morphism from a Lie algebra to its universal enveloping algebra. -/ def ι (R : Type u₁) {L : Type u₂} [comm_ring R] [lie_ring L] [lie_algebra R L] : lie_algebra.morphism R L (universal_enveloping_algebra R L) := lie_algebra.morphism.mk (linear_map.to_fun (linear_map.comp (alg_hom.to_linear_map (mk_alg_hom R L)) (tensor_algebra.ι R))) sorry sorry sorry /-- The universal property of the universal enveloping algebra: Lie algebra morphisms into associative algebras lift to associative algebra morphisms from the universal enveloping algebra. -/ def lift (R : Type u₁) {L : Type u₂} [comm_ring R] [lie_ring L] [lie_algebra R L] {A : Type u₃} [ring A] [algebra R A] : lie_algebra.morphism R L A ≃ alg_hom R (universal_enveloping_algebra R L) A := equiv.mk (fun (f : lie_algebra.morphism R L A) => coe_fn (ring_quot.lift_alg_hom R) { val := coe_fn (tensor_algebra.lift R) ↑f, property := sorry }) (fun (F : alg_hom R (universal_enveloping_algebra R L) A) => lie_algebra.morphism.comp (lie_algebra.of_associative_algebra_hom F) (ι R)) sorry sorry @[simp] theorem lift_symm_apply (R : Type u₁) {L : Type u₂} [comm_ring R] [lie_ring L] [lie_algebra R L] {A : Type u₃} [ring A] [algebra R A] (F : alg_hom R (universal_enveloping_algebra R L) A) : coe_fn (equiv.symm (lift R)) F = lie_algebra.morphism.comp (lie_algebra.of_associative_algebra_hom F) (ι R) := rfl @[simp] theorem ι_comp_lift (R : Type u₁) {L : Type u₂} [comm_ring R] [lie_ring L] [lie_algebra R L] {A : Type u₃} [ring A] [algebra R A] (f : lie_algebra.morphism R L A) : ⇑(coe_fn (lift R) f) ∘ ⇑(ι R) = ⇑f := funext (iff.mp lie_algebra.morphism.ext_iff (equiv.symm_apply_apply (lift R) f)) @[simp] theorem lift_ι_apply (R : Type u₁) {L : Type u₂} [comm_ring R] [lie_ring L] [lie_algebra R L] {A : Type u₃} [ring A] [algebra R A] (f : lie_algebra.morphism R L A) (x : L) : coe_fn (coe_fn (lift R) f) (coe_fn (ι R) x) = coe_fn f x := sorry theorem lift_unique (R : Type u₁) {L : Type u₂} [comm_ring R] [lie_ring L] [lie_algebra R L] {A : Type u₃} [ring A] [algebra R A] (f : lie_algebra.morphism R L A) (g : alg_hom R (universal_enveloping_algebra R L) A) : ⇑g ∘ ⇑(ι R) = ⇑f ↔ g = coe_fn (lift R) f := sorry /-- See note [partially-applied ext lemmas]. -/ theorem hom_ext (R : Type u₁) {L : Type u₂} [comm_ring R] [lie_ring L] [lie_algebra R L] {A : Type u₃} [ring A] [algebra R A] {g₁ : alg_hom R (universal_enveloping_algebra R L) A} {g₂ : alg_hom R (universal_enveloping_algebra R L) A} (h : ⇑g₁ ∘ ⇑(ι R) = ⇑g₂ ∘ ⇑(ι R)) : g₁ = g₂ := sorry
7b781718b519b4a2a97c84ef3ffa23ee9c246bb4
e2fc96178628c7451e998a0db2b73877d0648be5
/src/classes/context_free/basics/inclusion.lean
25a5ff57fafc62a3df708049c38c4a281db814a3
[ "BSD-2-Clause" ]
permissive
madvorak/grammars
cd324ae19b28f7b8be9c3ad010ef7bf0fabe5df2
1447343a45fcb7821070f1e20b57288d437323a6
refs/heads/main
1,692,383,644,884
1,692,032,429,000
1,692,032,429,000
453,948,141
7
0
null
null
null
null
UTF-8
Lean
false
false
3,892
lean
import classes.context_free.basics.toolbox import classes.context_sensitive.basics.inclusion variables {T : Type} def csg_of_cfg (g : CF_grammar T) : CS_grammar T := CS_grammar.mk g.nt g.initial (list.map (λ r : g.nt × (list (symbol T g.nt)), csrule.mk [] r.fst [] r.snd) g.rules) def grammar_of_cfg (g : CF_grammar T) : grammar T := grammar.mk g.nt g.initial (list.map (λ r : g.nt × (list (symbol T g.nt)), grule.mk [] r.fst [] r.snd) g.rules) lemma grammar_of_cfg_well_defined (g : CF_grammar T) : grammar_of_csg (csg_of_cfg g) = grammar_of_cfg g := begin unfold grammar_of_cfg, delta csg_of_cfg, delta grammar_of_csg, simp only [list.map_map, eq_self_iff_true, heq_iff_eq, true_and], ext1, rw [list.nth_map, list.nth_map], apply congr_fun, ext1, cases x, { refl, }, apply congr_arg option.some, simp [list.append_nil], end lemma grammar_of_csg_of_cfg : grammar_of_csg ∘ csg_of_cfg = @grammar_of_cfg T := begin ext, apply grammar_of_cfg_well_defined, end lemma CF_language_eq_CS_language (g : CF_grammar T) : CF_language g = CS_language (csg_of_cfg g) := begin unfold CF_language, unfold CS_language, ext1 w, change CF_derives g [symbol.nonterminal g.initial] (list.map symbol.terminal w) = CS_derives (csg_of_cfg g) [symbol.nonterminal (csg_of_cfg g).initial] (list.map symbol.terminal w), rw eq_iff_iff, split, { have indu : ∀ v : list (symbol T g.nt), CF_derives g [symbol.nonterminal g.initial] v → CS_derives (csg_of_cfg g) [symbol.nonterminal (csg_of_cfg g).initial] v, { clear w, intros v h, induction h with x y trash hyp ih, { apply CS_deri_self, }, apply CS_deri_of_deri_tran, { exact ih, }, unfold CF_transforms at hyp, unfold CS_transforms, delta csg_of_cfg, dsimp only, rcases hyp with ⟨r, rin, u, w, bef, aft⟩, use csrule.mk [] r.fst [] r.snd, split, { rw list.mem_map, use r, split, { exact rin, }, { refl, }, }, use u, use w, split; { dsimp only, rw list.append_nil, rw list.append_nil, assumption, }, }, exact indu (list.map symbol.terminal w), }, { have indu : ∀ v : list (symbol T g.nt), CS_derives (csg_of_cfg g) [symbol.nonterminal g.initial] v → CF_derives g [symbol.nonterminal (csg_of_cfg g).initial] v, { clear w, intros v h, induction h with x y trash hyp ih, { apply CF_deri_self, }, apply CF_deri_of_deri_tran, { exact ih, }, unfold CS_transforms at hyp, unfold CF_transforms, delta csg_of_cfg at hyp, dsimp only at hyp, rcases hyp with ⟨r, rin, u, w, bef, aft⟩, use (r.input_nonterminal, r.output_string), split, { finish, }, use u, use w, have cl_empty : r.context_left = list.nil, { finish, }, have cr_empty : r.context_right = list.nil, { finish, }, rw [cl_empty, cr_empty] at *, repeat { rw list.append_nil at *, }, split; assumption, }, exact indu (list.map symbol.terminal w), }, end lemma CF_language_eq_grammar_language (g : CF_grammar T) : CF_language g = grammar_language (grammar_of_cfg g) := begin rw ←grammar_of_cfg_well_defined, rw CF_language_eq_CS_language, rw CS_language_eq_grammar_language, end theorem CF_subclass_CS {L : language T} : is_CF L → is_CS L := begin rintro ⟨g, eq_L⟩, use csg_of_cfg g, rw ←eq_L, rw CF_language_eq_CS_language, end theorem CF_subclass_RE {L : language T} : is_CF L → is_RE L := CS_subclass_RE ∘ CF_subclass_CS
140de7eaa32f93cf8a668d6e50dc463140718b96
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/data/nat/bquant.lean
e16dd5f7cf27d049a6bce02ff9702c8aefb5efd9
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,747
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 Show that "bounded" quantifiers: (∃x, x < n ∧ P x) and (∀x, x < n → P x) are decidable when P is decidable. This module allow us to write if-then-else expressions such as if (∀ x : nat, x < n → ∃ y : nat, y < n ∧ y * y = x) then t else s without assuming classical axioms. More importantly, they can be reduced inside of the Lean kernel. -/ import data.nat.order data.nat.div namespace nat open subtype definition bex [reducible] (n : nat) (P : nat → Prop) : Prop := ∃ x, x < n ∧ P x definition bsub [reducible] (n : nat) (P : nat → Prop) : Type₁ := {x | x < n ∧ P x} definition ball [reducible] (n : nat) (P : nat → Prop) : Prop := ∀ x, x < n → P x lemma bex_of_bsub {n : nat} {P : nat → Prop} : bsub n P → bex n P := assume h, ex_of_sub h theorem not_bex_zero (P : nat → Prop) : ¬ bex 0 P := λ H, obtain (w : nat) (Hw : w < 0 ∧ P w), from H, and.rec_on Hw (λ h₁ h₂, absurd h₁ (not_lt_zero w)) theorem not_bsub_zero (P : nat → Prop) : bsub 0 P → false := λ H, absurd (bex_of_bsub H) (not_bex_zero P) definition bsub_succ {P : nat → Prop} {n : nat} (H : bsub n P) : bsub (succ n) P := obtain (w : nat) (Hw : w < n ∧ P w), from H, and.rec_on Hw (λ hlt hp, tag w (and.intro (lt.step hlt) hp)) theorem bex_succ {P : nat → Prop} {n : nat} (H : bex n P) : bex (succ n) P := obtain (w : nat) (Hw : w < n ∧ P w), from H, and.rec_on Hw (λ hlt hp, exists.intro w (and.intro (lt.step hlt) hp)) definition bsub_succ_of_pred {P : nat → Prop} {a : nat} (H : P a) : bsub (succ a) P := tag a (and.intro (lt.base a) H) theorem bex_succ_of_pred {P : nat → Prop} {a : nat} (H : P a) : bex (succ a) P := bex_of_bsub (bsub_succ_of_pred H) theorem not_bex_succ {P : nat → Prop} {n : nat} (H₁ : ¬ bex n P) (H₂ : ¬ P n) : ¬ bex (succ n) P := λ H, obtain (w : nat) (Hw : w < succ n ∧ P w), from H, and.rec_on Hw (λ hltsn hp, or.rec_on (nat.eq_or_lt_of_le (le_of_succ_le_succ hltsn)) (λ heq : w = n, absurd (eq.rec_on heq hp) H₂) (λ hltn : w < n, absurd (exists.intro w (and.intro hltn hp)) H₁)) theorem not_bsub_succ {P : nat → Prop} {n : nat} (H₁ : ¬ bex n P) (H₂ : ¬ P n) : bsub (succ n) P → false := λ H, absurd (bex_of_bsub H) (not_bex_succ H₁ H₂) theorem ball_zero (P : nat → Prop) : ball zero P := λ x Hlt, absurd Hlt !not_lt_zero theorem ball_of_ball_succ {n : nat} {P : nat → Prop} (H : ball (succ n) P) : ball n P := λ x Hlt, H x (lt.step Hlt) theorem ball_succ_of_ball {n : nat} {P : nat → Prop} (H₁ : ball n P) (H₂ : P n) : ball (succ n) P := λ (x : nat) (Hlt : x < succ n), or.elim (nat.eq_or_lt_of_le (le_of_succ_le_succ Hlt)) (λ heq : x = n, eq.rec_on (eq.rec_on heq rfl) H₂) (λ hlt : x < n, H₁ x hlt) theorem not_ball_of_not {n : nat} {P : nat → Prop} (H₁ : ¬ P n) : ¬ ball (succ n) P := λ (H : ball (succ n) P), absurd (H n (lt.base n)) H₁ theorem not_ball_succ_of_not_ball {n : nat} {P : nat → Prop} (H₁ : ¬ ball n P) : ¬ ball (succ n) P := λ (H : ball (succ n) P), absurd (ball_of_ball_succ H) H₁ end nat section open nat decidable definition decidable_bex [instance] (n : nat) (P : nat → Prop) [H : decidable_pred P] : decidable (bex n P) := nat.rec_on n (inr (not_bex_zero P)) (λ a ih, decidable.rec_on ih (λ hpos : bex a P, inl (bex_succ hpos)) (λ hneg : ¬ bex a P, decidable.rec_on (H a) (λ hpa : P a, inl (bex_succ_of_pred hpa)) (λ hna : ¬ P a, inr (not_bex_succ hneg hna)))) definition decidable_ball [instance] (n : nat) (P : nat → Prop) [H : decidable_pred P] : decidable (ball n P) := nat.rec_on n (inl (ball_zero P)) (λ n₁ ih, decidable.rec_on ih (λ ih_pos, decidable.rec_on (H n₁) (λ p_pos, inl (ball_succ_of_ball ih_pos p_pos)) (λ p_neg, inr (not_ball_of_not p_neg))) (λ ih_neg, inr (not_ball_succ_of_not_ball ih_neg))) definition decidable_bex_le [instance] (n : nat) (P : nat → Prop) [H : decidable_pred P] : decidable (∃ x, x ≤ n ∧ P x) := decidable_of_decidable_of_iff (decidable_bex (succ n) P) (exists_congr (λn, and_congr !lt_succ_iff_le !iff.refl)) definition decidable_ball_le [instance] (n : nat) (P : nat → Prop) [H : decidable_pred P] : decidable (∀ x, x ≤ n → P x) := decidable_of_decidable_of_iff (decidable_ball (succ n) P) (forall_congr (λ n, imp_congr !lt_succ_iff_le !iff.refl)) end namespace nat open decidable variable {P : nat → Prop} variable [decP : decidable_pred P] include decP definition bsub_not_of_not_ball : ∀ {n : nat}, ¬ ball n P → {i | i < n ∧ ¬ P i} | 0 h := absurd (ball_zero P) h | (succ n) h := decidable.by_cases (λ hp : P n, have ¬ ball n P, from assume b : ball n P, absurd (ball_succ_of_ball b hp) h, have {i | i < n ∧ ¬ P i}, from bsub_not_of_not_ball this, bsub_succ this) (λ hn : ¬ P n, bsub_succ_of_pred hn) theorem bex_not_of_not_ball {n : nat} (H : ¬ ball n P) : bex n (λ n, ¬ P n) := bex_of_bsub (bsub_not_of_not_ball H) theorem ball_not_of_not_bex : ∀ {n : nat}, ¬ bex n P → ball n (λ n, ¬ P n) | 0 h := ball_zero _ | (succ n) h := by_cases (λ hp : P n, absurd (bex_succ_of_pred hp) h) (λ hn : ¬ P n, have ¬ bex n P, from assume b : bex n P, absurd (bex_succ b) h, have ball n (λ n, ¬ P n), from ball_not_of_not_bex this, ball_succ_of_ball this hn) end nat
7bf0df62316623a59029f65dae49167c77e95f1c
ec62863c729b7eedee77b86d974f2c529fa79d25
/18/b.lean
5fa05cd7dc8489369c729aacd82d1efc412b84ec
[]
no_license
rwbarton/advent-of-lean-4
2ac9b17ba708f66051e3d8cd694b0249bc433b65
417c7e2718253ba7148c0279fcb251b6fc291477
refs/heads/main
1,675,917,092,057
1,609,864,581,000
1,609,864,581,000
317,700,289
24
0
null
null
null
null
UTF-8
Lean
false
false
1,559
lean
import Lean.Data.Json.Parser open Lean Lean.Quickparse Lean.Json.Parser inductive Node | num : Int → Node | add : Node → Node → Node | mul : Node → Node → Node instance : Inhabited Node := ⟨Node.num 0⟩ def Node.toString | (Node.num n) => s!"{n}" | (Node.add e₁ e₂) => "(" ++ e₁.toString ++ " + " ++ e₂.toString ++ ")" | (Node.mul e₁ e₂) => "(" ++ e₁.toString ++ " * " ++ e₂.toString ++ ")" instance : ToString Node := ⟨Node.toString⟩ partial def parseParens : Quickparse Node := do let c ← peek! if c.isDigit then Node.num <*> natMaybeZero else if c == '(' then do skip let rec goSum : Quickparse Node := do let n ← parseParens match (← peek!) with | '+' => do skip; Node.add n <*> goSum | _ => n let rec goProd : Quickparse Node := do let n ← goSum match (← peek!) with | '*' => do skip; Node.mul n <*> goProd | ')' => do skip; pure n | _ => fail "bad parse" goProd else fail "bad parse" def mungeString (s : String) : String := "(" ++ String.mk (s.toList.filter (· ≠ ' ')) ++ ")" def parseLine (s : String) : Node := match (parseParens <* eoi) (mungeString s).mkIterator with | Result.success _ n => n | Result.error _ err => panic! err def Node.eval | (Node.num n) => n | (Node.add e₁ e₂) => e₁.eval + e₂.eval | (Node.mul e₁ e₂) => e₁.eval * e₂.eval def main : IO Unit := do let input ← IO.FS.lines "a.in" let result := (input.map (λ l => (parseLine l).eval)).foldl (· + ·) 0 IO.print s!"{result}\n"
5fb56089f6d344c165ca06b8c3135d15e7b3673a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/module/equiv.lean
7808fe6759225a1f7366488f341d0ba55eddd885
[ "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
25,380
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro, Anne Baanen, Frédéric Dupuis, Heather Macbeth -/ import algebra.module.linear_map /-! # (Semi)linear equivalences In this file we define * `linear_equiv σ M M₂`, `M ≃ₛₗ[σ] M₂`: an invertible semilinear map. Here, `σ` is a `ring_hom` from `R` to `R₂` and an `e : M ≃ₛₗ[σ] M₂` satisfies `e (c • x) = (σ c) • (e x)`. The plain linear version, with `σ` being `ring_hom.id R`, is denoted by `M ≃ₗ[R] M₂`, and the star-linear version (with `σ` being `star_ring_end`) is denoted by `M ≃ₗ⋆[R] M₂`. ## Implementation notes To ensure that composition works smoothly for semilinear equivalences, we use the typeclasses `ring_hom_comp_triple`, `ring_hom_inv_pair` and `ring_hom_surjective` from `algebra/ring/comp_typeclasses`. The group structure on automorphisms, `linear_equiv.automorphism_group`, is provided elsewhere. ## TODO * Parts of this file have not yet been generalized to semilinear maps ## Tags linear equiv, linear equivalences, linear isomorphism, linear isomorphic -/ open function open_locale big_operators universes u u' v w x y z variables {R : Type*} {R₁ : Type*} {R₂ : Type*} {R₃ : Type*} variables {k : Type*} {S : Type*} {M : Type*} {M₁ : Type*} {M₂ : Type*} {M₃ : Type*} variables {N₁ : Type*} {N₂ : Type*} {N₃ : Type*} {N₄ : Type*} {ι : Type*} section set_option old_structure_cmd true /-- A linear equivalence is an invertible linear map. -/ @[nolint has_nonempty_instance] structure linear_equiv {R : Type*} {S : Type*} [semiring R] [semiring S] (σ : R →+* S) {σ' : S →+* R} [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] (M : Type*) (M₂ : Type*) [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module S M₂] extends linear_map σ M M₂, M ≃+ M₂ attribute [nolint doc_blame] linear_equiv.to_linear_map attribute [nolint doc_blame] linear_equiv.to_add_equiv notation M ` ≃ₛₗ[`:50 σ `] ` M₂ := linear_equiv σ M M₂ notation M ` ≃ₗ[`:50 R `] ` M₂ := linear_equiv (ring_hom.id R) M M₂ notation M ` ≃ₗ⋆[`:50 R `] ` M₂ := linear_equiv (star_ring_end R) M M₂ /-- `semilinear_equiv_class F σ M M₂` asserts `F` is a type of bundled `σ`-semilinear equivs `M → M₂`. See also `linear_equiv_class F R M M₂` for the case where `σ` is the identity map on `R`. A map `f` between an `R`-module and an `S`-module over a ring homomorphism `σ : R →+* S` is semilinear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = (σ c) • f x`. -/ class semilinear_equiv_class (F : Type*) {R S : out_param Type*} [semiring R] [semiring S] (σ : out_param $ R →+* S) {σ' : out_param $ S →+* R} [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] (M M₂ : out_param Type*) [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module S M₂] extends add_equiv_class F M M₂ := (map_smulₛₗ : ∀ (f : F) (r : R) (x : M), f (r • x) = (σ r) • f x) -- `R, S, σ, σ'` become metavars, but it's OK since they are outparams. attribute [nolint dangerous_instance] semilinear_equiv_class.to_add_equiv_class /-- `linear_equiv_class F R M M₂` asserts `F` is a type of bundled `R`-linear equivs `M → M₂`. This is an abbreviation for `semilinear_equiv_class F (ring_hom.id R) M M₂`. -/ abbreviation linear_equiv_class (F : Type*) (R M M₂ : out_param Type*) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] := semilinear_equiv_class F (ring_hom.id R) M M₂ end namespace semilinear_equiv_class variables (F : Type*) [semiring R] [semiring S] variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] variables [module R M] [module S M₂] {σ : R →+* S} {σ' : S →+* R} -- `σ'` becomes a metavariable, but it's OK since it's an outparam @[priority 100, nolint dangerous_instance] instance [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] [s : semilinear_equiv_class F σ M M₂] : semilinear_map_class F σ M M₂ := { coe := (coe : F → M → M₂), coe_injective' := @fun_like.coe_injective F _ _ _, ..s } end semilinear_equiv_class namespace linear_equiv section add_comm_monoid variables {M₄ : Type*} variables [semiring R] [semiring S] section variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] variables [module R M] [module S M₂] {σ : R →+* S} {σ' : S →+* R} variables [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] include R include σ' instance : has_coe (M ≃ₛₗ[σ] M₂) (M →ₛₗ[σ] M₂) := ⟨to_linear_map⟩ -- see Note [function coercion] instance : has_coe_to_fun (M ≃ₛₗ[σ] M₂) (λ _, M → M₂) := ⟨to_fun⟩ @[simp] lemma coe_mk {to_fun inv_fun map_add map_smul left_inv right_inv } : ⇑(⟨to_fun, map_add, map_smul, inv_fun, left_inv, right_inv⟩ : M ≃ₛₗ[σ] M₂) = to_fun := rfl -- This exists for compatibility, previously `≃ₗ[R]` extended `≃` instead of `≃+`. @[nolint doc_blame] def to_equiv : (M ≃ₛₗ[σ] M₂) → M ≃ M₂ := λ f, f.to_add_equiv.to_equiv lemma to_equiv_injective : function.injective (to_equiv : (M ≃ₛₗ[σ] M₂) → M ≃ M₂) := λ ⟨_, _, _, _, _, _⟩ ⟨_, _, _, _, _, _⟩ h, linear_equiv.mk.inj_eq.mpr (equiv.mk.inj h) @[simp] lemma to_equiv_inj {e₁ e₂ : M ≃ₛₗ[σ] M₂} : e₁.to_equiv = e₂.to_equiv ↔ e₁ = e₂ := to_equiv_injective.eq_iff lemma to_linear_map_injective : injective (coe : (M ≃ₛₗ[σ] M₂) → (M →ₛₗ[σ] M₂)) := λ e₁ e₂ H, to_equiv_injective $ equiv.ext $ linear_map.congr_fun H @[simp, norm_cast] lemma to_linear_map_inj {e₁ e₂ : M ≃ₛₗ[σ] M₂} : (e₁ : M →ₛₗ[σ] M₂) = e₂ ↔ e₁ = e₂ := to_linear_map_injective.eq_iff instance : semilinear_equiv_class (M ≃ₛₗ[σ] M₂) σ M M₂ := { coe := linear_equiv.to_fun, inv := linear_equiv.inv_fun, coe_injective' := λ f g h₁ h₂, by { cases f, cases g, congr' }, left_inv := linear_equiv.left_inv, right_inv := linear_equiv.right_inv, map_add := map_add', map_smulₛₗ := map_smul' } lemma coe_injective : @injective (M ≃ₛₗ[σ] M₂) (M → M₂) coe_fn := fun_like.coe_injective end section variables [semiring R₁] [semiring R₂] [semiring R₃] variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] variables [add_comm_monoid M₃] [add_comm_monoid M₄] variables [add_comm_monoid N₁] [add_comm_monoid N₂] variables {module_M : module R M} {module_S_M₂ : module S M₂} {σ : R →+* S} {σ' : S →+* R} variables {re₁ : ring_hom_inv_pair σ σ'} {re₂ : ring_hom_inv_pair σ' σ} variables (e e' : M ≃ₛₗ[σ] M₂) lemma to_linear_map_eq_coe : e.to_linear_map = (e : M →ₛₗ[σ] M₂) := rfl @[simp, norm_cast] theorem coe_coe : ⇑(e : M →ₛₗ[σ] M₂) = e := rfl @[simp] lemma coe_to_equiv : ⇑e.to_equiv = e := rfl @[simp] lemma coe_to_linear_map : ⇑e.to_linear_map = e := rfl @[simp] lemma to_fun_eq_coe : e.to_fun = e := rfl section variables {e e'} @[ext] lemma ext (h : ∀ x, e x = e' x) : e = e' := fun_like.ext _ _ h lemma ext_iff : e = e' ↔ ∀ x, e x = e' x := fun_like.ext_iff protected lemma congr_arg {x x'} : x = x' → e x = e x' := fun_like.congr_arg e protected lemma congr_fun (h : e = e') (x : M) : e x = e' x := fun_like.congr_fun h x end section variables (M R) /-- The identity map is a linear equivalence. -/ @[refl] def refl [module R M] : M ≃ₗ[R] M := { .. linear_map.id, .. equiv.refl M } end @[simp] lemma refl_apply [module R M] (x : M) : refl R M x = x := rfl include module_M module_S_M₂ re₁ re₂ /-- Linear equivalences are symmetric. -/ @[symm] def symm (e : M ≃ₛₗ[σ] M₂) : M₂ ≃ₛₗ[σ'] M := { to_fun := e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv, inv_fun := e.to_equiv.symm.inv_fun, map_smul' := λ r x, by rw map_smulₛₗ, .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv, .. e.to_equiv.symm } omit module_M module_S_M₂ re₁ re₂ /-- See Note [custom simps projection] -/ def simps.symm_apply {R : Type*} {S : Type*} [semiring R] [semiring S] {σ : R →+* S} {σ' : S →+* R} [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] {M : Type*} {M₂ : Type*} [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module S M₂] (e : M ≃ₛₗ[σ] M₂) : M₂ → M := e.symm initialize_simps_projections linear_equiv (to_fun → apply, inv_fun → symm_apply) include σ' @[simp] lemma inv_fun_eq_symm : e.inv_fun = e.symm := rfl omit σ' @[simp] lemma coe_to_equiv_symm : ⇑e.to_equiv.symm = e.symm := rfl variables {module_M₁ : module R₁ M₁} {module_M₂ : module R₂ M₂} {module_M₃ : module R₃ M₃} variables {module_N₁ : module R₁ N₁} {module_N₂ : module R₁ N₂} variables {σ₁₂ : R₁ →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R₁ →+* R₃} variables {σ₂₁ : R₂ →+* R₁} {σ₃₂ : R₃ →+* R₂} {σ₃₁ : R₃ →+* R₁} variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] variables [ring_hom_comp_triple σ₃₂ σ₂₁ σ₃₁] variables {re₁₂ : ring_hom_inv_pair σ₁₂ σ₂₁} {re₂₃ : ring_hom_inv_pair σ₂₃ σ₃₂} variables [ring_hom_inv_pair σ₁₃ σ₃₁] {re₂₁ : ring_hom_inv_pair σ₂₁ σ₁₂} variables {re₃₂ : ring_hom_inv_pair σ₃₂ σ₂₃} [ring_hom_inv_pair σ₃₁ σ₁₃] variables (e₁₂ : M₁ ≃ₛₗ[σ₁₂] M₂) (e₂₃ : M₂ ≃ₛₗ[σ₂₃] M₃) include σ₃₁ /-- Linear equivalences are transitive. -/ -- Note: The linter thinks the `ring_hom_comp_triple` argument is doubled -- it is not. @[trans, nolint unused_arguments] def trans : M₁ ≃ₛₗ[σ₁₃] M₃ := { .. e₂₃.to_linear_map.comp e₁₂.to_linear_map, .. e₁₂.to_equiv.trans e₂₃.to_equiv } omit σ₃₁ infixl ` ≪≫ₗ `:80 := @linear_equiv.trans _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ (ring_hom.id _) (ring_hom.id _) (ring_hom.id _) (ring_hom.id _) (ring_hom.id _) (ring_hom.id _) ring_hom_comp_triple.ids ring_hom_comp_triple.ids ring_hom_inv_pair.ids ring_hom_inv_pair.ids ring_hom_inv_pair.ids ring_hom_inv_pair.ids ring_hom_inv_pair.ids ring_hom_inv_pair.ids variables {e₁₂} {e₂₃} @[simp] lemma coe_to_add_equiv : ⇑(e.to_add_equiv) = e := rfl /-- The two paths coercion can take to an `add_monoid_hom` are equivalent -/ lemma to_add_monoid_hom_commutes : e.to_linear_map.to_add_monoid_hom = e.to_add_equiv.to_add_monoid_hom := rfl include σ₃₁ @[simp] theorem trans_apply (c : M₁) : (e₁₂.trans e₂₃ : M₁ ≃ₛₗ[σ₁₃] M₃) c = e₂₃ (e₁₂ c) := rfl theorem coe_trans : (e₁₂.trans e₂₃ : M₁ →ₛₗ[σ₁₃] M₃) = (e₂₃ : M₂ →ₛₗ[σ₂₃] M₃).comp (e₁₂ : M₁ →ₛₗ[σ₁₂] M₂) := rfl omit σ₃₁ include σ' @[simp] theorem apply_symm_apply (c : M₂) : e (e.symm c) = c := e.right_inv c @[simp] theorem symm_apply_apply (b : M) : e.symm (e b) = b := e.left_inv b omit σ' include σ₃₁ σ₂₁ σ₃₂ @[simp] lemma trans_symm : (e₁₂.trans e₂₃ : M₁ ≃ₛₗ[σ₁₃] M₃).symm = e₂₃.symm.trans e₁₂.symm := rfl lemma symm_trans_apply (c : M₃) : (e₁₂.trans e₂₃ : M₁ ≃ₛₗ[σ₁₃] M₃).symm c = e₁₂.symm (e₂₃.symm c) := rfl omit σ₃₁ σ₂₁ σ₃₂ @[simp] lemma trans_refl : e.trans (refl S M₂) = e := to_equiv_injective e.to_equiv.trans_refl @[simp] lemma refl_trans : (refl R M).trans e = e := to_equiv_injective e.to_equiv.refl_trans include σ' lemma symm_apply_eq {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq lemma eq_symm_apply {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply omit σ' lemma eq_comp_symm {α : Type*} (f : M₂ → α) (g : M₁ → α) : f = g ∘ e₁₂.symm ↔ f ∘ e₁₂ = g := e₁₂.to_equiv.eq_comp_symm f g lemma comp_symm_eq {α : Type*} (f : M₂ → α) (g : M₁ → α) : g ∘ e₁₂.symm = f ↔ g = f ∘ e₁₂ := e₁₂.to_equiv.comp_symm_eq f g lemma eq_symm_comp {α : Type*} (f : α → M₁) (g : α → M₂) : f = e₁₂.symm ∘ g ↔ e₁₂ ∘ f = g := e₁₂.to_equiv.eq_symm_comp f g lemma symm_comp_eq {α : Type*} (f : α → M₁) (g : α → M₂) : e₁₂.symm ∘ g = f ↔ g = e₁₂ ∘ f := e₁₂.to_equiv.symm_comp_eq f g variables [ring_hom_comp_triple σ₂₁ σ₁₃ σ₂₃] [ring_hom_comp_triple σ₃₁ σ₁₂ σ₃₂] include module_M₃ lemma eq_comp_to_linear_map_symm (f : M₂ →ₛₗ[σ₂₃] M₃) (g : M₁ →ₛₗ[σ₁₃] M₃) : f = g.comp e₁₂.symm.to_linear_map ↔ f.comp e₁₂.to_linear_map = g := begin split; intro H; ext, { simp [H, e₁₂.to_equiv.eq_comp_symm f g] }, { simp [←H, ←e₁₂.to_equiv.eq_comp_symm f g] } end lemma comp_to_linear_map_symm_eq (f : M₂ →ₛₗ[σ₂₃] M₃) (g : M₁ →ₛₗ[σ₁₃] M₃) : g.comp e₁₂.symm.to_linear_map = f ↔ g = f.comp e₁₂.to_linear_map := begin split; intro H; ext, { simp [←H, ←e₁₂.to_equiv.comp_symm_eq f g] }, { simp [H, e₁₂.to_equiv.comp_symm_eq f g] } end lemma eq_to_linear_map_symm_comp (f : M₃ →ₛₗ[σ₃₁] M₁) (g : M₃ →ₛₗ[σ₃₂] M₂) : f = e₁₂.symm.to_linear_map.comp g ↔ e₁₂.to_linear_map.comp f = g := begin split; intro H; ext, { simp [H, e₁₂.to_equiv.eq_symm_comp f g] }, { simp [←H, ←e₁₂.to_equiv.eq_symm_comp f g] } end lemma to_linear_map_symm_comp_eq (f : M₃ →ₛₗ[σ₃₁] M₁) (g : M₃ →ₛₗ[σ₃₂] M₂) : e₁₂.symm.to_linear_map.comp g = f ↔ g = e₁₂.to_linear_map.comp f := begin split; intro H; ext, { simp [←H, ←e₁₂.to_equiv.symm_comp_eq f g] }, { simp [H, e₁₂.to_equiv.symm_comp_eq f g] } end omit module_M₃ @[simp] lemma refl_symm [module R M] : (refl R M).symm = linear_equiv.refl R M := rfl include re₁₂ re₂₁ module_M₁ module_M₂ @[simp] lemma self_trans_symm (f : M₁ ≃ₛₗ[σ₁₂] M₂) : f.trans f.symm = linear_equiv.refl R₁ M₁ := by { ext x, simp } @[simp] lemma symm_trans_self (f : M₁ ≃ₛₗ[σ₁₂] M₂) : f.symm.trans f = linear_equiv.refl R₂ M₂ := by { ext x, simp } omit re₁₂ re₂₁ module_M₁ module_M₂ @[simp, norm_cast] lemma refl_to_linear_map [module R M] : (linear_equiv.refl R M : M →ₗ[R] M) = linear_map.id := rfl @[simp, norm_cast] lemma comp_coe [module R M] [module R M₂] [module R M₃] (f : M ≃ₗ[R] M₂) (f' : M₂ ≃ₗ[R] M₃) : (f' : M₂ →ₗ[R] M₃).comp (f : M →ₗ[R] M₂) = (f.trans f' : M ≃ₗ[R] M₃) := rfl @[simp] lemma mk_coe (h₁ h₂ f h₃ h₄) : (linear_equiv.mk e h₁ h₂ f h₃ h₄ : M ≃ₛₗ[σ] M₂) = e := ext $ λ _, rfl protected theorem map_add (a b : M) : e (a + b) = e a + e b := map_add e a b protected theorem map_zero : e 0 = 0 := map_zero e -- TODO: `simp` isn't picking up `map_smulₛₗ` for `linear_equiv`s without specifying `map_smulₛₗ f` @[simp] protected theorem map_smulₛₗ (c : R) (x : M) : e (c • x) = (σ c) • e x := e.map_smul' c x include module_N₁ module_N₂ theorem map_smul (e : N₁ ≃ₗ[R₁] N₂) (c : R₁) (x : N₁) : e (c • x) = c • e x := map_smulₛₗ e c x omit module_N₁ module_N₂ @[simp] lemma map_sum {s : finset ι} (u : ι → M) : e (∑ i in s, u i) = ∑ i in s, e (u i) := e.to_linear_map.map_sum @[simp] theorem map_eq_zero_iff {x : M} : e x = 0 ↔ x = 0 := e.to_add_equiv.map_eq_zero_iff theorem map_ne_zero_iff {x : M} : e x ≠ 0 ↔ x ≠ 0 := e.to_add_equiv.map_ne_zero_iff include module_M module_S_M₂ re₁ re₂ @[simp] theorem symm_symm (e : M ≃ₛₗ[σ] M₂): e.symm.symm = e := by { cases e, refl } omit module_M module_S_M₂ re₁ re₂ lemma symm_bijective [module R M] [module S M₂] [ring_hom_inv_pair σ' σ] [ring_hom_inv_pair σ σ'] : function.bijective (symm : (M ≃ₛₗ[σ] M₂) → (M₂ ≃ₛₗ[σ'] M)) := equiv.bijective ⟨(symm : (M ≃ₛₗ[σ] M₂) → (M₂ ≃ₛₗ[σ'] M)), (symm : (M₂ ≃ₛₗ[σ'] M) → (M ≃ₛₗ[σ] M₂)), symm_symm, symm_symm⟩ @[simp] lemma mk_coe' (f h₁ h₂ h₃ h₄) : (linear_equiv.mk f h₁ h₂ ⇑e h₃ h₄ : M₂ ≃ₛₗ[σ'] M) = e.symm := symm_bijective.injective $ ext $ λ x, rfl @[simp] theorem symm_mk (f h₁ h₂ h₃ h₄) : (⟨e, h₁, h₂, f, h₃, h₄⟩ : M ≃ₛₗ[σ] M₂).symm = { to_fun := f, inv_fun := e, ..(⟨e, h₁, h₂, f, h₃, h₄⟩ : M ≃ₛₗ[σ] M₂).symm } := rfl @[simp] lemma coe_symm_mk [module R M] [module R M₂] {to_fun inv_fun map_add map_smul left_inv right_inv} : ⇑((⟨to_fun, map_add, map_smul, inv_fun, left_inv, right_inv⟩ : M ≃ₗ[R] M₂).symm) = inv_fun := rfl protected lemma bijective : function.bijective e := e.to_equiv.bijective protected lemma injective : function.injective e := e.to_equiv.injective protected lemma surjective : function.surjective e := e.to_equiv.surjective protected lemma image_eq_preimage (s : set M) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s protected lemma image_symm_eq_preimage (s : set M₂) : e.symm '' s = e ⁻¹' s := e.to_equiv.symm.image_eq_preimage s end /-- Interpret a `ring_equiv` `f` as an `f`-semilinear equiv. -/ @[simps] def _root_.ring_equiv.to_semilinear_equiv (f : R ≃+* S) : by haveI := ring_hom_inv_pair.of_ring_equiv f; haveI := ring_hom_inv_pair.symm (↑f : R →+* S) (f.symm : S →+* R); exact (R ≃ₛₗ[(↑f : R →+* S)] S) := by exact { to_fun := f, map_smul' := f.map_mul, .. f} variables [semiring R₁] [semiring R₂] [semiring R₃] variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] /-- An involutive linear map is a linear equivalence. -/ def of_involutive {σ σ' : R →+* R} [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] {module_M : module R M} (f : M →ₛₗ[σ] M) (hf : involutive f) : M ≃ₛₗ[σ] M := { .. f, .. hf.to_perm f } @[simp] lemma coe_of_involutive {σ σ' : R →+* R} [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] {module_M : module R M} (f : M →ₛₗ[σ] M) (hf : involutive f) : ⇑(of_involutive f hf) = f := rfl section restrict_scalars variables (R) [module R M] [module R M₂] [module S M] [module S M₂] [linear_map.compatible_smul M M₂ R S] /-- If `M` and `M₂` are both `R`-semimodules and `S`-semimodules and `R`-semimodule structures are defined by an action of `R` on `S` (formally, we have two scalar towers), then any `S`-linear equivalence from `M` to `M₂` is also an `R`-linear equivalence. See also `linear_map.restrict_scalars`. -/ @[simps] def restrict_scalars (f : M ≃ₗ[S] M₂) : M ≃ₗ[R] M₂ := { to_fun := f, inv_fun := f.symm, left_inv := f.left_inv, right_inv := f.right_inv, .. f.to_linear_map.restrict_scalars R } lemma restrict_scalars_injective : function.injective (restrict_scalars R : (M ≃ₗ[S] M₂) → (M ≃ₗ[R] M₂)) := λ f g h, ext (linear_equiv.congr_fun h : _) @[simp] lemma restrict_scalars_inj (f g : M ≃ₗ[S] M₂) : f.restrict_scalars R = g.restrict_scalars R ↔ f = g := (restrict_scalars_injective R).eq_iff end restrict_scalars section automorphisms variables [module R M] instance automorphism_group : group (M ≃ₗ[R] M) := { mul := λ f g, g.trans f, one := linear_equiv.refl R M, inv := λ f, f.symm, mul_assoc := λ f g h, rfl, mul_one := λ f, ext $ λ x, rfl, one_mul := λ f, ext $ λ x, rfl, mul_left_inv := λ f, ext $ f.left_inv } /-- Restriction from `R`-linear automorphisms of `M` to `R`-linear endomorphisms of `M`, promoted to a monoid hom. -/ @[simps] def automorphism_group.to_linear_map_monoid_hom : (M ≃ₗ[R] M) →* (M →ₗ[R] M) := { to_fun := coe, map_one' := rfl, map_mul' := λ _ _, rfl } /-- The tautological action by `M ≃ₗ[R] M` on `M`. This generalizes `function.End.apply_mul_action`. -/ instance apply_distrib_mul_action : distrib_mul_action (M ≃ₗ[R] M) M := { smul := ($), smul_zero := linear_equiv.map_zero, smul_add := linear_equiv.map_add, one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] protected lemma smul_def (f : M ≃ₗ[R] M) (a : M) : f • a = f a := rfl /-- `linear_equiv.apply_distrib_mul_action` is faithful. -/ instance apply_has_faithful_smul : has_faithful_smul (M ≃ₗ[R] M) M := ⟨λ _ _, linear_equiv.ext⟩ instance apply_smul_comm_class : smul_comm_class R (M ≃ₗ[R] M) M := { smul_comm := λ r e m, (e.map_smul r m).symm } instance apply_smul_comm_class' : smul_comm_class (M ≃ₗ[R] M) R M := { smul_comm := linear_equiv.map_smul } end automorphisms section of_subsingleton variables (M M₂) [module R M] [module R M₂] [subsingleton M] [subsingleton M₂] /-- Any two modules that are subsingletons are isomorphic. -/ @[simps] def of_subsingleton : M ≃ₗ[R] M₂ := { to_fun := λ _, 0, inv_fun := λ _, 0, left_inv := λ x, subsingleton.elim _ _, right_inv := λ x, subsingleton.elim _ _, .. (0 : M →ₗ[R] M₂)} @[simp] lemma of_subsingleton_self : of_subsingleton M M = refl R M := by { ext, simp } end of_subsingleton end add_comm_monoid end linear_equiv namespace module /-- `g : R ≃+* S` is `R`-linear when the module structure on `S` is `module.comp_hom S g` . -/ @[simps] def comp_hom.to_linear_equiv {R S : Type*} [semiring R] [semiring S] (g : R ≃+* S) : (by haveI := comp_hom S (↑g : R →+* S); exact (R ≃ₗ[R] S)) := by exact { to_fun := (g : R → S), inv_fun := (g.symm : S → R), map_smul' := g.map_mul, ..g } end module namespace distrib_mul_action variables (R M) [semiring R] [add_comm_monoid M] [module R M] variables [group S] [distrib_mul_action S M] [smul_comm_class S R M] /-- Each element of the group defines a linear equivalence. This is a stronger version of `distrib_mul_action.to_add_equiv`. -/ @[simps] def to_linear_equiv (s : S) : M ≃ₗ[R] M := { ..to_add_equiv M s, ..to_linear_map R M s } /-- Each element of the group defines a module automorphism. This is a stronger version of `distrib_mul_action.to_add_aut`. -/ @[simps] def to_module_aut : S →* M ≃ₗ[R] M := { to_fun := to_linear_equiv R M, map_one' := linear_equiv.ext $ one_smul _, map_mul' := λ a b, linear_equiv.ext $ mul_smul _ _ } end distrib_mul_action namespace add_equiv section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] variable (e : M ≃+ M₂) /-- An additive equivalence whose underlying function preserves `smul` is a linear equivalence. -/ def to_linear_equiv (h : ∀ (c : R) x, e (c • x) = c • e x) : M ≃ₗ[R] M₂ := { map_smul' := h, .. e, } @[simp] lemma coe_to_linear_equiv (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h) = e := rfl @[simp] lemma coe_to_linear_equiv_symm (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h).symm = e.symm := rfl /-- An additive equivalence between commutative additive monoids is a linear equivalence between ℕ-modules -/ def to_nat_linear_equiv : M ≃ₗ[ℕ] M₂ := e.to_linear_equiv $ λ c a, by { erw e.to_add_monoid_hom.map_nsmul, refl } @[simp] lemma coe_to_nat_linear_equiv : ⇑(e.to_nat_linear_equiv) = e := rfl @[simp] lemma to_nat_linear_equiv_to_add_equiv : e.to_nat_linear_equiv.to_add_equiv = e := by { ext, refl } @[simp] lemma _root_.linear_equiv.to_add_equiv_to_nat_linear_equiv (e : M ≃ₗ[ℕ] M₂) : e.to_add_equiv.to_nat_linear_equiv = e := fun_like.coe_injective rfl @[simp] lemma to_nat_linear_equiv_symm : (e.to_nat_linear_equiv).symm = e.symm.to_nat_linear_equiv := rfl @[simp] lemma to_nat_linear_equiv_refl : ((add_equiv.refl M).to_nat_linear_equiv) = linear_equiv.refl ℕ M := rfl @[simp] lemma to_nat_linear_equiv_trans (e₂ : M₂ ≃+ M₃) : (e.to_nat_linear_equiv).trans (e₂.to_nat_linear_equiv) = (e.trans e₂).to_nat_linear_equiv := rfl end add_comm_monoid section add_comm_group variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variable (e : M ≃+ M₂) /-- An additive equivalence between commutative additive groups is a linear equivalence between ℤ-modules -/ def to_int_linear_equiv : M ≃ₗ[ℤ] M₂ := e.to_linear_equiv $ λ c a, e.to_add_monoid_hom.map_zsmul a c @[simp] lemma coe_to_int_linear_equiv : ⇑(e.to_int_linear_equiv) = e := rfl @[simp] lemma to_int_linear_equiv_to_add_equiv : e.to_int_linear_equiv.to_add_equiv = e := by { ext, refl } @[simp] lemma _root_.linear_equiv.to_add_equiv_to_int_linear_equiv (e : M ≃ₗ[ℤ] M₂) : e.to_add_equiv.to_int_linear_equiv = e := fun_like.coe_injective rfl @[simp] lemma to_int_linear_equiv_symm : (e.to_int_linear_equiv).symm = e.symm.to_int_linear_equiv := rfl @[simp] lemma to_int_linear_equiv_refl : ((add_equiv.refl M).to_int_linear_equiv) = linear_equiv.refl ℤ M := rfl @[simp] lemma to_int_linear_equiv_trans (e₂ : M₂ ≃+ M₃) : (e.to_int_linear_equiv).trans (e₂.to_int_linear_equiv) = (e.trans e₂).to_int_linear_equiv := rfl end add_comm_group end add_equiv
f7bbcccb7b459bdbdeb58fc554bad417b24d6339
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/include/includer.lean
87d25e584c31a317ce451c42fe8141cd2cfc57bd
[]
no_license
AbigailCastro17/CS2102-Discrete-Math
cf296251be9418ce90206f5e66bde9163e21abf9
d741e4d2d6a9b2e0c8380e51706218b8f608cee4
refs/heads/main
1,682,891,087,358
1,621,401,341,000
1,621,401,341,000
368,749,959
0
0
null
null
null
null
UTF-8
Lean
false
false
42
lean
import .includee #check x #check bor tt ff
abeac8eefdd278a6d84d54a00fbdd2c834bad38b
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/data/finite/basic.lean
cd984fca51e8361f3cf3ecb90e29f4efc3e26e0e
[ "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
5,137
lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import data.fintype.basic /-! # Finite types In this file we prove some theorems about `finite` and provide some instances. This typeclass is a `Prop`-valued counterpart of the typeclass `fintype`. See more details in the file where `finite` is defined. ## Main definitions * `fintype.finite`, `finite.of_fintype` creates a `finite` instance from a `fintype` instance. The former lemma takes `fintype α` as an explicit argument while the latter takes it as an instance argument. * `fintype.of_finite` noncomputably creates a `fintype` instance from a `finite` instance. * `finite_or_infinite` is that every type is either `finite` or `infinite`. ## Implementation notes There is an apparent duplication of many `fintype` instances in this module, however they follow a pattern: if a `fintype` instance depends on `decidable` instances or other `fintype` instances, then we need to "lower" the instance to be a `finite` instance by removing the `decidable` instances and switching the `fintype` instances to `finite` instances. These are precisely the ones that cannot be inferred using `finite.of_fintype`. (However, when using `open_locale classical` or the `classical` tactic the instances relying only on `decidable` instances will give `finite` instances.) In the future we might consider writing automation to create these "lowered" instances. ## Tags finiteness, finite types -/ noncomputable theory open_locale classical variables {α β γ : Type*} lemma finite_or_infinite (α : Type*) : finite α ∨ infinite α := begin rw ← not_finite_iff_infinite, apply em end namespace finite @[priority 100] -- see Note [lower instance priority] instance of_subsingleton {α : Sort*} [subsingleton α] : finite α := of_injective (function.const α ()) $ function.injective_of_subsingleton _ @[nolint instance_priority] -- Higher priority for `Prop`s instance prop (p : Prop) : finite p := finite.of_subsingleton instance [finite α] [finite β] : finite (α × β) := by { haveI := fintype.of_finite α, haveI := fintype.of_finite β, apply_instance } instance {α β : Sort*} [finite α] [finite β] : finite (pprod α β) := of_equiv _ equiv.pprod_equiv_prod_plift.symm lemma prod_left (β) [finite (α × β)] [nonempty β] : finite α := of_surjective (prod.fst : α × β → α) prod.fst_surjective lemma prod_right (α) [finite (α × β)] [nonempty α] : finite β := of_surjective (prod.snd : α × β → β) prod.snd_surjective instance [finite α] [finite β] : finite (α ⊕ β) := by { haveI := fintype.of_finite α, haveI := fintype.of_finite β, apply_instance } lemma sum_left (β) [finite (α ⊕ β)] : finite α := of_injective (sum.inl : α → α ⊕ β) sum.inl_injective lemma sum_right (α) [finite (α ⊕ β)] : finite β := of_injective (sum.inr : β → α ⊕ β) sum.inr_injective instance {β : α → Type*} [finite α] [Π a, finite (β a)] : finite (Σ a, β a) := by { letI := fintype.of_finite α, letI := λ a, fintype.of_finite (β a), apply_instance } instance {ι : Sort*} {π : ι → Sort*} [finite ι] [Π i, finite (π i)] : finite (Σ' i, π i) := of_equiv _ (equiv.psigma_equiv_sigma_plift π).symm instance [finite α] : finite (set α) := by { casesI nonempty_fintype α, apply_instance } end finite /-- This instance also provides `[finite s]` for `s : set α`. -/ instance subtype.finite {α : Sort*} [finite α] {p : α → Prop} : finite {x // p x} := finite.of_injective coe subtype.coe_injective instance pi.finite {α : Sort*} {β : α → Sort*} [finite α] [∀ a, finite (β a)] : finite (Π a, β a) := begin haveI := fintype.of_finite (plift α), haveI := λ a, fintype.of_finite (plift (β a)), exact finite.of_equiv (Π (a : plift α), plift (β (equiv.plift a))) (equiv.Pi_congr equiv.plift (λ _, equiv.plift)), end instance vector.finite {α : Type*} [finite α] {n : ℕ} : finite (vector α n) := by { haveI := fintype.of_finite α, apply_instance } instance quot.finite {α : Sort*} [finite α] (r : α → α → Prop) : finite (quot r) := finite.of_surjective _ (surjective_quot_mk r) instance quotient.finite {α : Sort*} [finite α] (s : setoid α) : finite (quotient s) := quot.finite _ instance function.embedding.finite {α β : Sort*} [finite β] : finite (α ↪ β) := begin casesI is_empty_or_nonempty (α ↪ β) with _ h, { apply_instance, }, { refine h.elim (λ f, _), haveI : finite α := finite.of_injective _ f.injective, exact finite.of_injective _ fun_like.coe_injective }, end instance equiv.finite_right {α β : Sort*} [finite β] : finite (α ≃ β) := finite.of_injective equiv.to_embedding $ λ e₁ e₂ h, equiv.ext $ by convert fun_like.congr_fun h instance equiv.finite_left {α β : Sort*} [finite α] : finite (α ≃ β) := finite.of_equiv _ ⟨equiv.symm, equiv.symm, equiv.symm_symm, equiv.symm_symm⟩ instance [finite α] {n : ℕ} : finite (sym α n) := by { haveI := fintype.of_finite α, apply_instance }
7454fbf44f322b92b7ed505ad833130e6237478c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/probability/independence/basic.lean
7223f9b23c01e1217b282b34cafc08b32763eb6c
[ "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
45,062
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.constructions.pi /-! # Independence of sets of sets and measure spaces (σ-algebras) > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. * A family of sets of sets `π : ι → set (set Ω)` is independent with respect to a measure `μ` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ π i_1, ..., f i_n ∈ π i_n`, `μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `. It will be used for families of π-systems. * A family of measurable space structures (i.e. of σ-algebras) is independent with respect to a measure `μ` (typically defined on a finer σ-algebra) if the family of sets of measurable sets they define is independent. I.e., `m : ι → measurable_space Ω` is independent with respect to a measure `μ` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ m i_1, ..., f i_n ∈ m i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i)`. * Independence of sets (or events in probabilistic parlance) is defined as independence of the measurable space structures they generate: a set `s` generates the measurable space structure with measurable sets `∅, s, sᶜ, univ`. * Independence of functions (or random variables) is also defined as independence of the measurable space structures they generate: a function `f` for which we have a measurable space `m` on the codomain generates `measurable_space.comap f m`. ## Main statements * `Indep_sets.Indep`: if π-systems are independent as sets of sets, then the measurable space structures they generate are independent. * `indep_sets.indep`: variant with two π-systems. ## Implementation notes We provide one main definition of independence: * `Indep_sets`: independence of a family of sets of sets `pi : ι → set (set Ω)`. Three other independence notions are defined using `Indep_sets`: * `Indep`: independence of a family of measurable space structures `m : ι → measurable_space Ω`, * `Indep_set`: independence of a family of sets `s : ι → set Ω`, * `Indep_fun`: independence of a family of functions. For measurable spaces `m : Π (i : ι), measurable_space (β i)`, we consider functions `f : Π (i : ι), Ω → β i`. Additionally, we provide four corresponding statements for two measurable space structures (resp. sets of sets, sets, functions) instead of a family. These properties are denoted by the same names as for a family, but without a capital letter, for example `indep_fun` is the version of `Indep_fun` for two functions. The definition of independence for `Indep_sets` uses finite sets (`finset`). An alternative and equivalent way of defining independence would have been to use countable sets. TODO: prove that equivalence. Most of the definitions and lemma in this file list all variables instead of using the `variables` keyword at the beginning of a section, for example `lemma indep.symm {Ω} {m₁ m₂ : measurable_space Ω} [measurable_space Ω] {μ : measure Ω} ...` . This is intentional, to be able to control the order of the `measurable_space` variables. Indeed when defining `μ` in the example above, the measurable space used is the last one defined, here `[measurable_space Ω]`, and not `m₁` or `m₂`. ## References * Williams, David. Probability with martingales. Cambridge university press, 1991. Part A, Chapter 4. -/ open measure_theory measurable_space open_locale big_operators measure_theory ennreal namespace probability_theory variables {Ω ι : Type*} section definitions /-- A family of sets of sets `π : ι → set (set Ω)` is independent with respect to a measure `μ` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ π i_1, ..., f i_n ∈ π i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `. It will be used for families of pi_systems. -/ def Indep_sets [measurable_space Ω] (π : ι → set (set Ω)) (μ : measure Ω . volume_tac) : Prop := ∀ (s : finset ι) {f : ι → set Ω} (H : ∀ i, i ∈ s → f i ∈ π i), μ (⋂ i ∈ s, f i) = ∏ i in s, μ (f i) /-- Two sets of sets `s₁, s₂` are independent with respect to a measure `μ` if for any sets `t₁ ∈ p₁, t₂ ∈ s₂`, then `μ (t₁ ∩ t₂) = μ (t₁) * μ (t₂)` -/ def indep_sets [measurable_space Ω] (s1 s2 : set (set Ω)) (μ : measure Ω . volume_tac) : Prop := ∀ t1 t2 : set Ω, t1 ∈ s1 → t2 ∈ s2 → μ (t1 ∩ t2) = μ t1 * μ t2 /-- A family of measurable space structures (i.e. of σ-algebras) is independent with respect to a measure `μ` (typically defined on a finer σ-algebra) if the family of sets of measurable sets they define is independent. `m : ι → measurable_space Ω` is independent with respect to measure `μ` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ m i_1, ..., f i_n ∈ m i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `. -/ def Indep (m : ι → measurable_space Ω) [measurable_space Ω] (μ : measure Ω . volume_tac) : Prop := Indep_sets (λ x, {s | measurable_set[m x] s}) μ /-- Two measurable space structures (or σ-algebras) `m₁, m₂` are independent with respect to a measure `μ` (defined on a third σ-algebra) if for any sets `t₁ ∈ m₁, t₂ ∈ m₂`, `μ (t₁ ∩ t₂) = μ (t₁) * μ (t₂)` -/ def indep (m₁ m₂ : measurable_space Ω) [measurable_space Ω] (μ : measure Ω . volume_tac) : Prop := indep_sets {s | measurable_set[m₁] s} {s | measurable_set[m₂] s} μ /-- A family of sets is independent if the family of measurable space structures they generate is independent. For a set `s`, the generated measurable space has measurable sets `∅, s, sᶜ, univ`. -/ def Indep_set [measurable_space Ω] (s : ι → set Ω) (μ : measure Ω . volume_tac) : Prop := Indep (λ i, generate_from {s i}) μ /-- Two sets are independent if the two measurable space structures they generate are independent. For a set `s`, the generated measurable space structure has measurable sets `∅, s, sᶜ, univ`. -/ def indep_set [measurable_space Ω] (s t : set Ω) (μ : measure Ω . volume_tac) : Prop := indep (generate_from {s}) (generate_from {t}) μ /-- A family of functions defined on the same space `Ω` and taking values in possibly different spaces, each with a measurable space structure, is independent if the family of measurable space structures they generate on `Ω` is independent. For a function `g` with codomain having measurable space structure `m`, the generated measurable space structure is `measurable_space.comap g m`. -/ def Indep_fun [measurable_space Ω] {β : ι → Type*} (m : Π (x : ι), measurable_space (β x)) (f : Π (x : ι), Ω → β x) (μ : measure Ω . volume_tac) : Prop := Indep (λ x, measurable_space.comap (f x) (m x)) μ /-- Two functions are independent if the two measurable space structures they generate are independent. For a function `f` with codomain having measurable space structure `m`, the generated measurable space structure is `measurable_space.comap f m`. -/ def indep_fun {β γ} [measurable_space Ω] [mβ : measurable_space β] [mγ : measurable_space γ] (f : Ω → β) (g : Ω → γ) (μ : measure Ω . volume_tac) : Prop := indep (measurable_space.comap f mβ) (measurable_space.comap g mγ) μ end definitions section indep @[symm] lemma indep_sets.symm {s₁ s₂ : set (set Ω)} [measurable_space Ω] {μ : measure Ω} (h : indep_sets s₁ s₂ μ) : indep_sets s₂ s₁ μ := by { intros t1 t2 ht1 ht2, rw [set.inter_comm, mul_comm], exact h t2 t1 ht2 ht1, } @[symm] lemma indep.symm {m₁ m₂ : measurable_space Ω} [measurable_space Ω] {μ : measure Ω} (h : indep m₁ m₂ μ) : indep m₂ m₁ μ := indep_sets.symm h lemma indep_bot_right (m' : measurable_space Ω) {m : measurable_space Ω} {μ : measure Ω} [is_probability_measure μ] : indep m' ⊥ μ := begin intros s t hs ht, rw [set.mem_set_of_eq, measurable_space.measurable_set_bot_iff] at ht, cases ht, { rw [ht, set.inter_empty, measure_empty, mul_zero], }, { rw [ht, set.inter_univ, measure_univ, mul_one], }, end lemma indep_bot_left (m' : measurable_space Ω) {m : measurable_space Ω} {μ : measure Ω} [is_probability_measure μ] : indep ⊥ m' μ := (indep_bot_right m').symm lemma indep_set_empty_right {m : measurable_space Ω} {μ : measure Ω} [is_probability_measure μ] (s : set Ω) : indep_set s ∅ μ := by { simp only [indep_set, generate_from_singleton_empty], exact indep_bot_right _, } lemma indep_set_empty_left {m : measurable_space Ω} {μ : measure Ω} [is_probability_measure μ] (s : set Ω) : indep_set ∅ s μ := (indep_set_empty_right s).symm lemma indep_sets_of_indep_sets_of_le_left {s₁ s₂ s₃: set (set Ω)} [measurable_space Ω] {μ : measure Ω} (h_indep : indep_sets s₁ s₂ μ) (h31 : s₃ ⊆ s₁) : indep_sets s₃ s₂ μ := λ t1 t2 ht1 ht2, h_indep t1 t2 (set.mem_of_subset_of_mem h31 ht1) ht2 lemma indep_sets_of_indep_sets_of_le_right {s₁ s₂ s₃: set (set Ω)} [measurable_space Ω] {μ : measure Ω} (h_indep : indep_sets s₁ s₂ μ) (h32 : s₃ ⊆ s₂) : indep_sets s₁ s₃ μ := λ t1 t2 ht1 ht2, h_indep t1 t2 ht1 (set.mem_of_subset_of_mem h32 ht2) lemma indep_of_indep_of_le_left {m₁ m₂ m₃: measurable_space Ω} [measurable_space Ω] {μ : measure Ω} (h_indep : indep m₁ m₂ μ) (h31 : m₃ ≤ m₁) : indep m₃ m₂ μ := λ t1 t2 ht1 ht2, h_indep t1 t2 (h31 _ ht1) ht2 lemma indep_of_indep_of_le_right {m₁ m₂ m₃: measurable_space Ω} [measurable_space Ω] {μ : measure Ω} (h_indep : indep m₁ m₂ μ) (h32 : m₃ ≤ m₂) : indep m₁ m₃ μ := λ t1 t2 ht1 ht2, h_indep t1 t2 ht1 (h32 _ ht2) lemma indep_sets.union [measurable_space Ω] {s₁ s₂ s' : set (set Ω)} {μ : measure Ω} (h₁ : indep_sets s₁ s' μ) (h₂ : indep_sets s₂ s' μ) : indep_sets (s₁ ∪ s₂) s' μ := begin intros t1 t2 ht1 ht2, cases (set.mem_union _ _ _).mp ht1 with ht1₁ ht1₂, { exact h₁ t1 t2 ht1₁ ht2, }, { exact h₂ t1 t2 ht1₂ ht2, }, end @[simp] lemma indep_sets.union_iff [measurable_space Ω] {s₁ s₂ s' : set (set Ω)} {μ : measure Ω} : indep_sets (s₁ ∪ s₂) s' μ ↔ indep_sets s₁ s' μ ∧ indep_sets s₂ s' μ := ⟨λ h, ⟨indep_sets_of_indep_sets_of_le_left h (set.subset_union_left s₁ s₂), indep_sets_of_indep_sets_of_le_left h (set.subset_union_right s₁ s₂)⟩, λ h, indep_sets.union h.left h.right⟩ lemma indep_sets.Union [measurable_space Ω] {s : ι → set (set Ω)} {s' : set (set Ω)} {μ : measure Ω} (hyp : ∀ n, indep_sets (s n) s' μ) : indep_sets (⋃ n, s n) s' μ := begin intros t1 t2 ht1 ht2, rw set.mem_Union at ht1, cases ht1 with n ht1, exact hyp n t1 t2 ht1 ht2, end lemma indep_sets.bUnion [measurable_space Ω] {s : ι → set (set Ω)} {s' : set (set Ω)} {μ : measure Ω} {u : set ι} (hyp : ∀ n ∈ u, indep_sets (s n) s' μ) : indep_sets (⋃ n ∈ u, s n) s' μ := begin intros t1 t2 ht1 ht2, simp_rw set.mem_Union at ht1, rcases ht1 with ⟨n, hpn, ht1⟩, exact hyp n hpn t1 t2 ht1 ht2, end lemma indep_sets.inter [measurable_space Ω] {s₁ s' : set (set Ω)} (s₂ : set (set Ω)) {μ : measure Ω} (h₁ : indep_sets s₁ s' μ) : indep_sets (s₁ ∩ s₂) s' μ := λ t1 t2 ht1 ht2, h₁ t1 t2 ((set.mem_inter_iff _ _ _).mp ht1).left ht2 lemma indep_sets.Inter [measurable_space Ω] {s : ι → set (set Ω)} {s' : set (set Ω)} {μ : measure Ω} (h : ∃ n, indep_sets (s n) s' μ) : indep_sets (⋂ n, s n) s' μ := by {intros t1 t2 ht1 ht2, cases h with n h, exact h t1 t2 (set.mem_Inter.mp ht1 n) ht2 } lemma indep_sets.bInter [measurable_space Ω] {s : ι → set (set Ω)} {s' : set (set Ω)} {μ : measure Ω} {u : set ι} (h : ∃ n ∈ u, indep_sets (s n) s' μ) : indep_sets (⋂ n ∈ u, s n) s' μ := begin intros t1 t2 ht1 ht2, rcases h with ⟨n, hn, h⟩, exact h t1 t2 (set.bInter_subset_of_mem hn ht1) ht2, end lemma indep_sets_singleton_iff [measurable_space Ω] {s t : set Ω} {μ : measure Ω} : indep_sets {s} {t} μ ↔ μ (s ∩ t) = μ s * μ t := ⟨λ h, h s t rfl rfl, λ h s1 t1 hs1 ht1, by rwa [set.mem_singleton_iff.mp hs1, set.mem_singleton_iff.mp ht1]⟩ end indep /-! ### Deducing `indep` from `Indep` -/ section from_Indep_to_indep lemma Indep_sets.indep_sets {s : ι → set (set Ω)} [measurable_space Ω] {μ : measure Ω} (h_indep : Indep_sets s μ) {i j : ι} (hij : i ≠ j) : indep_sets (s i) (s j) μ := begin classical, intros t₁ t₂ ht₁ ht₂, have hf_m : ∀ (x : ι), x ∈ {i, j} → (ite (x=i) t₁ t₂) ∈ s x, { intros x hx, cases finset.mem_insert.mp hx with hx hx, { simp [hx, ht₁], }, { simp [finset.mem_singleton.mp hx, hij.symm, ht₂], }, }, have h1 : t₁ = ite (i = i) t₁ t₂, by simp only [if_true, eq_self_iff_true], have h2 : t₂ = ite (j = i) t₁ t₂, by simp only [hij.symm, if_false], have h_inter : (⋂ (t : ι) (H : t ∈ ({i, j} : finset ι)), ite (t = i) t₁ t₂) = (ite (i = i) t₁ t₂) ∩ (ite (j = i) t₁ t₂), by simp only [finset.set_bInter_singleton, finset.set_bInter_insert], have h_prod : (∏ (t : ι) in ({i, j} : finset ι), μ (ite (t = i) t₁ t₂)) = μ (ite (i = i) t₁ t₂) * μ (ite (j = i) t₁ t₂), by simp only [hij, finset.prod_singleton, finset.prod_insert, not_false_iff, finset.mem_singleton], rw h1, nth_rewrite 1 h2, nth_rewrite 3 h2, rw [← h_inter, ← h_prod, h_indep {i, j} hf_m], end lemma Indep.indep {m : ι → measurable_space Ω} [measurable_space Ω] {μ : measure Ω} (h_indep : Indep m μ) {i j : ι} (hij : i ≠ j) : indep (m i) (m j) μ := begin change indep_sets ((λ x, measurable_set[m x]) i) ((λ x, measurable_set[m x]) j) μ, exact Indep_sets.indep_sets h_indep hij, end lemma Indep_fun.indep_fun {m₀ : measurable_space Ω} {μ : measure Ω} {β : ι → Type*} {m : Π x, measurable_space (β x)} {f : Π i, Ω → β i} (hf_Indep : Indep_fun m f μ) {i j : ι} (hij : i ≠ j) : indep_fun (f i) (f j) μ := hf_Indep.indep hij end from_Indep_to_indep /-! ## π-system lemma Independence of measurable spaces is equivalent to independence of generating π-systems. -/ section from_measurable_spaces_to_sets_of_sets /-! ### Independence of measurable space structures implies independence of generating π-systems -/ lemma Indep.Indep_sets [measurable_space Ω] {μ : measure Ω} {m : ι → measurable_space Ω} {s : ι → set (set Ω)} (hms : ∀ n, m n = generate_from (s n)) (h_indep : Indep m μ) : Indep_sets s μ := λ S f hfs, h_indep S $ λ x hxS, ((hms x).symm ▸ measurable_set_generate_from (hfs x hxS) : measurable_set[m x] (f x)) lemma indep.indep_sets [measurable_space Ω] {μ : measure Ω} {s1 s2 : set (set Ω)} (h_indep : indep (generate_from s1) (generate_from s2) μ) : indep_sets s1 s2 μ := λ t1 t2 ht1 ht2, h_indep t1 t2 (measurable_set_generate_from ht1) (measurable_set_generate_from ht2) end from_measurable_spaces_to_sets_of_sets section from_pi_systems_to_measurable_spaces /-! ### Independence of generating π-systems implies independence of measurable space structures -/ private lemma indep_sets.indep_aux {m2 : measurable_space Ω} {m : measurable_space Ω} {μ : measure Ω} [is_probability_measure μ] {p1 p2 : set (set Ω)} (h2 : m2 ≤ m) (hp2 : is_pi_system p2) (hpm2 : m2 = generate_from p2) (hyp : indep_sets p1 p2 μ) {t1 t2 : set Ω} (ht1 : t1 ∈ p1) (ht2m : measurable_set[m2] t2) : μ (t1 ∩ t2) = μ t1 * μ t2 := begin let μ_inter := μ.restrict t1, let ν := (μ t1) • μ, have h_univ : μ_inter set.univ = ν set.univ, by rw [measure.restrict_apply_univ, measure.smul_apply, smul_eq_mul, measure_univ, mul_one], haveI : is_finite_measure μ_inter := @restrict.is_finite_measure Ω _ t1 μ ⟨measure_lt_top μ t1⟩, rw [set.inter_comm, ← measure.restrict_apply (h2 t2 ht2m)], refine ext_on_measurable_space_of_generate_finite m p2 (λ t ht, _) h2 hpm2 hp2 h_univ ht2m, have ht2 : measurable_set[m] t, { refine h2 _ _, rw hpm2, exact measurable_set_generate_from ht, }, rw [measure.restrict_apply ht2, measure.smul_apply, set.inter_comm], exact hyp t1 t ht1 ht, end lemma indep_sets.indep {m1 m2 : measurable_space Ω} {m : measurable_space Ω} {μ : measure Ω} [is_probability_measure μ] {p1 p2 : set (set Ω)} (h1 : m1 ≤ m) (h2 : m2 ≤ m) (hp1 : is_pi_system p1) (hp2 : is_pi_system p2) (hpm1 : m1 = generate_from p1) (hpm2 : m2 = generate_from p2) (hyp : indep_sets p1 p2 μ) : indep m1 m2 μ := begin intros t1 t2 ht1 ht2, let μ_inter := μ.restrict t2, let ν := (μ t2) • μ, have h_univ : μ_inter set.univ = ν set.univ, by rw [measure.restrict_apply_univ, measure.smul_apply, smul_eq_mul, measure_univ, mul_one], haveI : is_finite_measure μ_inter := @restrict.is_finite_measure Ω _ t2 μ ⟨measure_lt_top μ t2⟩, rw [mul_comm, ← measure.restrict_apply (h1 t1 ht1)], refine ext_on_measurable_space_of_generate_finite m p1 (λ t ht, _) h1 hpm1 hp1 h_univ ht1, have ht1 : measurable_set[m] t, { refine h1 _ _, rw hpm1, exact measurable_set_generate_from ht, }, rw [measure.restrict_apply ht1, measure.smul_apply, smul_eq_mul, mul_comm], exact indep_sets.indep_aux h2 hp2 hpm2 hyp ht ht2, end lemma indep_sets.indep' {m : measurable_space Ω} {μ : measure Ω} [is_probability_measure μ] {p1 p2 : set (set Ω)} (hp1m : ∀ s ∈ p1, measurable_set s) (hp2m : ∀ s ∈ p2, measurable_set s) (hp1 : is_pi_system p1) (hp2 : is_pi_system p2) (hyp : indep_sets p1 p2 μ) : indep (generate_from p1) (generate_from p2) μ := hyp.indep (generate_from_le hp1m) (generate_from_le hp2m) hp1 hp2 rfl rfl variables {m0 : measurable_space Ω} {μ : measure Ω} lemma indep_sets_pi_Union_Inter_of_disjoint [is_probability_measure μ] {s : ι → set (set Ω)} {S T : set ι} (h_indep : Indep_sets s μ) (hST : disjoint S T) : indep_sets (pi_Union_Inter s S) (pi_Union_Inter s T) μ := begin rintros t1 t2 ⟨p1, hp1, f1, ht1_m, ht1_eq⟩ ⟨p2, hp2, f2, ht2_m, ht2_eq⟩, classical, let g := λ i, ite (i ∈ p1) (f1 i) set.univ ∩ ite (i ∈ p2) (f2 i) set.univ, have h_P_inter : μ (t1 ∩ t2) = ∏ n in p1 ∪ p2, μ (g n), { have hgm : ∀ i ∈ p1 ∪ p2, g i ∈ s i, { intros i hi_mem_union, rw finset.mem_union at hi_mem_union, cases hi_mem_union with hi1 hi2, { have hi2 : i ∉ p2 := λ hip2, set.disjoint_left.mp hST (hp1 hi1) (hp2 hip2), simp_rw [g, if_pos hi1, if_neg hi2, set.inter_univ], exact ht1_m i hi1, }, { have hi1 : i ∉ p1 := λ hip1, set.disjoint_right.mp hST (hp2 hi2) (hp1 hip1), simp_rw [g, if_neg hi1, if_pos hi2, set.univ_inter], exact ht2_m i hi2, }, }, have h_p1_inter_p2 : ((⋂ x ∈ p1, f1 x) ∩ ⋂ x ∈ p2, f2 x) = ⋂ i ∈ p1 ∪ p2, (ite (i ∈ p1) (f1 i) set.univ ∩ ite (i ∈ p2) (f2 i) set.univ), { ext1 x, simp only [set.mem_ite_univ_right, set.mem_inter_iff, set.mem_Inter, finset.mem_union], exact ⟨λ h i _, ⟨h.1 i, h.2 i⟩, λ h, ⟨λ i hi, (h i (or.inl hi)).1 hi, λ i hi, (h i (or.inr hi)).2 hi⟩⟩, }, rw [ht1_eq, ht2_eq, h_p1_inter_p2, ← h_indep _ hgm], }, have h_μg : ∀ n, μ (g n) = (ite (n ∈ p1) (μ (f1 n)) 1) * (ite (n ∈ p2) (μ (f2 n)) 1), { intro n, simp_rw g, split_ifs, { exact absurd rfl (set.disjoint_iff_forall_ne.mp hST _ (hp1 h) _ (hp2 h_1)), }, all_goals { simp only [measure_univ, one_mul, mul_one, set.inter_univ, set.univ_inter], }, }, simp_rw [h_P_inter, h_μg, finset.prod_mul_distrib, finset.prod_ite_mem (p1 ∪ p2) p1 (λ x, μ (f1 x)), finset.union_inter_cancel_left, finset.prod_ite_mem (p1 ∪ p2) p2 (λ x, μ (f2 x)), finset.union_inter_cancel_right, ht1_eq, ← h_indep p1 ht1_m, ht2_eq, ← h_indep p2 ht2_m], end lemma Indep_set.indep_generate_from_of_disjoint [is_probability_measure μ] {s : ι → set Ω} (hsm : ∀ n, measurable_set (s n)) (hs : Indep_set s μ) (S T : set ι) (hST : disjoint S T) : indep (generate_from {t | ∃ n ∈ S, s n = t}) (generate_from {t | ∃ k ∈ T, s k = t}) μ := begin rw [← generate_from_pi_Union_Inter_singleton_left, ← generate_from_pi_Union_Inter_singleton_left], refine indep_sets.indep' (λ t ht, generate_from_pi_Union_Inter_le _ _ _ _ (measurable_set_generate_from ht)) (λ t ht, generate_from_pi_Union_Inter_le _ _ _ _ (measurable_set_generate_from ht)) _ _ _, { exact λ k, generate_from_le $ λ t ht, (set.mem_singleton_iff.1 ht).symm ▸ hsm k, }, { exact λ k, generate_from_le $ λ t ht, (set.mem_singleton_iff.1 ht).symm ▸ hsm k, }, { exact is_pi_system_pi_Union_Inter _ (λ k, is_pi_system.singleton _) _, }, { exact is_pi_system_pi_Union_Inter _ (λ k, is_pi_system.singleton _) _, }, { classical, exact indep_sets_pi_Union_Inter_of_disjoint (Indep.Indep_sets (λ n, rfl) hs) hST, }, end lemma indep_supr_of_disjoint [is_probability_measure μ] {m : ι → measurable_space Ω} (h_le : ∀ i, m i ≤ m0) (h_indep : Indep m μ) {S T : set ι} (hST : disjoint S T) : indep (⨆ i ∈ S, m i) (⨆ i ∈ T, m i) μ := begin refine indep_sets.indep (supr₂_le (λ i _, h_le i)) (supr₂_le (λ i _, h_le i)) _ _ (generate_from_pi_Union_Inter_measurable_set m S).symm (generate_from_pi_Union_Inter_measurable_set m T).symm _, { exact is_pi_system_pi_Union_Inter _ (λ n, @is_pi_system_measurable_set Ω (m n)) _, }, { exact is_pi_system_pi_Union_Inter _ (λ n, @is_pi_system_measurable_set Ω (m n)) _ , }, { classical, exact indep_sets_pi_Union_Inter_of_disjoint h_indep hST, }, end lemma indep_supr_of_directed_le {Ω} {m : ι → measurable_space Ω} {m' m0 : measurable_space Ω} {μ : measure Ω} [is_probability_measure μ] (h_indep : ∀ i, indep (m i) m' μ) (h_le : ∀ i, m i ≤ m0) (h_le' : m' ≤ m0) (hm : directed (≤) m) : indep (⨆ i, m i) m' μ := begin let p : ι → set (set Ω) := λ n, {t | measurable_set[m n] t}, have hp : ∀ n, is_pi_system (p n) := λ n, @is_pi_system_measurable_set Ω (m n), have h_gen_n : ∀ n, m n = generate_from (p n), from λ n, (@generate_from_measurable_set Ω (m n)).symm, have hp_supr_pi : is_pi_system (⋃ n, p n) := is_pi_system_Union_of_directed_le p hp hm, let p' := {t : set Ω | measurable_set[m'] t}, have hp'_pi : is_pi_system p' := @is_pi_system_measurable_set Ω m', have h_gen' : m' = generate_from p' := (@generate_from_measurable_set Ω m').symm, -- the π-systems defined are independent have h_pi_system_indep : indep_sets (⋃ n, p n) p' μ, { refine indep_sets.Union _, simp_rw [h_gen_n, h_gen'] at h_indep, exact λ n, (h_indep n).indep_sets, }, -- now go from π-systems to σ-algebras refine indep_sets.indep (supr_le h_le) h_le' hp_supr_pi hp'_pi _ h_gen' h_pi_system_indep, exact (generate_from_Union_measurable_set _).symm, end lemma Indep_set.indep_generate_from_lt [preorder ι] [is_probability_measure μ] {s : ι → set Ω} (hsm : ∀ n, measurable_set (s n)) (hs : Indep_set s μ) (i : ι) : indep (generate_from {s i}) (generate_from {t | ∃ j < i, s j = t}) μ := begin convert hs.indep_generate_from_of_disjoint hsm {i} {j | j < i} (set.disjoint_singleton_left.mpr (lt_irrefl _)), simp only [set.mem_singleton_iff, exists_prop, exists_eq_left, set.set_of_eq_eq_singleton'], end lemma Indep_set.indep_generate_from_le [linear_order ι] [is_probability_measure μ] {s : ι → set Ω} (hsm : ∀ n, measurable_set (s n)) (hs : Indep_set s μ) (i : ι) {k : ι} (hk : i < k) : indep (generate_from {s k}) (generate_from {t | ∃ j ≤ i, s j = t}) μ := begin convert hs.indep_generate_from_of_disjoint hsm {k} {j | j ≤ i} (set.disjoint_singleton_left.mpr hk.not_le), simp only [set.mem_singleton_iff, exists_prop, exists_eq_left, set.set_of_eq_eq_singleton'], end lemma Indep_set.indep_generate_from_le_nat [is_probability_measure μ] {s : ℕ → set Ω} (hsm : ∀ n, measurable_set (s n)) (hs : Indep_set s μ) (n : ℕ): indep (generate_from {s (n + 1)}) (generate_from {t | ∃ k ≤ n, s k = t}) μ := hs.indep_generate_from_le hsm _ n.lt_succ_self lemma indep_supr_of_monotone [semilattice_sup ι] {Ω} {m : ι → measurable_space Ω} {m' m0 : measurable_space Ω} {μ : measure Ω} [is_probability_measure μ] (h_indep : ∀ i, indep (m i) m' μ) (h_le : ∀ i, m i ≤ m0) (h_le' : m' ≤ m0) (hm : monotone m) : indep (⨆ i, m i) m' μ := indep_supr_of_directed_le h_indep h_le h_le' (monotone.directed_le hm) lemma indep_supr_of_antitone [semilattice_inf ι] {Ω} {m : ι → measurable_space Ω} {m' m0 : measurable_space Ω} {μ : measure Ω} [is_probability_measure μ] (h_indep : ∀ i, indep (m i) m' μ) (h_le : ∀ i, m i ≤ m0) (h_le' : m' ≤ m0) (hm : antitone m) : indep (⨆ i, m i) m' μ := indep_supr_of_directed_le h_indep h_le h_le' (directed_of_inf hm) lemma Indep_sets.pi_Union_Inter_of_not_mem {π : ι → set (set Ω)} {a : ι} {S : finset ι} (hp_ind : Indep_sets π μ) (haS : a ∉ S) : indep_sets (pi_Union_Inter π S) (π a) μ := begin rintros t1 t2 ⟨s, hs_mem, ft1, hft1_mem, ht1_eq⟩ ht2_mem_pia, rw [finset.coe_subset] at hs_mem, classical, let f := λ n, ite (n = a) t2 (ite (n ∈ s) (ft1 n) set.univ), have h_f_mem : ∀ n ∈ insert a s, f n ∈ π n, { intros n hn_mem_insert, simp_rw f, cases (finset.mem_insert.mp hn_mem_insert) with hn_mem hn_mem, { simp [hn_mem, ht2_mem_pia], }, { have hn_ne_a : n ≠ a, by { rintro rfl, exact haS (hs_mem hn_mem), }, simp [hn_ne_a, hn_mem, hft1_mem n hn_mem], }, }, have h_f_mem_pi : ∀ n ∈ s, f n ∈ π n, from λ x hxS, h_f_mem x (by simp [hxS]), have h_t1 : t1 = ⋂ n ∈ s, f n, { suffices h_forall : ∀ n ∈ s, f n = ft1 n, { rw ht1_eq, congr' with n x, congr' with hns y, simp only [(h_forall n hns).symm], }, intros n hnS, have hn_ne_a : n ≠ a, by { rintro rfl, exact haS (hs_mem hnS), }, simp_rw [f, if_pos hnS, if_neg hn_ne_a], }, have h_μ_t1 : μ t1 = ∏ n in s, μ (f n), by rw [h_t1, ← hp_ind s h_f_mem_pi], have h_t2 : t2 = f a, by { simp_rw [f], simp, }, have h_μ_inter : μ (t1 ∩ t2) = ∏ n in insert a s, μ (f n), { have h_t1_inter_t2 : t1 ∩ t2 = ⋂ n ∈ insert a s, f n, by rw [h_t1, h_t2, finset.set_bInter_insert, set.inter_comm], rw [h_t1_inter_t2, ← hp_ind (insert a s) h_f_mem], }, have has : a ∉ s := λ has_mem, haS (hs_mem has_mem), rw [h_μ_inter, finset.prod_insert has, h_t2, mul_comm, h_μ_t1], end /-- The measurable space structures generated by independent pi-systems are independent. -/ theorem Indep_sets.Indep [is_probability_measure μ] (m : ι → measurable_space Ω) (h_le : ∀ i, m i ≤ m0) (π : ι → set (set Ω)) (h_pi : ∀ n, is_pi_system (π n)) (h_generate : ∀ i, m i = generate_from (π i)) (h_ind : Indep_sets π μ) : Indep m μ := begin classical, refine finset.induction _ _, { simp only [measure_univ, implies_true_iff, set.Inter_false, set.Inter_univ, finset.prod_empty, eq_self_iff_true], }, intros a S ha_notin_S h_rec f hf_m, have hf_m_S : ∀ x ∈ S, measurable_set[m x] (f x) := λ x hx, hf_m x (by simp [hx]), rw [finset.set_bInter_insert, finset.prod_insert ha_notin_S, ← h_rec hf_m_S], let p := pi_Union_Inter π S, set m_p := generate_from p with hS_eq_generate, have h_indep : indep m_p (m a) μ, { have hp : is_pi_system p := is_pi_system_pi_Union_Inter π h_pi S, have h_le' : ∀ i, generate_from (π i) ≤ m0 := λ i, (h_generate i).symm.trans_le (h_le i), have hm_p : m_p ≤ m0 := generate_from_pi_Union_Inter_le π h_le' S, exact indep_sets.indep hm_p (h_le a) hp (h_pi a) hS_eq_generate (h_generate a) (h_ind.pi_Union_Inter_of_not_mem ha_notin_S), }, refine h_indep.symm (f a) (⋂ n ∈ S, f n) (hf_m a (finset.mem_insert_self a S)) _, have h_le_p : ∀ i ∈ S, m i ≤ m_p, { intros n hn, rw [hS_eq_generate, h_generate n], exact le_generate_from_pi_Union_Inter S hn, }, have h_S_f : ∀ i ∈ S, measurable_set[m_p] (f i) := λ i hi, (h_le_p i hi) (f i) (hf_m_S i hi), exact S.measurable_set_bInter h_S_f, end end from_pi_systems_to_measurable_spaces section indep_set /-! ### Independence of measurable sets We prove the following equivalences on `indep_set`, for measurable sets `s, t`. * `indep_set s t μ ↔ μ (s ∩ t) = μ s * μ t`, * `indep_set s t μ ↔ indep_sets {s} {t} μ`. -/ variables {s t : set Ω} (S T : set (set Ω)) lemma indep_set_iff_indep_sets_singleton {m0 : measurable_space Ω} (hs_meas : measurable_set s) (ht_meas : measurable_set t) (μ : measure Ω . volume_tac) [is_probability_measure μ] : indep_set s t μ ↔ indep_sets {s} {t} μ := ⟨indep.indep_sets, λ h, indep_sets.indep (generate_from_le (λ u hu, by rwa set.mem_singleton_iff.mp hu)) (generate_from_le (λ u hu, by rwa set.mem_singleton_iff.mp hu)) (is_pi_system.singleton s) (is_pi_system.singleton t) rfl rfl h⟩ lemma indep_set_iff_measure_inter_eq_mul {m0 : measurable_space Ω} (hs_meas : measurable_set s) (ht_meas : measurable_set t) (μ : measure Ω . volume_tac) [is_probability_measure μ] : indep_set s t μ ↔ μ (s ∩ t) = μ s * μ t := (indep_set_iff_indep_sets_singleton hs_meas ht_meas μ).trans indep_sets_singleton_iff lemma indep_sets.indep_set_of_mem {m0 : measurable_space Ω} (hs : s ∈ S) (ht : t ∈ T) (hs_meas : measurable_set s) (ht_meas : measurable_set t) (μ : measure Ω . volume_tac) [is_probability_measure μ] (h_indep : indep_sets S T μ) : indep_set s t μ := (indep_set_iff_measure_inter_eq_mul hs_meas ht_meas μ).mpr (h_indep s t hs ht) lemma indep.indep_set_of_measurable_set {m₁ m₂ m0 : measurable_space Ω} {μ : measure Ω} (h_indep : indep m₁ m₂ μ) {s t : set Ω} (hs : measurable_set[m₁] s) (ht : measurable_set[m₂] t) : indep_set s t μ := begin refine λ s' t' hs' ht', h_indep s' t' _ _, { refine generate_from_induction (λ u, measurable_set[m₁] u) {s} _ _ _ _ hs', { simp only [hs, set.mem_singleton_iff, set.mem_set_of_eq, forall_eq], }, { exact @measurable_set.empty _ m₁, }, { exact λ u hu, hu.compl, }, { exact λ f hf, measurable_set.Union hf, }, }, { refine generate_from_induction (λ u, measurable_set[m₂] u) {t} _ _ _ _ ht', { simp only [ht, set.mem_singleton_iff, set.mem_set_of_eq, forall_eq], }, { exact @measurable_set.empty _ m₂, }, { exact λ u hu, hu.compl, }, { exact λ f hf, measurable_set.Union hf, },}, end lemma indep_iff_forall_indep_set (m₁ m₂ : measurable_space Ω) {m0 : measurable_space Ω} (μ : measure Ω) : indep m₁ m₂ μ ↔ ∀ s t, measurable_set[m₁] s → measurable_set[m₂] t → indep_set s t μ := ⟨λ h, λ s t hs ht, h.indep_set_of_measurable_set hs ht, λ h s t hs ht, h s t hs ht s t (measurable_set_generate_from (set.mem_singleton s)) (measurable_set_generate_from (set.mem_singleton t))⟩ end indep_set section indep_fun /-! ### Independence of random variables -/ variables {β β' γ γ' : Type*} {mΩ : measurable_space Ω} {μ : measure Ω} {f : Ω → β} {g : Ω → β'} lemma indep_fun_iff_measure_inter_preimage_eq_mul {mβ : measurable_space β} {mβ' : measurable_space β'} : indep_fun f g μ ↔ ∀ s t, measurable_set s → measurable_set t → μ (f ⁻¹' s ∩ g ⁻¹' t) = μ (f ⁻¹' s) * μ (g ⁻¹' t) := begin split; intro h, { refine λ s t hs ht, h (f ⁻¹' s) (g ⁻¹' t) ⟨s, hs, rfl⟩ ⟨t, ht, rfl⟩, }, { rintros _ _ ⟨s, hs, rfl⟩ ⟨t, ht, rfl⟩, exact h s t hs ht, }, end lemma Indep_fun_iff_measure_inter_preimage_eq_mul {ι : Type*} {β : ι → Type*} (m : Π x, measurable_space (β x)) (f : Π i, Ω → β i) : Indep_fun m f μ ↔ ∀ (S : finset ι) {sets : Π i : ι, set (β i)} (H : ∀ i, i ∈ S → measurable_set[m i] (sets i)), μ (⋂ i ∈ S, (f i) ⁻¹' (sets i)) = ∏ i in S, μ ((f i) ⁻¹' (sets i)) := begin refine ⟨λ h S sets h_meas, h _ (λ i hi_mem, ⟨sets i, h_meas i hi_mem, rfl⟩), _⟩, intros h S setsΩ h_meas, classical, let setsβ : (Π i : ι, set (β i)) := λ i, dite (i ∈ S) (λ hi_mem, (h_meas i hi_mem).some) (λ _, set.univ), have h_measβ : ∀ i ∈ S, measurable_set[m i] (setsβ i), { intros i hi_mem, simp_rw [setsβ, dif_pos hi_mem], exact (h_meas i hi_mem).some_spec.1, }, have h_preim : ∀ i ∈ S, setsΩ i = (f i) ⁻¹' (setsβ i), { intros i hi_mem, simp_rw [setsβ, dif_pos hi_mem], exact (h_meas i hi_mem).some_spec.2.symm, }, have h_left_eq : μ (⋂ i ∈ S, setsΩ i) = μ (⋂ i ∈ S, (f i) ⁻¹' (setsβ i)), { congr' with i x, simp only [set.mem_Inter], split; intros h hi_mem; specialize h hi_mem, { rwa h_preim i hi_mem at h, }, { rwa h_preim i hi_mem, }, }, have h_right_eq : (∏ i in S, μ (setsΩ i)) = ∏ i in S, μ ((f i) ⁻¹' (setsβ i)), { refine finset.prod_congr rfl (λ i hi_mem, _), rw h_preim i hi_mem, }, rw [h_left_eq, h_right_eq], exact h S h_measβ, end lemma indep_fun_iff_indep_set_preimage {mβ : measurable_space β} {mβ' : measurable_space β'} [is_probability_measure μ] (hf : measurable f) (hg : measurable g) : indep_fun f g μ ↔ ∀ s t, measurable_set s → measurable_set t → indep_set (f ⁻¹' s) (g ⁻¹' t) μ := begin refine indep_fun_iff_measure_inter_preimage_eq_mul.trans _, split; intros h s t hs ht; specialize h s t hs ht, { rwa indep_set_iff_measure_inter_eq_mul (hf hs) (hg ht) μ, }, { rwa ← indep_set_iff_measure_inter_eq_mul (hf hs) (hg ht) μ, }, end @[symm] lemma indep_fun.symm {mβ : measurable_space β} {f g : Ω → β} (hfg : indep_fun f g μ) : indep_fun g f μ := hfg.symm lemma indep_fun.ae_eq {mβ : measurable_space β} {f g f' g' : Ω → β} (hfg : indep_fun f g μ) (hf : f =ᵐ[μ] f') (hg : g =ᵐ[μ] g') : indep_fun f' g' μ := begin rintro _ _ ⟨A, hA, rfl⟩ ⟨B, hB, rfl⟩, have h1 : f ⁻¹' A =ᵐ[μ] f' ⁻¹' A := hf.fun_comp A, have h2 : g ⁻¹' B =ᵐ[μ] g' ⁻¹' B := hg.fun_comp B, rw [← measure_congr h1, ← measure_congr h2, ← measure_congr (h1.inter h2)], exact hfg _ _ ⟨_, hA, rfl⟩ ⟨_, hB, rfl⟩ end lemma indep_fun.comp {mβ : measurable_space β} {mβ' : measurable_space β'} {mγ : measurable_space γ} {mγ' : measurable_space γ'} {φ : β → γ} {ψ : β' → γ'} (hfg : indep_fun f g μ) (hφ : measurable φ) (hψ : measurable ψ) : indep_fun (φ ∘ f) (ψ ∘ g) μ := begin rintro _ _ ⟨A, hA, rfl⟩ ⟨B, hB, rfl⟩, apply hfg, { exact ⟨φ ⁻¹' A, hφ hA, set.preimage_comp.symm⟩ }, { exact ⟨ψ ⁻¹' B, hψ hB, set.preimage_comp.symm⟩ } end /-- If `f` is a family of mutually independent random variables (`Indep_fun m f μ`) and `S, T` are two disjoint finite index sets, then the tuple formed by `f i` for `i ∈ S` is independent of the tuple `(f i)_i` for `i ∈ T`. -/ lemma Indep_fun.indep_fun_finset [is_probability_measure μ] {ι : Type*} {β : ι → Type*} {m : Π i, measurable_space (β i)} {f : Π i, Ω → β i} (S T : finset ι) (hST : disjoint S T) (hf_Indep : Indep_fun m f μ) (hf_meas : ∀ i, measurable (f i)) : indep_fun (λ a (i : S), f i a) (λ a (i : T), f i a) μ := begin -- We introduce π-systems, build from the π-system of boxes which generates `measurable_space.pi`. let πSβ := (set.pi (set.univ : set S) '' (set.pi (set.univ : set S) (λ i, {s : set (β i) | measurable_set[m i] s}))), let πS := {s : set Ω | ∃ t ∈ πSβ, (λ a (i : S), f i a) ⁻¹' t = s}, have hπS_pi : is_pi_system πS := is_pi_system_pi.comap (λ a i, f i a), have hπS_gen : measurable_space.pi.comap (λ a (i : S), f i a) = generate_from πS, { rw [generate_from_pi.symm, comap_generate_from], { congr' with s, simp only [set.mem_image, set.mem_set_of_eq, exists_prop], }, { apply_instance } }, let πTβ := (set.pi (set.univ : set T) '' (set.pi (set.univ : set T) (λ i, {s : set (β i) | measurable_set[m i] s}))), let πT := {s : set Ω | ∃ t ∈ πTβ, (λ a (i : T), f i a) ⁻¹' t = s}, have hπT_pi : is_pi_system πT := is_pi_system_pi.comap (λ a i, f i a), have hπT_gen : measurable_space.pi.comap (λ a (i : T), f i a) = generate_from πT, { rw [generate_from_pi.symm, comap_generate_from], { congr' with s, simp only [set.mem_image, set.mem_set_of_eq, exists_prop], }, { apply_instance } }, -- To prove independence, we prove independence of the generating π-systems. refine indep_sets.indep (measurable.comap_le (measurable_pi_iff.mpr (λ i, hf_meas i))) (measurable.comap_le (measurable_pi_iff.mpr (λ i, hf_meas i))) hπS_pi hπT_pi hπS_gen hπT_gen _, rintros _ _ ⟨s, ⟨sets_s, hs1, hs2⟩, rfl⟩ ⟨t, ⟨sets_t, ht1, ht2⟩, rfl⟩, simp only [set.mem_univ_pi, set.mem_set_of_eq] at hs1 ht1, rw [← hs2, ← ht2], classical, let sets_s' : (Π i : ι, set (β i)) := λ i, dite (i ∈ S) (λ hi, sets_s ⟨i, hi⟩) (λ _, set.univ), have h_sets_s'_eq : ∀ {i} (hi : i ∈ S), sets_s' i = sets_s ⟨i, hi⟩, { intros i hi, simp_rw [sets_s', dif_pos hi], }, have h_sets_s'_univ : ∀ {i} (hi : i ∈ T), sets_s' i = set.univ, { intros i hi, simp_rw [sets_s', dif_neg (finset.disjoint_right.mp hST hi)], }, let sets_t' : (Π i : ι, set (β i)) := λ i, dite (i ∈ T) (λ hi, sets_t ⟨i, hi⟩) (λ _, set.univ), have h_sets_t'_univ : ∀ {i} (hi : i ∈ S), sets_t' i = set.univ, { intros i hi, simp_rw [sets_t', dif_neg (finset.disjoint_left.mp hST hi)], }, have h_meas_s' : ∀ i ∈ S, measurable_set (sets_s' i), { intros i hi, rw h_sets_s'_eq hi, exact hs1 _, }, have h_meas_t' : ∀ i ∈ T, measurable_set (sets_t' i), { intros i hi, simp_rw [sets_t', dif_pos hi], exact ht1 _, }, have h_eq_inter_S : (λ (ω : Ω) (i : ↥S), f ↑i ω) ⁻¹' set.pi set.univ sets_s = ⋂ i ∈ S, (f i) ⁻¹' (sets_s' i), { ext1 x, simp only [set.mem_preimage, set.mem_univ_pi, set.mem_Inter], split; intro h, { intros i hi, rw [h_sets_s'_eq hi], exact h ⟨i, hi⟩, }, { rintros ⟨i, hi⟩, specialize h i hi, rw [h_sets_s'_eq hi] at h, exact h, }, }, have h_eq_inter_T : (λ (ω : Ω) (i : ↥T), f ↑i ω) ⁻¹' set.pi set.univ sets_t = ⋂ i ∈ T, (f i) ⁻¹' (sets_t' i), { ext1 x, simp only [set.mem_preimage, set.mem_univ_pi, set.mem_Inter], split; intro h, { intros i hi, simp_rw [sets_t', dif_pos hi], exact h ⟨i, hi⟩, }, { rintros ⟨i, hi⟩, specialize h i hi, simp_rw [sets_t', dif_pos hi] at h, exact h, }, }, rw Indep_fun_iff_measure_inter_preimage_eq_mul at hf_Indep, rw [h_eq_inter_S, h_eq_inter_T, hf_Indep S h_meas_s', hf_Indep T h_meas_t'], have h_Inter_inter : (⋂ i ∈ S, (f i) ⁻¹' (sets_s' i)) ∩ (⋂ i ∈ T, (f i) ⁻¹' (sets_t' i)) = ⋂ i ∈ (S ∪ T), (f i) ⁻¹' (sets_s' i ∩ sets_t' i), { ext1 x, simp only [set.mem_inter_iff, set.mem_Inter, set.mem_preimage, finset.mem_union], split; intro h, { intros i hi, cases hi, { rw h_sets_t'_univ hi, exact ⟨h.1 i hi, set.mem_univ _⟩, }, { rw h_sets_s'_univ hi, exact ⟨set.mem_univ _, h.2 i hi⟩, }, }, { exact ⟨λ i hi, (h i (or.inl hi)).1, λ i hi, (h i (or.inr hi)).2⟩, }, }, rw [h_Inter_inter, hf_Indep (S ∪ T)], swap, { intros i hi_mem, rw finset.mem_union at hi_mem, cases hi_mem, { rw [h_sets_t'_univ hi_mem, set.inter_univ], exact h_meas_s' i hi_mem, }, { rw [h_sets_s'_univ hi_mem, set.univ_inter], exact h_meas_t' i hi_mem, }, }, rw finset.prod_union hST, congr' 1, { refine finset.prod_congr rfl (λ i hi, _), rw [h_sets_t'_univ hi, set.inter_univ], }, { refine finset.prod_congr rfl (λ i hi, _), rw [h_sets_s'_univ hi, set.univ_inter], }, end lemma Indep_fun.indep_fun_prod [is_probability_measure μ] {ι : Type*} {β : ι → Type*} {m : Π i, measurable_space (β i)} {f : Π i, Ω → β i} (hf_Indep : Indep_fun m f μ) (hf_meas : ∀ i, measurable (f i)) (i j k : ι) (hik : i ≠ k) (hjk : j ≠ k) : indep_fun (λ a, (f i a, f j a)) (f k) μ := begin classical, have h_right : f k = (λ p : (Π j : ({k} : finset ι), β j), p ⟨k, finset.mem_singleton_self k⟩) ∘ (λ a (j : ({k} : finset ι)), f j a) := rfl, have h_meas_right : measurable (λ p : (Π j : ({k} : finset ι), β j), p ⟨k, finset.mem_singleton_self k⟩), from measurable_pi_apply ⟨k, finset.mem_singleton_self k⟩, let s : finset ι := {i, j}, have h_left : (λ ω, (f i ω, f j ω)) = (λ p : (Π l : s, β l), (p ⟨i, finset.mem_insert_self i _⟩, p ⟨j, finset.mem_insert_of_mem (finset.mem_singleton_self _)⟩)) ∘ (λ a (j : s), f j a), { ext1 a, simp only [prod.mk.inj_iff], split; refl, }, have h_meas_left : measurable (λ p : (Π l : s, β l), (p ⟨i, finset.mem_insert_self i _⟩, p ⟨j, finset.mem_insert_of_mem (finset.mem_singleton_self _)⟩)), from measurable.prod (measurable_pi_apply ⟨i, finset.mem_insert_self i {j}⟩) (measurable_pi_apply ⟨j, finset.mem_insert_of_mem (finset.mem_singleton_self j)⟩), rw [h_left, h_right], refine (hf_Indep.indep_fun_finset s {k} _ hf_meas).comp h_meas_left h_meas_right, rw finset.disjoint_singleton_right, simp only [finset.mem_insert, finset.mem_singleton, not_or_distrib], exact ⟨hik.symm, hjk.symm⟩, end @[to_additive] lemma Indep_fun.mul [is_probability_measure μ] {ι : Type*} {β : Type*} {m : measurable_space β} [has_mul β] [has_measurable_mul₂ β] {f : ι → Ω → β} (hf_Indep : Indep_fun (λ _, m) f μ) (hf_meas : ∀ i, measurable (f i)) (i j k : ι) (hik : i ≠ k) (hjk : j ≠ k) : indep_fun (f i * f j) (f k) μ := begin have : indep_fun (λ ω, (f i ω, f j ω)) (f k) μ := hf_Indep.indep_fun_prod hf_meas i j k hik hjk, change indep_fun ((λ p : β × β, p.fst * p.snd) ∘ (λ ω, (f i ω, f j ω))) (id ∘ (f k)) μ, exact indep_fun.comp this (measurable_fst.mul measurable_snd) measurable_id, end @[to_additive] lemma Indep_fun.indep_fun_finset_prod_of_not_mem [is_probability_measure μ] {ι : Type*} {β : Type*} {m : measurable_space β} [comm_monoid β] [has_measurable_mul₂ β] {f : ι → Ω → β} (hf_Indep : Indep_fun (λ _, m) f μ) (hf_meas : ∀ i, measurable (f i)) {s : finset ι} {i : ι} (hi : i ∉ s) : indep_fun (∏ j in s, f j) (f i) μ := begin classical, have h_right : f i = (λ p : (Π j : ({i} : finset ι), β), p ⟨i, finset.mem_singleton_self i⟩) ∘ (λ a (j : ({i} : finset ι)), f j a) := rfl, have h_meas_right : measurable (λ p : (Π j : ({i} : finset ι), β), p ⟨i, finset.mem_singleton_self i⟩), from measurable_pi_apply ⟨i, finset.mem_singleton_self i⟩, have h_left : (∏ j in s, f j) = (λ p : (Π j : s, β), ∏ j, p j) ∘ (λ a (j : s), f j a), { ext1 a, simp only [function.comp_app], have : (∏ (j : ↥s), f ↑j a) = (∏ (j : ↥s), f ↑j) a, by rw finset.prod_apply, rw [this, finset.prod_coe_sort], }, have h_meas_left : measurable (λ p : (Π j : s, β), ∏ j, p j), from finset.univ.measurable_prod (λ (j : ↥s) (H : j ∈ finset.univ), measurable_pi_apply j), rw [h_left, h_right], exact (hf_Indep.indep_fun_finset s {i} (finset.disjoint_singleton_left.mpr hi).symm hf_meas).comp h_meas_left h_meas_right, end @[to_additive] lemma Indep_fun.indep_fun_prod_range_succ [is_probability_measure μ] {β : Type*} {m : measurable_space β} [comm_monoid β] [has_measurable_mul₂ β] {f : ℕ → Ω → β} (hf_Indep : Indep_fun (λ _, m) f μ) (hf_meas : ∀ i, measurable (f i)) (n : ℕ) : indep_fun (∏ j in finset.range n, f j) (f n) μ := hf_Indep.indep_fun_finset_prod_of_not_mem hf_meas finset.not_mem_range_self lemma Indep_set.Indep_fun_indicator [has_zero β] [has_one β] {m : measurable_space β} {s : ι → set Ω} (hs : Indep_set s μ) : Indep_fun (λ n, m) (λ n, (s n).indicator (λ ω, 1)) μ := begin classical, rw Indep_fun_iff_measure_inter_preimage_eq_mul, rintro S π hπ, simp_rw set.indicator_const_preimage_eq_union, refine @hs S (λ i, ite (1 ∈ π i) (s i) ∅ ∪ ite ((0 : β) ∈ π i) (s i)ᶜ ∅) (λ i hi, _), have hsi : measurable_set[generate_from {s i}] (s i), from measurable_set_generate_from (set.mem_singleton _), refine measurable_set.union (measurable_set.ite' (λ _, hsi) (λ _, _)) (measurable_set.ite' (λ _, hsi.compl) (λ _, _)), { exact @measurable_set.empty _ (generate_from {s i}), }, { exact @measurable_set.empty _ (generate_from {s i}), }, end end indep_fun end probability_theory
f1518a47a485b093ba5b1aab19c270bffeebdcf1
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/computability/turing_machine.lean
7dee8011654626d3c4b9ca322813a6fa1e9b28b1
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
109,916
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import algebra.order import data.fintype.basic import data.pfun import tactic.apply_fun import logic.function.iterate /-! # Turing machines This file defines a sequence of simple machine languages, starting with Turing machines and working up to more complex languages based on Wang B-machines. ## Naming conventions Each model of computation in this file shares a naming convention for the elements of a model of computation. These are the parameters for the language: * `Γ` is the alphabet on the tape. * `Λ` is the set of labels, or internal machine states. * `σ` is the type of internal memory, not on the tape. This does not exist in the TM0 model, and later models achieve this by mixing it into `Λ`. * `K` is used in the TM2 model, which has multiple stacks, and denotes the number of such stacks. All of these variables denote "essentially finite" types, but for technical reasons it is convenient to allow them to be infinite anyway. When using an infinite type, we will be interested to prove that only finitely many values of the type are ever interacted with. Given these parameters, there are a few common structures for the model that arise: * `stmt` is the set of all actions that can be performed in one step. For the TM0 model this set is finite, and for later models it is an infinite inductive type representing "possible program texts". * `cfg` is the set of instantaneous configurations, that is, the state of the machine together with its environment. * `machine` is the set of all machines in the model. Usually this is approximately a function `Λ → stmt`, although different models have different ways of halting and other actions. * `step : cfg → option cfg` is the function that describes how the state evolves over one step. If `step c = none`, then `c` is a terminal state, and the result of the computation is read off from `c`. Because of the type of `step`, these models are all deterministic by construction. * `init : input → cfg` sets up the initial state. The type `input` depends on the model; in most cases it is `list Γ`. * `eval : machine → input → roption output`, given a machine `M` and input `i`, starts from `init i`, runs `step` until it reaches an output, and then applies a function `cfg → output` to the final state to obtain the result. The type `output` depends on the model. * `supports : machine → finset Λ → Prop` asserts that a machine `M` starts in `S : finset Λ`, and can only ever jump to other states inside `S`. This implies that the behavior of `M` on any input cannot depend on its values outside `S`. We use this to allow `Λ` to be an infinite set when convenient, and prove that only finitely many of these states are actually accessible. This formalizes "essentially finite" mentioned above. -/ open relation open nat (iterate) open function (update iterate_succ iterate_succ_apply iterate_succ' iterate_succ_apply' iterate_zero_apply) namespace turing /-- The `blank_extends` partial order holds of `l₁` and `l₂` if `l₂` is obtained by adding blanks (`default Γ`) to the end of `l₁`. -/ def blank_extends {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop := ∃ n, l₂ = l₁ ++ list.repeat (default Γ) n @[refl] theorem blank_extends.refl {Γ} [inhabited Γ] (l : list Γ) : blank_extends l l := ⟨0, by simp⟩ @[trans] theorem blank_extends.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} : blank_extends l₁ l₂ → blank_extends l₂ l₃ → blank_extends l₁ l₃ := by rintro ⟨i, rfl⟩ ⟨j, rfl⟩; exact ⟨i+j, by simp [list.repeat_add]⟩ theorem blank_extends.below_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} : blank_extends l l₁ → blank_extends l l₂ → l₁.length ≤ l₂.length → blank_extends l₁ l₂ := begin rintro ⟨i, rfl⟩ ⟨j, rfl⟩ h, use j - i, simp only [list.length_append, add_le_add_iff_left, list.length_repeat] at h, simp only [← list.repeat_add, nat.add_sub_cancel' h, list.append_assoc], end /-- Any two extensions by blank `l₁,l₂` of `l` have a common join (which can be taken to be the longer of `l₁` and `l₂`). -/ def blank_extends.above {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} (h₁ : blank_extends l l₁) (h₂ : blank_extends l l₂) : {l' // blank_extends l₁ l' ∧ blank_extends l₂ l'} := if h : l₁.length ≤ l₂.length then ⟨l₂, h₁.below_of_le h₂ h, blank_extends.refl _⟩ else ⟨l₁, blank_extends.refl _, h₂.below_of_le h₁ (le_of_not_ge h)⟩ theorem blank_extends.above_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} : blank_extends l₁ l → blank_extends l₂ l → l₁.length ≤ l₂.length → blank_extends l₁ l₂ := begin rintro ⟨i, rfl⟩ ⟨j, e⟩ h, use i - j, refine list.append_right_cancel (e.symm.trans _), rw [list.append_assoc, ← list.repeat_add, nat.sub_add_cancel], apply_fun list.length at e, simp only [list.length_append, list.length_repeat] at e, rwa [← add_le_add_iff_left, e, add_le_add_iff_right] end /-- `blank_rel` is the symmetric closure of `blank_extends`, turning it into an equivalence relation. Two lists are related by `blank_rel` if one extends the other by blanks. -/ def blank_rel {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop := blank_extends l₁ l₂ ∨ blank_extends l₂ l₁ @[refl] theorem blank_rel.refl {Γ} [inhabited Γ] (l : list Γ) : blank_rel l l := or.inl (blank_extends.refl _) @[symm] theorem blank_rel.symm {Γ} [inhabited Γ] {l₁ l₂ : list Γ} : blank_rel l₁ l₂ → blank_rel l₂ l₁ := or.symm @[trans] theorem blank_rel.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} : blank_rel l₁ l₂ → blank_rel l₂ l₃ → blank_rel l₁ l₃ := begin rintro (h₁|h₁) (h₂|h₂), { exact or.inl (h₁.trans h₂) }, { cases le_total l₁.length l₃.length with h h, { exact or.inl (h₁.above_of_le h₂ h) }, { exact or.inr (h₂.above_of_le h₁ h) } }, { cases le_total l₁.length l₃.length with h h, { exact or.inl (h₁.below_of_le h₂ h) }, { exact or.inr (h₂.below_of_le h₁ h) } }, { exact or.inr (h₂.trans h₁) }, end /-- Given two `blank_rel` lists, there exists (constructively) a common join. -/ def blank_rel.above {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) : {l // blank_extends l₁ l ∧ blank_extends l₂ l} := begin refine if hl : l₁.length ≤ l₂.length then ⟨l₂, or.elim h id (λ h', _), blank_extends.refl _⟩ else ⟨l₁, blank_extends.refl _, or.elim h (λ h', _) id⟩, exact (blank_extends.refl _).above_of_le h' hl, exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl) end /-- Given two `blank_rel` lists, there exists (constructively) a common meet. -/ def blank_rel.below {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) : {l // blank_extends l l₁ ∧ blank_extends l l₂} := begin refine if hl : l₁.length ≤ l₂.length then ⟨l₁, blank_extends.refl _, or.elim h id (λ h', _)⟩ else ⟨l₂, or.elim h (λ h', _) id, blank_extends.refl _⟩, exact (blank_extends.refl _).above_of_le h' hl, exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl) end theorem blank_rel.equivalence (Γ) [inhabited Γ] : equivalence (@blank_rel Γ _) := ⟨blank_rel.refl, @blank_rel.symm _ _, @blank_rel.trans _ _⟩ /-- Construct a setoid instance for `blank_rel`. -/ def blank_rel.setoid (Γ) [inhabited Γ] : setoid (list Γ) := ⟨_, blank_rel.equivalence _⟩ /-- A `list_blank Γ` is a quotient of `list Γ` by extension by blanks at the end. This is used to represent half-tapes of a Turing machine, so that we can pretend that the list continues infinitely with blanks. -/ def list_blank (Γ) [inhabited Γ] := quotient (blank_rel.setoid Γ) instance list_blank.inhabited {Γ} [inhabited Γ] : inhabited (list_blank Γ) := ⟨quotient.mk' []⟩ instance list_blank.has_emptyc {Γ} [inhabited Γ] : has_emptyc (list_blank Γ) := ⟨quotient.mk' []⟩ /-- A modified version of `quotient.lift_on'` specialized for `list_blank`, with the stronger precondition `blank_extends` instead of `blank_rel`. -/ @[elab_as_eliminator, reducible] protected def list_blank.lift_on {Γ} [inhabited Γ] {α} (l : list_blank Γ) (f : list Γ → α) (H : ∀ a b, blank_extends a b → f a = f b) : α := l.lift_on' f $ by rintro a b (h|h); [exact H _ _ h, exact (H _ _ h).symm] /-- The quotient map turning a `list` into a `list_blank`. -/ def list_blank.mk {Γ} [inhabited Γ] : list Γ → list_blank Γ := quotient.mk' @[elab_as_eliminator] protected lemma list_blank.induction_on {Γ} [inhabited Γ] {p : list_blank Γ → Prop} (q : list_blank Γ) (h : ∀ a, p (list_blank.mk a)) : p q := quotient.induction_on' q h /-- The head of a `list_blank` is well defined. -/ def list_blank.head {Γ} [inhabited Γ] (l : list_blank Γ) : Γ := l.lift_on list.head begin rintro _ _ ⟨i, rfl⟩, cases a, {cases i; refl}, refl end @[simp] theorem list_blank.head_mk {Γ} [inhabited Γ] (l : list Γ) : list_blank.head (list_blank.mk l) = l.head := rfl /-- The tail of a `list_blank` is well defined (up to the tail of blanks). -/ def list_blank.tail {Γ} [inhabited Γ] (l : list_blank Γ) : list_blank Γ := l.lift_on (λ l, list_blank.mk l.tail) begin rintro _ _ ⟨i, rfl⟩, refine quotient.sound' (or.inl _), cases a; [{cases i; [exact ⟨0, rfl⟩, exact ⟨i, rfl⟩]}, exact ⟨i, rfl⟩] end @[simp] theorem list_blank.tail_mk {Γ} [inhabited Γ] (l : list Γ) : list_blank.tail (list_blank.mk l) = list_blank.mk l.tail := rfl /-- We can cons an element onto a `list_blank`. -/ def list_blank.cons {Γ} [inhabited Γ] (a : Γ) (l : list_blank Γ) : list_blank Γ := l.lift_on (λ l, list_blank.mk (list.cons a l)) begin rintro _ _ ⟨i, rfl⟩, exact quotient.sound' (or.inl ⟨i, rfl⟩), end @[simp] theorem list_blank.cons_mk {Γ} [inhabited Γ] (a : Γ) (l : list Γ) : list_blank.cons a (list_blank.mk l) = list_blank.mk (a :: l) := rfl @[simp] theorem list_blank.head_cons {Γ} [inhabited Γ] (a : Γ) : ∀ (l : list_blank Γ), (l.cons a).head = a := quotient.ind' $ by exact λ l, rfl @[simp] theorem list_blank.tail_cons {Γ} [inhabited Γ] (a : Γ) : ∀ (l : list_blank Γ), (l.cons a).tail = l := quotient.ind' $ by exact λ l, rfl /-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where this only holds for nonempty lists. -/ @[simp] theorem list_blank.cons_head_tail {Γ} [inhabited Γ] : ∀ (l : list_blank Γ), l.tail.cons l.head = l := quotient.ind' begin refine (λ l, quotient.sound' (or.inr _)), cases l, {exact ⟨1, rfl⟩}, {refl}, end /-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where this only holds for nonempty lists. -/ theorem list_blank.exists_cons {Γ} [inhabited Γ] (l : list_blank Γ) : ∃ a l', l = list_blank.cons a l' := ⟨_, _, (list_blank.cons_head_tail _).symm⟩ /-- The n-th element of a `list_blank` is well defined for all `n : ℕ`, unlike in a `list`. -/ def list_blank.nth {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) : Γ := l.lift_on (λ l, list.inth l n) begin rintro l _ ⟨i, rfl⟩, simp only [list.inth], cases lt_or_le _ _ with h h, {rw list.nth_append h}, rw list.nth_len_le h, cases le_or_lt _ _ with h₂ h₂, {rw list.nth_len_le h₂}, rw [list.nth_le_nth h₂, list.nth_le_append_right h, list.nth_le_repeat] end @[simp] theorem list_blank.nth_mk {Γ} [inhabited Γ] (l : list Γ) (n : ℕ) : (list_blank.mk l).nth n = l.inth n := rfl @[simp] theorem list_blank.nth_zero {Γ} [inhabited Γ] (l : list_blank Γ) : l.nth 0 = l.head := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l.tail (λ l, rfl) end @[simp] theorem list_blank.nth_succ {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) : l.nth (n + 1) = l.tail.nth n := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l.tail (λ l, rfl) end @[ext] theorem list_blank.ext {Γ} [inhabited Γ] {L₁ L₂ : list_blank Γ} : (∀ i, L₁.nth i = L₂.nth i) → L₁ = L₂ := list_blank.induction_on L₁ $ λ l₁, list_blank.induction_on L₂ $ λ l₂ H, begin wlog h : l₁.length ≤ l₂.length using l₁ l₂, swap, { exact (this $ λ i, (H i).symm).symm }, refine quotient.sound' (or.inl ⟨l₂.length - l₁.length, _⟩), refine list.ext_le _ (λ i h h₂, eq.symm _), { simp only [nat.add_sub_of_le h, list.length_append, list.length_repeat] }, simp at H, cases lt_or_le i l₁.length with h' h', { simpa only [list.nth_le_append _ h', list.nth_le_nth h, list.nth_le_nth h', option.iget] using H i }, { simpa only [list.nth_le_append_right h', list.nth_le_repeat, list.nth_le_nth h, list.nth_len_le h', option.iget] using H i }, end /-- Apply a function to a value stored at the nth position of the list. -/ @[simp] def list_blank.modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) : ℕ → list_blank Γ → list_blank Γ | 0 L := L.tail.cons (f L.head) | (n+1) L := (L.tail.modify_nth n).cons L.head theorem list_blank.nth_modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) (n i) (L : list_blank Γ) : (L.modify_nth f n).nth i = if i = n then f (L.nth i) else L.nth i := begin induction n with n IH generalizing i L, { cases i; simp only [list_blank.nth_zero, if_true, list_blank.head_cons, list_blank.modify_nth, eq_self_iff_true, list_blank.nth_succ, if_false, list_blank.tail_cons] }, { cases i, { rw if_neg (nat.succ_ne_zero _).symm, simp only [list_blank.nth_zero, list_blank.head_cons, list_blank.modify_nth] }, { simp only [IH, list_blank.modify_nth, list_blank.nth_succ, list_blank.tail_cons], congr } } end /-- A pointed map of `inhabited` types is a map that sends one default value to the other. -/ structure {u v} pointed_map (Γ : Type u) (Γ' : Type v) [inhabited Γ] [inhabited Γ'] : Type (max u v) := (f : Γ → Γ') (map_pt' : f (default _) = default _) instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : inhabited (pointed_map Γ Γ') := ⟨⟨λ _, default _, rfl⟩⟩ instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : has_coe_to_fun (pointed_map Γ Γ') := ⟨_, pointed_map.f⟩ @[simp] theorem pointed_map.mk_val {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') (pt) : (pointed_map.mk f pt : Γ → Γ') = f := rfl @[simp] theorem pointed_map.map_pt {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') : f (default _) = default _ := pointed_map.map_pt' _ @[simp] theorem pointed_map.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (l.map f).head = f l.head := by cases l; [exact (pointed_map.map_pt f).symm, refl] /-- The `map` function on lists is well defined on `list_blank`s provided that the map is pointed. -/ def list_blank.map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : list_blank Γ' := l.lift_on (λ l, list_blank.mk (list.map f l)) begin rintro l _ ⟨i, rfl⟩, refine quotient.sound' (or.inl ⟨i, _⟩), simp only [pointed_map.map_pt, list.map_append, list.map_repeat], end @[simp] theorem list_blank.map_mk {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (list_blank.mk l).map f = list_blank.mk (l.map f) := rfl @[simp] theorem list_blank.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).head = f l.head := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l (λ a, rfl) end @[simp] theorem list_blank.tail_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).tail = l.tail.map f := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l (λ a, rfl) end @[simp] theorem list_blank.map_cons {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) (a : Γ) : (l.cons a).map f = (l.map f).cons (f a) := begin refine (list_blank.cons_head_tail _).symm.trans _, simp only [list_blank.head_map, list_blank.head_cons, list_blank.tail_map, list_blank.tail_cons] end @[simp] theorem list_blank.nth_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) (n : ℕ) : (l.map f).nth n = f (l.nth n) := l.induction_on begin intro l, simp only [list.nth_map, list_blank.map_mk, list_blank.nth_mk, list.inth], cases l.nth n, {exact f.2.symm}, {refl} end /-- The `i`-th projection as a pointed map. -/ def proj {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι) : pointed_map (∀ i, Γ i) (Γ i) := ⟨λ a, a i, rfl⟩ theorem proj_map_nth {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι) (L n) : (list_blank.map (@proj ι Γ _ i) L).nth n = L.nth n i := by rw list_blank.nth_map; refl theorem list_blank.map_modify_nth {Γ Γ'} [inhabited Γ] [inhabited Γ'] (F : pointed_map Γ Γ') (f : Γ → Γ) (f' : Γ' → Γ') (H : ∀ x, F (f x) = f' (F x)) (n) (L : list_blank Γ) : (L.modify_nth f n).map F = (L.map F).modify_nth f' n := by induction n with n IH generalizing L; simp only [*, list_blank.head_map, list_blank.modify_nth, list_blank.map_cons, list_blank.tail_map] /-- Append a list on the left side of a list_blank. -/ @[simp] def list_blank.append {Γ} [inhabited Γ] : list Γ → list_blank Γ → list_blank Γ | [] L := L | (a :: l) L := list_blank.cons a (list_blank.append l L) @[simp] theorem list_blank.append_mk {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : list_blank.append l₁ (list_blank.mk l₂) = list_blank.mk (l₁ ++ l₂) := by induction l₁; simp only [*, list_blank.append, list.nil_append, list.cons_append, list_blank.cons_mk] theorem list_blank.append_assoc {Γ} [inhabited Γ] (l₁ l₂ : list Γ) (l₃ : list_blank Γ) : list_blank.append (l₁ ++ l₂) l₃ = list_blank.append l₁ (list_blank.append l₂ l₃) := l₃.induction_on $ by intro; simp only [list_blank.append_mk, list.append_assoc] /-- The `bind` function on lists is well defined on `list_blank`s provided that the default element is sent to a sequence of default elements. -/ def list_blank.bind {Γ Γ'} [inhabited Γ] [inhabited Γ'] (l : list_blank Γ) (f : Γ → list Γ') (hf : ∃ n, f (default _) = list.repeat (default _) n) : list_blank Γ' := l.lift_on (λ l, list_blank.mk (list.bind l f)) begin rintro l _ ⟨i, rfl⟩, cases hf with n e, refine quotient.sound' (or.inl ⟨i * n, _⟩), rw [list.bind_append, mul_comm], congr, induction i with i IH, refl, simp only [IH, e, list.repeat_add, nat.mul_succ, add_comm, list.repeat_succ, list.cons_bind], end @[simp] lemma list_blank.bind_mk {Γ Γ'} [inhabited Γ] [inhabited Γ'] (l : list Γ) (f : Γ → list Γ') (hf) : (list_blank.mk l).bind f hf = list_blank.mk (l.bind f) := rfl @[simp] lemma list_blank.cons_bind {Γ Γ'} [inhabited Γ] [inhabited Γ'] (a : Γ) (l : list_blank Γ) (f : Γ → list Γ') (hf) : (l.cons a).bind f hf = (l.bind f hf).append (f a) := l.induction_on $ by intro; simp only [list_blank.append_mk, list_blank.bind_mk, list_blank.cons_mk, list.cons_bind] /-- The tape of a Turing machine is composed of a head element (which we imagine to be the current position of the head), together with two `list_blank`s denoting the portions of the tape going off to the left and right. When the Turing machine moves right, an element is pulled from the right side and becomes the new head, while the head element is consed onto the left side. -/ structure tape (Γ : Type*) [inhabited Γ] := (head : Γ) (left : list_blank Γ) (right : list_blank Γ) instance tape.inhabited {Γ} [inhabited Γ] : inhabited (tape Γ) := ⟨by constructor; apply default⟩ /-- A direction for the turing machine `move` command, either left or right. -/ @[derive decidable_eq, derive inhabited] inductive dir | left | right /-- The "inclusive" left side of the tape, including both `left` and `head`. -/ def tape.left₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.left.cons T.head /-- The "inclusive" right side of the tape, including both `right` and `head`. -/ def tape.right₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.right.cons T.head /-- Move the tape in response to a motion of the Turing machine. Note that `T.move dir.left` makes `T.left` smaller; the Turing machine is moving left and the tape is moving right. -/ def tape.move {Γ} [inhabited Γ] : dir → tape Γ → tape Γ | dir.left ⟨a, L, R⟩ := ⟨L.head, L.tail, R.cons a⟩ | dir.right ⟨a, L, R⟩ := ⟨R.head, L.cons a, R.tail⟩ @[simp] theorem tape.move_left_right {Γ} [inhabited Γ] (T : tape Γ) : (T.move dir.left).move dir.right = T := by cases T; simp [tape.move] @[simp] theorem tape.move_right_left {Γ} [inhabited Γ] (T : tape Γ) : (T.move dir.right).move dir.left = T := by cases T; simp [tape.move] /-- Construct a tape from a left side and an inclusive right side. -/ def tape.mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : tape Γ := ⟨R.head, L, R.tail⟩ @[simp] theorem tape.mk'_left {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).left = L := rfl @[simp] theorem tape.mk'_head {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).head = R.head := rfl @[simp] theorem tape.mk'_right {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).right = R.tail := rfl @[simp] theorem tape.mk'_right₀ {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).right₀ = R := list_blank.cons_head_tail _ @[simp] theorem tape.mk'_left_right₀ {Γ} [inhabited Γ] (T : tape Γ) : tape.mk' T.left T.right₀ = T := by cases T; simp only [tape.right₀, tape.mk', list_blank.head_cons, list_blank.tail_cons, eq_self_iff_true, and_self] theorem tape.exists_mk' {Γ} [inhabited Γ] (T : tape Γ) : ∃ L R, T = tape.mk' L R := ⟨_, _, (tape.mk'_left_right₀ _).symm⟩ @[simp] theorem tape.move_left_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).move dir.left = tape.mk' L.tail (R.cons L.head) := by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true, list_blank.cons_head_tail, and_self, list_blank.tail_cons] @[simp] theorem tape.move_right_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).move dir.right = tape.mk' (L.cons R.head) R.tail := by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true, list_blank.cons_head_tail, and_self, list_blank.tail_cons] /-- Construct a tape from a left side and an inclusive right side. -/ def tape.mk₂ {Γ} [inhabited Γ] (L R : list Γ) : tape Γ := tape.mk' (list_blank.mk L) (list_blank.mk R) /-- Construct a tape from a list, with the head of the list at the TM head and the rest going to the right. -/ def tape.mk₁ {Γ} [inhabited Γ] (l : list Γ) : tape Γ := tape.mk₂ [] l /-- The `nth` function of a tape is integer-valued, with index `0` being the head, negative indexes on the left and positive indexes on the right. (Picture a number line.) -/ def tape.nth {Γ} [inhabited Γ] (T : tape Γ) : ℤ → Γ | 0 := T.head | (n+1:ℕ) := T.right.nth n | -[1+ n] := T.left.nth n @[simp] theorem tape.nth_zero {Γ} [inhabited Γ] (T : tape Γ) : T.nth 0 = T.1 := rfl theorem tape.right₀_nth {Γ} [inhabited Γ] (T : tape Γ) (n : ℕ) : T.right₀.nth n = T.nth n := by cases n; simp only [tape.nth, tape.right₀, int.coe_nat_zero, list_blank.nth_zero, list_blank.nth_succ, list_blank.head_cons, list_blank.tail_cons] @[simp] theorem tape.mk'_nth_nat {Γ} [inhabited Γ] (L R : list_blank Γ) (n : ℕ) : (tape.mk' L R).nth n = R.nth n := by rw [← tape.right₀_nth, tape.mk'_right₀] @[simp] theorem tape.move_left_nth {Γ} [inhabited Γ] : ∀ (T : tape Γ) (i : ℤ), (T.move dir.left).nth i = T.nth (i-1) | ⟨a, L, R⟩ -[1+ n] := (list_blank.nth_succ _ _).symm | ⟨a, L, R⟩ 0 := (list_blank.nth_zero _).symm | ⟨a, L, R⟩ 1 := (list_blank.nth_zero _).trans (list_blank.head_cons _ _) | ⟨a, L, R⟩ ((n+1:ℕ)+1) := begin rw add_sub_cancel, change (R.cons a).nth (n+1) = R.nth n, rw [list_blank.nth_succ, list_blank.tail_cons] end @[simp] theorem tape.move_right_nth {Γ} [inhabited Γ] (T : tape Γ) (i : ℤ) : (T.move dir.right).nth i = T.nth (i+1) := by conv {to_rhs, rw ← T.move_right_left}; rw [tape.move_left_nth, add_sub_cancel] @[simp] theorem tape.move_right_n_head {Γ} [inhabited Γ] (T : tape Γ) (i : ℕ) : ((tape.move dir.right)^[i] T).head = T.nth i := by induction i generalizing T; [refl, simp only [*, tape.move_right_nth, int.coe_nat_succ, iterate_succ]] /-- Replace the current value of the head on the tape. -/ def tape.write {Γ} [inhabited Γ] (b : Γ) (T : tape Γ) : tape Γ := {head := b, ..T} @[simp] theorem tape.write_self {Γ} [inhabited Γ] : ∀ (T : tape Γ), T.write T.1 = T := by rintro ⟨⟩; refl @[simp] theorem tape.write_nth {Γ} [inhabited Γ] (b : Γ) : ∀ (T : tape Γ) {i : ℤ}, (T.write b).nth i = if i = 0 then b else T.nth i | ⟨a, L, R⟩ 0 := rfl | ⟨a, L, R⟩ (n+1:ℕ) := rfl | ⟨a, L, R⟩ -[1+ n] := rfl @[simp] theorem tape.write_mk' {Γ} [inhabited Γ] (a b : Γ) (L R : list_blank Γ) : (tape.mk' L (R.cons a)).write b = tape.mk' L (R.cons b) := by simp only [tape.write, tape.mk', list_blank.head_cons, list_blank.tail_cons, eq_self_iff_true, and_self] /-- Apply a pointed map to a tape to change the alphabet. -/ def tape.map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) : tape Γ' := ⟨f T.1, T.2.map f, T.3.map f⟩ @[simp] theorem tape.map_fst {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') : ∀ (T : tape Γ), (T.map f).1 = f T.1 := by rintro ⟨⟩; refl @[simp] theorem tape.map_write {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (b : Γ) : ∀ (T : tape Γ), (T.write b).map f = (T.map f).write (f b) := by rintro ⟨⟩; refl @[simp] theorem tape.write_move_right_n {Γ} [inhabited Γ] (f : Γ → Γ) (L R : list_blank Γ) (n : ℕ) : ((tape.move dir.right)^[n] (tape.mk' L R)).write (f (R.nth n)) = ((tape.move dir.right)^[n] (tape.mk' L (R.modify_nth f n))) := begin induction n with n IH generalizing L R, { simp only [list_blank.nth_zero, list_blank.modify_nth, iterate_zero_apply], rw [← tape.write_mk', list_blank.cons_head_tail] }, simp only [list_blank.head_cons, list_blank.nth_succ, list_blank.modify_nth, tape.move_right_mk', list_blank.tail_cons, iterate_succ_apply, IH] end theorem tape.map_move {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) (d) : (T.move d).map f = (T.map f).move d := by cases T; cases d; simp only [tape.move, tape.map, list_blank.head_map, eq_self_iff_true, list_blank.map_cons, and_self, list_blank.tail_map] theorem tape.map_mk' {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (L R : list_blank Γ) : (tape.mk' L R).map f = tape.mk' (L.map f) (R.map f) := by simp only [tape.mk', tape.map, list_blank.head_map, eq_self_iff_true, and_self, list_blank.tail_map] theorem tape.map_mk₂ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (L R : list Γ) : (tape.mk₂ L R).map f = tape.mk₂ (L.map f) (R.map f) := by simp only [tape.mk₂, tape.map_mk', list_blank.map_mk] theorem tape.map_mk₁ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (tape.mk₁ l).map f = tape.mk₁ (l.map f) := tape.map_mk₂ _ _ _ /-- Run a state transition function `σ → option σ` "to completion". The return value is the last state returned before a `none` result. If the state transition function always returns `some`, then the computation diverges, returning `roption.none`. -/ def eval {σ} (f : σ → option σ) : σ → roption σ := pfun.fix (λ s, roption.some $ (f s).elim (sum.inl s) sum.inr) /-- The reflexive transitive closure of a state transition function. `reaches f a b` means there is a finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`. This relation permits zero steps of the state transition function. -/ def reaches {σ} (f : σ → option σ) : σ → σ → Prop := refl_trans_gen (λ a b, b ∈ f a) /-- The transitive closure of a state transition function. `reaches₁ f a b` means there is a nonempty finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`. This relation does not permit zero steps of the state transition function. -/ def reaches₁ {σ} (f : σ → option σ) : σ → σ → Prop := trans_gen (λ a b, b ∈ f a) theorem reaches₁_eq {σ} {f : σ → option σ} {a b c} (h : f a = f b) : reaches₁ f a c ↔ reaches₁ f b c := trans_gen.head'_iff.trans (trans_gen.head'_iff.trans $ by rw h).symm theorem reaches_total {σ} {f : σ → option σ} {a b c} : reaches f a b → reaches f a c → reaches f b c ∨ reaches f c b := refl_trans_gen.total_of_right_unique ⟨λ _ _ _, option.mem_unique⟩ theorem reaches₁_fwd {σ} {f : σ → option σ} {a b c} (h₁ : reaches₁ f a c) (h₂ : b ∈ f a) : reaches f b c := begin rcases trans_gen.head'_iff.1 h₁ with ⟨b', hab, hbc⟩, cases option.mem_unique hab h₂, exact hbc end /-- A variation on `reaches`. `reaches₀ f a b` holds if whenever `reaches₁ f b c` then `reaches₁ f a c`. This is a weaker property than `reaches` and is useful for replacing states with equivalent states without taking a step. -/ def reaches₀ {σ} (f : σ → option σ) (a b : σ) : Prop := ∀ c, reaches₁ f b c → reaches₁ f a c theorem reaches₀.trans {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h₂ : reaches₀ f b c) : reaches₀ f a c | d h₃ := h₁ _ (h₂ _ h₃) @[refl] theorem reaches₀.refl {σ} {f : σ → option σ} (a : σ) : reaches₀ f a a | b h := h theorem reaches₀.single {σ} {f : σ → option σ} {a b : σ} (h : b ∈ f a) : reaches₀ f a b | c h₂ := h₂.head h theorem reaches₀.head {σ} {f : σ → option σ} {a b c : σ} (h : b ∈ f a) (h₂ : reaches₀ f b c) : reaches₀ f a c := (reaches₀.single h).trans h₂ theorem reaches₀.tail {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h : c ∈ f b) : reaches₀ f a c := h₁.trans (reaches₀.single h) theorem reaches₀_eq {σ} {f : σ → option σ} {a b} (e : f a = f b) : reaches₀ f a b | d h := (reaches₁_eq e).2 h theorem reaches₁.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches₁ f a b) : reaches₀ f a b | c h₂ := h.trans h₂ theorem reaches.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches f a b) : reaches₀ f a b | c h₂ := h₂.trans_right h theorem reaches₀.tail' {σ} {f : σ → option σ} {a b c : σ} (h : reaches₀ f a b) (h₂ : c ∈ f b) : reaches₁ f a c := h _ (trans_gen.single h₂) /-- (co-)Induction principle for `eval`. If a property `C` holds of any point `a` evaluating to `b` which is either terminal (meaning `a = b`) or where the next point also satisfies `C`, then it holds of any point where `eval f a` evaluates to `b`. This formalizes the notion that if `eval f a` evaluates to `b` then it reaches terminal state `b` in finitely many steps. -/ @[elab_as_eliminator] def eval_induction {σ} {f : σ → option σ} {b : σ} {C : σ → Sort*} {a : σ} (h : b ∈ eval f a) (H : ∀ a, b ∈ eval f a → (∀ a', b ∈ eval f a' → f a = some a' → C a') → C a) : C a := pfun.fix_induction h (λ a' ha' h', H _ ha' $ λ b' hb' e, h' _ hb' $ roption.mem_some_iff.2 $ by rw e; refl) theorem mem_eval {σ} {f : σ → option σ} {a b} : b ∈ eval f a ↔ reaches f a b ∧ f b = none := ⟨λ h, begin refine eval_induction h (λ a h IH, _), cases e : f a with a', { rw roption.mem_unique h (pfun.mem_fix_iff.2 $ or.inl $ roption.mem_some_iff.2 $ by rw e; refl), exact ⟨refl_trans_gen.refl, e⟩ }, { rcases pfun.mem_fix_iff.1 h with h | ⟨_, h, h'⟩; rw e at h; cases roption.mem_some_iff.1 h, cases IH a' h' (by rwa e) with h₁ h₂, exact ⟨refl_trans_gen.head e h₁, h₂⟩ } end, λ ⟨h₁, h₂⟩, begin refine refl_trans_gen.head_induction_on h₁ _ (λ a a' h _ IH, _), { refine pfun.mem_fix_iff.2 (or.inl _), rw h₂, apply roption.mem_some }, { refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH⟩), rw show f a = _, from h, apply roption.mem_some } end⟩ theorem eval_maximal₁ {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) (c) : ¬ reaches₁ f b c | bc := let ⟨ab, b0⟩ := mem_eval.1 h, ⟨b', h', _⟩ := trans_gen.head'_iff.1 bc in by cases b0.symm.trans h' theorem eval_maximal {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) {c} : reaches f b c ↔ c = b := let ⟨ab, b0⟩ := mem_eval.1 h in refl_trans_gen_iff_eq $ λ b' h', by cases b0.symm.trans h' theorem reaches_eval {σ} {f : σ → option σ} {a b} (ab : reaches f a b) : eval f a = eval f b := roption.ext $ λ c, ⟨λ h, let ⟨ac, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨(or_iff_left_of_imp $ by exact λ cb, (eval_maximal h).1 cb ▸ refl_trans_gen.refl).1 (reaches_total ab ac), c0⟩, λ h, let ⟨bc, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨ab.trans bc, c0⟩,⟩ /-- Given a relation `tr : σ₁ → σ₂ → Prop` between state spaces, and state transition functions `f₁ : σ₁ → option σ₁` and `f₂ : σ₂ → option σ₂`, `respects f₁ f₂ tr` means that if `tr a₁ a₂` holds initially and `f₁` takes a step to `a₂` then `f₂` will take one or more steps before reaching a state `b₂` satisfying `tr a₂ b₂`, and if `f₁ a₁` terminates then `f₂ a₂` also terminates. Such a relation `tr` is also known as a refinement. -/ def respects {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂ → Prop) := ∀ ⦃a₁ a₂⦄, tr a₁ a₂ → (match f₁ a₁ with | some b₁ := ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ | none := f₂ a₂ = none end : Prop) theorem tr_reaches₁ {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches₁ f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ := begin induction ab with c₁ ac c₁ d₁ ac cd IH, { have := H aa, rwa (show f₁ a₁ = _, from ac) at this }, { rcases IH with ⟨c₂, cc, ac₂⟩, have := H cc, rw (show f₁ c₁ = _, from cd) at this, rcases this with ⟨d₂, dd, cd₂⟩, exact ⟨_, dd, ac₂.trans cd₂⟩ } end theorem tr_reaches {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches f₂ a₂ b₂ := begin rcases refl_trans_gen_iff_eq_or_trans_gen.1 ab with rfl | ab, { exact ⟨_, aa, refl_trans_gen.refl⟩ }, { exact let ⟨b₂, bb, h⟩ := tr_reaches₁ H aa ab in ⟨b₂, bb, h.to_refl⟩ } end theorem tr_reaches_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₂} (ab : reaches f₂ a₂ b₂) : ∃ c₁ c₂, reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ reaches f₁ a₁ c₁ := begin induction ab with c₂ d₂ ac cd IH, { exact ⟨_, _, refl_trans_gen.refl, aa, refl_trans_gen.refl⟩ }, { rcases IH with ⟨e₁, e₂, ce, ee, ae⟩, rcases refl_trans_gen.cases_head ce with rfl | ⟨d', cd', de⟩, { have := H ee, revert this, cases eg : f₁ e₁ with g₁; simp only [respects, and_imp, exists_imp_distrib], { intro c0, cases cd.symm.trans c0 }, { intros g₂ gg cg, rcases trans_gen.head'_iff.1 cg with ⟨d', cd', dg⟩, cases option.mem_unique cd cd', exact ⟨_, _, dg, gg, ae.tail eg⟩ } }, { cases option.mem_unique cd cd', exact ⟨_, _, de, ee, ae⟩ } } end theorem tr_eval {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₁ a₂} (aa : tr a₁ a₂) (ab : b₁ ∈ eval f₁ a₁) : ∃ b₂, tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches H aa ab with ⟨b₂, bb, ab⟩, refine ⟨_, bb, mem_eval.2 ⟨ab, _⟩⟩, have := H bb, rwa b0 at this end theorem tr_eval_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₂ a₂} (aa : tr a₁ a₂) (ab : b₂ ∈ eval f₂ a₂) : ∃ b₁, tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches_rev H aa ab with ⟨c₁, c₂, bc, cc, ac⟩, cases (refl_trans_gen_iff_eq (by exact option.eq_none_iff_forall_not_mem.1 b0)).1 bc, refine ⟨_, cc, mem_eval.2 ⟨ac, _⟩⟩, have := H cc, cases f₁ c₁ with d₁, {refl}, rcases this with ⟨d₂, dd, bd⟩, rcases trans_gen.head'_iff.1 bd with ⟨e, h, _⟩, cases b0.symm.trans h end theorem tr_eval_dom {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) : (eval f₂ a₂).dom ↔ (eval f₁ a₁).dom := ⟨λ h, let ⟨b₂, tr, h, _⟩ := tr_eval_rev H aa ⟨h, rfl⟩ in h, λ h, let ⟨b₂, tr, h, _⟩ := tr_eval H aa ⟨h, rfl⟩ in h⟩ /-- A simpler version of `respects` when the state transition relation `tr` is a function. -/ def frespects {σ₁ σ₂} (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) : option σ₁ → Prop | (some b₁) := reaches₁ f₂ a₂ (tr b₁) | none := f₂ a₂ = none theorem frespects_eq {σ₁ σ₂} {f₂ : σ₂ → option σ₂} {tr : σ₁ → σ₂} {a₂ b₂} (h : f₂ a₂ = f₂ b₂) : ∀ {b₁}, frespects f₂ tr a₂ b₁ ↔ frespects f₂ tr b₂ b₁ | (some b₁) := reaches₁_eq h | none := by unfold frespects; rw h theorem fun_respects {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂} : respects f₁ f₂ (λ a b, tr a = b) ↔ ∀ ⦃a₁⦄, frespects f₂ tr (tr a₁) (f₁ a₁) := forall_congr $ λ a₁, by cases f₁ a₁; simp only [frespects, respects, exists_eq_left', forall_eq'] theorem tr_eval' {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (H : respects f₁ f₂ (λ a b, tr a = b)) (a₁) : eval f₂ (tr a₁) = tr <$> eval f₁ a₁ := roption.ext $ λ b₂, ⟨λ h, let ⟨b₁, bb, hb⟩ := tr_eval_rev H rfl h in (roption.mem_map_iff _).2 ⟨b₁, hb, bb⟩, λ h, begin rcases (roption.mem_map_iff _).1 h with ⟨b₁, ab, bb⟩, rcases tr_eval H rfl ab with ⟨_, rfl, h⟩, rwa bb at h end⟩ /-! ## The TM0 model A TM0 turing machine is essentially a Post-Turing machine, adapted for type theory. A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function `Λ → Γ → option (Λ × stmt)`, where a `stmt` can be either `move left`, `move right` or `write a` for `a : Γ`. The machine works over a "tape", a doubly-infinite sequence of elements of `Γ`, and an instantaneous configuration, `cfg`, is a label `q : Λ` indicating the current internal state of the machine, and a `tape Γ` (which is essentially `ℤ →₀ Γ`). The evolution is described by the `step` function: * If `M q T.head = none`, then the machine halts. * If `M q T.head = some (q', s)`, then the machine performs action `s : stmt` and then transitions to state `q'`. The initial state takes a `list Γ` and produces a `tape Γ` where the head of the list is the head of the tape and the rest of the list extends to the right, with the left side all blank. The final state takes the entire right side of the tape right or equal to the current position of the machine. (This is actually a `list_blank Γ`, not a `list Γ`, because we don't know, at this level of generality, where the output ends. If equality to `default Γ` is decidable we can trim the list to remove the infinite tail of blanks.) -/ namespace TM0 section parameters (Γ : Type*) [inhabited Γ] -- type of tape symbols parameters (Λ : Type*) [inhabited Λ] -- type of "labels" or TM states /-- A Turing machine "statement" is just a command to either move left or right, or write a symbol on the tape. -/ inductive stmt | move : dir → stmt | write : Γ → stmt instance stmt.inhabited : inhabited stmt := ⟨stmt.write (default _)⟩ /-- A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function which, given the current state `q : Λ` and the tape head `a : Γ`, either halts (returns `none`) or returns a new state `q' : Λ` and a `stmt` describing what to do, either a move left or right, or a write command. Both `Λ` and `Γ` are required to be inhabited; the default value for `Γ` is the "blank" tape value, and the default value of `Λ` is the initial state. -/ @[nolint unused_arguments] -- [inhabited Λ]: this is a deliberate addition, see comment def machine := Λ → Γ → option (Λ × stmt) instance machine.inhabited : inhabited machine := by unfold machine; apply_instance /-- The configuration state of a Turing machine during operation consists of a label (machine state), and a tape, represented in the form `(a, L, R)` meaning the tape looks like `L.rev ++ [a] ++ R` with the machine currently reading the `a`. The lists are automatically extended with blanks as the machine moves around. -/ structure cfg := (q : Λ) (tape : tape Γ) instance cfg.inhabited : inhabited cfg := ⟨⟨default _, default _⟩⟩ parameters {Γ Λ} /-- Execution semantics of the Turing machine. -/ def step (M : machine) : cfg → option cfg | ⟨q, T⟩ := (M q T.1).map (λ ⟨q', a⟩, ⟨q', match a with | stmt.move d := T.move d | stmt.write a := T.write a end⟩) /-- The statement `reaches M s₁ s₂` means that `s₂` is obtained starting from `s₁` after a finite number of steps from `s₂`. -/ def reaches (M : machine) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) /-- The initial configuration. -/ def init (l : list Γ) : cfg := ⟨default Λ, tape.mk₁ l⟩ /-- Evaluate a Turing machine on initial input to a final state, if it terminates. -/ def eval (M : machine) (l : list Γ) : roption (list_blank Γ) := (eval (step M) (init l)).map (λ c, c.tape.right₀) /-- The raw definition of a Turing machine does not require that `Γ` and `Λ` are finite, and in practice we will be interested in the infinite `Λ` case. We recover instead a notion of "effectively finite" Turing machines, which only make use of a finite subset of their states. We say that a set `S ⊆ Λ` supports a Turing machine `M` if `S` is closed under the transition function and contains the initial state. -/ def supports (M : machine) (S : set Λ) := default Λ ∈ S ∧ ∀ {q a q' s}, (q', s) ∈ M q a → q ∈ S → q' ∈ S theorem step_supports (M : machine) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.q ∈ S → c'.q ∈ S | ⟨q, T⟩ c' h₁ h₂ := begin rcases option.map_eq_some'.1 h₁ with ⟨⟨q', a⟩, h, rfl⟩, exact ss.2 h h₂, end theorem univ_supports (M : machine) : supports M set.univ := ⟨trivial, λ q a q' s h₁ h₂, trivial⟩ end section variables {Γ : Type*} [inhabited Γ] variables {Γ' : Type*} [inhabited Γ'] variables {Λ : Type*} [inhabited Λ] variables {Λ' : Type*} [inhabited Λ'] /-- Map a TM statement across a function. This does nothing to move statements and maps the write values. -/ def stmt.map (f : pointed_map Γ Γ') : stmt Γ → stmt Γ' | (stmt.move d) := stmt.move d | (stmt.write a) := stmt.write (f a) /-- Map a configuration across a function, given `f : Γ → Γ'` a map of the alphabets and `g : Λ → Λ'` a map of the machine states. -/ def cfg.map (f : pointed_map Γ Γ') (g : Λ → Λ') : cfg Γ Λ → cfg Γ' Λ' | ⟨q, T⟩ := ⟨g q, T.map f⟩ variables (M : machine Γ Λ) (f₁ : pointed_map Γ Γ') (f₂ : pointed_map Γ' Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ) /-- Because the state transition function uses the alphabet and machine states in both the input and output, to map a machine from one alphabet and machine state space to another we need functions in both directions, essentially an `equiv` without the laws. -/ def machine.map : machine Γ' Λ' | q l := (M (g₂ q) (f₂ l)).map (prod.map g₁ (stmt.map f₁)) theorem machine.map_step {S : set Λ} (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : ∀ c : cfg Γ Λ, c.q ∈ S → (step M c).map (cfg.map f₁ g₁) = step (M.map f₁ f₂ g₁ g₂) (cfg.map f₁ g₁ c) | ⟨q, T⟩ h := begin unfold step machine.map cfg.map, simp only [turing.tape.map_fst, g₂₁ q h, f₂₁ _], rcases M q T.1 with _|⟨q', d|a⟩, {refl}, { simp only [step, cfg.map, option.map_some', tape.map_move f₁], refl }, { simp only [step, cfg.map, option.map_some', tape.map_write], refl } end theorem map_init (g₁ : pointed_map Λ Λ') (l : list Γ) : (init l).map f₁ g₁ = init (l.map f₁) := congr (congr_arg cfg.mk g₁.map_pt) (tape.map_mk₁ _ _) theorem machine.map_respects (g₁ : pointed_map Λ Λ') (g₂ : Λ' → Λ) {S} (ss : supports M S) (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : respects (step M) (step (M.map f₁ f₂ g₁ g₂)) (λ a b, a.q ∈ S ∧ cfg.map f₁ g₁ a = b) | c _ ⟨cs, rfl⟩ := begin cases e : step M c with c'; unfold respects, { rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], refl }, { refine ⟨_, ⟨step_supports M ss e cs, rfl⟩, trans_gen.single _⟩, rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], exact rfl } end end end TM0 /-! ## The TM1 model The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `stmt`. Most of the regular commands are allowed to use the current value `a` of the local variables and the value `T.head` on the tape to calculate what to write or how to change local state, but the statements themselves have a fixed structure. The `stmt`s can be as follows: * `move d q`: move left or right, and then do `q` * `write (f : Γ → σ → Γ) q`: write `f a T.head` to the tape, then do `q` * `load (f : Γ → σ → σ) q`: change the internal state to `f a T.head` * `branch (f : Γ → σ → bool) qtrue qfalse`: If `f a T.head` is true, do `qtrue`, else `qfalse` * `goto (f : Γ → σ → Λ)`: Go to label `f a T.head` * `halt`: Transition to the halting state, which halts on the following step Note that here most statements do not have labels; `goto` commands can only go to a new function. Only the `goto` and `halt` statements actually take a step; the rest is done by recursion on statements and so take 0 steps. (There is a uniform bound on many statements can be executed before the next `goto`, so this is an `O(1)` speedup with the constant depending on the machine.) The `halt` command has a one step stutter before actually halting so that any changes made before the halt have a chance to be "committed", since the `eval` relation uses the final configuration before the halt as the output, and `move` and `write` etc. take 0 steps in this model. -/ namespace TM1 section parameters (Γ : Type*) [inhabited Γ] -- Type of tape symbols parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `stmt`, which can either be a `move` or `write` command, a `branch` (if statement based on the current tape value), a `load` (set the variable value), a `goto` (call another function), or `halt`. Note that here most statements do not have labels; `goto` commands can only go to a new function. All commands have access to the variable value and current tape value. -/ inductive stmt | move : dir → stmt → stmt | write : (Γ → σ → Γ) → stmt → stmt | load : (Γ → σ → σ) → stmt → stmt | branch : (Γ → σ → bool) → stmt → stmt → stmt | goto : (Γ → σ → Λ) → stmt | halt : stmt open stmt instance stmt.inhabited : inhabited stmt := ⟨halt⟩ /-- The configuration of a TM1 machine is given by the currently evaluating statement, the variable store value, and the tape. -/ structure cfg := (l : option Λ) (var : σ) (tape : tape Γ) instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default _, default _, default _⟩⟩ parameters {Γ Λ σ} /-- The semantics of TM1 evaluation. -/ def step_aux : stmt → σ → tape Γ → cfg | (move d q) v T := step_aux q v (T.move d) | (write a q) v T := step_aux q v (T.write (a T.1 v)) | (load s q) v T := step_aux q (s T.1 v) T | (branch p q₁ q₂) v T := cond (p T.1 v) (step_aux q₁ v T) (step_aux q₂ v T) | (goto l) v T := ⟨some (l T.1 v), v, T⟩ | halt v T := ⟨none, v, T⟩ /-- The state transition function. -/ def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, T⟩ := none | ⟨some l, v, T⟩ := some (step_aux (M l) v T) /-- A set `S` of labels supports the statement `q` if all the `goto` statements in `q` refer only to other functions in `S`. -/ def supports_stmt (S : finset Λ) : stmt → Prop | (move d q) := supports_stmt q | (write a q) := supports_stmt q | (load s q) := supports_stmt q | (branch p q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ a v, l a v ∈ S | halt := true open_locale classical /-- The subterm closure of a statement. -/ noncomputable def stmts₁ : stmt → finset stmt | Q@(move d q) := insert Q (stmts₁ q) | Q@(write a q) := insert Q (stmts₁ q) | Q@(load s q) := insert Q (stmts₁ q) | Q@(branch p q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self] theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.mem_union, finset.mem_singleton] at h₁₂, iterate 3 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ $ IH₁ h₁₂) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ $ IH₂ h₁₂) } }, case TM1.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM1.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.mem_singleton] at h hs, iterate 3 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM1.stmt.goto : l { subst h, exact hs }, case TM1.stmt.halt { subst h, trivial } end /-- The set of all statements in a turing machine, plus one extra value `none` representing the halt state. This is used in the TM1 to TM0 reduction. -/ noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bUnion (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ variable [inhabited Λ] /-- A set `S` of labels supports machine `M` if all the `goto` statements in the functions in `S` refer only to other functions in `S`. -/ def supports (M : Λ → stmt) (S : finset Λ) := default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T; intro hs, iterate 3 { exact IH _ _ hs }, case TM1.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p T.1 v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM1.stmt.goto { exact finset.some_mem_insert_none.2 (hs _ _) }, case TM1.stmt.halt { apply multiset.mem_cons_self } end variable [inhabited σ] /-- The initial state, given a finite input that is placed on the tape starting at the TM head and going to the right. -/ def init (l : list Γ) : cfg := ⟨some (default _), default _, tape.mk₁ l⟩ /-- Evaluate a TM to completion, resulting in an output list on the tape (with an indeterminate number of blanks on the end). -/ def eval (M : Λ → stmt) (l : list Γ) : roption (list_blank Γ) := (eval (step M) (init l)).map (λ c, c.tape.right₀) end end TM1 /-! ## TM1 emulator in TM0 To prove that TM1 computable functions are TM0 computable, we need to reduce each TM1 program to a TM0 program. So suppose a TM1 program is given. We take the following: * The alphabet `Γ` is the same for both TM1 and TM0 * The set of states `Λ'` is defined to be `option stmt₁ × σ`, that is, a TM1 statement or `none` representing halt, and the possible settings of the internal variables. Note that this is an infinite set, because `stmt₁` is infinite. This is okay because we assume that from the initial TM1 state, only finitely many other labels are reachable, and there are only finitely many statements that appear in all of these functions. Even though `stmt₁` contains a statement called `halt`, we must separate it from `none` (`some halt` steps to `none` and `none` actually halts) because there is a one step stutter in the TM1 semantics. -/ namespace TM1to0 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := TM1.stmt Γ Λ σ local notation `cfg₁` := TM1.cfg Γ Λ σ local notation `stmt₀` := TM0.stmt Γ parameters (M : Λ → stmt₁) include M /-- The base machine state space is a pair of an `option stmt₁` representing the current program to be executed, or `none` for the halt state, and a `σ` which is the local state (stored in the TM, not the tape). Because there are an infinite number of programs, this state space is infinite, but for a finitely supported TM1 machine and a finite type `σ`, only finitely many of these states are reachable. -/ @[nolint unused_arguments] -- [inhabited Λ] [inhabited σ] (M : Λ → stmt₁): We need the M assumption -- because of the inhabited instance, but we could avoid the inhabited instances on Λ and σ here. -- But they are parameters so we cannot easily skip them for just this definition. def Λ' := option stmt₁ × σ instance : inhabited Λ' := ⟨(some (M (default _)), default _)⟩ open TM0.stmt /-- The core TM1 → TM0 translation function. Here `s` is the current value on the tape, and the `stmt₁` is the TM1 statement to translate, with local state `v : σ`. We evaluate all regular instructions recursively until we reach either a `move` or `write` command, or a `goto`; in the latter case we emit a dummy `write s` step and transition to the new target location. -/ def tr_aux (s : Γ) : stmt₁ → σ → Λ' × stmt₀ | (TM1.stmt.move d q) v := ((some q, v), move d) | (TM1.stmt.write a q) v := ((some q, v), write (a s v)) | (TM1.stmt.load a q) v := tr_aux q (a s v) | (TM1.stmt.branch p q₁ q₂) v := cond (p s v) (tr_aux q₁ v) (tr_aux q₂ v) | (TM1.stmt.goto l) v := ((some (M (l s v)), v), write s) | TM1.stmt.halt v := ((none, v), write s) local notation `cfg₀` := TM0.cfg Γ Λ' /-- The translated TM0 machine (given the TM1 machine input). -/ def tr : TM0.machine Γ Λ' | (none, v) s := none | (some q, v) s := some (tr_aux s q v) /-- Translate configurations from TM1 to TM0. -/ def tr_cfg : cfg₁ → cfg₀ | ⟨l, v, T⟩ := ⟨(l.map M, v), T⟩ theorem tr_respects : respects (TM1.step M) (TM0.step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, T⟩, begin cases l₁ with l₁, {exact rfl}, unfold tr_cfg TM1.step frespects option.map function.comp option.bind, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T, case TM1.stmt.move : d q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.write : a q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.load : a q IH { exact (reaches₁_eq (by refl)).2 (IH _ _) }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold TM1.step_aux, cases e : p T.1 v, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₂ _ _) }, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₁ _ _) } }, iterate 2 { exact trans_gen.single (congr_arg some (congr (congr_arg TM0.cfg.mk rfl) (tape.write_self T))) } end theorem tr_eval (l : list Γ) : TM0.eval tr l = TM1.eval M l := (congr_arg _ (tr_eval' _ _ _ tr_respects ⟨some _, _, _⟩)).trans begin rw [roption.map_eq_map, roption.map_map, TM1.eval], congr' with ⟨⟩, refl end variables [fintype σ] /-- Given a finite set of accessible `Λ` machine states, there is a finite set of accessible machine states in the target (even though the type `Λ'` is infinite). -/ noncomputable def tr_stmts (S : finset Λ) : finset Λ' := (TM1.stmts M S).product finset.univ open_locale classical local attribute [simp] TM1.stmts₁_self theorem tr_supports {S : finset Λ} (ss : TM1.supports M S) : TM0.supports tr (↑(tr_stmts S)) := ⟨finset.mem_product.2 ⟨finset.some_mem_insert_none.2 (finset.mem_bUnion.2 ⟨_, ss.1, TM1.stmts₁_self⟩), finset.mem_univ _⟩, λ q a q' s h₁ h₂, begin rcases q with ⟨_|q, v⟩, {cases h₁}, cases q' with q' v', simp only [tr_stmts, finset.mem_coe, finset.mem_product, finset.mem_univ, and_true] at h₂ ⊢, cases q', {exact multiset.mem_cons_self _ _}, simp only [tr, option.mem_def] at h₁, have := TM1.stmts_supports_stmt ss h₂, revert this, induction q generalizing v; intro hs, case TM1.stmt.move : d q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.write : b q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.load : b q IH { refine IH (TM1.stmts_trans _ h₂) _ h₁ hs, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { change cond (p a v) _ _ = ((some q', v'), s) at h₁, cases p a v, { refine IH₂ (TM1.stmts_trans _ h₂) _ h₁ hs.2, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_right _ TM1.stmts₁_self) }, { refine IH₁ (TM1.stmts_trans _ h₂) _ h₁ hs.1, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_left _ TM1.stmts₁_self) } }, case TM1.stmt.goto : l { cases h₁, exact finset.some_mem_insert_none.2 (finset.mem_bUnion.2 ⟨_, hs _ _, TM1.stmts₁_self⟩) }, case TM1.stmt.halt { cases h₁ } end⟩ end end TM1to0 /-! ## TM1(Γ) emulator in TM1(bool) The most parsimonious Turing machine model that is still Turing complete is `TM0` with `Γ = bool`. Because our construction in the previous section reducing `TM1` to `TM0` doesn't change the alphabet, we can do the alphabet reduction on `TM1` instead of `TM0` directly. The basic idea is to use a bijection between `Γ` and a subset of `vector bool n`, where `n` is a fixed constant. Each tape element is represented as a block of `n` bools. Whenever the machine wants to read a symbol from the tape, it traverses over the block, performing `n` `branch` instructions to each any of the `2^n` results. For the `write` instruction, we have to use a `goto` because we need to follow a different code path depending on the local state, which is not available in the TM1 model, so instead we jump to a label computed using the read value and the local state, which performs the writing and returns to normal execution. Emulation overhead is `O(1)`. If not for the above `write` behavior it would be 1-1 because we are exploiting the 0-step behavior of regular commands to avoid taking steps, but there are nevertheless a bounded number of `write` calls between `goto` statements because TM1 statements are finitely long. -/ namespace TM1to1 open TM1 section parameters {Γ : Type*} [inhabited Γ] theorem exists_enc_dec [fintype Γ] : ∃ n (enc : Γ → vector bool n) (dec : vector bool n → Γ), enc (default _) = vector.repeat ff n ∧ ∀ a, dec (enc a) = a := begin rcases fintype.exists_equiv_fin Γ with ⟨n, ⟨F⟩⟩, let G : fin n ↪ fin n → bool := ⟨λ a b, a = b, λ a b h, of_to_bool_true $ (congr_fun h b).trans $ to_bool_tt rfl⟩, let H := (F.to_embedding.trans G).trans (equiv.vector_equiv_fin _ _).symm.to_embedding, classical, let enc := H.set_value (default _) (vector.repeat ff n), exact ⟨_, enc, function.inv_fun enc, H.set_value_eq _ _, function.left_inverse_inv_fun enc.2⟩ end parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := stmt Γ Λ σ local notation `cfg₁` := cfg Γ Λ σ /-- The configuration state of the TM. -/ inductive Λ' : Type (max u_1 u_2 u_3) | normal : Λ → Λ' | write : Γ → stmt₁ → Λ' instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩ local notation `stmt'` := stmt bool Λ' σ local notation `cfg'` := cfg bool Λ' σ /-- Read a vector of length `n` from the tape. -/ def read_aux : ∀ n, (vector bool n → stmt') → stmt' | 0 f := f vector.nil | (i+1) f := stmt.branch (λ a s, a) (stmt.move dir.right $ read_aux i (λ v, f (tt ::ᵥ v))) (stmt.move dir.right $ read_aux i (λ v, f (ff ::ᵥ v))) parameters {n : ℕ} (enc : Γ → vector bool n) (dec : vector bool n → Γ) /-- A move left or right corresponds to `n` moves across the super-cell. -/ def move (d : dir) (q : stmt') : stmt' := (stmt.move d)^[n] q /-- To read a symbol from the tape, we use `read_aux` to traverse the symbol, then return to the original position with `n` moves to the left. -/ def read (f : Γ → stmt') : stmt' := read_aux n (λ v, move dir.left $ f (dec v)) /-- Write a list of bools on the tape. -/ def write : list bool → stmt' → stmt' | [] q := q | (a :: l) q := stmt.write (λ _ _, a) $ stmt.move dir.right $ write l q /-- Translate a normal instruction. For the `write` command, we use a `goto` indirection so that we can access the current value of the tape. -/ def tr_normal : stmt₁ → stmt' | (stmt.move d q) := move d $ tr_normal q | (stmt.write f q) := read $ λ a, stmt.goto $ λ _ s, Λ'.write (f a s) q | (stmt.load f q) := read $ λ a, stmt.load (λ _ s, f a s) $ tr_normal q | (stmt.branch p q₁ q₂) := read $ λ a, stmt.branch (λ _ s, p a s) (tr_normal q₁) (tr_normal q₂) | (stmt.goto l) := read $ λ a, stmt.goto $ λ _ s, Λ'.normal (l a s) | stmt.halt := stmt.halt theorem step_aux_move (d q v T) : step_aux (move d q) v T = step_aux q v ((tape.move d)^[n] T) := begin suffices : ∀ i, step_aux (stmt.move d^[i] q) v T = step_aux q v (tape.move d^[i] T), from this n, intro, induction i with i IH generalizing T, {refl}, rw [iterate_succ', step_aux, IH, iterate_succ] end theorem supports_stmt_move {S d q} : supports_stmt S (move d q) = supports_stmt S q := suffices ∀ {i}, supports_stmt S (stmt.move d^[i] q) = _, from this, by intro; induction i generalizing q; simp only [*, iterate]; refl theorem supports_stmt_write {S l q} : supports_stmt S (write l q) = supports_stmt S q := by induction l with a l IH; simp only [write, supports_stmt, *] theorem supports_stmt_read {S} : ∀ {f : Γ → stmt'}, (∀ a, supports_stmt S (f a)) → supports_stmt S (read f) := suffices ∀ i (f : vector bool i → stmt'), (∀ v, supports_stmt S (f v)) → supports_stmt S (read_aux i f), from λ f hf, this n _ (by intro; simp only [supports_stmt_move, hf]), λ i f hf, begin induction i with i IH, {exact hf _}, split; apply IH; intro; apply hf, end parameter (enc0 : enc (default _) = vector.repeat ff n) section parameter {enc} include enc0 /-- The low level tape corresponding to the given tape over alphabet `Γ`. -/ def tr_tape' (L R : list_blank Γ) : tape bool := begin refine tape.mk' (L.bind (λ x, (enc x).to_list.reverse) ⟨n, _⟩) (R.bind (λ x, (enc x).to_list) ⟨n, _⟩); simp only [enc0, vector.repeat, list.reverse_repeat, bool.default_bool, vector.to_list_mk] end /-- The low level tape corresponding to the given tape over alphabet `Γ`. -/ def tr_tape (T : tape Γ) : tape bool := tr_tape' T.left T.right₀ theorem tr_tape_mk' (L R : list_blank Γ) : tr_tape (tape.mk' L R) = tr_tape' L R := by simp only [tr_tape, tape.mk'_left, tape.mk'_right₀] end parameters (M : Λ → stmt₁) /-- The top level program. -/ def tr : Λ' → stmt' | (Λ'.normal l) := tr_normal (M l) | (Λ'.write a q) := write (enc a).to_list $ move dir.left $ tr_normal q /-- The machine configuration translation. -/ def tr_cfg : cfg₁ → cfg' | ⟨l, v, T⟩ := ⟨l.map Λ'.normal, v, tr_tape T⟩ parameter {enc} include enc0 theorem tr_tape'_move_left (L R) : (tape.move dir.left)^[n] (tr_tape' L R) = (tr_tape' L.tail (R.cons L.head)) := begin obtain ⟨a, L, rfl⟩ := L.exists_cons, simp only [tr_tape', list_blank.cons_bind, list_blank.head_cons, list_blank.tail_cons], suffices : ∀ {L' R' l₁ l₂} (e : vector.to_list (enc a) = list.reverse_core l₁ l₂), tape.move dir.left^[l₁.length] (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) = tape.mk' L' (list_blank.append (vector.to_list (enc a)) R'), { simpa only [list.length_reverse, vector.to_list_length] using this (list.reverse_reverse _).symm }, intros, induction l₁ with b l₁ IH generalizing l₂, { cases e, refl }, simp only [list.length, list.cons_append, iterate_succ_apply], convert IH e, simp only [list_blank.tail_cons, list_blank.append, tape.move_left_mk', list_blank.head_cons] end theorem tr_tape'_move_right (L R) : (tape.move dir.right)^[n] (tr_tape' L R) = (tr_tape' (L.cons R.head) R.tail) := begin suffices : ∀ i L, (tape.move dir.right)^[i] ((tape.move dir.left)^[i] L) = L, { refine (eq.symm _).trans (this n _), simp only [tr_tape'_move_left, list_blank.cons_head_tail, list_blank.head_cons, list_blank.tail_cons] }, intros, induction i with i IH, {refl}, rw [iterate_succ_apply, iterate_succ_apply', tape.move_left_right, IH] end theorem step_aux_write (q v a b L R) : step_aux (write (enc a).to_list q) v (tr_tape' L (list_blank.cons b R)) = step_aux q v (tr_tape' (list_blank.cons a L) R) := begin simp only [tr_tape', list.cons_bind, list.append_assoc], suffices : ∀ {L' R'} (l₁ l₂ l₂' : list bool) (e : l₂'.length = l₂.length), step_aux (write l₂ q) v (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂' R')) = step_aux q v (tape.mk' (L'.append (list.reverse_core l₂ l₁)) R'), { convert this [] _ _ ((enc b).2.trans (enc a).2.symm); rw list_blank.cons_bind; refl }, clear a b L R, intros, induction l₂ with a l₂ IH generalizing l₁ l₂', { cases list.length_eq_zero.1 e, refl }, cases l₂' with b l₂'; injection e with e, dunfold write step_aux, convert IH _ _ e using 1, simp only [list_blank.head_cons, list_blank.tail_cons, list_blank.append, tape.move_right_mk', tape.write_mk'] end parameters (encdec : ∀ a, dec (enc a) = a) include encdec theorem step_aux_read (f v L R) : step_aux (read f) v (tr_tape' L R) = step_aux (f R.head) v (tr_tape' L R) := begin suffices : ∀ f, step_aux (read_aux n f) v (tr_tape' enc0 L R) = step_aux (f (enc R.head)) v (tr_tape' enc0 (L.cons R.head) R.tail), { rw [read, this, step_aux_move, encdec, tr_tape'_move_left enc0], simp only [list_blank.head_cons, list_blank.cons_head_tail, list_blank.tail_cons] }, obtain ⟨a, R, rfl⟩ := R.exists_cons, simp only [list_blank.head_cons, list_blank.tail_cons, tr_tape', list_blank.cons_bind, list_blank.append_assoc], suffices : ∀ i f L' R' l₁ l₂ h, step_aux (read_aux i f) v (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) = step_aux (f ⟨l₂, h⟩) v (tape.mk' (list_blank.append (l₂.reverse_core l₁) L') R'), { intro f, convert this n f _ _ _ _ (enc a).2; simp }, clear f L a R, intros, subst i, induction l₂ with a l₂ IH generalizing l₁, {refl}, transitivity step_aux (read_aux l₂.length (λ v, f (a ::ᵥ v))) v (tape.mk' ((L'.append l₁).cons a) (R'.append l₂)), { dsimp [read_aux, step_aux], simp, cases a; refl }, rw [← list_blank.append, IH], refl end theorem tr_respects : respects (step M) (step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, T⟩, begin obtain ⟨L, R, rfl⟩ := T.exists_mk', cases l₁ with l₁, {exact rfl}, suffices : ∀ q R, reaches (step (tr enc dec M)) (step_aux (tr_normal dec q) v (tr_tape' enc0 L R)) (tr_cfg enc0 (step_aux q v (tape.mk' L R))), { refine trans_gen.head' rfl _, rw tr_tape_mk', exact this _ R }, clear R l₁, intros, induction q with _ q IH _ q IH _ q IH generalizing v L R, case TM1.stmt.move : d q IH { cases d; simp only [tr_normal, iterate, step_aux_move, step_aux, list_blank.head_cons, tape.move_left_mk', list_blank.cons_head_tail, list_blank.tail_cons, tr_tape'_move_left enc0, tr_tape'_move_right enc0]; apply IH }, case TM1.stmt.write : f q IH { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux], refine refl_trans_gen.head rfl _, obtain ⟨a, R, rfl⟩ := R.exists_cons, rw [tr, tape.mk'_head, step_aux_write, list_blank.head_cons, step_aux_move, tr_tape'_move_left enc0, list_blank.head_cons, list_blank.tail_cons, tape.write_mk'], apply IH }, case TM1.stmt.load : a q IH { simp only [tr_normal, step_aux_read dec enc0 encdec], apply IH }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux], cases p R.head v; [apply IH₂, apply IH₁] }, case TM1.stmt.goto : l { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux, tr_cfg, tr_tape_mk'], apply refl_trans_gen.refl }, case TM1.stmt.halt { simp only [tr_normal, step_aux, tr_cfg, step_aux_move, tr_tape'_move_left enc0, tr_tape'_move_right enc0, tr_tape_mk'], apply refl_trans_gen.refl } end omit enc0 encdec open_locale classical parameters [fintype Γ] /-- The set of accessible `Λ'.write` machine states. -/ noncomputable def writes : stmt₁ → finset Λ' | (stmt.move d q) := writes q | (stmt.write f q) := finset.univ.image (λ a, Λ'.write a q) ∪ writes q | (stmt.load f q) := writes q | (stmt.branch p q₁ q₂) := writes q₁ ∪ writes q₂ | (stmt.goto l) := ∅ | stmt.halt := ∅ /-- The set of accessible machine states, assuming that the input machine is supported on `S`, are the normal states embedded from `S`, plus all write states accessible from these states. -/ noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bUnion (λ l, insert (Λ'.normal l) (writes (M l))) theorem tr_supports {S} (ss : supports M S) : supports tr (tr_supp S) := ⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert_self _ _⟩, λ q h, begin suffices : ∀ q, supports_stmt S q → (∀ q' ∈ writes q, q' ∈ tr_supp M S) → supports_stmt (tr_supp M S) (tr_normal dec q) ∧ ∀ q' ∈ writes q, supports_stmt (tr_supp M S) (tr enc dec M q'), { rcases finset.mem_bUnion.1 h with ⟨l, hl, h⟩, have := this _ (ss.2 _ hl) (λ q' hq, finset.mem_bUnion.2 ⟨_, hl, finset.mem_insert_of_mem hq⟩), rcases finset.mem_insert.1 h with rfl | h, exacts [this.1, this.2 _ h] }, intros q hs hw, induction q, case TM1.stmt.move : d q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨_, IH.2⟩, cases d; simp only [tr_normal, iterate, supports_stmt_move, IH] }, case TM1.stmt.write : f q IH { unfold writes at hw ⊢, simp only [finset.mem_image, finset.mem_union, finset.mem_univ, exists_prop, true_and] at hw ⊢, replace IH := IH hs (λ q hq, hw q (or.inr hq)), refine ⟨supports_stmt_read _ $ λ a _ s, hw _ (or.inl ⟨_, rfl⟩), λ q' hq, _⟩, rcases hq with ⟨a, q₂, rfl⟩ | hq, { simp only [tr, supports_stmt_write, supports_stmt_move, IH.1] }, { exact IH.2 _ hq } }, case TM1.stmt.load : a q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨supports_stmt_read _ (λ a, IH.1), IH.2⟩ }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold writes at hw ⊢, simp only [finset.mem_union] at hw ⊢, replace IH₁ := IH₁ hs.1 (λ q hq, hw q (or.inl hq)), replace IH₂ := IH₂ hs.2 (λ q hq, hw q (or.inr hq)), exact ⟨supports_stmt_read _ (λ a, ⟨IH₁.1, IH₂.1⟩), λ q, or.rec (IH₁.2 _) (IH₂.2 _)⟩ }, case TM1.stmt.goto : l { refine ⟨_, λ _, false.elim⟩, refine supports_stmt_read _ (λ a _ s, _), exact finset.mem_bUnion.2 ⟨_, hs _ _, finset.mem_insert_self _ _⟩ }, case TM1.stmt.halt { refine ⟨_, λ _, false.elim⟩, simp only [supports_stmt, supports_stmt_move, tr_normal] } end⟩ end end TM1to1 /-! ## TM0 emulator in TM1 To establish that TM0 and TM1 are equivalent computational models, we must also have a TM0 emulator in TM1. The main complication here is that TM0 allows an action to depend on the value at the head and local state, while TM1 doesn't (in order to have more programming language-like semantics). So we use a computed `goto` to go to a state that performes the desired action and then returns to normal execution. One issue with this is that the `halt` instruction is supposed to halt immediately, not take a step to a halting state. To resolve this we do a check for `halt` first, then `goto` (with an unreachable branch). -/ namespace TM0to1 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] /-- The machine states for a TM1 emulating a TM0 machine. States of the TM0 machine are embedded as `normal q` states, but the actual operation is split into two parts, a jump to `act s q` followed by the action and a jump to the next `normal` state. -/ inductive Λ' | normal : Λ → Λ' | act : TM0.stmt Γ → Λ → Λ' instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩ local notation `cfg₀` := TM0.cfg Γ Λ local notation `stmt₁` := TM1.stmt Γ Λ' unit local notation `cfg₁` := TM1.cfg Γ Λ' unit parameters (M : TM0.machine Γ Λ) open TM1.stmt /-- The program. -/ def tr : Λ' → stmt₁ | (Λ'.normal q) := branch (λ a _, (M q a).is_none) halt $ goto (λ a _, match M q a with | none := default _ -- unreachable | some (q', s) := Λ'.act s q' end) | (Λ'.act (TM0.stmt.move d) q) := move d $ goto (λ _ _, Λ'.normal q) | (Λ'.act (TM0.stmt.write a) q) := write (λ _ _, a) $ goto (λ _ _, Λ'.normal q) /-- The configuration translation. -/ def tr_cfg : cfg₀ → cfg₁ | ⟨q, T⟩ := ⟨cond (M q T.1).is_some (some (Λ'.normal q)) none, (), T⟩ theorem tr_respects : respects (TM0.step M) (TM1.step tr) (λ a b, tr_cfg a = b) := fun_respects.2 $ λ ⟨q, T⟩, begin cases e : M q T.1, { simp only [TM0.step, tr_cfg, e]; exact eq.refl none }, cases val with q' s, simp only [frespects, TM0.step, tr_cfg, e, option.is_some, cond, option.map_some'], have : TM1.step (tr M) ⟨some (Λ'.act s q'), (), T⟩ = some ⟨some (Λ'.normal q'), (), TM0.step._match_1 T s⟩, { cases s with d a; refl }, refine trans_gen.head _ (trans_gen.head' this _), { unfold TM1.step TM1.step_aux tr has_mem.mem, rw e, refl }, cases e' : M q' _, { apply refl_trans_gen.single, unfold TM1.step TM1.step_aux tr has_mem.mem, rw e', refl }, { refl } end end end TM0to1 /-! ## The TM2 model The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks, each with elements of different types (the alphabet of stack `k : K` is `Γ k`). The statements are: * `push k (f : σ → Γ k) q` puts `f a` on the `k`-th stack, then does `q`. * `pop k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the value of the `k`-th stack, and removes this element from the stack, then does `q`. * `peek k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the value of the `k`-th stack, then does `q`. * `load (f : σ → σ) q` reads nothing but applies `f` to the internal state, then does `q`. * `branch (f : σ → bool) qtrue qfalse` does `qtrue` or `qfalse` according to `f a`. * `goto (f : σ → Λ)` jumps to label `f a`. * `halt` halts on the next step. The configuration is a tuple `(l, var, stk)` where `l : option Λ` is the current label to run or `none` for the halting state, `var : σ` is the (finite) internal state, and `stk : ∀ k, list (Γ k)` is the collection of stacks. (Note that unlike the `TM0` and `TM1` models, these are not `list_blank`s, they have definite ends that can be detected by the `pop` command.) Given a designated stack `k` and a value `L : list (Γ k)`, the initial configuration has all the stacks empty except the designated "input" stack; in `eval` this designated stack also functions as the output stack. -/ namespace TM2 section parameters {K : Type*} [decidable_eq K] -- Index type of stacks parameters (Γ : K → Type*) -- Type of stack elements parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks. The operation `push` puts an element on one of the stacks, and `pop` removes an element from a stack (and modifying the internal state based on the result). `peek` modifies the internal state but does not remove an element. -/ inductive stmt | push : ∀ k, (σ → Γ k) → stmt → stmt | peek : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | pop : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | load : (σ → σ) → stmt → stmt | branch : (σ → bool) → stmt → stmt → stmt | goto : (σ → Λ) → stmt | halt : stmt open stmt instance stmt.inhabited : inhabited stmt := ⟨halt⟩ /-- A configuration in the TM2 model is a label (or `none` for the halt state), the state of local variables, and the stacks. (Note that the stacks are not `list_blank`s, they have a definite size.) -/ structure cfg := (l : option Λ) (var : σ) (stk : ∀ k, list (Γ k)) instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default _, default _, default _⟩⟩ parameters {Γ Λ σ K} /-- The step function for the TM2 model. -/ @[simp] def step_aux : stmt → σ → (∀ k, list (Γ k)) → cfg | (push k f q) v S := step_aux q v (update S k (f v :: S k)) | (peek k f q) v S := step_aux q (f v (S k).head') S | (pop k f q) v S := step_aux q (f v (S k).head') (update S k (S k).tail) | (load a q) v S := step_aux q (a v) S | (branch f q₁ q₂) v S := cond (f v) (step_aux q₁ v S) (step_aux q₂ v S) | (goto f) v S := ⟨some (f v), v, S⟩ | halt v S := ⟨none, v, S⟩ /-- The step function for the TM2 model. -/ @[simp] def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, S⟩ := none | ⟨some l, v, S⟩ := some (step_aux (M l) v S) /-- The (reflexive) reachability relation for the TM2 model. -/ def reaches (M : Λ → stmt) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) /-- Given a set `S` of states, `support_stmt S q` means that `q` only jumps to states in `S`. -/ def supports_stmt (S : finset Λ) : stmt → Prop | (push k f q) := supports_stmt q | (peek k f q) := supports_stmt q | (pop k f q) := supports_stmt q | (load a q) := supports_stmt q | (branch f q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ v, l v ∈ S | halt := true open_locale classical /-- The set of subtree statements in a statement. -/ noncomputable def stmts₁ : stmt → finset stmt | Q@(push k f q) := insert Q (stmts₁ q) | Q@(peek k f q) := insert Q (stmts₁ q) | Q@(pop k f q) := insert Q (stmts₁ q) | Q@(load a q) := insert Q (stmts₁ q) | Q@(branch f q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q@(goto l) := {Q} | Q@halt := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self] theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.mem_singleton, finset.mem_union] at h₁₂, iterate 4 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ (IH₁ h₁₂)) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ (IH₂ h₁₂)) } }, case TM2.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM2.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.mem_singleton] at h hs, iterate 4 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM2.stmt.goto : l { subst h, exact hs }, case TM2.stmt.halt { subst h, trivial } end /-- The set of statements accessible from initial set `S` of labels. -/ noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bUnion (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ variable [inhabited Λ] /-- Given a TM2 machine `M` and a set `S` of states, `supports M S` means that all states in `S` jump only to other states in `S`. -/ def supports (M : Λ → stmt) (S : finset Λ) := default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ _ q IH _ _ q IH _ _ q IH _ q IH generalizing v T; intro hs, iterate 4 { exact IH _ _ hs }, case TM2.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM2.stmt.goto { exact finset.some_mem_insert_none.2 (hs _) }, case TM2.stmt.halt { apply multiset.mem_cons_self } end variable [inhabited σ] /-- The initial state of the TM2 model. The input is provided on a designated stack. -/ def init (k) (L : list (Γ k)) : cfg := ⟨some (default _), default _, update (λ _, []) k L⟩ /-- Evaluates a TM2 program to completion, with the output on the same stack as the input. -/ def eval (M : Λ → stmt) (k) (L : list (Γ k)) : roption (list (Γ k)) := (eval (step M) (init k L)).map $ λ c, c.stk k end end TM2 /-! ## TM2 emulator in TM1 To prove that TM2 computable functions are TM1 computable, we need to reduce each TM2 program to a TM1 program. So suppose a TM2 program is given. This program has to maintain a whole collection of stacks, but we have only one tape, so we must "multiplex" them all together. Pictorially, if stack 1 contains `[a, b]` and stack 2 contains `[c, d, e, f]` then the tape looks like this: ``` bottom: ... | _ | T | _ | _ | _ | _ | ... stack 1: ... | _ | b | a | _ | _ | _ | ... stack 2: ... | _ | f | e | d | c | _ | ... ``` where a tape element is a vertical slice through the diagram. Here the alphabet is `Γ' := bool × ∀ k, option (Γ k)`, where: * `bottom : bool` is marked only in one place, the initial position of the TM, and represents the tail of all stacks. It is never modified. * `stk k : option (Γ k)` is the value of the `k`-th stack, if in range, otherwise `none` (which is the blank value). Note that the head of the stack is at the far end; this is so that push and pop don't have to do any shifting. In "resting" position, the TM is sitting at the position marked `bottom`. For non-stack actions, it operates in place, but for the stack actions `push`, `peek`, and `pop`, it must shuttle to the end of the appropriate stack, make its changes, and then return to the bottom. So the states are: * `normal (l : Λ)`: waiting at `bottom` to execute function `l` * `go k (s : st_act k) (q : stmt₂)`: travelling to the right to get to the end of stack `k` in order to perform stack action `s`, and later continue with executing `q` * `ret (q : stmt₂)`: travelling to the left after having performed a stack action, and executing `q` once we arrive Because of the shuttling, emulation overhead is `O(n)`, where `n` is the current maximum of the length of all stacks. Therefore a program that takes `k` steps to run in TM2 takes `O((m+k)k)` steps to run when emulated in TM1, where `m` is the length of the input. -/ namespace TM2to1 -- A displaced lemma proved in unnecessary generality theorem stk_nth_val {K : Type*} {Γ : K → Type*} {L : list_blank (∀ k, option (Γ k))} {k S} (n) (hL : list_blank.map (proj k) L = list_blank.mk (list.map some S).reverse) : L.nth n k = S.reverse.nth n := begin rw [← proj_map_nth, hL, ← list.map_reverse, list_blank.nth_mk, list.inth, list.nth_map], cases S.reverse.nth n; refl end section parameters {K : Type*} [decidable_eq K] parameters {Γ : K → Type*} parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₂` := TM2.stmt Γ Λ σ local notation `cfg₂` := TM2.cfg Γ Λ σ /-- The alphabet of the TM2 simulator on TM1 is a marker for the stack bottom, plus a vector of stack elements for each stack, or none if the stack does not extend this far. -/ @[nolint unused_arguments] -- [decidable_eq K]: Because K is a parameter, we cannot easily skip -- the decidable_eq assumption, and this is a local definition anyway so it's not important. def Γ' := bool × ∀ k, option (Γ k) instance Γ'.inhabited : inhabited Γ' := ⟨⟨ff, λ _, none⟩⟩ instance Γ'.fintype [fintype K] [∀ k, fintype (Γ k)] : fintype Γ' := prod.fintype _ _ /-- The bottom marker is fixed throughout the calculation, so we use the `add_bottom` function to express the program state in terms of a tape with only the stacks themselves. -/ def add_bottom (L : list_blank (∀ k, option (Γ k))) : list_blank Γ' := list_blank.cons (tt, L.head) (L.tail.map ⟨prod.mk ff, rfl⟩) theorem add_bottom_map (L) : (add_bottom L).map ⟨prod.snd, rfl⟩ = L := begin simp only [add_bottom, list_blank.map_cons]; convert list_blank.cons_head_tail _, generalize : list_blank.tail L = L', refine L'.induction_on _, intro l, simp, rw (_ : _ ∘ _ = id), {simp}, funext a, refl end theorem add_bottom_modify_nth (f : (∀ k, option (Γ k)) → (∀ k, option (Γ k))) (L n) : (add_bottom L).modify_nth (λ a, (a.1, f a.2)) n = add_bottom (L.modify_nth f n) := begin cases n; simp only [add_bottom, list_blank.head_cons, list_blank.modify_nth, list_blank.tail_cons], congr, symmetry, apply list_blank.map_modify_nth, intro, refl end theorem add_bottom_nth_snd (L n) : ((add_bottom L).nth n).2 = L.nth n := by conv {to_rhs, rw [← add_bottom_map L, list_blank.nth_map]}; refl theorem add_bottom_nth_succ_fst (L n) : ((add_bottom L).nth (n+1)).1 = ff := by rw [list_blank.nth_succ, add_bottom, list_blank.tail_cons, list_blank.nth_map]; refl theorem add_bottom_head_fst (L) : (add_bottom L).head.1 = tt := by rw [add_bottom, list_blank.head_cons]; refl /-- A stack action is a command that interacts with the top of a stack. Our default position is at the bottom of all the stacks, so we have to hold on to this action while going to the end to modify the stack. -/ inductive st_act (k : K) | push : (σ → Γ k) → st_act | peek : (σ → option (Γ k) → σ) → st_act | pop : (σ → option (Γ k) → σ) → st_act instance st_act.inhabited {k} : inhabited (st_act k) := ⟨st_act.peek (λ s _, s)⟩ section open st_act /-- The TM2 statement corresponding to a stack action. -/ @[nolint unused_arguments] -- [inhabited Λ]: as this is a local definition it is more trouble than -- it is worth to omit the typeclass assumption without breaking the parameters def st_run {k : K} : st_act k → stmt₂ → stmt₂ | (push f) := TM2.stmt.push k f | (peek f) := TM2.stmt.peek k f | (pop f) := TM2.stmt.pop k f /-- The effect of a stack action on the local variables, given the value of the stack. -/ def st_var {k : K} (v : σ) (l : list (Γ k)) : st_act k → σ | (push f) := v | (peek f) := f v l.head' | (pop f) := f v l.head' /-- The effect of a stack action on the stack. -/ def st_write {k : K} (v : σ) (l : list (Γ k)) : st_act k → list (Γ k) | (push f) := f v :: l | (peek f) := l | (pop f) := l.tail /-- We have partitioned the TM2 statements into "stack actions", which require going to the end of the stack, and all other actions, which do not. This is a modified recursor which lumps the stack actions into one. -/ @[elab_as_eliminator] def {l} stmt_st_rec {C : stmt₂ → Sort l} (H₁ : Π k (s : st_act k) q (IH : C q), C (st_run s q)) (H₂ : Π a q (IH : C q), C (TM2.stmt.load a q)) (H₃ : Π p q₁ q₂ (IH₁ : C q₁) (IH₂ : C q₂), C (TM2.stmt.branch p q₁ q₂)) (H₄ : Π l, C (TM2.stmt.goto l)) (H₅ : C TM2.stmt.halt) : ∀ n, C n | (TM2.stmt.push k f q) := H₁ _ (push f) _ (stmt_st_rec q) | (TM2.stmt.peek k f q) := H₁ _ (peek f) _ (stmt_st_rec q) | (TM2.stmt.pop k f q) := H₁ _ (pop f) _ (stmt_st_rec q) | (TM2.stmt.load a q) := H₂ _ _ (stmt_st_rec q) | (TM2.stmt.branch a q₁ q₂) := H₃ _ _ _ (stmt_st_rec q₁) (stmt_st_rec q₂) | (TM2.stmt.goto l) := H₄ _ | TM2.stmt.halt := H₅ theorem supports_run (S : finset Λ) {k} (s : st_act k) (q) : TM2.supports_stmt S (st_run s q) ↔ TM2.supports_stmt S q := by rcases s with _|_|_; refl end /-- The machine states of the TM2 emulator. We can either be in a normal state when waiting for the next TM2 action, or we can be in the "go" and "return" states to go to the top of the stack and return to the bottom, respectively. -/ inductive Λ' : Type (max u_1 u_2 u_3 u_4) | normal : Λ → Λ' | go (k) : st_act k → stmt₂ → Λ' | ret : stmt₂ → Λ' open Λ' instance Λ'.inhabited : inhabited Λ' := ⟨normal (default _)⟩ local notation `stmt₁` := TM1.stmt Γ' Λ' σ local notation `cfg₁` := TM1.cfg Γ' Λ' σ open TM1.stmt /-- The program corresponding to state transitions at the end of a stack. Here we start out just after the top of the stack, and should end just after the new top of the stack. -/ def tr_st_act {k} (q : stmt₁) : st_act k → stmt₁ | (st_act.push f) := write (λ a s, (a.1, update a.2 k $ some $ f s)) $ move dir.right q | (st_act.peek f) := move dir.left $ load (λ a s, f s (a.2 k)) $ move dir.right q | (st_act.pop f) := branch (λ a _, a.1) ( load (λ a s, f s none) q ) ( move dir.left $ load (λ a s, f s (a.2 k)) $ write (λ a s, (a.1, update a.2 k none)) q ) /-- The initial state for the TM2 emulator, given an initial TM2 state. All stacks start out empty except for the input stack, and the stack bottom mark is set at the head. -/ def tr_init (k) (L : list (Γ k)) : list Γ' := let L' : list Γ' := L.reverse.map (λ a, (ff, update (λ _, none) k a)) in (tt, L'.head.2) :: L'.tail theorem step_run {k : K} (q v S) : ∀ s : st_act k, TM2.step_aux (st_run s q) v S = TM2.step_aux q (st_var v (S k) s) (update S k (st_write v (S k) s)) | (st_act.push f) := rfl | (st_act.peek f) := by unfold st_write; rw function.update_eq_self; refl | (st_act.pop f) := rfl /-- The translation of TM2 statements to TM1 statements. regular actions have direct equivalents, but stack actions are deferred by going to the corresponding `go` state, so that we can find the appropriate stack top. -/ def tr_normal : stmt₂ → stmt₁ | (TM2.stmt.push k f q) := goto (λ _ _, go k (st_act.push f) q) | (TM2.stmt.peek k f q) := goto (λ _ _, go k (st_act.peek f) q) | (TM2.stmt.pop k f q) := goto (λ _ _, go k (st_act.pop f) q) | (TM2.stmt.load a q) := load (λ _, a) (tr_normal q) | (TM2.stmt.branch f q₁ q₂) := branch (λ a, f) (tr_normal q₁) (tr_normal q₂) | (TM2.stmt.goto l) := goto (λ a s, normal (l s)) | TM2.stmt.halt := halt theorem tr_normal_run {k} (s q) : tr_normal (st_run s q) = goto (λ _ _, go k s q) := by rcases s with _|_|_; refl open_locale classical /-- The set of machine states accessible from an initial TM2 statement. -/ noncomputable def tr_stmts₁ : stmt₂ → finset Λ' | Q@(TM2.stmt.push k f q) := {go k (st_act.push f) q, ret q} ∪ tr_stmts₁ q | Q@(TM2.stmt.peek k f q) := {go k (st_act.peek f) q, ret q} ∪ tr_stmts₁ q | Q@(TM2.stmt.pop k f q) := {go k (st_act.pop f) q, ret q} ∪ tr_stmts₁ q | Q@(TM2.stmt.load a q) := tr_stmts₁ q | Q@(TM2.stmt.branch f q₁ q₂) := tr_stmts₁ q₁ ∪ tr_stmts₁ q₂ | _ := ∅ theorem tr_stmts₁_run {k s q} : tr_stmts₁ (st_run s q) = {go k s q, ret q} ∪ tr_stmts₁ q := by rcases s with _|_|_; unfold tr_stmts₁ st_run theorem tr_respects_aux₂ {k q v} {S : Π k, list (Γ k)} {L : list_blank (∀ k, option (Γ k))} (hL : ∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) (o) : let v' := st_var v (S k) o, Sk' := st_write v (S k) o, S' := update S k Sk' in ∃ (L' : list_blank (∀ k, option (Γ k))), (∀ k, L'.map (proj k) = list_blank.mk ((S' k).map some).reverse) ∧ TM1.step_aux (tr_st_act q o) v ((tape.move dir.right)^[(S k).length] (tape.mk' ∅ (add_bottom L))) = TM1.step_aux q v' ((tape.move dir.right)^[(S' k).length] (tape.mk' ∅ (add_bottom L'))) := begin dsimp only, simp, cases o; simp only [st_write, st_var, tr_st_act, TM1.step_aux], case TM2to1.st_act.push : f { have := tape.write_move_right_n (λ a : Γ', (a.1, update a.2 k (some (f v)))), dsimp only at this, refine ⟨_, λ k', _, by rw [ tape.move_right_n_head, list.length, tape.mk'_nth_nat, this, add_bottom_modify_nth (λ a, update a k (some (f v))), nat.add_one, iterate_succ']⟩, refine list_blank.ext (λ i, _), rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val], by_cases h' : k' = k, { subst k', split_ifs; simp only [list.reverse_cons, function.update_same, list_blank.nth_mk, list.inth, list.map], { rw [list.nth_le_nth, list.nth_le_append_right]; simp only [h, list.nth_le_singleton, list.length_map, list.length_reverse, nat.succ_pos', list.length_append, lt_add_iff_pos_right, list.length] }, rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth], cases decidable.lt_or_gt_of_ne h with h h, { rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h }, { rw [list.nth_len_le, list.nth_len_le]; simp only [nat.add_one_le_iff, h, list.length, le_of_lt, list.length_reverse, list.length_append, list.length_map] } }, { split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL], rw function.update_noteq h' } }, case TM2to1.st_act.peek : f { rw function.update_eq_self, use [L, hL], rw [tape.move_left_right], congr, cases e : S k, {refl}, rw [list.length_cons, iterate_succ', tape.move_right_left, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_snd, stk_nth_val _ (hL k), e, list.reverse_cons, ← list.length_reverse, list.nth_concat_length], refl }, case TM2to1.st_act.pop : f { cases e : S k, { simp only [tape.mk'_head, list_blank.head_cons, tape.move_left_mk', list.length, tape.write_mk', list.head', iterate_zero_apply, list.tail_nil], rw [← e, function.update_eq_self], exact ⟨L, hL, by rw [add_bottom_head_fst, cond]⟩ }, { refine ⟨_, λ k', _, by rw [ list.length_cons, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_succ_fst, cond, iterate_succ', tape.move_right_left, tape.move_right_n_head, tape.mk'_nth_nat, tape.write_move_right_n (λ a:Γ', (a.1, update a.2 k none)), add_bottom_modify_nth (λ a, update a k none), add_bottom_nth_snd, stk_nth_val _ (hL k), e, show (list.cons hd tl).reverse.nth tl.length = some hd, by rw [list.reverse_cons, ← list.length_reverse, list.nth_concat_length]; refl, list.head', list.tail]⟩, refine list_blank.ext (λ i, _), rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val], by_cases h' : k' = k, { subst k', split_ifs; simp only [ function.update_same, list_blank.nth_mk, list.tail, list.inth], { rw [list.nth_len_le], {refl}, rw [h, list.length_reverse, list.length_map] }, rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth, e, list.map, list.reverse_cons], cases decidable.lt_or_gt_of_ne h with h h, { rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h }, { rw [list.nth_len_le, list.nth_len_le]; simp only [nat.add_one_le_iff, h, list.length, le_of_lt, list.length_reverse, list.length_append, list.length_map] } }, { split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL], rw function.update_noteq h' } } }, end parameters (M : Λ → stmt₂) include M /-- The TM2 emulator machine states written as a TM1 program. This handles the `go` and `ret` states, which shuttle to and from a stack top. -/ def tr : Λ' → stmt₁ | (normal q) := tr_normal (M q) | (go k s q) := branch (λ a s, (a.2 k).is_none) (tr_st_act (goto (λ _ _, ret q)) s) (move dir.right $ goto (λ _ _, go k s q)) | (ret q) := branch (λ a s, a.1) (tr_normal q) (move dir.left $ goto (λ _ _, ret q)) local attribute [pp_using_anonymous_constructor] turing.TM1.cfg /-- The relation between TM2 configurations and TM1 configurations of the TM2 emulator. -/ inductive tr_cfg : cfg₂ → cfg₁ → Prop | mk {q v} {S : ∀ k, list (Γ k)} (L : list_blank (∀ k, option (Γ k))) : (∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) → tr_cfg ⟨q, v, S⟩ ⟨q.map normal, v, tape.mk' ∅ (add_bottom L)⟩ theorem tr_respects_aux₁ {k} (o q v) {S : list (Γ k)} {L : list_blank (∀ k, option (Γ k))} (hL : L.map (proj k) = list_blank.mk (S.map some).reverse) (n ≤ S.length) : reaches₀ (TM1.step tr) ⟨some (go k o q), v, (tape.mk' ∅ (add_bottom L))⟩ ⟨some (go k o q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩ := begin induction n with n IH, {refl}, apply (IH (le_of_lt H)).tail, rw iterate_succ_apply', simp only [TM1.step, TM1.step_aux, tr, tape.mk'_nth_nat, tape.move_right_n_head, add_bottom_nth_snd, option.mem_def], rw [stk_nth_val _ hL, list.nth_le_nth], refl, rwa list.length_reverse end theorem tr_respects_aux₃ {q v} {L : list_blank (∀ k, option (Γ k))} (n) : reaches₀ (TM1.step tr) ⟨some (ret q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩ ⟨some (ret q), v, (tape.mk' ∅ (add_bottom L))⟩ := begin induction n with n IH, {refl}, refine reaches₀.head _ IH, rw [option.mem_def, TM1.step, tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_succ_fst, TM1.step_aux, iterate_succ', tape.move_right_left], refl, end theorem tr_respects_aux {q v T k} {S : Π k, list (Γ k)} (hT : ∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse) (o : st_act k) (IH : ∀ {v : σ} {S : Π (k : K), list (Γ k)} {T : list_blank (∀ k, option (Γ k))}, (∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse) → (∃ b, tr_cfg (TM2.step_aux q v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal q) v (tape.mk' ∅ (add_bottom T))) b)) : ∃ b, tr_cfg (TM2.step_aux (st_run o q) v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal (st_run o q)) v (tape.mk' ∅ (add_bottom T))) b := begin simp only [tr_normal_run, step_run], have hgo := tr_respects_aux₁ M o q v (hT k) _ (le_refl _), obtain ⟨T', hT', hrun⟩ := tr_respects_aux₂ hT o, have hret := tr_respects_aux₃ M _, have := hgo.tail' rfl, rw [tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_snd, stk_nth_val _ (hT k), list.nth_len_le (le_of_eq (list.length_reverse _)), option.is_none, cond, hrun, TM1.step_aux] at this, obtain ⟨c, gc, rc⟩ := IH hT', refine ⟨c, gc, (this.to₀.trans hret c (trans_gen.head' rfl _)).to_refl⟩, rw [tr, TM1.step_aux, tape.mk'_head, add_bottom_head_fst], exact rc, end local attribute [simp] respects TM2.step TM2.step_aux tr_normal theorem tr_respects : respects (TM2.step M) (TM1.step tr) tr_cfg := λ c₁ c₂ h, begin cases h with l v S L hT, clear h, cases l, {constructor}, simp only [TM2.step, respects, option.map_some'], suffices : ∃ b, _ ∧ reaches (TM1.step (tr M)) _ _, from let ⟨b, c, r⟩ := this in ⟨b, c, trans_gen.head' rfl r⟩, rw [tr], revert v S L hT, refine stmt_st_rec _ _ _ _ _ (M l); intros, { exact tr_respects_aux M hT s @IH }, { exact IH _ hT }, { unfold TM2.step_aux tr_normal TM1.step_aux, cases p v; [exact IH₂ _ hT, exact IH₁ _ hT] }, { exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ }, { exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ } end theorem tr_cfg_init (k) (L : list (Γ k)) : tr_cfg (TM2.init k L) (TM1.init (tr_init k L)) := begin rw (_ : TM1.init _ = _), { refine ⟨list_blank.mk (L.reverse.map $ λ a, update (default _) k (some a)), λ k', _⟩, refine list_blank.ext (λ i, _), rw [list_blank.map_mk, list_blank.nth_mk, list.inth, list.map_map, (∘), list.nth_map, proj, pointed_map.mk_val], by_cases k' = k, { subst k', simp only [function.update_same], rw [list_blank.nth_mk, list.inth, ← list.map_reverse, list.nth_map] }, { simp only [function.update_noteq h], rw [list_blank.nth_mk, list.inth, list.map, list.reverse_nil, list.nth], cases L.reverse.nth i; refl } }, { rw [tr_init, TM1.init], dsimp only, congr; cases L.reverse; try {refl}, simp only [list.map_map, list.tail_cons, list.map], refl } end theorem tr_eval_dom (k) (L : list (Γ k)) : (TM1.eval tr (tr_init k L)).dom ↔ (TM2.eval M k L).dom := tr_eval_dom tr_respects (tr_cfg_init _ _) theorem tr_eval (k) (L : list (Γ k)) {L₁ L₂} (H₁ : L₁ ∈ TM1.eval tr (tr_init k L)) (H₂ : L₂ ∈ TM2.eval M k L) : ∃ (S : ∀ k, list (Γ k)) (L' : list_blank (∀ k, option (Γ k))), add_bottom L' = L₁ ∧ (∀ k, L'.map (proj k) = list_blank.mk ((S k).map some).reverse) ∧ S k = L₂ := begin obtain ⟨c₁, h₁, rfl⟩ := (roption.mem_map_iff _).1 H₁, obtain ⟨c₂, h₂, rfl⟩ := (roption.mem_map_iff _).1 H₂, obtain ⟨_, ⟨q, v, S, L', hT⟩, h₃⟩ := tr_eval (tr_respects M) (tr_cfg_init M k L) h₂, cases roption.mem_unique h₁ h₃, exact ⟨S, L', by simp only [tape.mk'_right₀], hT, rfl⟩ end /-- The support of a set of TM2 states in the TM2 emulator. -/ noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bUnion (λ l, insert (normal l) (tr_stmts₁ (M l))) theorem tr_supports {S} (ss : TM2.supports M S) : TM1.supports tr (tr_supp S) := ⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert.2 $ or.inl rfl⟩, λ l' h, begin suffices : ∀ q (ss' : TM2.supports_stmt S q) (sub : ∀ x ∈ tr_stmts₁ q, x ∈ tr_supp M S), TM1.supports_stmt (tr_supp M S) (tr_normal q) ∧ (∀ l' ∈ tr_stmts₁ q, TM1.supports_stmt (tr_supp M S) (tr M l')), { rcases finset.mem_bUnion.1 h with ⟨l, lS, h⟩, have := this _ (ss.2 l lS) (λ x hx, finset.mem_bUnion.2 ⟨_, lS, finset.mem_insert_of_mem hx⟩), rcases finset.mem_insert.1 h with rfl | h; [exact this.1, exact this.2 _ h] }, clear h l', refine stmt_st_rec _ _ _ _ _; intros, { -- stack op rw TM2to1.supports_run at ss', simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.mem_insert, finset.mem_singleton] at sub, have hgo := sub _ (or.inl $ or.inl rfl), have hret := sub _ (or.inl $ or.inr rfl), cases IH ss' (λ x hx, sub x $ or.inr hx) with IH₁ IH₂, refine ⟨by simp only [tr_normal_run, TM1.supports_stmt]; intros; exact hgo, λ l h, _⟩, rw [tr_stmts₁_run] at h, simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.mem_insert, finset.mem_singleton] at h, rcases h with ⟨rfl | rfl⟩ | h, { unfold TM1.supports_stmt TM2to1.tr, rcases s with _|_|_, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨⟨λ _ _, hret, λ _ _, hret⟩, λ _ _, hgo⟩ } }, { unfold TM1.supports_stmt TM2to1.tr, exact ⟨IH₁, λ _ _, hret⟩ }, { exact IH₂ _ h } }, { -- load unfold TM2to1.tr_stmts₁ at ss' sub ⊢, exact IH ss' sub }, { -- branch unfold TM2to1.tr_stmts₁ at sub, cases IH₁ ss'.1 (λ x hx, sub x $ finset.mem_union_left _ hx) with IH₁₁ IH₁₂, cases IH₂ ss'.2 (λ x hx, sub x $ finset.mem_union_right _ hx) with IH₂₁ IH₂₂, refine ⟨⟨IH₁₁, IH₂₁⟩, λ l h, _⟩, rw [tr_stmts₁] at h, rcases finset.mem_union.1 h with h | h; [exact IH₁₂ _ h, exact IH₂₂ _ h] }, { -- goto rw tr_stmts₁, unfold TM2to1.tr_normal TM1.supports_stmt, unfold TM2.supports_stmt at ss', exact ⟨λ _ v, finset.mem_bUnion.2 ⟨_, ss' v, finset.mem_insert_self _ _⟩, λ _, false.elim⟩ }, { exact ⟨trivial, λ _, false.elim⟩ } -- halt end⟩ end end TM2to1 end turing
6bf69ccc7644d568a9a159b4e6410f77da059446
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Data/Lsp/Diagnostics.lean
d2744731da5b990027123078b7749da901d9f650
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,247
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Lean.Data.Json import Lean.Data.Lsp.Basic import Lean.Data.Lsp.Utf16 import Lean.Message /-! Definitions and functionality for emitting diagnostic information such as errors, warnings and #command outputs from the LSP server. -/ namespace Lean namespace Lsp open Json inductive DiagnosticSeverity where | error | warning | information | hint deriving Inhabited, BEq instance : FromJson DiagnosticSeverity := ⟨fun j => match j.getNat? with | some 1 => DiagnosticSeverity.error | some 2 => DiagnosticSeverity.warning | some 3 => DiagnosticSeverity.information | some 4 => DiagnosticSeverity.hint | _ => none⟩ instance : ToJson DiagnosticSeverity := ⟨fun | DiagnosticSeverity.error => 1 | DiagnosticSeverity.warning => 2 | DiagnosticSeverity.information => 3 | DiagnosticSeverity.hint => 4⟩ inductive DiagnosticCode where | int (i : Int) | string (s : String) deriving Inhabited, BEq instance : FromJson DiagnosticCode := ⟨fun | num (i : Int) => DiagnosticCode.int i | str s => DiagnosticCode.string s | _ => none⟩ instance : ToJson DiagnosticCode := ⟨fun | DiagnosticCode.int i => i | DiagnosticCode.string s => s⟩ inductive DiagnosticTag where | unnecessary | deprecated deriving Inhabited, BEq instance : FromJson DiagnosticTag := ⟨fun j => match j.getNat? with | some 1 => DiagnosticTag.unnecessary | some 2 => DiagnosticTag.deprecated | _ => none⟩ instance : ToJson DiagnosticTag := ⟨fun | DiagnosticTag.unnecessary => (1 : Nat) | DiagnosticTag.deprecated => (2 : Nat)⟩ structure DiagnosticRelatedInformation where location : Location message : String deriving Inhabited, BEq, ToJson, FromJson structure Diagnostic where range : Range severity? : Option DiagnosticSeverity := none code? : Option DiagnosticCode := none source? : Option String := none message : String tags? : Option (Array DiagnosticTag) := none relatedInformation? : Option (Array DiagnosticRelatedInformation) := none deriving Inhabited, BEq, ToJson, FromJson structure PublishDiagnosticsParams where uri : DocumentUri version? : Option Int := none diagnostics: Array Diagnostic deriving Inhabited, BEq, ToJson, FromJson /-- Transform a Lean Message concerning the given text into an LSP Diagnostic. -/ def msgToDiagnostic (text : FileMap) (m : Message) : IO Diagnostic := do let low : Lsp.Position := text.leanPosToLspPos m.pos let high : Lsp.Position := match m.endPos with | some endPos => text.leanPosToLspPos endPos | none => low let range : Range := ⟨low, high⟩ let severity := match m.severity with | MessageSeverity.information => DiagnosticSeverity.information | MessageSeverity.warning => DiagnosticSeverity.warning | MessageSeverity.error => DiagnosticSeverity.error let source := "Lean 4 server" let message ← m.data.toString pure { range := range, severity? := severity, source? := source, message := message } end Lsp end Lean
654ccbc89b5bd94c0bdd6b74fe165be9166e8c5b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/set/enumerate.lean
78fe97525dd956ee515b9d61f170f9a0a5537fda
[ "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
3,061
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.set.lattice import data.nat.order.basic import tactic.wlog /-! # Set enumeration > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file allows enumeration of sets given a choice function. The definition does not assume `sel` actually is a choice function, i.e. `sel s ∈ s` and `sel s = none ↔ s = ∅`. These assumptions are added to the lemmas needing them. -/ noncomputable theory open function namespace set section enumerate parameters {α : Type*} (sel : set α → option α) /-- Given a choice function `sel`, enumerates the elements of a set in the order `a 0 = sel s`, `a 1 = sel (s \ {a 0})`, `a 2 = sel (s \ {a 0, a 1})`, ... and stops when `sel (s \ {a 0, ..., a n}) = none`. Note that we don't require `sel` to be a choice function. -/ def enumerate : set α → ℕ → option α | s 0 := sel s | s (n + 1) := do a ← sel s, enumerate (s \ {a}) n lemma enumerate_eq_none_of_sel {s : set α} (h : sel s = none) : ∀ {n}, enumerate s n = none | 0 := by simp [h, enumerate]; refl | (n + 1) := by simp [h, enumerate]; refl lemma enumerate_eq_none : ∀ {s n₁ n₂}, enumerate s n₁ = none → n₁ ≤ n₂ → enumerate s n₂ = none | s 0 m := λ h _, enumerate_eq_none_of_sel h | s (n + 1) m := λ h hm, begin cases hs : sel s, { exact enumerate_eq_none_of_sel sel hs }, { cases m, case nat.zero { have : n + 1 = 0, from nat.eq_zero_of_le_zero hm, contradiction }, case nat.succ : m' { simp [hs, enumerate] at h ⊢, have hm : n ≤ m', from nat.le_of_succ_le_succ hm, exact enumerate_eq_none h hm } } end lemma enumerate_mem (h_sel : ∀ s a, sel s = some a → a ∈ s) : ∀ {s n a}, enumerate s n = some a → a ∈ s | s 0 a := h_sel s a | s (n+1) a := begin cases h : sel s, case none { simp [enumerate_eq_none_of_sel, h] }, case some : a' { simp [enumerate, h], exact λ h' : enumerate _ (s \ {a'}) n = some a, have a ∈ s \ {a'}, from enumerate_mem h', this.left } end lemma enumerate_inj {n₁ n₂ : ℕ} {a : α} {s : set α} (h_sel : ∀ s a, sel s = some a → a ∈ s) (h₁ : enumerate s n₁ = some a) (h₂ : enumerate s n₂ = some a) : n₁ = n₂ := begin wlog hn : n₁ ≤ n₂, { cases le_total n₁ n₂ with H H; [skip, symmetry]; apply_assumption; assumption }, { rcases nat.le.dest hn with ⟨m, rfl⟩, clear hn, induction n₁ generalizing s, case nat.zero { cases m, case nat.zero { refl }, case nat.succ : m { have : enumerate sel (s \ {a}) m = some a, { simp [enumerate, *] at * }, have : a ∈ s \ {a}, from enumerate_mem _ h_sel this, by simpa } }, case nat.succ { cases h : sel s; simp [enumerate, nat.add_succ, add_comm, *] at *; tauto } } end end enumerate end set
63d513891cfd7d64a09fad1fc9be849e3a18b864
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/interactive/completion7.lean
2c2abc6a514da962509d8772fa899dab33d29bac
[ "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
96
lean
#check And --^ textDocument/completion #check And. --^ textDocument/completion
081a452cb23e590d31b0f3fde06427261ab67329
35677d2df3f081738fa6b08138e03ee36bc33cad
/test/library_search/basic.lean
2722c04970cdd16071c2432aaa7afa4a5e77b16d
[ "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
2,569
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 data.nat.basic /- Turn off trace messages so they don't pollute the test build: -/ set_option trace.silence_library_search true /- For debugging purposes, we can display the list of lemmas: -/ -- set_option trace.suggest true namespace test.library_search -- Check that `library_search` fails if there are no goals. example : true := begin trivial, success_if_fail { library_search }, end -- Verify that `library_search` solves goals via `solve_by_elim` when the library isn't -- even needed. example (P : Prop) (p : P) : P := by library_search example (P : Prop) (p : P) (np : ¬P) : false := by library_search example (X : Type) (P : Prop) (x : X) (h : Π x : X, x = x → P) : P := by library_search def lt_one (n : ℕ) := n < 1 lemma zero_lt_one (n : ℕ) (h : n = 0) : lt_one n := by subst h; dsimp [lt_one]; simp -- Verify that calls to solve_by_elim to discharge subgoals use `rfl` example : lt_one 0 := by library_search example (a b : ℕ) : a + b = b + a := by library_search -- says: `exact add_comm a b` example {a b : ℕ} : a ≤ a + b := by library_search -- says: `exact nat.le.intro rfl` example (n m k : ℕ) : n * (m - k) = n * m - n * k := by library_search -- says: `exact nat.mul_sub_left_distrib n m k` -- TODO this doesn't work yet, and would require `library_search` to use `symmetry` -- example (n m k : ℕ) : n * m - n * k = n * (m - k) := -- by library_search -- says: `exact eq.symm (nat.mul_sub_left_distrib n m k)` example {n m : ℕ} (h : m < n) : m ≤ n - 1 := by library_search -- says: `exact nat.le_pred_of_lt h` example {α : Type} (x y : α) : x = y ↔ y = x := by library_search -- says: `exact eq_comm` example (a b : ℕ) (ha : 0 < a) (hb : 0 < b) : 0 < a + b := by library_search -- says: `exact add_pos ha hb` example (a b : ℕ) : 0 < a → 0 < b → 0 < a + b := by library_search -- says: `exact add_pos` example (a b : ℕ) (h : a ∣ b) (w : b > 0) : a ≤ b := by library_search -- says: `exact nat.le_of_dvd w h` -- We even find `iff` results: example : ∀ P : Prop, ¬(P ↔ ¬P) := by library_search -- says: `λ (a : Prop), (iff_not_self a).mp` example {a b c : ℕ} (ha : a > 0) (w : b ∣ c) : a * b ∣ a * c := by library_search -- exact mul_dvd_mul_left a w example {a b c : ℕ} (h₁ : a ∣ c) (h₂ : a ∣ b + c) : a ∣ b := by library_search -- says `exact (nat.dvd_add_left h₁).mp h₂` end test.library_search
2fb848f2da23ba190370959c5c386323ade7f269
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/separation.lean
8dd71dfa17655c4cf5e360a1279486744c9f8018
[ "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
23,700
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 Separation properties of topological spaces. -/ import topology.subset_properties open set filter open_locale topological_space filter local attribute [instance] classical.prop_decidable -- TODO: use "open_locale classical" universes u v variables {α : Type u} {β : Type v} [topological_space α] section separation /-- A T₀ space, also known as a Kolmogorov space, is a topological space where for every pair `x ≠ y`, there is an open set containing one but not the other. -/ class t0_space (α : Type u) [topological_space α] : Prop := (t0 : ∀ x y, x ≠ y → ∃ U:set α, is_open U ∧ (xor (x ∈ U) (y ∈ U))) theorem exists_open_singleton_of_open_finset [t0_space α] (s : finset α) (sne : s.nonempty) (hso : is_open (↑s : set α)) : ∃ x ∈ s, is_open ({x} : set α):= begin induction s using finset.strong_induction_on with s ihs, by_cases hs : set.subsingleton (↑s : set α), { rcases sne with ⟨x, hx⟩, refine ⟨x, hx, _⟩, have : (↑s : set α) = {x}, from hs.eq_singleton_of_mem hx, rwa this at hso }, { dunfold set.subsingleton at hs, push_neg at hs, rcases hs with ⟨x, hx, y, hy, hxy⟩, rcases t0_space.t0 x y hxy with ⟨U, hU, hxyU⟩, wlog H : x ∈ U ∧ y ∉ U := hxyU using [x y, y x], obtain ⟨z, hzs, hz⟩ : ∃ z ∈ s.filter (λ z, z ∈ U), is_open ({z} : set α), { refine ihs _ (finset.filter_ssubset.2 ⟨y, hy, H.2⟩) ⟨x, finset.mem_filter.2 ⟨hx, H.1⟩⟩ _, rw [finset.coe_filter], exact is_open_inter hso hU }, exact ⟨z, (finset.mem_filter.1 hzs).1, hz⟩ } end theorem exists_open_singleton_of_fintype [t0_space α] [f : fintype α] [ha : nonempty α] : ∃ x:α, is_open ({x}:set α) := begin refine ha.elim (λ x, _), have : is_open (↑(finset.univ : finset α) : set α), { simp }, rcases exists_open_singleton_of_open_finset _ ⟨x, finset.mem_univ x⟩ this with ⟨x, _, hx⟩, exact ⟨x, hx⟩ end instance subtype.t0_space [t0_space α] {p : α → Prop} : t0_space (subtype p) := ⟨λ x y hxy, let ⟨U, hU, hxyU⟩ := t0_space.t0 (x:α) y ((not_congr subtype.ext_iff_val).1 hxy) in ⟨(coe : subtype p → α) ⁻¹' U, is_open_induced hU, hxyU⟩⟩ /-- A T₁ space, also known as a Fréchet space, is a topological space where every singleton set is closed. Equivalently, for every pair `x ≠ y`, there is an open set containing `x` and not `y`. -/ class t1_space (α : Type u) [topological_space α] : Prop := (t1 : ∀x, is_closed ({x} : set α)) lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) := t1_space.t1 x lemma is_open_ne [t1_space α] {x : α} : is_open {y | y ≠ x} := compl_singleton_eq x ▸ is_open_compl_iff.2 (t1_space.t1 x) instance subtype.t1_space {α : Type u} [topological_space α] [t1_space α] {p : α → Prop} : t1_space (subtype p) := ⟨λ ⟨x, hx⟩, is_closed_induced_iff.2 $ ⟨{x}, is_closed_singleton, set.ext $ λ y, by simp [subtype.ext_iff_val]⟩⟩ @[priority 100] -- see Note [lower instance priority] instance t1_space.t0_space [t1_space α] : t0_space α := ⟨λ x y h, ⟨{z | z ≠ y}, is_open_ne, or.inl ⟨h, not_not_intro rfl⟩⟩⟩ lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : {x}ᶜ ∈ 𝓝 y := mem_nhds_sets is_closed_singleton $ by rwa [mem_compl_eq, mem_singleton_iff] @[simp] lemma closure_singleton [t1_space α] {a : α} : closure ({a} : set α) = {a} := is_closed_singleton.closure_eq lemma is_closed_map_const {α β} [topological_space α] [topological_space β] [t1_space β] {y : β} : is_closed_map (function.const α y) := begin apply is_closed_map.of_nonempty, intros s hs h2s, simp_rw [h2s.image_const, is_closed_singleton] end /-- A T₂ space, also known as a Hausdorff space, is one in which for every `x ≠ y` there exists disjoint open sets around `x` and `y`. This is the most widely used of the separation axioms. -/ class t2_space (α : Type u) [topological_space α] : Prop := (t2 : ∀x y, x ≠ y → ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅) lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := t2_space.t2 x y h @[priority 100] -- see Note [lower instance priority] instance t2_space.t1_space [t2_space α] : t1_space α := ⟨λ x, is_open_iff_forall_mem_open.2 $ λ y hxy, let ⟨u, v, hu, hv, hyu, hxv, huv⟩ := t2_separation (mt mem_singleton_of_eq hxy) in ⟨u, λ z hz1 hz2, (ext_iff.1 huv x).1 ⟨mem_singleton_iff.1 hz2 ▸ hz1, hxv⟩, hu, hyu⟩⟩ lemma eq_of_nhds_ne_bot [ht : t2_space α] {x y : α} (h : ne_bot (𝓝 x ⊓ 𝓝 y)) : x = y := classical.by_contradiction $ assume : x ≠ y, let ⟨u, v, hu, hv, hx, hy, huv⟩ := t2_space.t2 x y this in absurd huv $ (inf_ne_bot_iff.1 h (mem_nhds_sets hu hx) (mem_nhds_sets hv hy)).ne_empty lemma t2_iff_nhds : t2_space α ↔ ∀ {x y : α}, ne_bot (𝓝 x ⊓ 𝓝 y) → x = y := ⟨assume h, by exactI λ x y, eq_of_nhds_ne_bot, assume h, ⟨assume x y xy, have 𝓝 x ⊓ 𝓝 y = ⊥ := classical.by_contradiction (mt h xy), let ⟨u', hu', v', hv', u'v'⟩ := empty_in_sets_eq_bot.mpr this, ⟨u, uu', uo, hu⟩ := mem_nhds_sets_iff.mp hu', ⟨v, vv', vo, hv⟩ := mem_nhds_sets_iff.mp hv' in ⟨u, v, uo, vo, hu, hv, disjoint.eq_bot $ disjoint.mono uu' vv' u'v'⟩⟩⟩ lemma t2_iff_ultrafilter : t2_space α ↔ ∀ f {x y : α}, is_ultrafilter f → f ≤ 𝓝 x → f ≤ 𝓝 y → x = y := t2_iff_nhds.trans ⟨assume h f x y u fx fy, h $ u.1.mono (le_inf fx fy), assume h x y xy, let ⟨f, hf, uf⟩ := @@exists_ultrafilter _ xy in h f uf (le_trans hf inf_le_left) (le_trans hf inf_le_right)⟩ lemma is_closed_diagonal [t2_space α] : is_closed (diagonal α) := is_closed_iff_cluster_pt.mpr $ assume ⟨a₁, a₂⟩ h, eq_of_nhds_ne_bot $ assume : 𝓝 a₁ ⊓ 𝓝 a₂ = ⊥, h $ let ⟨t₁, ht₁, t₂, ht₂, (h' : t₁ ∩ t₂ ⊆ ∅)⟩ := by rw [←empty_in_sets_eq_bot, mem_inf_sets] at this; exact this in begin change t₁ ∈ 𝓝 a₁ at ht₁, change t₂ ∈ 𝓝 a₂ at ht₂, rw [nhds_prod_eq, ←empty_in_sets_eq_bot], apply filter.sets_of_superset, apply inter_mem_inf_sets (prod_mem_prod ht₁ ht₂) (mem_principal_sets.mpr (subset.refl _)), exact assume ⟨x₁, x₂⟩ ⟨⟨hx₁, hx₂⟩, (heq : x₁ = x₂)⟩, show false, from @h' x₁ ⟨hx₁, heq.symm ▸ hx₂⟩ end lemma t2_iff_is_closed_diagonal : t2_space α ↔ is_closed (diagonal α) := begin split, { introI h, exact is_closed_diagonal }, { intro h, constructor, intros x y hxy, have : (x, y) ∈ (diagonal α)ᶜ, by rwa [mem_compl_iff], obtain ⟨t, t_sub, t_op, xyt⟩ : ∃ t ⊆ (diagonal α)ᶜ, is_open t ∧ (x, y) ∈ t := is_open_iff_forall_mem_open.mp h _ this, rcases is_open_prod_iff.mp t_op x y xyt with ⟨U, V, U_op, V_op, xU, yV, H⟩, use [U, V, U_op, V_op, xU, yV], have := subset.trans H t_sub, rw eq_empty_iff_forall_not_mem, rintros z ⟨zU, zV⟩, have : ¬ (z, z) ∈ diagonal α := this (mk_mem_prod zU zV), exact this rfl }, end @[simp] lemma nhds_eq_nhds_iff {a b : α} [t2_space α] : 𝓝 a = 𝓝 b ↔ a = b := ⟨assume h, eq_of_nhds_ne_bot $ by rw [h, inf_idem]; exact nhds_ne_bot, assume h, h ▸ rfl⟩ @[simp] lemma nhds_le_nhds_iff {a b : α} [t2_space α] : 𝓝 a ≤ 𝓝 b ↔ a = b := ⟨assume h, eq_of_nhds_ne_bot $ by rw [inf_of_le_left h]; exact nhds_ne_bot, assume h, h ▸ le_refl _⟩ lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α} [ne_bot l] (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b := eq_of_nhds_ne_bot $ ne_bot_of_le $ le_inf ha hb lemma tendsto_nhds_unique' [t2_space α] {f : β → α} {l : filter β} {a b : α} (hl : ne_bot l) (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b := eq_of_nhds_ne_bot $ ne_bot_of_le $ le_inf ha hb section lim variables [t2_space α] {f : filter α} /-! ### Properties of `Lim` and `lim` In this section we use explicit `nonempty α` instances for `Lim` and `lim`. This way the lemmas are useful without a `nonempty α` instance. -/ lemma Lim_eq {a : α} [ne_bot f] (h : f ≤ 𝓝 a) : @Lim _ _ ⟨a⟩ f = a := tendsto_nhds_unique (le_nhds_Lim ⟨a, h⟩) h lemma Lim_eq_iff [ne_bot f] (h : ∃ (a : α), f ≤ nhds a) {a} : @Lim _ _ ⟨a⟩ f = a ↔ f ≤ 𝓝 a := ⟨λ c, c ▸ le_nhds_Lim h, Lim_eq⟩ lemma is_ultrafilter.Lim_eq_iff_le_nhds [compact_space α] (x : α) (F : ultrafilter α) : @Lim _ _ ⟨x⟩ F.1 = x ↔ F.1 ≤ 𝓝 x := ⟨λ h, h ▸ is_ultrafilter.le_nhds_Lim _, Lim_eq⟩ lemma is_open_iff_ultrafilter' [compact_space α] (U : set α) : is_open U ↔ (∀ F : ultrafilter α, F.Lim ∈ U → U ∈ F.1) := begin rw is_open_iff_ultrafilter, refine ⟨λ h F hF, h _ hF _ F.2 (is_ultrafilter.le_nhds_Lim _), _⟩, intros cond x hx f hf h, let F : ultrafilter α := ⟨f, hf⟩, change F.1 ≤ _ at h, rw ←is_ultrafilter.Lim_eq_iff_le_nhds at h, rw ←h at *, exact cond _ hx end lemma filter.tendsto.lim_eq {a : α} {f : filter β} [ne_bot f] {g : β → α} (h : tendsto g f (𝓝 a)) : @lim _ _ _ ⟨a⟩ f g = a := Lim_eq h lemma filter.lim_eq_iff {f : filter β} [ne_bot f] {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) {a} : @lim _ _ _ ⟨a⟩ f g = a ↔ tendsto g f (𝓝 a) := ⟨λ c, c ▸ tendsto_nhds_lim h, filter.tendsto.lim_eq⟩ lemma continuous.lim_eq [topological_space β] {f : β → α} (h : continuous f) (a : β) : @lim _ _ _ ⟨f a⟩ (𝓝 a) f = f a := (h.tendsto a).lim_eq @[simp] lemma Lim_nhds (a : α) : @Lim _ _ ⟨a⟩ (𝓝 a) = a := Lim_eq (le_refl _) @[simp] lemma lim_nhds_id (a : α) : @lim _ _ _ ⟨a⟩ (𝓝 a) id = a := Lim_nhds a @[simp] lemma Lim_nhds_within {a : α} {s : set α} (h : a ∈ closure s) : @Lim _ _ ⟨a⟩ (𝓝[s] a) = a := by haveI : ne_bot (𝓝[s] a) := mem_closure_iff_cluster_pt.1 h; exact Lim_eq inf_le_left @[simp] lemma lim_nhds_within_id {a : α} {s : set α} (h : a ∈ closure s) : @lim _ _ _ ⟨a⟩ (𝓝[s] a) id = a := Lim_nhds_within h end lim @[priority 100] -- see Note [lower instance priority] instance t2_space_discrete {α : Type*} [topological_space α] [discrete_topology α] : t2_space α := { t2 := assume x y hxy, ⟨{x}, {y}, is_open_discrete _, is_open_discrete _, rfl, rfl, eq_empty_iff_forall_not_mem.2 $ by intros z hz; cases eq_of_mem_singleton hz.1; cases eq_of_mem_singleton hz.2; cc⟩ } private lemma separated_by_f {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] [t2_space β] (f : α → β) (hf : tα ≤ tβ.induced f) {x y : α} (h : f x ≠ f y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in ⟨f ⁻¹' u, f ⁻¹' v, hf _ ⟨u, uo, rfl⟩, hf _ ⟨v, vo, rfl⟩, xu, yv, by rw [←preimage_inter, uv, preimage_empty]⟩ instance {α : Type*} {p : α → Prop} [t : topological_space α] [t2_space α] : t2_space (subtype p) := ⟨assume x y h, separated_by_f subtype.val (le_refl _) (mt subtype.eq h)⟩ instance {α : Type*} {β : Type*} [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] : t2_space (α × β) := ⟨assume ⟨x₁,x₂⟩ ⟨y₁,y₂⟩ h, or.elim (not_and_distrib.mp (mt prod.ext_iff.mpr h)) (λ h₁, separated_by_f prod.fst inf_le_left h₁) (λ h₂, separated_by_f prod.snd inf_le_right h₂)⟩ instance Pi.t2_space {α : Type*} {β : α → Type v} [t₂ : Πa, topological_space (β a)] [Πa, t2_space (β a)] : t2_space (Πa, β a) := ⟨assume x y h, let ⟨i, hi⟩ := not_forall.mp (mt funext h) in separated_by_f (λz, z i) (infi_le _ i) hi⟩ variables [topological_space β] lemma is_closed_eq [t2_space α] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal /-- If two continuous maps are equal on `s`, then they are equal on the closure of `s`. -/ lemma set.eq_on.closure [t2_space α] {s : set β} {f g : β → α} (h : eq_on f g s) (hf : continuous f) (hg : continuous g) : eq_on f g (closure s) := closure_minimal h (is_closed_eq hf hg) /-- If two continuous functions are equal on a dense set, then they are equal. -/ lemma continuous.ext_on [t2_space α] {s : set β} (hs : dense s) {f g : β → α} (hf : continuous f) (hg : continuous g) (h : eq_on f g s) : f = g := funext $ λ x, h.closure hf hg (hs x) lemma diagonal_eq_range_diagonal_map {α : Type*} : {p:α×α | p.1 = p.2} = range (λx, (x,x)) := ext $ assume p, iff.intro (assume h, ⟨p.1, prod.ext_iff.2 ⟨rfl, h⟩⟩) (assume ⟨x, hx⟩, show p.1 = p.2, by rw ←hx) lemma prod_subset_compl_diagonal_iff_disjoint {α : Type*} {s t : set α} : set.prod s t ⊆ {p:α×α | p.1 = p.2}ᶜ ↔ s ∩ t = ∅ := by rw [eq_empty_iff_forall_not_mem, subset_compl_comm, diagonal_eq_range_diagonal_map, range_subset_iff]; simp lemma compact_compact_separated [t2_space α] {s t : set α} (hs : is_compact s) (ht : is_compact t) (hst : s ∩ t = ∅) : ∃u v : set α, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ∩ v = ∅ := by simp only [prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst; exact generalized_tube_lemma hs ht is_closed_diagonal hst /-- In a `t2_space`, every compact set is closed. -/ lemma is_compact.is_closed [t2_space α] {s : set α} (hs : is_compact s) : is_closed s := is_open_compl_iff.mpr $ is_open_iff_forall_mem_open.mpr $ assume x hx, let ⟨u, v, uo, vo, su, xv, uv⟩ := compact_compact_separated hs (compact_singleton : is_compact {x}) (by rwa [inter_comm, ←subset_compl_iff_disjoint, singleton_subset_iff]) in have v ⊆ sᶜ, from subset_compl_comm.mp (subset.trans su (subset_compl_iff_disjoint.mpr uv)), ⟨v, this, vo, by simpa using xv⟩ lemma is_compact.inter [t2_space α] {s t : set α} (hs : is_compact s) (ht : is_compact t) : is_compact (s ∩ t) := hs.inter_right $ ht.is_closed /-- If a compact set is covered by two open sets, then we can cover it by two compact subsets. -/ lemma is_compact.binary_compact_cover [t2_space α] {K U V : set α} (hK : is_compact K) (hU : is_open U) (hV : is_open V) (h2K : K ⊆ U ∪ V) : ∃ K₁ K₂ : set α, is_compact K₁ ∧ is_compact K₂ ∧ K₁ ⊆ U ∧ K₂ ⊆ V ∧ K = K₁ ∪ K₂ := begin rcases compact_compact_separated (compact_diff hK hU) (compact_diff hK hV) (by rwa [diff_inter_diff, diff_eq_empty]) with ⟨O₁, O₂, h1O₁, h1O₂, h2O₁, h2O₂, hO⟩, refine ⟨_, _, compact_diff hK h1O₁, compact_diff hK h1O₂, by rwa [diff_subset_comm], by rwa [diff_subset_comm], by rw [← diff_inter, hO, diff_empty]⟩ end section open finset function /-- For every finite open cover `Uᵢ` of a compact set, there exists a compact cover `Kᵢ ⊆ Uᵢ`. -/ lemma is_compact.finite_compact_cover [t2_space α] {s : set α} (hs : is_compact s) {ι} (t : finset ι) (U : ι → set α) (hU : ∀ i ∈ t, is_open (U i)) (hsC : s ⊆ ⋃ i ∈ t, U i) : ∃ K : ι → set α, (∀ i, is_compact (K i)) ∧ (∀i, K i ⊆ U i) ∧ s = ⋃ i ∈ t, K i := begin classical, induction t using finset.induction with x t hx ih generalizing U hU s hs hsC, { refine ⟨λ _, ∅, λ i, compact_empty, λ i, empty_subset _, _⟩, simpa only [subset_empty_iff, finset.not_mem_empty, Union_neg, Union_empty, not_false_iff] using hsC }, simp only [finset.bUnion_insert] at hsC, simp only [finset.mem_insert] at hU, have hU' : ∀ i ∈ t, is_open (U i) := λ i hi, hU i (or.inr hi), rcases hs.binary_compact_cover (hU x (or.inl rfl)) (is_open_bUnion hU') hsC with ⟨K₁, K₂, h1K₁, h1K₂, h2K₁, h2K₂, hK⟩, rcases ih U hU' h1K₂ h2K₂ with ⟨K, h1K, h2K, h3K⟩, refine ⟨update K x K₁, _, _, _⟩, { intros i, by_cases hi : i = x, { simp only [update_same, hi, h1K₁] }, { rw [← ne.def] at hi, simp only [update_noteq hi, h1K] }}, { intros i, by_cases hi : i = x, { simp only [update_same, hi, h2K₁] }, { rw [← ne.def] at hi, simp only [update_noteq hi, h2K] }}, { simp only [bUnion_insert_update _ hx, hK, h3K] } end end lemma locally_compact_of_compact_nhds [t2_space α] (h : ∀ x : α, ∃ s, s ∈ 𝓝 x ∧ is_compact s) : locally_compact_space α := ⟨assume x n hn, let ⟨u, un, uo, xu⟩ := mem_nhds_sets_iff.mp hn in let ⟨k, kx, kc⟩ := h x in -- K is compact but not necessarily contained in N. -- K \ U is again compact and doesn't contain x, so -- we may find open sets V, W separating x from K \ U. -- Then K \ W is a compact neighborhood of x contained in U. let ⟨v, w, vo, wo, xv, kuw, vw⟩ := compact_compact_separated compact_singleton (compact_diff kc uo) (by rw [singleton_inter_eq_empty]; exact λ h, h.2 xu) in have wn : wᶜ ∈ 𝓝 x, from mem_nhds_sets_iff.mpr ⟨v, subset_compl_iff_disjoint.mpr vw, vo, singleton_subset_iff.mp xv⟩, ⟨k \ w, filter.inter_mem_sets kx wn, subset.trans (diff_subset_comm.mp kuw) un, compact_diff kc wo⟩⟩ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_compact [t2_space α] [compact_space α] : locally_compact_space α := locally_compact_of_compact_nhds (assume x, ⟨univ, mem_nhds_sets is_open_univ trivial, compact_univ⟩) /-- In a locally compact T₂ space, every point has an open neighborhood with compact closure -/ lemma exists_open_with_compact_closure [locally_compact_space α] [t2_space α] (x : α) : ∃ (U : set α), is_open U ∧ x ∈ U ∧ is_compact (closure U) := begin rcases locally_compact_space.local_compact_nhds x set.univ filter.univ_mem_sets with ⟨K, h1K, _, h2K⟩, rw [mem_nhds_sets_iff] at h1K, rcases h1K with ⟨t, h1t, h2t, h3t⟩, exact ⟨t, h2t, h3t, compact_of_is_closed_subset h2K is_closed_closure $ closure_minimal h1t $ h2K.is_closed⟩ end /-- In a locally compact T₂ space, every compact set is contained in the interior of a compact set. -/ lemma exists_compact_superset [locally_compact_space α] [t2_space α] {K : set α} (hK : is_compact K) : ∃ (K' : set α), is_compact K' ∧ K ⊆ interior K' := begin choose U hU using λ x : K, exists_open_with_compact_closure (x : α), rcases hK.elim_finite_subcover U (λ x, (hU x).1) (λ x hx, ⟨_, ⟨⟨x, hx⟩, rfl⟩, (hU ⟨x, hx⟩).2.1⟩) with ⟨s, hs⟩, refine ⟨⋃ (i : K) (H : i ∈ s), closure (U i), _, _⟩, exact (finite_mem_finset s).compact_bUnion (λ x hx, (hU x).2.2), refine subset.trans hs _, rw subset_interior_iff_subset_of_open, exact bUnion_subset_bUnion_right (λ x hx, subset_closure), exact is_open_bUnion (λ x hx, (hU x).1) end end separation section regularity /-- A T₃ space, also known as a regular space (although this condition sometimes omits T₂), is one in which for every closed `C` and `x ∉ C`, there exist disjoint open sets containing `x` and `C` respectively. -/ class regular_space (α : Type u) [topological_space α] extends t1_space α : Prop := (regular : ∀{s:set α} {a}, is_closed s → a ∉ s → ∃t, is_open t ∧ s ⊆ t ∧ 𝓝[t] a = ⊥) lemma nhds_is_closed [regular_space α] {a : α} {s : set α} (h : s ∈ 𝓝 a) : ∃t∈(𝓝 a), t ⊆ s ∧ is_closed t := let ⟨s', h₁, h₂, h₃⟩ := mem_nhds_sets_iff.mp h in have ∃t, is_open t ∧ s'ᶜ ⊆ t ∧ 𝓝[t] a = ⊥, from regular_space.regular (is_closed_compl_iff.mpr h₂) (not_not_intro h₃), let ⟨t, ht₁, ht₂, ht₃⟩ := this in ⟨tᶜ, mem_sets_of_eq_bot $ by rwa [compl_compl], subset.trans (compl_subset_comm.1 ht₂) h₁, is_closed_compl_iff.mpr ht₁⟩ lemma closed_nhds_basis [regular_space α] (a : α) : (𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_closed s) id := ⟨λ t, ⟨λ t_in, let ⟨s, s_in, h_st, h⟩ := nhds_is_closed t_in in ⟨s, ⟨s_in, h⟩, h_st⟩, λ ⟨s, ⟨s_in, hs⟩, hst⟩, mem_sets_of_superset s_in hst⟩⟩ instance subtype.regular_space [regular_space α] {p : α → Prop} : regular_space (subtype p) := ⟨begin intros s a hs ha, rcases is_closed_induced_iff.1 hs with ⟨s, hs', rfl⟩, rcases regular_space.regular hs' ha with ⟨t, ht, hst, hat⟩, refine ⟨coe ⁻¹' t, is_open_induced ht, preimage_mono hst, _⟩, rw [nhds_within, nhds_induced, ← comap_principal, ← comap_inf, ← nhds_within, hat, comap_bot] end⟩ variable (α) @[priority 100] -- see Note [lower instance priority] instance regular_space.t2_space [regular_space α] : t2_space α := ⟨λ x y hxy, let ⟨s, hs, hys, hxs⟩ := regular_space.regular is_closed_singleton (mt mem_singleton_iff.1 hxy), ⟨t, hxt, u, hsu, htu⟩ := empty_in_sets_eq_bot.2 hxs, ⟨v, hvt, hv, hxv⟩ := mem_nhds_sets_iff.1 hxt in ⟨v, s, hv, hs, hxv, singleton_subset_iff.1 hys, eq_empty_of_subset_empty $ λ z ⟨hzv, hzs⟩, htu ⟨hvt hzv, hsu hzs⟩⟩⟩ variable {α} lemma disjoint_nested_nhds [regular_space α] {x y : α} (h : x ≠ y) : ∃ (U₁ V₁ ∈ 𝓝 x) (U₂ V₂ ∈ 𝓝 y), is_closed V₁ ∧ is_closed V₂ ∧ is_open U₁ ∧ is_open U₂ ∧ V₁ ⊆ U₁ ∧ V₂ ⊆ U₂ ∧ U₁ ∩ U₂ = ∅ := begin rcases t2_separation h with ⟨U₁, U₂, U₁_op, U₂_op, x_in, y_in, H⟩, rcases nhds_is_closed (mem_nhds_sets U₁_op x_in) with ⟨V₁, V₁_in, h₁, V₁_closed⟩, rcases nhds_is_closed (mem_nhds_sets U₂_op y_in) with ⟨V₂, V₂_in, h₂, V₂_closed⟩, use [U₁, V₁, mem_sets_of_superset V₁_in h₁, V₁_in, U₂, V₂, mem_sets_of_superset V₂_in h₂, V₂_in], tauto end end regularity section normality /-- A T₄ space, also known as a normal space (although this condition sometimes omits T₂), is one in which for every pair of disjoint closed sets `C` and `D`, there exist disjoint open sets containing `C` and `D` respectively. -/ class normal_space (α : Type u) [topological_space α] extends t1_space α : Prop := (normal : ∀ s t : set α, is_closed s → is_closed t → disjoint s t → ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v) theorem normal_separation [normal_space α] (s t : set α) (H1 : is_closed s) (H2 : is_closed t) (H3 : disjoint s t) : ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v := normal_space.normal s t H1 H2 H3 @[priority 100] -- see Note [lower instance priority] instance normal_space.regular_space [normal_space α] : regular_space α := { regular := λ s x hs hxs, let ⟨u, v, hu, hv, hsu, hxv, huv⟩ := normal_separation s {x} hs is_closed_singleton (λ _ ⟨hx, hy⟩, hxs $ set.mem_of_eq_of_mem (set.eq_of_mem_singleton hy).symm hx) in ⟨u, hu, hsu, filter.empty_in_sets_eq_bot.1 $ filter.mem_inf_sets.2 ⟨v, mem_nhds_sets hv (set.singleton_subset_iff.1 hxv), u, filter.mem_principal_self u, set.inter_comm u v ▸ huv⟩⟩ } -- We can't make this an instance because it could cause an instance loop. lemma normal_of_compact_t2 [compact_space α] [t2_space α] : normal_space α := begin refine ⟨assume s t hs ht st, _⟩, simp only [disjoint_iff], exact compact_compact_separated hs.compact ht.compact st.eq_bot end end normality
e853ebad87359e95de315252b5a6e1a3c31705ae
4727251e0cd73359b15b664c3170e5d754078599
/src/tactic/linarith/lemmas.lean
d14c9a2497a22c006acc84571a797c520263c1a0
[ "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
3,801
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import algebra.order.ring import data.int.basic import tactic.norm_num /-! # Lemmas for `linarith` This file contains auxiliary lemmas that `linarith` uses to construct proofs. If you find yourself looking for a theorem here, you might be in the wrong place. -/ namespace linarith lemma int.coe_nat_bit0 (n : ℕ) : (↑(bit0 n : ℕ) : ℤ) = bit0 (↑n : ℤ) := by simp [bit0] lemma int.coe_nat_bit1 (n : ℕ) : (↑(bit1 n : ℕ) : ℤ) = bit1 (↑n : ℤ) := by simp [bit1, bit0] lemma int.coe_nat_bit0_mul (n : ℕ) (x : ℕ) : (↑(bit0 n * x) : ℤ) = (↑(bit0 n) : ℤ) * (↑x : ℤ) := by simp lemma int.coe_nat_bit1_mul (n : ℕ) (x : ℕ) : (↑(bit1 n * x) : ℤ) = (↑(bit1 n) : ℤ) * (↑x : ℤ) := by simp lemma int.coe_nat_one_mul (x : ℕ) : (↑(1 * x) : ℤ) = 1 * (↑x : ℤ) := by simp lemma int.coe_nat_zero_mul (x : ℕ) : (↑(0 * x) : ℤ) = 0 * (↑x : ℤ) := by simp lemma int.coe_nat_mul_bit0 (n : ℕ) (x : ℕ) : (↑(x * bit0 n) : ℤ) = (↑x : ℤ) * (↑(bit0 n) : ℤ) := by simp lemma int.coe_nat_mul_bit1 (n : ℕ) (x : ℕ) : (↑(x * bit1 n) : ℤ) = (↑x : ℤ) * (↑(bit1 n) : ℤ) := by simp lemma int.coe_nat_mul_one (x : ℕ) : (↑(x * 1) : ℤ) = (↑x : ℤ) * 1 := by simp lemma int.coe_nat_mul_zero (x : ℕ) : (↑(x * 0) : ℤ) = (↑x : ℤ) * 0 := by simp lemma nat_eq_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 = n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 = z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_eq_coe_nat_iff] lemma nat_le_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 ≤ n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 ≤ z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_le] lemma nat_lt_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 < n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 < z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_lt] lemma eq_of_eq_of_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b = 0) : a + b = 0 := by simp * lemma le_of_eq_of_le {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b ≤ 0) : a + b ≤ 0 := by simp * lemma lt_of_eq_of_lt {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b < 0) : a + b < 0 := by simp * lemma le_of_le_of_eq {α} [ordered_semiring α] {a b : α} (ha : a ≤ 0) (hb : b = 0) : a + b ≤ 0 := by simp * lemma lt_of_lt_of_eq {α} [ordered_semiring α] {a b : α} (ha : a < 0) (hb : b = 0) : a + b < 0 := by simp * lemma mul_neg {α} [ordered_ring α] {a b : α} (ha : a < 0) (hb : 0 < b) : b * a < 0 := have (-b)*a > 0, from mul_pos_of_neg_of_neg (neg_neg_of_pos hb) ha, neg_of_neg_pos (by simpa) lemma mul_nonpos {α} [ordered_ring α] {a b : α} (ha : a ≤ 0) (hb : 0 < b) : b * a ≤ 0 := have (-b)*a ≥ 0, from mul_nonneg_of_nonpos_of_nonpos (le_of_lt (neg_neg_of_pos hb)) ha, by simpa -- used alongside `mul_neg` and `mul_nonpos`, so has the same argument pattern for uniformity @[nolint unused_arguments] lemma mul_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : 0 < b) : b * a = 0 := by simp * lemma eq_of_not_lt_of_not_gt {α} [linear_order α] (a b : α) (h1 : ¬ a < b) (h2 : ¬ b < a) : a = b := le_antisymm (le_of_not_gt h2) (le_of_not_gt h1) -- used in the `nlinarith` normalization steps. The `_` argument is for uniformity. @[nolint unused_arguments] lemma mul_zero_eq {α} {R : α → α → Prop} [semiring α] {a b : α} (_ : R a 0) (h : b = 0) : a * b = 0 := by simp [h] -- used in the `nlinarith` normalization steps. The `_` argument is for uniformity. @[nolint unused_arguments] lemma zero_mul_eq {α} {R : α → α → Prop} [semiring α] {a b : α} (h : a = 0) (_ : R b 0) : a * b = 0 := by simp [h] end linarith
db723153237dd8052ebf0deac9ef367af3637882
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/box_integral/partition/subbox_induction.lean
739d1b473f00f0377cfc2fc2d8e8819653c85a9a
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
10,541
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.box.subbox_induction import analysis.box_integral.partition.tagged /-! # Induction on subboxes In this file we prove (see `box_integral.tagged_partition.exists_is_Henstock_is_subordinate_homothetic`) that for every box `I` in `ℝⁿ` and a function `r : ℝⁿ → ℝ` positive on `I` there exists a tagged partition `π` of `I` such that * `π` is a Henstock partition; * `π` is subordinate to `r`; * each box in `π` is homothetic to `I` with coefficient of the form `1 / 2 ^ n`. Later we will use this lemma to prove that the Henstock filter is nontrivial, hence the Henstock integral is well-defined. ## Tags partition, tagged partition, Henstock integral -/ namespace box_integral open set metric open_locale classical topological_space noncomputable theory variables {ι : Type*} [fintype ι] {I J : box ι} namespace prepartition /-- Split a box in `ℝⁿ` into `2 ^ n` boxes by hyperplanes passing through its center. -/ def split_center (I : box ι) : prepartition I := { boxes := finset.univ.map (box.split_center_box_emb I), le_of_mem' := by simp [I.split_center_box_le], pairwise_disjoint := begin rw [finset.coe_map, finset.coe_univ, image_univ], rintro _ ⟨s, rfl⟩ _ ⟨t, rfl⟩ Hne, exact I.disjoint_split_center_box (mt (congr_arg _) Hne) end } @[simp] lemma mem_split_center : J ∈ split_center I ↔ ∃ s, I.split_center_box s = J := by simp [split_center] lemma is_partition_split_center (I : box ι) : is_partition (split_center I) := λ x hx, by simp [hx] lemma upper_sub_lower_of_mem_split_center (h : J ∈ split_center I) (i : ι) : J.upper i - J.lower i = (I.upper i - I.lower i) / 2 := let ⟨s, hs⟩ := mem_split_center.1 h in hs ▸ I.upper_sub_lower_split_center_box s i end prepartition namespace box open prepartition tagged_prepartition /-- Let `p` be a predicate on `box ι`, let `I` be a box. Suppose that the following two properties hold true. * Consider a smaller box `J ≤ I`. The hyperplanes passing through the center of `J` split it into `2 ^ n` boxes. If `p` holds true on each of these boxes, then it true on `J`. * For each `z` in the closed box `I.Icc` there exists a neighborhood `U` of `z` within `I.Icc` such that for every box `J ≤ I` such that `z ∈ J.Icc ⊆ U`, if `J` is homothetic to `I` with a coefficient of the form `1 / 2 ^ m`, then `p` is true on `J`. Then `p I` is true. See also `box_integral.box.subbox_induction_on'` for a version using `box_integral.box.split_center_box` instead of `box_integral.prepartition.split_center`. -/ @[elab_as_eliminator] lemma subbox_induction_on {p : box ι → Prop} (I : box ι) (H_ind : ∀ J ≤ I, (∀ J' ∈ split_center J, p J') → p J) (H_nhds : ∀ z ∈ I.Icc, ∃ (U ∈ 𝓝[I.Icc] z), ∀ (J ≤ I) (m : ℕ), z ∈ J.Icc → J.Icc ⊆ U → (∀ i, J.upper i - J.lower i = (I.upper i - I.lower i) / 2 ^ m) → p J) : p I := begin refine subbox_induction_on' I (λ J hle hs, H_ind J hle $ λ J' h', _) H_nhds, rcases mem_split_center.1 h' with ⟨s, rfl⟩, exact hs s end /-- Given a box `I` in `ℝⁿ` and a function `r : ℝⁿ → (0, ∞)`, there exists a tagged partition `π` of `I` such that * `π` is a Henstock partition; * `π` is subordinate to `r`; * each box in `π` is homothetic to `I` with coefficient of the form `1 / 2 ^ m`. This lemma implies that the Henstock filter is nontrivial, hence the Henstock integral is well-defined. -/ lemma exists_tagged_partition_is_Henstock_is_subordinate_homothetic (I : box ι) (r : (ι → ℝ) → Ioi (0 : ℝ)) : ∃ π : tagged_prepartition I, π.is_partition ∧ π.is_Henstock ∧ π.is_subordinate r ∧ (∀ J ∈ π, ∃ m : ℕ, ∀ i, (J : _).upper i - J.lower i = (I.upper i - I.lower i) / 2 ^ m) ∧ π.distortion = I.distortion := begin refine subbox_induction_on I (λ J hle hJ, _) (λ z hz, _), { choose! πi hP hHen hr Hn Hd using hJ, choose! n hn using Hn, have hP : ((split_center J).bUnion_tagged πi).is_partition, from (is_partition_split_center _).bUnion_tagged hP, have hsub : ∀ (J' ∈ (split_center J).bUnion_tagged πi), ∃ n : ℕ, ∀ i, (J' : _).upper i - J'.lower i = (J.upper i - J.lower i) / 2 ^ n, { intros J' hJ', rcases (split_center J).mem_bUnion_tagged.1 hJ' with ⟨J₁, h₁, h₂⟩, refine ⟨n J₁ J' + 1, λ i, _⟩, simp only [hn J₁ h₁ J' h₂, upper_sub_lower_of_mem_split_center h₁, pow_succ, div_div] }, refine ⟨_, hP, is_Henstock_bUnion_tagged.2 hHen, is_subordinate_bUnion_tagged.2 hr, hsub, _⟩, refine tagged_prepartition.distortion_of_const _ hP.nonempty_boxes (λ J' h', _), rcases hsub J' h' with ⟨n, hn⟩, exact box.distortion_eq_of_sub_eq_div hn }, { refine ⟨I.Icc ∩ closed_ball z (r z), inter_mem_nhds_within _ (closed_ball_mem_nhds _ (r z).coe_prop), _⟩, intros J Hle n Hmem HIcc Hsub, rw set.subset_inter_iff at HIcc, refine ⟨single _ _ le_rfl _ Hmem, is_partition_single _, is_Henstock_single _, (is_subordinate_single _ _).2 HIcc.2, _, distortion_single _ _⟩, simp only [tagged_prepartition.mem_single, forall_eq], refine ⟨0, λ i, _⟩, simp } end end box namespace prepartition open tagged_prepartition finset function /-- Given a box `I` in `ℝⁿ`, a function `r : ℝⁿ → (0, ∞)`, and a prepartition `π` of `I`, there exists a tagged prepartition `π'` of `I` such that * each box of `π'` is included in some box of `π`; * `π'` is a Henstock partition; * `π'` is subordinate to `r`; * `π'` covers exactly the same part of `I` as `π`; * the distortion of `π'` is equal to the distortion of `π`. -/ lemma exists_tagged_le_is_Henstock_is_subordinate_Union_eq {I : box ι} (r : (ι → ℝ) → Ioi (0 : ℝ)) (π : prepartition I) : ∃ π' : tagged_prepartition I, π'.to_prepartition ≤ π ∧ π'.is_Henstock ∧ π'.is_subordinate r ∧ π'.distortion = π.distortion ∧ π'.Union = π.Union := begin have := λ J, box.exists_tagged_partition_is_Henstock_is_subordinate_homothetic J r, choose! πi πip πiH πir hsub πid, clear hsub, refine ⟨π.bUnion_tagged πi, bUnion_le _ _, is_Henstock_bUnion_tagged.2 (λ J _, πiH J), is_subordinate_bUnion_tagged.2 (λ J _, πir J), _, π.Union_bUnion_partition (λ J _, πip J)⟩, rw [distortion_bUnion_tagged], exact sup_congr rfl (λ J _, πid J) end /-- Given a prepartition `π` of a box `I` and a function `r : ℝⁿ → (0, ∞)`, `π.to_subordinate r` is a tagged partition `π'` such that * each box of `π'` is included in some box of `π`; * `π'` is a Henstock partition; * `π'` is subordinate to `r`; * `π'` covers exactly the same part of `I` as `π`; * the distortion of `π'` is equal to the distortion of `π`. -/ def to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : tagged_prepartition I := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some lemma to_subordinate_to_prepartition_le (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π.to_subordinate r).to_prepartition ≤ π := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.1 lemma is_Henstock_to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π.to_subordinate r).is_Henstock := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.2.1 lemma is_subordinate_to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π.to_subordinate r).is_subordinate r := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.2.2.1 @[simp] lemma distortion_to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π.to_subordinate r).distortion = π.distortion := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.2.2.2.1 @[simp] lemma Union_to_subordinate (π : prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π.to_subordinate r).Union = π.Union := (π.exists_tagged_le_is_Henstock_is_subordinate_Union_eq r).some_spec.2.2.2.2 end prepartition namespace tagged_prepartition /-- Given a tagged prepartition `π₁`, a prepartition `π₂` that covers exactly `I \ π₁.Union`, and a function `r : ℝⁿ → (0, ∞)`, returns the union of `π₁` and `π₂.to_subordinate r`. This partition `π` has the following properties: * `π` is a partition, i.e. it covers the whole `I`; * `π₁.boxes ⊆ π.boxes`; * `π.tag J = π₁.tag J` whenever `J ∈ π₁`; * `π` is Henstock outside of `π₁`: `π.tag J ∈ J.Icc` whenever `J ∈ π`, `J ∉ π₁`; * `π` is subordinate to `r` outside of `π₁`; * the distortion of `π` is equal to the maximum of the distortions of `π₁` and `π₂`. -/ def union_compl_to_subordinate (π₁ : tagged_prepartition I) (π₂ : prepartition I) (hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) : tagged_prepartition I := π₁.disj_union (π₂.to_subordinate r) (((π₂.Union_to_subordinate r).trans hU).symm ▸ disjoint_diff) lemma is_partition_union_compl_to_subordinate (π₁ : tagged_prepartition I) (π₂ : prepartition I) (hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) : is_partition (π₁.union_compl_to_subordinate π₂ hU r) := prepartition.is_partition_disj_union_of_eq_diff ((π₂.Union_to_subordinate r).trans hU) @[simp] lemma union_compl_to_subordinate_boxes (π₁ : tagged_prepartition I) (π₂ : prepartition I) (hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π₁.union_compl_to_subordinate π₂ hU r).boxes = π₁.boxes ∪ (π₂.to_subordinate r).boxes := rfl @[simp] lemma Union_union_compl_to_subordinate_boxes (π₁ : tagged_prepartition I) (π₂ : prepartition I) (hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π₁.union_compl_to_subordinate π₂ hU r).Union = I := (is_partition_union_compl_to_subordinate _ _ _ _).Union_eq @[simp] lemma distortion_union_compl_to_subordinate (π₁ : tagged_prepartition I) (π₂ : prepartition I) (hU : π₂.Union = I \ π₁.Union) (r : (ι → ℝ) → Ioi (0 : ℝ)) : (π₁.union_compl_to_subordinate π₂ hU r).distortion = max π₁.distortion π₂.distortion := by simp [union_compl_to_subordinate] end tagged_prepartition end box_integral
52be73894aa172181053749340bfb9b4b242f151
618003631150032a5676f229d13a079ac875ff77
/src/algebra/char_zero.lean
9a6c9ec552c24342070b7ef8ac4491f9a4fc4093
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
3,305
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import algebra.field import data.nat.cast import tactic.wlog /-- Typeclass for monoids with characteristic zero. (This is usually stated on fields but it makes sense for any additive monoid with 1.) -/ class char_zero (α : Type*) [add_monoid α] [has_one α] : Prop := (cast_injective : function.injective (coe : ℕ → α)) theorem char_zero_of_inj_zero {α : Type*} [add_monoid α] [has_one α] (add_left_cancel : ∀ a b c : α, a + b = a + c → b = c) (H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α := ⟨λ m n, begin assume h, wlog hle : m ≤ n, cases nat.le.dest hle with k e, suffices : k = 0, by rw [← e, this, add_zero], apply H, apply add_left_cancel n, rw [← h, ← nat.cast_add, e, add_zero, h] end⟩ -- We have no `left_cancel_add_monoid`, so we restate it for `add_group` -- and `ordered_cancel_comm_monoid`. theorem add_group.char_zero_of_inj_zero {α : Type*} [add_group α] [has_one α] (H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α := char_zero_of_inj_zero (@add_left_cancel _ _) H theorem ordered_cancel_comm_monoid.char_zero_of_inj_zero {α : Type*} [ordered_cancel_add_comm_monoid α] [has_one α] (H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α := char_zero_of_inj_zero (@add_left_cancel _ _) H @[priority 100] -- see Note [lower instance priority] instance linear_ordered_semiring.to_char_zero {α : Type*} [linear_ordered_semiring α] : char_zero α := ordered_cancel_comm_monoid.char_zero_of_inj_zero $ λ n h, nat.eq_zero_of_le_zero $ (@nat.cast_le α _ _ _).1 (le_of_eq h) namespace nat variables {α : Type*} [add_monoid α] [has_one α] [char_zero α] theorem cast_injective : function.injective (coe : ℕ → α) := char_zero.cast_injective @[simp, norm_cast] theorem cast_inj {m n : ℕ} : (m : α) = n ↔ m = n := cast_injective.eq_iff @[simp, norm_cast] theorem cast_eq_zero {n : ℕ} : (n : α) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] @[norm_cast] theorem cast_ne_zero {n : ℕ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero lemma cast_add_one_ne_zero (n : ℕ) : (n + 1 : α) ≠ 0 := by exact_mod_cast n.succ_ne_zero end nat @[field_simps] lemma two_ne_zero' {α : Type*} [add_monoid α] [has_one α] [char_zero α] : (2:α) ≠ 0 := have ((2:ℕ):α) ≠ 0, from nat.cast_ne_zero.2 dec_trivial, by rwa [nat.cast_succ, nat.cast_one] at this section variables {α : Type*} [domain α] [char_zero α] lemma add_self_eq_zero {a : α} : a + a = 0 ↔ a = 0 := by simp only [(two_mul a).symm, mul_eq_zero, two_ne_zero', false_or] lemma bit0_eq_zero {a : α} : bit0 a = 0 ↔ a = 0 := add_self_eq_zero end section variables {α : Type*} [division_ring α] [char_zero α] @[simp] lemma half_add_self (a : α) : (a + a) / 2 = a := by rw [← mul_two, mul_div_cancel a two_ne_zero'] @[simp] lemma add_halves' (a : α) : a / 2 + a / 2 = a := by rw [← add_div, half_add_self] lemma sub_half (a : α) : a - a / 2 = a / 2 := by rw [sub_eq_iff_eq_add, add_halves'] lemma half_sub (a : α) : a / 2 - a = - (a / 2) := by rw [← neg_sub, sub_half] end
97179a2b0d718b8de4679a814369005734c7e48b
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/data/set/intervals.lean
315f4bbf6f3f5b11f5878156c507e39c267f7357
[ "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,622
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 Intervals Naming conventions: `i`: infinite `o`: open `c`: closed Each interval has the name `I` + letter for left side + letter for right side TODO: This is just the beginning; a lot of rules are missing -/ import data.set.lattice algebra.order algebra.order_functions import tactic.linarith namespace set open set section intervals variables {α : Type*} [preorder α] {a a₁ a₂ b b₁ b₂ x : α} /-- Left-open right-open interval -/ def Ioo (a b : α) := {x | a < x ∧ x < b} /-- Left-closed right-open interval -/ def Ico (a b : α) := {x | a ≤ x ∧ x < b} /-- Left-infinite right-open interval -/ def Iio (a : α) := {x | x < a} /-- Left-closed right-closed interval -/ def Icc (a b : α) := {x | a ≤ x ∧ x ≤ b} /-- Left-infinite right-closed interval -/ def Iic (b : α) := {x | x ≤ b} /-- Left-open right-closed interval -/ def Ioc (a b : α) := {x | a < x ∧ x ≤ b} /-- Left-closed right-infinite interval -/ def Ici (a : α) := {x | a ≤ x} /-- Left-open right-infinite interval -/ def Ioi (a : α) := {x | a < x} @[simp] lemma mem_Ioo : x ∈ Ioo a b ↔ a < x ∧ x < b := iff.rfl @[simp] lemma mem_Ico : x ∈ Ico a b ↔ a ≤ x ∧ x < b := iff.rfl @[simp] lemma mem_Iio : x ∈ Iio b ↔ x < b := iff.rfl @[simp] lemma mem_Icc : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Iic : x ∈ Iic b ↔ x ≤ b := iff.rfl @[simp] lemma mem_Ioc : x ∈ Ioc a b ↔ a < x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Ici : x ∈ Ici a ↔ a ≤ x := iff.rfl @[simp] lemma mem_Ioi : x ∈ Ioi a ↔ a < x := iff.rfl @[simp] lemma Ioo_eq_empty (h : b ≤ a) : Ioo a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_trans h₁ h₂) h @[simp] lemma Ico_eq_empty (h : b ≤ a) : Ico a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_of_le_of_lt h₁ h₂) h @[simp] lemma Icc_eq_empty (h : b < a) : Icc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₁ h₂) h @[simp] lemma Ioc_eq_empty (h : b ≤ a) : Ioc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₂ h) h₁ @[simp] lemma Ioo_self (a : α) : Ioo a a = ∅ := Ioo_eq_empty $ le_refl _ @[simp] lemma Ico_self (a : α) : Ico a a = ∅ := Ico_eq_empty $ le_refl _ lemma Iio_ne_empty [no_bot_order α] (a : α) : Iio a ≠ ∅ := ne_empty_iff_exists_mem.2 (no_bot a) lemma Ioi_ne_empty [no_top_order α] (a : α) : Ioi a ≠ ∅ := ne_empty_iff_exists_mem.2 (no_top a) lemma Iic_ne_empty (b : α) : Iic b ≠ ∅ := ne_empty_iff_exists_mem.2 ⟨b, le_refl b⟩ lemma Ici_ne_empty (a : α) : Ici a ≠ ∅ := ne_empty_iff_exists_mem.2 ⟨a, le_refl a⟩ lemma Ioo_subset_Ioo (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ioo_subset_Ioo_left (h : a₁ ≤ a₂) : Ioo a₂ b ⊆ Ioo a₁ b := Ioo_subset_Ioo h (le_refl _) lemma Ioo_subset_Ioo_right (h : b₁ ≤ b₂) : Ioo a b₁ ⊆ Ioo a b₂ := Ioo_subset_Ioo (le_refl _) h lemma Ico_subset_Ico (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ico a₁ b₁ ⊆ Ico a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ico_subset_Ico_left (h : a₁ ≤ a₂) : Ico a₂ b ⊆ Ico a₁ b := Ico_subset_Ico h (le_refl _) lemma Ico_subset_Ico_right (h : b₁ ≤ b₂) : Ico a b₁ ⊆ Ico a b₂ := Ico_subset_Ico (le_refl _) h lemma Icc_subset_Icc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Icc a₁ b₁ ⊆ Icc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, le_trans hx₂ h₂⟩ lemma Icc_subset_Icc_left (h : a₁ ≤ a₂) : Icc a₂ b ⊆ Icc a₁ b := Icc_subset_Icc h (le_refl _) lemma Icc_subset_Icc_right (h : b₁ ≤ b₂) : Icc a b₁ ⊆ Icc a b₂ := Icc_subset_Icc (le_refl _) h lemma Ico_subset_Ioo_left (h₁ : a₁ < a₂) : Ico a₂ b ⊆ Ioo a₁ b := λ x, and.imp_left $ lt_of_lt_of_le h₁ lemma Icc_subset_Ico_right (h₁ : b₁ < b₂) : Icc a b₁ ⊆ Ico a b₂ := λ x, and.imp_right $ λ h₂, lt_of_le_of_lt h₂ h₁ lemma Ioo_subset_Ico_self : Ioo a b ⊆ Ico a b := λ x, and.imp_left le_of_lt lemma Ico_subset_Icc_self : Ico a b ⊆ Icc a b := λ x, and.imp_right le_of_lt lemma Ioo_subset_Icc_self : Ioo a b ⊆ Icc a b := subset.trans Ioo_subset_Ico_self Ico_subset_Icc_self lemma Ico_subset_Iio_self : Ioo a b ⊆ Iio b := λ x, and.right lemma Icc_subset_Icc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Icc a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Ioo_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ < a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ico_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ioc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ a₂ < a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Iio_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iio b₂ ↔ b₁ < b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, lt_of_le_of_lt hx' h⟩ lemma Icc_subset_Ioi_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioi a₂ ↔ a₂ < a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, lt_of_lt_of_le h hx⟩ lemma Icc_subset_Iic_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iic b₂ ↔ b₁ ≤ b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, le_trans hx' h⟩ lemma Icc_subset_Ici_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ici a₂ ↔ a₂ ≤ a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, le_trans h hx⟩ end intervals section partial_order variables {α : Type*} [partial_order α] {a b : α} @[simp] lemma Icc_self (a : α) : Icc a a = {a} := set.ext $ by simp [Icc, le_antisymm_iff, and_comm] lemma Ico_diff_Ioo_eq_singleton (h : a < b) : Ico a b \ Ioo a b = {a} := set.ext $ λ x, begin simp, split, { rintro ⟨⟨ax, xb⟩, h⟩, exact eq.symm (classical.by_contradiction (λ ne, h (lt_of_le_of_ne ax ne) xb)) }, { rintro rfl, exact ⟨⟨le_refl _, h⟩, (lt_irrefl x).elim⟩ } end lemma Icc_diff_Ico_eq_singleton (h : a ≤ b) : Icc a b \ Ico a b = {b} := set.ext $ λ x, begin simp, split, { rintro ⟨⟨ax, xb⟩, h⟩, exact classical.by_contradiction (λ ne, h ax (lt_of_le_of_ne xb ne)) }, { rintro rfl, exact ⟨⟨h, le_refl _⟩, λ _, lt_irrefl x⟩ } end end partial_order section linear_order variables {α : Type*} [linear_order α] {a a₁ a₂ b b₁ b₂ : α} lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, let ⟨x, h₁, h₂⟩ := dense h in eq_empty_iff_forall_not_mem.1 eq x ⟨h₁, h₂⟩, Ioo_eq_empty⟩ lemma Ico_eq_empty_iff : Ico a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Ico_eq_empty⟩ lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ b < a := ⟨λ eq, lt_of_not_ge $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Icc_eq_empty⟩ lemma Ico_subset_Ico_iff (h₁ : a₁ < b₁) : Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, have a₂ ≤ a₁ ∧ a₁ < b₂ := h ⟨le_refl _, h₁⟩, ⟨this.1, le_of_not_lt $ λ h', lt_irrefl b₂ (h ⟨le_of_lt this.2, h'⟩).2⟩, λ ⟨h₁, h₂⟩, Ico_subset_Ico h₁ h₂⟩ lemma Ioo_subset_Ioo_iff [densely_ordered α] (h₁ : a₁ < b₁) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, begin rcases dense h₁ with ⟨x, xa, xb⟩, split; refine le_of_not_lt (λ h', _), { have ab := lt_trans (h ⟨xa, xb⟩).1 xb, exact lt_irrefl _ (h ⟨h', ab⟩).1 }, { have ab := lt_trans xa (h ⟨xa, xb⟩).2, exact lt_irrefl _ (h ⟨ab, h'⟩).2 } end, λ ⟨h₁, h₂⟩, Ioo_subset_Ioo h₁ h₂⟩ lemma Ico_eq_Ico_iff (h : a₁ < b₁ ∨ a₂ < b₂) : Ico a₁ b₁ = Ico a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨λ e, begin simp [subset.antisymm_iff] at e, simp [le_antisymm_iff], cases h; simp [Ico_subset_Ico_iff h] at e; [ rcases e with ⟨⟨h₁, h₂⟩, e'⟩, rcases e with ⟨e', ⟨h₁, h₂⟩⟩ ]; have := (Ico_subset_Ico_iff (lt_of_le_of_lt h₁ $ lt_of_lt_of_le h h₂)).1 e'; tauto end, λ ⟨h₁, h₂⟩, by rw [h₁, h₂]⟩ end linear_order section decidable_linear_order variables {α : Type*} [decidable_linear_order α] {a a₁ a₂ b b₁ b₂ : α} @[simp] lemma Ico_diff_Iio {a b c : α} : Ico a b \ Iio c = Ico (max a c) b := set.ext $ by simp [Ico, Iio, iff_def, max_le_iff] {contextual:=tt} @[simp] lemma Ico_inter_Iio {a b c : α} : Ico a b ∩ Iio c = Ico a (min b c) := set.ext $ by simp [Ico, Iio, iff_def, lt_min_iff] {contextual:=tt} lemma Ioo_inter_Ioo {a b c d : α} : Ioo a b ∩ Ioo c d = Ioo (max a c) (min b d) := set.ext $ by simp [iff_def, Ioo, lt_min_iff, max_lt_iff] {contextual := tt} end decidable_linear_order section ordered_comm_group variables {α : Type*} [ordered_comm_group α] lemma image_neg_Iio (r : α) : image (λz, -z) (Iio r) = Ioi (-r) := begin apply set.ext, intros z, apply iff.intro, { intros hz, apply exists.elim hz, intros z' hz', rw [←hz'.2], simp at *, exact hz'.1 }, { intros hz, simp at *, use -z, simp [hz], exact neg_lt.1 hz } end lemma image_neg_Iic (r : α) : image (λz, -z) (Iic r) = Ici (-r) := begin apply set.ext, intros z, apply iff.intro, { intros hz, apply exists.elim hz, intros z' hz', rw [←hz'.2], simp at *, exact hz'.1 }, { intros hz, simp at *, use -z, simp [hz], exact neg_le.1 hz } end end ordered_comm_group end set
80e11f8a4a3fb6789c9db529147f4f94c31987ba
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/scc.lean
1c56014d8d57aac7a5242fc53dad56ae8744557a
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
7,566
lean
/- Copyright (c) 2018 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon Tactics based on the strongly connected components (SCC) of a graph where the vertices are propositions and the edges are implications found in the context. They are used for finding the sets of equivalent propositions in a set of implications. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.tauto import Mathlib.data.sum import Mathlib.PostPort namespace Mathlib /-! # Strongly Connected Components This file defines tactics to construct proofs of equivalences between a set of mutually equivalent propositions. The tactics use implications transitively to find sets of equivalent propositions. ## Implementation notes The tactics use a strongly connected components algorithm on a graph where propositions are vertices and edges are proofs that the source implies the target. The strongly connected components are therefore sets of propositions that are pairwise equivalent to each other. The resulting strongly connected components are encoded in a disjoint set data structure to facilitate the construction of equivalence proofs between two arbitrary members of an equivalence class. ## Possible generalizations Instead of reasoning about implications and equivalence, we could generalize the machinery to reason about arbitrary partial orders. ## References * Tarjan, R. E. (1972), "Depth-first search and linear graph algorithms", SIAM Journal on Computing, 1 (2): 146–160, doi:10.1137/0201010 * Dijkstra, Edsger (1976), A Discipline of Programming, NJ: Prentice Hall, Ch. 25. * <https://en.wikipedia.org/wiki/Disjoint-set_data_structure> ## Tags graphs, tactic, strongly connected components, disjoint sets -/ namespace tactic /-- `closure` implements a disjoint set data structure using path compression optimization. For the sake of the scc algorithm, it also stores the preorder numbering of the equivalence graph of the local assumptions. The `expr_map` encodes a directed forest by storing for every non-root node, a reference to its parent and a proof of equivalence between that node's expression and its parent's expression. Given that data structure, checking that two nodes belong to the same tree is easy and fast by repeatedly following the parent references until a root is reached. If both nodes have the same root, they belong to the same tree, i.e. their expressions are equivalent. The proof of equivalence can be formed by composing the proofs along the edges of the paths to the root. More concretely, if we ignore preorder numbering, the set `{ {e₀,e₁,e₂,e₃}, {e₄,e₅} }` is represented as: ``` e₀ → ⊥ -- no parent, i.e. e₀ is a root e₁ → e₀, p₁ -- with p₁ : e₁ ↔ e₀ e₂ → e₁, p₂ -- with p₂ : e₂ ↔ e₁ e₃ → e₀, p₃ -- with p₃ : e₃ ↔ e₀ e₄ → ⊥ -- no parent, i.e. e₄ is a root e₅ → e₄, p₅ -- with p₅ : e₅ ↔ e₄ ``` We can check that `e₂` and `e₃` are equivalent by seeking the root of the tree of each. The parent of `e₂` is `e₁`, the parent of `e₁` is `e₀` and `e₀` does not have a parent, and thus, this is the root of its tree. The parent of `e₃` is `e₀` and it's also the root, the same as for `e₂` and they are therefore equivalent. We can build a proof of that equivalence by using transitivity on `p₂`, `p₁` and `p₃.symm` in that order. Similarly, we can discover that `e₂` and `e₅` aren't equivalent. A description of the path compression optimization can be found at: <https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Path_compression> -/ namespace closure /-- `with_new_closure f` creates an empty `closure` `c`, executes `f` on `c`, and then deletes `c`, returning the output of `f`. -/ /-- `to_tactic_format cl` pretty-prints the `closure` `cl` as a list. Assuming `cl` was built by `dfs_at`, each element corresponds to a node `pᵢ : expr` and is one of the folllowing: - if `pᵢ` is a root: `"pᵢ ⇐ i"`, where `i` is the preorder number of `pᵢ`, - otherwise: `"(pᵢ, pⱼ) : P"`, where `P` is `pᵢ ↔ pⱼ`. Useful for debugging. -/ /-- `(n,r,p) ← root cl e` returns `r` the root of the tree that `e` is a part of (which might be itself) along with `p` a proof of `e ↔ r` and `n`, the preorder numbering of the root. -/ /-- (Implementation of `merge`.) -/ /-- `merge cl p`, with `p` a proof of `e₀ ↔ e₁` for some `e₀` and `e₁`, merges the trees of `e₀` and `e₁` and keeps the root with the smallest preorder number as the root. This ensures that, in the depth-first traversal of the graph, when encountering an edge going into a vertex whose equivalence class includes a vertex that originated the current search, that vertex will be the root of the corresponding tree. -/ /-- Sequentially assign numbers to the nodes of the graph as they are being visited. -/ /-- `prove_eqv cl e₀ e₁` constructs a proof of equivalence of `e₀` and `e₁` if they are equivalent. -/ /-- `prove_impl cl e₀ e₁` constructs a proof of `e₀ -> e₁` if they are equivalent. -/ /-- `is_eqv cl e₀ e₁` checks whether `e₀` and `e₁` are equivalent without building a proof. -/ end closure /-- mutable graphs between local propositions that imply each other with the proof of implication -/ /-- `with_impl_graph f` creates an empty `impl_graph` `g`, executes `f` on `g`, and then deletes `g`, returning the output of `f`. -/ namespace impl_graph /-- `add_edge g p`, with `p` a proof of `v₀ → v₁` or `v₀ ↔ v₁`, adds an edge to the implication graph `g`. -/ /-- `merge_path path e`, where `path` and `e` forms a cycle with proofs of implication between consecutive vertices. The proofs are compiled into proofs of equivalences and added to the closure structure. `e` and the first vertex of `path` do not have to be the same but they have to be in the same equivalence class. -/ /-- (implementation of `collapse`) -/ /-- `collapse path v`, where `v` is a vertex that originated the current search (or a vertex in the same equivalence class as the one that originated the current search). It or its equivalent should be found in `path`. Since the vertices following `v` in the path form a cycle with `v`, they can all be added to an equivalence class. -/ /-- Strongly connected component algorithm inspired by Tarjan's and Dijkstra's scc algorithm. Whereas they return strongly connected components by enumerating them, this algorithm returns a disjoint set data structure using path compression. This is a compact representation that allows us, after the fact, to construct a proof of equivalence between any two members of an equivalence class. * Tarjan, R. E. (1972), "Depth-first search and linear graph algorithms", SIAM Journal on Computing, 1 (2): 146–160, doi:10.1137/0201010 * Dijkstra, Edsger (1976), A Discipline of Programming, NJ: Prentice Hall, Ch. 25. -/ /-- Use the local assumptions to create a set of equivalence classes. -/ end impl_graph /-- `scc` uses the available equivalences and implications to prove a goal of the form `p ↔ q`. ```lean example (p q r : Prop) (hpq : p → q) (hqr : q ↔ r) (hrp : r → p) : p ↔ r := by scc ``` -/ /-- Collect all the available equivalences and implications and add assumptions for every equivalence that can be proven using the strongly connected components technique. Mostly useful for testing. -/ /-- `scc` uses the available equivalences and implications to prove
3a58f24d8ef41b7b7367bb9e96328bcf6e313429
92b50235facfbc08dfe7f334827d47281471333b
/library/theories/number_theory/prime_factorization.lean
d4f993f8846b2d5dce1f8be4606a5485cc78531b
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
9,735
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Multiplicity and prime factors. We have: mult p n := the greatest power of p dividing n if p > 1 and n > 0, and 0 otherwise. prime_factors n := the finite set of prime factors of n, assuming n > 0 -/ import data.nat data.finset .primes open eq.ops finset well_founded decidable namespace nat /- multiplicity -/ theorem mult_rec_decreasing {p n : ℕ} (Hp : p > 1) (Hn : n > 0) : n div p < n := have H' : n < n * p, by rewrite [-mul_one n at {1}]; apply mul_lt_mul_of_pos_left Hp Hn, div_lt_of_lt_mul H' private definition mult.F (p : ℕ) (n : ℕ) (f: Π {m : ℕ}, m < n → ℕ) : ℕ := if H : (p > 1 ∧ n > 0) ∧ p ∣ n then succ (f (mult_rec_decreasing (and.left (and.left H)) (and.right (and.left H)))) else 0 definition mult (p n : ℕ) : ℕ := fix (mult.F p) n theorem mult_rec {p n : ℕ} (pgt1 : p > 1) (ngt0 : n > 0) (pdivn : p ∣ n) : mult p n = succ (mult p (n div p)) := have H : (p > 1 ∧ n > 0) ∧ p ∣ n, from and.intro (and.intro pgt1 ngt0) pdivn, eq.trans (well_founded.fix_eq (mult.F p) n) (dif_pos H) private theorem mult_base {p n : ℕ} (H : ¬ ((p > 1 ∧ n > 0) ∧ p ∣ n)) : mult p n = 0 := eq.trans (well_founded.fix_eq (mult.F p) n) (dif_neg H) theorem mult_zero_right (p : ℕ) : mult p 0 = 0 := mult_base (assume H, !lt.irrefl (and.right (and.left H))) theorem mult_eq_zero_of_not_dvd {p n : ℕ} (H : ¬ p ∣ n) : mult p n = 0 := mult_base (assume H', H (and.right H')) theorem mult_eq_zero_of_le_one {p : ℕ} (n : ℕ) (H : p ≤ 1) : mult p n = 0 := mult_base (assume H', not_lt_of_ge H (and.left (and.left H'))) theorem mult_zero_left (n : ℕ) : mult 0 n = 0 := mult_eq_zero_of_le_one n !dec_trivial theorem mult_one_left (n : ℕ) : mult 1 n = 0 := mult_eq_zero_of_le_one n !dec_trivial theorem mult_pos_of_dvd {p n : ℕ} (pgt1 : p > 1) (npos : n > 0) (pdvdn : p ∣ n) : mult p n > 0 := by rewrite (mult_rec pgt1 npos pdvdn); apply succ_pos theorem not_dvd_of_mult_eq_zero {p n : ℕ} (pgt1 : p > 1) (npos : n > 0) (H : mult p n = 0) : ¬ p ∣ n := assume pdvdn : p ∣ n, ne_of_gt (mult_pos_of_dvd pgt1 npos pdvdn) H theorem dvd_of_mult_pos {p n : ℕ} (H : mult p n > 0) : p ∣ n := by_contradiction (assume npdvdn : ¬ p ∣ n, ne_of_gt H (mult_eq_zero_of_not_dvd npdvdn)) /- properties of mult -/ theorem pow_mult_dvd (p n : ℕ) : p^(mult p n) ∣ n := begin induction n using nat.strong_induction_on with [n, ih], cases eq_zero_or_pos n with [nz, npos], {rewrite nz, apply dvd_zero}, cases le_or_gt p 1 with [ple1, pgt1], {rewrite [!mult_eq_zero_of_le_one ple1, pow_zero], apply one_dvd}, cases (or.swap (em (p ∣ n))) with [pndvdn, pdvdn], {rewrite [mult_eq_zero_of_not_dvd pndvdn, pow_zero], apply one_dvd}, show p ^ (mult p n) ∣ n, from dvd.elim pdvdn (take n', assume Hn' : n = p * n', have ppos : p > 0, from lt.trans zero_lt_one pgt1, assert ndivpeq : n div p = n', from !div_eq_of_eq_mul_right ppos Hn', assert ndivplt : n' < n, by rewrite -ndivpeq; apply mult_rec_decreasing pgt1 npos, begin rewrite [mult_rec pgt1 npos pdvdn, ndivpeq, pow_succ', Hn'], apply mul_dvd_mul !dvd.refl, apply ih _ ndivplt end) end theorem mult_one_right (p : ℕ) : mult p 1 = 0:= assert H : p^(mult p 1) = 1, from eq_one_of_dvd_one !pow_mult_dvd, or.elim (le_or_gt p 1) (assume H1 : p ≤ 1, by rewrite [!mult_eq_zero_of_le_one H1]) (assume H1 : p > 1, by_contradiction assume H2 : mult p 1 ≠ 0, have H3 : mult p 1 > 0, from pos_of_ne_zero H2, assert H4 : p^(mult p 1) > 1, from pow_gt_one H1 H3, show false, by rewrite H at H4; apply !lt.irrefl H4) private theorem mult_pow_mul {p n : ℕ} (i : ℕ) (pgt1 : p > 1) (npos : n > 0) : mult p (p^i * n) = i + mult p n := begin induction i with [i, ih], rewrite [pow_zero, one_mul, zero_add], -- strange: this fails with {brackets} around it have ppos : p > 0, from lt.trans zero_lt_one pgt1, have psin_pos : p^(succ i) * n > 0, from mul_pos (!pow_pos_of_pos ppos) npos, have pdvd : p ∣ p^(succ i) * n, by rewrite [pow_succ', mul.assoc]; apply dvd_mul_right, rewrite [mult_rec pgt1 psin_pos pdvd, pow_succ, mul.right_comm, !mul_div_cancel ppos, ih], rewrite [add.comm i, add.comm (succ i)] end theorem mult_pow {p : ℕ} (i : ℕ) (pgt1 : p > 1) : mult p (p^i) = i := by rewrite [-(mul_one (p^i)), mult_pow_mul i pgt1 zero_lt_one, mult_one_right] theorem le_mult {p i n : ℕ} (pgt1 : p > 1) (npos : n > 0) (pidvd : p^i ∣ n) : i ≤ mult p n := dvd.elim pidvd (take m, assume neq : n = p^i * m, assert mpos : m > 0, from pos_of_mul_pos_left (neq ▸ npos), by rewrite [neq, mult_pow_mul i pgt1 mpos]; apply le_add_right) theorem not_dvd_div_pow_mult {p n : ℕ} (pgt1 : p > 1) (npos : n > 0) : ¬ p ∣ n div p^(mult p n) := assume pdvd : p ∣ n div p^(mult p n), obtain m (H : n div p^(mult p n) = p * m), from exists_eq_mul_right_of_dvd pdvd, assert neq : n = p^(succ (mult p n)) * m, from calc n = p^mult p n * (n div p^mult p n) : by rewrite (mul_div_cancel' !pow_mult_dvd) ... = p^(succ (mult p n)) * m : by rewrite [H, pow_succ, mul.assoc], have H1 : p^(succ (mult p n)) ∣ n, by rewrite neq at {2}; apply dvd_mul_right, have H2 : succ (mult p n) ≤ mult p n, from le_mult pgt1 npos H1, show false, from !not_succ_le_self H2 theorem mult_mul {p m n : ℕ} (primep : prime p) (mpos : m > 0) (npos : n > 0) : mult p (m * n) = mult p m + mult p n := let m' := m div p^mult p m, n' := n div p^mult p n in assert pgt1 : p > 1, from gt_one_of_prime primep, assert meq : m = p^mult p m * m', by rewrite (mul_div_cancel' !pow_mult_dvd), assert neq : n = p^mult p n * n', by rewrite (mul_div_cancel' !pow_mult_dvd), have m'pos : m' > 0, from pos_of_mul_pos_left (meq ▸ mpos), have n'pos : n' > 0, from pos_of_mul_pos_left (neq ▸ npos), have npdvdm' : ¬ p ∣ m', from !not_dvd_div_pow_mult pgt1 mpos, have npdvdn' : ¬ p ∣ n', from !not_dvd_div_pow_mult pgt1 npos, assert npdvdm'n' : ¬ p ∣ m' * n', from not_dvd_mul_of_prime primep npdvdm' npdvdn', assert m'n'pos : m' * n' > 0, from mul_pos m'pos n'pos, assert multm'n' : mult p (m' * n') = 0, from mult_eq_zero_of_not_dvd npdvdm'n', calc mult p (m * n) = mult p (p^(mult p m + mult p n) * (m' * n')) : by rewrite [pow_add, mul.right_comm, -mul.assoc, -meq, mul.assoc, mul.comm (n div _), -neq] ... = mult p m + mult p n : by rewrite [!mult_pow_mul pgt1 m'n'pos, multm'n'] theorem dvd_of_forall_prime_mult_le {m n : ℕ} (mpos : m > 0) (H : ∀ {p}, prime p → mult p m ≤ mult p n) : m ∣ n := begin revert H, revert n, induction m using nat.strong_induction_on with [m, ih], cases (decidable.em (m = 1)) with [meq, mneq], {intros, rewrite meq, apply one_dvd}, have mgt1 : m > 1, from lt_of_le_of_ne (succ_le_of_lt mpos) (ne.symm mneq), have mge2 : m ≥ 2, from succ_le_of_lt mgt1, have hpd : ∃ p, prime p ∧ p ∣ m, from ex_prime_and_dvd mge2, cases hpd with [p, H1], cases H1 with [primep, pdvdm], intro n, cases (eq_zero_or_pos n) with [nz, npos], {intros; rewrite nz; apply dvd_zero}, assume H : ∀ {p : ℕ}, prime p → mult p m ≤ mult p n, obtain m' (meq : m = p * m'), from exists_eq_mul_right_of_dvd pdvdm, assert pgt1 : p > 1, from gt_one_of_prime primep, assert m'pos : m' > 0, from pos_of_ne_zero (assume m'z, by revert mpos; rewrite [meq, m'z, mul_zero]; apply not_lt_zero), have m'ltm : m' < m, by rewrite [meq, -one_mul m' at {1}]; apply mul_lt_mul_of_lt_of_le m'pos pgt1 !le.refl, have multpm : mult p m ≥ 1, from le_mult pgt1 mpos (by rewrite pow_one; apply pdvdm), have multpn : mult p n ≥ 1, from le.trans multpm (H primep), obtain n' (neq : n = p * n'), from exists_eq_mul_right_of_dvd (dvd_of_mult_pos (lt_of_succ_le multpn)), assert n'pos : n' > 0, from pos_of_ne_zero (assume n'z, by revert npos; rewrite [neq, n'z, mul_zero]; apply not_lt_zero), have H' : ∀q, prime q → mult q m' ≤ mult q n', from (take q, assume primeq : prime q, have multqm : mult q m = mult q p + mult q m', by rewrite [meq, mult_mul primeq (pos_of_prime primep) m'pos], have multqn : mult q n = mult q p + mult q n', by rewrite [neq, mult_mul primeq (pos_of_prime primep) n'pos], show mult q m' ≤ mult q n', from le_of_add_le_add_left (multqm ▸ multqn ▸ H primeq)), assert m'dvdn' : m' ∣ n', from ih m' m'ltm m'pos n' H', show m ∣ n, by rewrite [meq, neq]; apply mul_dvd_mul !dvd.refl m'dvdn' end theorem eq_of_forall_prime_mult_eq {m n : ℕ} (mpos : m > 0) (npos : n > 0) (H : ∀ {p}, prime p → mult p m = mult p n) : m = n := dvd.antisymm (dvd_of_forall_prime_mult_le mpos (take p, assume primep, H primep ▸ !le.refl)) (dvd_of_forall_prime_mult_le npos (take p, assume primep, H primep ▸ !le.refl)) /- prime factors -/ definition prime_factors (n : ℕ) : finset ℕ := { p ∈ upto (succ n) | prime p ∧ p ∣ n } theorem prime_of_mem_prime_factors {p n : ℕ} (H : p ∈ prime_factors n) : prime p := and.left (of_mem_filter H) theorem dvd_of_mem_prime_factors {p n : ℕ} (H : p ∈ prime_factors n) : p ∣ n := and.right (of_mem_filter H) theorem mem_prime_factors {p n : ℕ} (npos : n > 0) (primep : prime p) (pdvdn : p ∣ n) : p ∈ prime_factors n := have plen : p ≤ n, from le_of_dvd npos pdvdn, mem_filter_of_mem (mem_upto_of_lt (lt_succ_of_le plen)) (and.intro primep pdvdn) end nat
038827b26bc957a9264141c72b2353871f3558e0
7d5ad87afb17e514aee234fcf0a24412eed6384f
/src/abel.lean
7e972615828e11a8bd0e44c40d89f9750deeb637
[]
no_license
digama0/flypitch
764f849eaef59c045dfbeca142a0f827973e70c1
2ec14b8da6a3964f09521d17e51f363d255b030f
refs/heads/master
1,586,980,069,651
1,547,078,141,000
1,547,078,283,000
164,965,135
1
0
null
1,547,082,858,000
1,547,082,857,000
null
UTF-8
Lean
false
false
2,601
lean
import .fol tactic.tidy open fol local notation h :: t := dvector.cons h t local notation `[]` := dvector.nil local notation `[` l:(foldr `, ` (h t, dvector.cons h t) dvector.nil `]`) := l namespace abel section /- The language of abelian groups -/ inductive abel_functions : ℕ → Type | zero : abel_functions 0 | plus : abel_functions 2 def L_abel : Language := ⟨abel_functions, λn, empty⟩ def L_abel_plus {n} (t₁ t₂ : bounded_term L_abel n) : bounded_term L_abel n := @bounded_term_of_function L_abel 2 n abel_functions.plus t₁ t₂ def zero {n} : bounded_term L_abel n := bd_const abel_functions.zero infix ` +' `:100 := _root_.abel.L_abel_plus def a_assoc : sentence L_abel := ∀' ∀' ∀' (((&2 +' &1) +' &0) ≃ (&2 +' (&1 +' &0))) def a_zero_right : sentence L_abel := ∀' (&0 +' zero ≃ &0) def a_zero_left : sentence L_abel := ∀'(zero +' &0 ≃ &0) def a_inv : sentence L_abel := ∀' ∃' (&1 +' &0 ≃ zero ⊓ &0 +' &1 ≃ zero) def a_comm : sentence L_abel := ∀' ∀' (&1 +' &0 ≃ &0 +' &1) /- axioms of abelian groups -/ def T_ab : Theory L_abel := {a_assoc, a_zero_right, a_zero_left, a_inv, a_comm} def L_abel_structure_of_int : Structure L_abel := begin refine ⟨ℤ,_,_⟩, {intros n f, induction f, exact λ v, 0, exact λ v, (v.nth 0 (by repeat{constructor})) + (v.nth 1 (by repeat{constructor}))}, {intros, cases a} end notation `ℤ'` := _root_.abel.L_abel_structure_of_int @[simp]lemma ℤ'_ℤ : ↥(ℤ') = ℤ := by refl @[reducible]instance has_zero_ℤ' : has_zero ℤ' := ⟨(0 : ℤ)⟩ @[reducible]instance has_add_ℤ' : has_add ℤ' := ⟨λx y, (x + y : ℤ)⟩ @[reducible]instance nonempty_ℤ' : nonempty ℤ' := by simp @[simp]lemma zero_is_zero : @realize_bounded_term L_abel ℤ' _ [] _ zero [] = (0 : ℤ) := by refl @[simp]lemma plus_is_plus_l : ∀ x y : ℤ', realize_bounded_term ([x,y]) (&0 +' &1) [] = x + y := by {intros, refl} @[simp]lemma plus_is_plus_r : ∀ x y : ℤ', realize_bounded_term ([x,y]) (&1 +' &0) [] = y + x := by {intros, refl} def presburger_arithmetic : Theory L_abel := Th ℤ' theorem ℤ'_is_abelian_group : T_ab ⊆ presburger_arithmetic := begin intros a H, repeat{cases H}, {tidy}, {intros x H, dsimp at H, unfold realize_bounded_formula, have : ∃ y : ℤ, x + y = 0, by exact ⟨-x, by tidy⟩, rcases this with ⟨y, hy⟩, apply H y, simp[hy], refl}, {tidy, conv {to_lhs, change (0 : ℤ) + x, rw[zero_add]}, refl}, {tidy, conv {to_lhs, change x + 0, rw[add_zero]}, refl}, {tidy, conv {to_lhs, change x + x_1 + x_2}, finish} end end end abel
412ef36bb150bac6bb4752d7fc86b9d92daaac68
94e33a31faa76775069b071adea97e86e218a8ee
/src/group_theory/specific_groups/dihedral.lean
e6c44a0b85319faeb21b995ab6b802179581516a
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
5,859
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.fintype.card import data.zmod.basic import group_theory.exponent import data.int.parity /-! # Dihedral Groups We define the dihedral groups `dihedral_group n`, with elements `r i` and `sr i` for `i : zmod n`. For `n ≠ 0`, `dihedral_group 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_group 0` corresponds to the infinite dihedral group. -/ /-- For `n ≠ 0`, `dihedral_group 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_group 0` corresponds to the infinite dihedral group. -/ @[derive decidable_eq] inductive dihedral_group (n : ℕ) : Type | r : zmod n → dihedral_group | sr : zmod n → dihedral_group namespace dihedral_group variables {n : ℕ} /-- Multiplication of the dihedral group. -/ private def mul : dihedral_group n → dihedral_group n → dihedral_group 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_group n := r 0 instance : inhabited (dihedral_group n) := ⟨one⟩ /-- The inverse of a an element of the dihedral group. -/ private def inv : dihedral_group n → dihedral_group n | (r i) := r (-i) | (sr i) := sr i /-- The group structure on `dihedral_group n`. -/ instance : group (dihedral_group 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_group n) = r 0 := rfl private def fintype_helper : (zmod n ⊕ zmod n) ≃ dihedral_group 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_group n` is a finite group. -/ instance [fact (0 < n)] : fintype (dihedral_group n) := fintype.of_equiv _ fintype_helper instance : nontrivial (dihedral_group n) := ⟨⟨r 0, sr 0, dec_trivial⟩⟩ /-- If `0 < n`, then `dihedral_group n` has `2n` elements. -/ lemma card [fact (0 < n)] : fintype.card (dihedral_group n) = 2 * n := by rw [← fintype.card_eq.mpr ⟨fintype_helper⟩, fintype.card_sum, zmod.card, two_mul] @[simp] lemma r_one_pow (k : ℕ) : (r 1 : dihedral_group n) ^ k = r k := begin induction k with k IH, { rw nat.cast_zero, 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 rw [r_one_pow, one_def], congr' 1, exact zmod.nat_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 (i : zmod n) : order_of (sr i) = 2 := begin rw order_of_eq_prime _ _, { exact ⟨nat.prime_two⟩ }, rw [sq, sr_mul_self], dec_trivial, end /-- If `0 < n`, then `r 1` has order `n`. -/ @[simp] lemma order_of_r_one : order_of (r 1 : dihedral_group n) = n := begin rcases n.eq_zero_or_pos with rfl | hn, { rw order_of_eq_zero_iff', intros n hn, rw [r_one_pow, one_def], apply mt r.inj, simpa using hn.ne' }, { haveI := fact.mk hn, apply (nat.le_of_dvd hn $ order_of_dvd_of_pow_eq_one $ @r_one_pow_n n).lt_or_eq.resolve_left, intro h, have h1 : (r 1 : dihedral_group 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_nat_cast, nat.mod_eq_of_lt h] at h2, exact absurd h2.symm (order_of_pos _).ne }, 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.nat_cast_zmod_val i }, rw [←r_one_pow, order_of_pow, order_of_r_one] end lemma exponent : monoid.exponent (dihedral_group n) = lcm n 2 := begin rcases n.eq_zero_or_pos with rfl | hn, { exact monoid.exponent_eq_zero_of_order_zero order_of_r_one }, haveI := fact.mk hn, apply nat.dvd_antisymm, { apply monoid.exponent_dvd_of_forall_pow_eq_one, rintro (m | m), { rw [←order_of_dvd_iff_pow_eq_one, order_of_r], refine nat.dvd_trans ⟨gcd n m.val, _⟩ (dvd_lcm_left n 2), { exact (nat.div_mul_cancel (nat.gcd_dvd_left n m.val)).symm } }, { rw [←order_of_dvd_iff_pow_eq_one, order_of_sr], exact dvd_lcm_right n 2 } }, { apply lcm_dvd, { convert monoid.order_dvd_exponent (r 1), exact order_of_r_one.symm }, { convert monoid.order_dvd_exponent (sr 0), exact (order_of_sr 0).symm } } end end dihedral_group
033553f64b0dd3534382b4241c59ac5c5de7e4e1
0408d6ea582e97d5cc55ac8a0980d26df896ce66
/src/padics/padic_numbers.lean
60ff4839e6472f5770f5cf31395887dfb69a69ec
[]
no_license
lean-forward/coe_tactic
bba94535c7fb6ef65fcd81bedc28062b238a1594
d5c30df244c3402de6323a538e99b5324779a2cb
refs/heads/master
1,588,474,971,049
1,557,135,293,000
1,557,135,293,000
178,387,237
1
0
null
1,556,542,286,000
1,553,856,413,000
Lean
UTF-8
Lean
false
false
30,070
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis Define the p-adic numbers (rationals) ℚ_p as the completion of ℚ wrt the p-adic norm. Show that the p-adic norm extends to ℚ_p, that ℚ is embedded in ℚ_p, and that ℚ_p is complete -/ import data.real.cau_seq_completion topology.metric_space.cau_seq_filter import algebra.archimedean analysis.normed_space.basic import padics.padic_norm norm_cast noncomputable theory local attribute [instance, priority 1] classical.prop_decidable open nat multiplicity padic_norm cau_seq cau_seq.completion metric theorem nat.find_le {p q : ℕ → Prop} [decidable_pred p] [decidable_pred q] (h : ∀ n, q n → p n) (hp : ∃ n, p n) (hq : ∃ n, q n) : nat.find hp ≤ nat.find hq := nat.find_min' _ ((h _) (nat.find_spec hq)) @[norm_cast] theorem int.coe_nat_multiplicity (a b : ℕ) : multiplicity a b = multiplicity (a : ℤ) (b : ℤ) := begin apply roption.ext', { repeat {rw [← finite_iff_dom, finite_def]}, norm_cast, simp }, { intros h1 h2, apply _root_.le_antisymm; { apply nat.find_le, norm_cast, simp }} end @[reducible] def padic_seq (p : ℕ) [p.prime] := cau_seq _ (padic_norm p) namespace padic_seq section variables {p : ℕ} [nat.prime p] lemma stationary {f : cau_seq ℚ (padic_norm p)} (hf : ¬ f ≈ 0) : ∃ N, ∀ m n, m ≥ N → n ≥ N → padic_norm p (f n) = padic_norm p (f m) := have ∃ ε > 0, ∃ N1, ∀ j ≥ N1, ε ≤ padic_norm p (f j), from cau_seq.abv_pos_of_not_lim_zero $ not_lim_zero_of_not_congr_zero hf, let ⟨ε, hε, N1, hN1⟩ := this, ⟨N2, hN2⟩ := cau_seq.cauchy₂ f hε in ⟨ max N1 N2, λ n m hn hm, have padic_norm p (f n - f m) < ε, from hN2 _ _ (max_le_iff.1 hn).2 (max_le_iff.1 hm).2, have padic_norm p (f n - f m) < padic_norm p (f n), from lt_of_lt_of_le this $ hN1 _ (max_le_iff.1 hn).1, have padic_norm p (f n - f m) < max (padic_norm p (f n)) (padic_norm p (f m)), from lt_max_iff.2 (or.inl this), begin by_contradiction hne, rw ←padic_norm.neg p (f m) at hne, have hnam := add_eq_max_of_ne p hne, rw [padic_norm.neg, max_comm] at hnam, rw ←hnam at this, apply _root_.lt_irrefl _ (by simp at this; exact this) end ⟩ def stationary_point {f : padic_seq p} (hf : ¬ f ≈ 0) : ℕ := classical.some $ stationary hf lemma stationary_point_spec {f : padic_seq p} (hf : ¬ f ≈ 0) : ∀ {m n}, m ≥ stationary_point hf → n ≥ stationary_point hf → padic_norm p (f n) = padic_norm p (f m) := classical.some_spec $ stationary hf def norm (f : padic_seq p) : ℚ := if hf : f ≈ 0 then 0 else padic_norm p (f (stationary_point hf)) lemma norm_zero_iff (f : padic_seq p) : f.norm = 0 ↔ f ≈ 0 := begin constructor, { intro h, by_contradiction hf, unfold norm at h, split_ifs at h, apply hf, intros ε hε, existsi stationary_point hf, intros j hj, have heq := stationary_point_spec hf (le_refl _) hj, simpa [h, heq] }, { intro h, simp [norm, h] } end end section embedding open cau_seq variables {p : ℕ} [nat.prime p] lemma equiv_zero_of_val_eq_of_equiv_zero {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) (hf : f ≈ 0) : g ≈ 0 := λ ε hε, let ⟨i, hi⟩ := hf _ hε in ⟨i, λ j hj, by simpa [h] using hi _ hj⟩ lemma norm_nonzero_of_not_equiv_zero {f : padic_seq p} (hf : ¬ f ≈ 0) : f.norm ≠ 0 := hf ∘ f.norm_zero_iff.1 lemma norm_eq_norm_app_of_nonzero {f : padic_seq p} (hf : ¬ f ≈ 0) : ∃ k, f.norm = padic_norm p k ∧ k ≠ 0 := have heq : f.norm = padic_norm p (f $ stationary_point hf), by simp [norm, hf], ⟨f $ stationary_point hf, heq, λ h, norm_nonzero_of_not_equiv_zero hf (by simpa [h] using heq)⟩ lemma not_lim_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ lim_zero (const (padic_norm p) q) := λ h', hq $ const_lim_zero.1 h' lemma not_equiv_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ (const (padic_norm p) q) ≈ 0 := λ h : lim_zero (const (padic_norm p) q - 0), not_lim_zero_const_of_nonzero hq $ by simpa using h lemma norm_nonneg (f : padic_seq p) : f.norm ≥ 0 := if hf : f ≈ 0 then by simp [hf, norm] else by simp [norm, hf, padic_norm.nonneg] lemma lift_index_left_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v2 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max (stationary_point hf) (max v2 v3))) := let i := max (stationary_point hf) (max v2 v3) in begin apply stationary_point_spec hf, { apply le_max_left }, { apply le_refl } end lemma lift_index_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max (stationary_point hf) v3))) := let i := max v1 (max (stationary_point hf) v3) in begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_left _ v3 }, { apply le_max_right } }, { apply le_refl } end lemma lift_index_right {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v2 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max v2 (stationary_point hf)))) := let i := max v1 (max v2 (stationary_point hf)) in begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_right v2 }, { apply le_max_right } }, { apply le_refl } end end embedding end padic_seq section open padic_seq meta def index_simp_core (hh hf hg : expr) (at_ : interactive.loc := interactive.loc.ns [none]) : tactic unit := do [v1, v2, v3] ← [hh, hf, hg].mmap (λ n, tactic.mk_app ``stationary_point [n] <|> return n), e1 ← tactic.mk_app ``lift_index_left_left [hh, v2, v3] <|> return `(true), e2 ← tactic.mk_app ``lift_index_left [hf, v1, v3] <|> return `(true), e3 ← tactic.mk_app ``lift_index_right [hg, v1, v2] <|> return `(true), sl ← [e1, e2, e3].mfoldl (λ s e, simp_lemmas.add s e) simp_lemmas.mk, when at_.include_goal (tactic.simp_target sl), hs ← at_.get_locals, hs.mmap' (tactic.simp_hyp sl []) /-- This is a special-purpose tactic that lifts padic_norm (f (stationary_point f)) to padic_norm (f (max _ _ _)). -/ meta def tactic.interactive.padic_index_simp (l : interactive.parse interactive.types.pexpr_list) (at_ : interactive.parse interactive.types.location) : tactic unit := do [h, f, g] ← l.mmap tactic.i_to_expr, index_simp_core h f g at_ end namespace padic_seq section embedding open cau_seq variables {p : ℕ} [hp : nat.prime p] include hp lemma norm_mul (f g : padic_seq p) : (f * g).norm = f.norm * g.norm := if hf : f ≈ 0 then have hg : f * g ≈ 0, from mul_equiv_zero' _ hf, by simp [hf, hg, norm] else if hg : g ≈ 0 then have hf : f * g ≈ 0, from mul_equiv_zero _ hg, by simp [hf, hg, norm] else have hfg : ¬ f * g ≈ 0, by apply mul_not_equiv_zero; assumption, begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.mul end lemma eq_zero_iff_equiv_zero (f : padic_seq p) : mk f = 0 ↔ f ≈ 0 := mk_eq lemma ne_zero_iff_nequiv_zero (f : padic_seq p) : mk f ≠ 0 ↔ ¬ f ≈ 0 := not_iff_not.2 (eq_zero_iff_equiv_zero _) lemma norm_const (q : ℚ) : norm (const (padic_norm p) q) = padic_norm p q := if hq : q = 0 then have (const (padic_norm p) q) ≈ 0, by simp [hq]; apply setoid.refl (const (padic_norm p) 0), by subst hq; simp [norm, this] else have ¬ (const (padic_norm p) q) ≈ 0, from not_equiv_zero_const_of_nonzero hq, by simp [norm, this] lemma norm_image (a : padic_seq p) (ha : ¬ a ≈ 0) : (∃ (n : ℤ), a.norm = ↑p ^ (-n)) := let ⟨k, hk, hk'⟩ := norm_eq_norm_app_of_nonzero ha in by simpa [hk] using padic_norm.image p hk' lemma norm_one : norm (1 : padic_seq p) = 1 := have h1 : ¬ (1 : padic_seq p) ≈ 0, from one_not_equiv_zero _, by simp [h1, norm, hp.gt_one] private lemma norm_eq_of_equiv_aux {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) (h : padic_norm p (f (stationary_point hf)) ≠ padic_norm p (g (stationary_point hg))) (hgt : padic_norm p (f (stationary_point hf)) > padic_norm p (g (stationary_point hg))) : false := begin have hpn : padic_norm p (f (stationary_point hf)) - padic_norm p (g (stationary_point hg)) > 0, from sub_pos_of_lt hgt, cases hfg _ hpn with N hN, let i := max N (max (stationary_point hf) (stationary_point hg)), have hi : i ≥ N, from le_max_left _ _, have hN' := hN _ hi, padic_index_simp [N, hf, hg] at hN' h hgt, have hpne : padic_norm p (f i) ≠ padic_norm p (-(g i)), by rwa [ ←padic_norm.neg p (g i)] at h, let hpnem := add_eq_max_of_ne p hpne, have hpeq : padic_norm p ((f - g) i) = max (padic_norm p (f i)) (padic_norm p (g i)), { rwa padic_norm.neg at hpnem }, rw [hpeq, max_eq_left_of_lt hgt] at hN', have : padic_norm p (f i) < padic_norm p (f i), { apply lt_of_lt_of_le hN', apply sub_le_self, apply padic_norm.nonneg }, exact lt_irrefl _ this end private lemma norm_eq_of_equiv {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) : padic_norm p (f (stationary_point hf)) = padic_norm p (g (stationary_point hg)) := begin by_contradiction h, cases (decidable.em (padic_norm p (f (stationary_point hf)) > padic_norm p (g (stationary_point hg)))) with hgt hngt, { exact norm_eq_of_equiv_aux hf hg hfg h hgt }, { apply norm_eq_of_equiv_aux hg hf (setoid.symm hfg) (ne.symm h), apply lt_of_le_of_ne, apply le_of_not_gt hngt, apply h } end theorem norm_equiv {f g : padic_seq p} (hfg : f ≈ g) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from setoid.trans (setoid.symm hfg) hf, by simp [norm, hf, hg] else have hg : ¬ g ≈ 0, from hf ∘ setoid.trans hfg, by unfold norm; split_ifs; exact norm_eq_of_equiv hf hg hfg private lemma norm_nonarchimedean_aux {f g : padic_seq p} (hfg : ¬ f + g ≈ 0) (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : (f + g).norm ≤ max (f.norm) (g.norm) := begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.nonarchimedean end theorem norm_nonarchimedean (f g : padic_seq p) : (f + g).norm ≤ max (f.norm) (g.norm) := if hfg : f + g ≈ 0 then have 0 ≤ max (f.norm) (g.norm), from le_max_left_of_le (norm_nonneg _), by simpa [hfg, norm] else if hf : f ≈ 0 then have hfg' : f + g ≈ g, { change lim_zero (f - 0) at hf, show lim_zero (f + g - g), by simpa using hf }, have hcfg : (f + g).norm = g.norm, from norm_equiv hfg', have hcl : f.norm = 0, from (norm_zero_iff f).2 hf, have max (f.norm) (g.norm) = g.norm, by rw hcl; exact max_eq_right (norm_nonneg _), by rw [this, hcfg] else if hg : g ≈ 0 then have hfg' : f + g ≈ f, { change lim_zero (g - 0) at hg, show lim_zero (f + g - f), by simpa [add_sub_cancel'] using hg }, have hcfg : (f + g).norm = f.norm, from norm_equiv hfg', have hcl : g.norm = 0, from (norm_zero_iff g).2 hg, have max (f.norm) (g.norm) = f.norm, by rw hcl; exact max_eq_left (norm_nonneg _), by rw [this, hcfg] else norm_nonarchimedean_aux hfg hf hg lemma norm_eq {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from equiv_zero_of_val_eq_of_equiv_zero h hf, by simp [hf, hg, norm] else have hg : ¬ g ≈ 0, from λ hg, hf $ equiv_zero_of_val_eq_of_equiv_zero (by simp [h]) hg, begin simp [hg, hf, norm], let i := max (stationary_point hf) (stationary_point hg), have hpf : padic_norm p (f (stationary_point hf)) = padic_norm p (f i), { apply stationary_point_spec, apply le_max_left, apply le_refl }, have hpg : padic_norm p (g (stationary_point hg)) = padic_norm p (g i), { apply stationary_point_spec, apply le_max_right, apply le_refl }, rw [hpf, hpg, h] end lemma norm_neg (a : padic_seq p) : (-a).norm = a.norm := norm_eq $ by simp lemma norm_eq_of_add_equiv_zero {f g : padic_seq p} (h : f + g ≈ 0) : f.norm = g.norm := have lim_zero (f + g - 0), from h, have f ≈ -g, from show lim_zero (f - (-g)), by simpa, have f.norm = (-g).norm, from norm_equiv this, by simpa [norm_neg] using this lemma add_eq_max_of_ne {f g : padic_seq p} (hfgne : f.norm ≠ g.norm) : (f + g).norm = max f.norm g.norm := have hfg : ¬f + g ≈ 0, from mt norm_eq_of_add_equiv_zero hfgne, if hf : f ≈ 0 then have lim_zero (f - 0), from hf, have f + g ≈ g, from show lim_zero ((f + g) - g), by simpa, have h1 : (f+g).norm = g.norm, from norm_equiv this, have h2 : f.norm = 0, from (norm_zero_iff _).2 hf, by rw [h1, h2]; rw max_eq_right (norm_nonneg _) else if hg : g ≈ 0 then have lim_zero (g - 0), from hg, have f + g ≈ f, from show lim_zero ((f + g) - f), by rw [add_sub_cancel']; simpa, have h1 : (f+g).norm = f.norm, from norm_equiv this, have h2 : g.norm = 0, from (norm_zero_iff _).2 hg, by rw [h1, h2]; rw max_eq_left (norm_nonneg _) else begin unfold norm at ⊢ hfgne, split_ifs at ⊢ hfgne, padic_index_simp [hfg, hf, hg] at ⊢ hfgne, apply padic_norm.add_eq_max_of_ne, simpa [hf, hg, norm] using hfgne end end embedding end padic_seq def padic (p : ℕ) [nat.prime p] := @cau_seq.completion.Cauchy _ _ _ _ (padic_norm p) _ notation `ℚ_[` p `]` := padic p namespace padic section completion variables {p : ℕ} [nat.prime p] instance discrete_field : discrete_field (ℚ_[p]) := cau_seq.completion.discrete_field -- short circuits instance : has_zero ℚ_[p] := by apply_instance instance : has_one ℚ_[p] := by apply_instance instance : has_add ℚ_[p] := by apply_instance instance : has_mul ℚ_[p] := by apply_instance instance : has_sub ℚ_[p] := by apply_instance instance : has_neg ℚ_[p] := by apply_instance instance : has_div ℚ_[p] := by apply_instance instance : add_comm_group ℚ_[p] := by apply_instance instance : comm_ring ℚ_[p] := by apply_instance def mk : padic_seq p → ℚ_[p] := quotient.mk end completion section completion variables (p : ℕ) [nat.prime p] lemma mk_eq {f g : padic_seq p} : mk f = mk g ↔ f ≈ g := quotient.eq def of_rat : ℚ → ℚ_[p] := cau_seq.completion.of_rat @[simp] lemma of_rat_add : ∀ (x y : ℚ), of_rat p (x + y) = of_rat p x + of_rat p y := cau_seq.completion.of_rat_add @[simp] lemma of_rat_neg : ∀ (x : ℚ), of_rat p (-x) = -of_rat p x := cau_seq.completion.of_rat_neg @[simp] lemma of_rat_mul : ∀ (x y : ℚ), of_rat p (x * y) = of_rat p x * of_rat p y := cau_seq.completion.of_rat_mul @[simp] lemma of_rat_sub : ∀ (x y : ℚ), of_rat p (x - y) = of_rat p x - of_rat p y := cau_seq.completion.of_rat_sub @[simp] lemma of_rat_div : ∀ (x y : ℚ), of_rat p (x / y) = of_rat p x / of_rat p y := cau_seq.completion.of_rat_div @[simp] lemma of_rat_one : of_rat p 1 = 1 := rfl @[simp] lemma of_rat_zero : of_rat p 0 = 0 := rfl @[simp] lemma cast_eq_of_rat_of_nat (n : ℕ) : (↑n : ℚ_[p]) = of_rat p n := begin induction n with n ih, { refl }, { simpa using ih } end -- without short circuits, this needs an increase of class.instance_max_depth @[simp] lemma cast_eq_of_rat_of_int (n : ℤ) : ↑n = of_rat p n := by induction n; simp lemma cast_eq_of_rat : ∀ (q : ℚ), (↑q : ℚ_[p]) = of_rat p q | ⟨n, d, h1, h2⟩ := show ↑n / ↑d = _, from have (⟨n, d, h1, h2⟩ : ℚ) = rat.mk n d, from rat.num_denom _, by simp [this, rat.mk_eq_div, of_rat_div] @[norm_cast] lemma coe_add : ∀ {x y : ℚ}, (↑(x + y) : ℚ_[p]) = ↑x + ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_neg : ∀ {x : ℚ}, (↑(-x) : ℚ_[p]) = -↑x := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_mul : ∀ {x y : ℚ}, (↑(x * y) : ℚ_[p]) = ↑x * ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_sub : ∀ {x y : ℚ}, (↑(x - y) : ℚ_[p]) = ↑x - ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_div : ∀ {x y : ℚ}, (↑(x / y) : ℚ_[p]) = ↑x / ↑y := by simp [cast_eq_of_rat] @[simp_cast] lemma coe_one : (↑1 : ℚ_[p]) = 1 := rfl @[simp_cast] lemma coe_zero : (↑1 : ℚ_[p]) = 1 := rfl lemma const_equiv {q r : ℚ} : const (padic_norm p) q ≈ const (padic_norm p) r ↔ q = r := ⟨ λ heq : lim_zero (const (padic_norm p) (q - r)), eq_of_sub_eq_zero $ const_lim_zero.1 heq, λ heq, by rw heq; apply setoid.refl _ ⟩ lemma of_rat_eq {q r : ℚ} : of_rat p q = of_rat p r ↔ q = r := ⟨(const_equiv p).1 ∘ quotient.eq.1, λ h, by rw h⟩ @[norm_cast] lemma coe_inj {q r : ℚ} : (↑q : ℚ_[p]) = ↑r ↔ q = r := by simp [cast_eq_of_rat, of_rat_eq] instance : char_zero ℚ_[p] := have ∀ n : ℕ, (↑(↑n : ℚ) : ℚ_[p]) = ↑n, by simp, ⟨λ m n, by {rw_mod_cast ← this, refl}⟩ end completion end padic def padic_norm_e {p : ℕ} [hp : nat.prime p] : ℚ_[p] → ℚ := quotient.lift padic_seq.norm $ @padic_seq.norm_equiv _ _ namespace padic_norm_e section embedding open padic_seq variables {p : ℕ} [nat.prime p] lemma defn (f : padic_seq p) {ε : ℚ} (hε : ε > 0) : ∃ N, ∀ i ≥ N, padic_norm_e (⟦f⟧ - f i) < ε := begin simp only [padic.cast_eq_of_rat], change ∃ N, ∀ i ≥ N, (f - const _ (f i)).norm < ε, by_contradiction h, cases cauchy₂ f hε with N hN, have : ∀ N, ∃ i ≥ N, (f - const _ (f i)).norm ≥ ε, by simpa [not_forall] using h, rcases this N with ⟨i, hi, hge⟩, have hne : ¬ (f - const (padic_norm p) (f i)) ≈ 0, { intro h, unfold padic_seq.norm at hge; split_ifs at hge, exact not_lt_of_ge hge hε }, unfold padic_seq.norm at hge; split_ifs at hge, apply not_le_of_gt _ hge, cases decidable.em ((stationary_point hne) ≥ N) with hgen hngen, { apply hN; assumption }, { have := stationary_point_spec hne (le_refl _) (le_of_not_le hngen), rw ←this, apply hN, apply le_refl, assumption } end protected lemma nonneg (q : ℚ_[p]) : padic_norm_e q ≥ 0 := quotient.induction_on q $ norm_nonneg lemma zero_def : (0 : ℚ_[p]) = ⟦0⟧ := rfl lemma zero_iff (q : ℚ_[p]) : padic_norm_e q = 0 ↔ q = 0 := quotient.induction_on q $ by simpa only [zero_def, quotient.eq] using norm_zero_iff @[simp] protected lemma zero : padic_norm_e (0 : ℚ_[p]) = 0 := (zero_iff _).2 rfl @[simp] protected lemma one' : padic_norm_e (1 : ℚ_[p]) = 1 := norm_one @[simp] protected lemma neg (q : ℚ_[p]) : padic_norm_e (-q) = padic_norm_e q := quotient.induction_on q $ norm_neg theorem nonarchimedean' (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ norm_nonarchimedean theorem add_eq_max_of_ne' {q r : ℚ_[p]} : padic_norm_e q ≠ padic_norm_e r → padic_norm_e (q + r) = max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ λ _ _, padic_seq.add_eq_max_of_ne lemma triangle_ineq (x y z : ℚ_[p]) : padic_norm_e (x - z) ≤ padic_norm_e (x - y) + padic_norm_e (y - z) := calc padic_norm_e (x - z) = padic_norm_e ((x - y) + (y - z)) : by rw sub_add_sub_cancel ... ≤ max (padic_norm_e (x - y)) (padic_norm_e (y - z)) : padic_norm_e.nonarchimedean' _ _ ... ≤ padic_norm_e (x - y) + padic_norm_e (y - z) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma add (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ (padic_norm_e q) + (padic_norm_e r) := calc padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) : nonarchimedean' _ _ ... ≤ (padic_norm_e q) + (padic_norm_e r) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma mul' (q r : ℚ_[p]) : padic_norm_e (q * r) = (padic_norm_e q) * (padic_norm_e r) := quotient.induction_on₂ q r $ norm_mul instance : is_absolute_value (@padic_norm_e p _) := { abv_nonneg := padic_norm_e.nonneg, abv_eq_zero := zero_iff, abv_add := padic_norm_e.add, abv_mul := padic_norm_e.mul' } @[simp] lemma eq_padic_norm' (q : ℚ) : padic_norm_e (padic.of_rat p q) = padic_norm p q := norm_const _ protected theorem image' {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, padic_norm_e q = p ^ (-n) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (ne_zero_iff_nequiv_zero f).1 hf, norm_image f this lemma sub_rev (q r : ℚ_[p]) : padic_norm_e (q - r) = padic_norm_e (r - q) := by rw ←(padic_norm_e.neg); simp end embedding end padic_norm_e namespace padic section complete open padic_seq padic theorem rat_dense' {p : ℕ} [nat.prime p] (q : ℚ_[p]) {ε : ℚ} (hε : ε > 0) : ∃ r : ℚ, padic_norm_e (q - r) < ε := quotient.induction_on q $ λ q', have ∃ N, ∀ m n ≥ N, padic_norm p (q' m - q' n) < ε, from cauchy₂ _ hε, let ⟨N, hN⟩ := this in ⟨q' N, begin simp only [padic.cast_eq_of_rat], change padic_seq.norm (q' - const _ (q' N)) < ε, cases decidable.em ((q' - const (padic_norm p) (q' N)) ≈ 0) with heq hne', { simpa only [heq, padic_seq.norm, dif_pos] }, { simp only [padic_seq.norm, dif_neg hne'], change padic_norm p (q' _ - q' _) < ε, have := stationary_point_spec hne', cases decidable.em (N ≥ stationary_point hne') with hle hle, { have := eq.symm (this (le_refl _) hle), simp at this, simpa [this] }, { apply hN, apply le_of_lt, apply lt_of_not_ge, apply hle, apply le_refl }} end⟩ variables {p : ℕ} [nat.prime p] (f : cau_seq _ (@padic_norm_e p _)) open classical private lemma div_nat_pos (n : ℕ) : (1 / ((n + 1): ℚ)) > 0 := div_pos zero_lt_one (by exact_mod_cast succ_pos _) def lim_seq : ℕ → ℚ := λ n, classical.some (rat_dense' (f n) (div_nat_pos n)) lemma exi_rat_seq_conv {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (f i - ((lim_seq f) i : ℚ_[p])) < ε := begin refine (exists_nat_gt (1/ε)).imp (λ N hN i hi, _), have h := classical.some_spec (rat_dense' (f i) (div_nat_pos i)), refine lt_of_lt_of_le h (div_le_of_le_mul (by exact_mod_cast succ_pos _) _), rw right_distrib, apply le_add_of_le_of_nonneg, { exact le_mul_of_div_le hε (le_trans (le_of_lt hN) (by exact_mod_cast hi)) }, { apply le_of_lt, simpa } end lemma exi_rat_seq_conv_cauchy : is_cau_seq (padic_norm p) (lim_seq f) := assume ε hε, have hε3 : ε / 3 > 0, from div_pos hε (by norm_num), let ⟨N, hN⟩ := exi_rat_seq_conv f hε3, ⟨N2, hN2⟩ := f.cauchy₂ hε3 in begin existsi max N N2, intros j hj, suffices : padic_norm_e ((↑(lim_seq f j) - f (max N N2)) + (f (max N N2) - lim_seq f (max N N2))) < ε, { ring at this ⊢, rw [← padic_norm_e.eq_padic_norm', ← padic.cast_eq_of_rat], exact_mod_cast this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : (3 : ℚ) ≠ 0, by norm_num, have : ε = ε / 3 + ε / 3 + ε / 3, { apply eq_of_mul_eq_mul_left this, simp [left_distrib, mul_div_cancel' _ this ], ring }, rw this, apply add_lt_add, { suffices : padic_norm_e ((↑(lim_seq f j) - f j) + (f j - f (max N N2))) < ε / 3 + ε / 3, by simpa, apply lt_of_le_of_lt, { apply padic_norm_e.add }, { apply add_lt_add, { rw [padic_norm_e.sub_rev], apply_mod_cast hN, exact le_of_max_le_left hj }, { apply hN2, exact le_of_max_le_right hj, apply le_max_right }}}, { apply_mod_cast hN, apply le_max_left }}} end private def lim' : padic_seq p := ⟨_, exi_rat_seq_conv_cauchy f⟩ private def lim : ℚ_[p] := ⟦lim' f⟧ theorem complete' : ∃ q : ℚ_[p], ∀ ε > 0, ∃ N, ∀ i ≥ N, padic_norm_e (q - f i) < ε := ⟨ lim f, λ ε hε, let ⟨N, hN⟩ := exi_rat_seq_conv f (show ε / 2 > 0, from div_pos hε (by norm_num)), ⟨N2, hN2⟩ := padic_norm_e.defn (lim' f) (show ε / 2 > 0, from div_pos hε (by norm_num)) in begin existsi max N N2, intros i hi, suffices : padic_norm_e ((lim f - lim' f i) + (lim' f i - f i)) < ε, { ring at this; exact this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : ε = ε / 2 + ε / 2, by rw ←(add_self_div_two ε); simp, rw this, apply add_lt_add, { apply hN2, exact le_of_max_le_right hi }, { rw_mod_cast [padic_norm_e.sub_rev], apply hN, exact le_of_max_le_left hi }}} end ⟩ end complete section normed_space variables (p : ℕ) [nat.prime p] instance : has_dist ℚ_[p] := ⟨λ x y, padic_norm_e (x - y)⟩ instance : metric_space ℚ_[p] := { dist_self := by simp [dist], dist_comm := λ x y, by unfold dist; rw ←padic_norm_e.neg (x - y); simp, dist_triangle := begin intros, unfold dist, exact_mod_cast padic_norm_e.triangle_ineq _ _ _, end, eq_of_dist_eq_zero := begin unfold dist, intros _ _ h, apply eq_of_sub_eq_zero, apply (padic_norm_e.zero_iff _).1, exact_mod_cast h end } instance : has_norm ℚ_[p] := ⟨λ x, padic_norm_e x⟩ instance : normed_field ℚ_[p] := { dist_eq := λ _ _, rfl, norm_mul := by simp [has_norm.norm, padic_norm_e.mul'] } instance : is_absolute_value (λ a : ℚ_[p], ∥a∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := norm_eq_zero, abv_add := norm_triangle, abv_mul := by simp [has_norm.norm, padic_norm_e.mul'] } theorem rat_dense {p : ℕ} {hp : p.prime} (q : ℚ_[p]) {ε : ℝ} (hε : ε > 0) : ∃ r : ℚ, ∥q - r∥ < ε := let ⟨ε', hε'l, hε'r⟩ := exists_rat_btwn hε, ⟨r, hr⟩ := rat_dense' q (by simpa using hε'l) in ⟨r, lt.trans (by simpa [has_norm.norm] using hr) hε'r⟩ end normed_space end padic namespace padic_norm_e section normed_space variables {p : ℕ} [hp : p.prime] include hp @[simp] protected lemma mul (q r : ℚ_[p]) : ∥q * r∥ = ∥q∥ * ∥r∥ := by simp [has_norm.norm, padic_norm_e.mul'] protected lemma is_norm (q : ℚ_[p]) : ↑(padic_norm_e q) = ∥q∥ := rfl theorem nonarchimedean (q r : ℚ_[p]) : ∥q + r∥ ≤ max (∥q∥) (∥r∥) := begin unfold has_norm.norm, exact_mod_cast nonarchimedean' _ _ end theorem add_eq_max_of_ne {q r : ℚ_[p]} (h : ∥q∥ ≠ ∥r∥) : ∥q+r∥ = max (∥q∥) (∥r∥) := begin unfold has_norm.norm, apply_mod_cast add_eq_max_of_ne', intro h', apply h, unfold has_norm.norm, exact_mod_cast h' end @[simp] lemma eq_padic_norm (q : ℚ) : ∥(↑q : ℚ_[p])∥ = padic_norm p q := begin unfold has_norm.norm, rw [← padic_norm_e.eq_padic_norm', ← padic.cast_eq_of_rat] end instance : nondiscrete_normed_field ℚ_[p] := { non_trivial := ⟨padic.of_rat p (p⁻¹), begin have h0 : p ≠ 0 := ne_of_gt (hp.pos), have h1 : 1 < p := prime.gt_one hp, rw [← padic.cast_eq_of_rat, eq_padic_norm], simp only [padic_norm, inv_eq_zero], rw if_neg, swap, exact_mod_cast h0, norm_cast, rw padic_val_rat.inv, swap, exact_mod_cast h0, rw [neg_neg, padic_val_rat.padic_val_rat_self h1], erw _root_.pow_one, exact_mod_cast h1, end⟩ } protected theorem image {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, ∥q∥ = ↑((↑p : ℚ) ^ (-n)) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (padic_seq.ne_zero_iff_nequiv_zero f).1 hf, let ⟨n, hn⟩ := padic_seq.norm_image f this in ⟨n, congr_arg rat.cast hn⟩ protected lemma is_rat (q : ℚ_[p]) : ∃ q' : ℚ, ∥q∥ = ↑q' := if h : q = 0 then ⟨0, by simp [h]⟩ else let ⟨n, hn⟩ := padic_norm_e.image h in ⟨_, hn⟩ def rat_norm (q : ℚ_[p]) : ℚ := classical.some (padic_norm_e.is_rat q) lemma eq_rat_norm (q : ℚ_[p]) : ∥q∥ = rat_norm q := classical.some_spec (padic_norm_e.is_rat q) theorem norm_rat_le_one : ∀ {q : ℚ} (hq : ¬ p ∣ q.denom), ∥(q : ℚ_[p])∥ ≤ 1 | ⟨n, d, hn, hd⟩ := λ hq : ¬ p ∣ d, if hnz : n = 0 then have (⟨n, d, hn, hd⟩ : ℚ) = 0, from rat.zero_iff_num_zero.mpr hnz, by norm_num [this] else begin have hnz' : {rat . num := n, denom := d, pos := hn, cop := hd} ≠ 0, from mt rat.zero_iff_num_zero.1 hnz, rw [padic_norm_e.eq_padic_norm], norm_cast, rw [padic_norm.eq_fpow_of_nonzero p hnz', padic_val_rat_def p hnz'], have h : (multiplicity p d).get _ = 0, by simp [multiplicity_eq_zero_of_not_dvd, hq], rw_mod_cast [h, sub_zero], apply fpow_le_one_of_nonpos, { exact_mod_cast le_of_lt hp.gt_one, }, { apply neg_nonpos_of_nonneg, norm_cast, simp, } end lemma eq_of_norm_add_lt_right {p : ℕ} {hp : p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_right) h lemma eq_of_norm_add_lt_left {p : ℕ} {hp : p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_left) h end normed_space end padic_norm_e namespace padic variables {p : ℕ} [nat.prime p] set_option eqn_compiler.zeta true instance complete : cau_seq.is_complete ℚ_[p] norm := begin split, intro f, have cau_seq_norm_e : is_cau_seq padic_norm_e f, by { intros ε hε, let h := is_cau f ε (by exact_mod_cast hε), unfold norm at h, apply_mod_cast h, }, cases padic.complete' ⟨f, cau_seq_norm_e⟩ with q hq, existsi q, intros ε hε, cases exists_rat_btwn hε with ε' hε', norm_cast at hε', cases hq ε' hε'.1 with N hN, existsi N, intros i hi, let h := hN i hi, unfold norm, rw_mod_cast [cau_seq.sub_apply, padic_norm_e.sub_rev], refine lt.trans _ hε'.2, exact_mod_cast hN i hi end lemma padic_norm_e_lim_le {f : cau_seq ℚ_[p] norm} {a : ℝ} (ha : a > 0) (hf : ∀ i, ∥f i∥ ≤ a) : ∥f.lim∥ ≤ a := let ⟨N, hN⟩ := setoid.symm (cau_seq.equiv_lim f) _ ha in calc ∥f.lim∥ = ∥f.lim - f N + f N∥ : by simp ... ≤ max (∥f.lim - f N∥) (∥f N∥) : padic_norm_e.nonarchimedean _ _ ... ≤ a : max_le (le_of_lt (hN _ (le_refl _))) (hf _) end padic
6870a839dc63e41586689783ef81518873e93735
e151e9053bfd6d71740066474fc500a087837323
/src/hott/types/nat/default.lean
a05f644c346f7004b77b9236f7154a11f1b0da4f
[ "Apache-2.0" ]
permissive
daniel-carranza/hott3
15bac2d90589dbb952ef15e74b2837722491963d
913811e8a1371d3a5751d7d32ff9dec8aa6815d9
refs/heads/master
1,610,091,349,670
1,596,222,336,000
1,596,222,336,000
241,957,822
0
0
Apache-2.0
1,582,222,839,000
1,582,222,838,000
null
UTF-8
Lean
false
false
196
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import .basic .order .sub .hott .div
434897738f06073bb538e833a24d7345f4615f6d
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/topology/metric_space/pi_Lp.lean
a5ca82948f30e611c91d3fcc917db986f0d9a782
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
15,311
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.mean_inequalities /-! # `L^p` distance on finite products of metric spaces Given finitely many metric spaces, one can put the max distance on their product, but there is also a whole family of natural distances, indexed by a real parameter `p ∈ [1, ∞)`, that also induce the product topology. We define them in this file. The distance on `Π i, α i` is given by $$ d(x, y) = \left(\sum d(x_i, y_i)^p\right)^{1/p}. $$ We give instances of this construction for emetric spaces, metric spaces, normed groups and normed spaces. To avoid conflicting instances, all these are defined on a copy of the original Pi type, named `pi_Lp p hp α`, where `hp : 1 ≤ p`. This assumption is included in the definition of the type to make sure that it is always available to typeclass inference to construct the instances. We ensure that the topology and uniform structure on `pi_Lp p hp α` are (defeq to) the product topology and product uniformity, to be able to use freely continuity statements for the coordinate functions, for instance. ## Implementation notes We only deal with the `L^p` distance on a product of finitely many metric spaces, which may be distinct. A closely related construction is the `L^p` norm on the space of functions from a measure space to a normed space, where the norm is $$ \left(\int ∥f (x)∥^p dμ\right)^{1/p}. $$ However, the topology induced by this construction is not the product topology, this only defines a seminorm (as almost everywhere zero functions have zero `L^p` norm), and some functions have infinite `L^p` norm. All these subtleties are not present in the case of finitely many metric spaces (which corresponds to the basis which is a finite space with the counting measure), hence it is worth devoting a file to this specific case which is particularly well behaved. The general case is not yet formalized in mathlib. To prove that the topology (and the uniform structure) on a finite product with the `L^p` distance are the same as those coming from the `L^∞` distance, we could argue that the `L^p` and `L^∞` norms are equivalent on `ℝ^n` for abstract (norm equivalence) reasons. Instead, we give a more explicit (easy) proof which provides a comparison between these two norms with explicit constants. We also set up the theory for `pseudo_emetric_space` and `pseudo_metric_space`. -/ open real set filter open_locale big_operators uniformity topological_space nnreal ennreal noncomputable theory variables {ι : Type*} /-- A copy of a Pi type, on which we will put the `L^p` distance. Since the Pi type itself is already endowed with the `L^∞` distance, we need the type synonym to avoid confusing typeclass resolution. Also, we let it depend on `p`, to get a whole family of type on which we can put different distances, and we provide the assumption `hp` in the definition, to make it available to typeclass resolution when it looks for a distance on `pi_Lp p hp α`. -/ @[nolint unused_arguments] def pi_Lp {ι : Type*} (p : ℝ) (hp : 1 ≤ p) (α : ι → Type*) : Type* := Π (i : ι), α i instance {ι : Type*} (p : ℝ) (hp : 1 ≤ p) (α : ι → Type*) [∀ i, inhabited (α i)] : inhabited (pi_Lp p hp α) := ⟨λ i, default (α i)⟩ namespace pi_Lp variables (p : ℝ) (hp : 1 ≤ p) (α : ι → Type*) (β : ι → Type*) /-- Canonical bijection between `pi_Lp p hp α` and the original Pi type. We introduce it to be able to compare the `L^p` and `L^∞` distances through it. -/ protected def equiv : pi_Lp p hp α ≃ Π (i : ι), α i := equiv.refl _ section /-! ### The uniformity on finite `L^p` products is the product uniformity In this section, we put the `L^p` edistance on `pi_Lp p hp α`, and we check that the uniformity coming from this edistance coincides with the product uniformity, by showing that the canonical map to the Pi type (with the `L^∞` distance) is a uniform embedding, as it is both Lipschitz and antiLipschitz. We only register this emetric space structure as a temporary instance, as the true instance (to be registered later) will have as uniformity exactly the product uniformity, instead of the one coming from the edistance (which is equal to it, but not defeq). See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ variables [∀ i, emetric_space (α i)] [∀ i, pseudo_emetric_space (β i)] [fintype ι] /-- Endowing the space `pi_Lp p hp β` with the `L^p` pseudoedistance. This definition is not satisfactory, as it does not register the fact that the topology and the uniform structure coincide with the product one. Therefore, we do not register it as an instance. Using this as a temporary pseudoemetric space instance, we will show that the uniform structure is equal (but not defeq) to the product one, and then register an instance in which we replace the uniform structure by the product one using this pseudoemetric space and `pseudo_emetric_space.replace_uniformity`. -/ def pseudo_emetric_aux : pseudo_emetric_space (pi_Lp p hp β) := have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, { edist := λ f g, (∑ (i : ι), (edist (f i) (g i)) ^ p) ^ (1/p), edist_self := λ f, by simp [edist, ennreal.zero_rpow_of_pos pos, ennreal.zero_rpow_of_pos (inv_pos.2 pos)], edist_comm := λ f g, by simp [edist, edist_comm], edist_triangle := λ f g h, calc (∑ (i : ι), edist (f i) (h i) ^ p) ^ (1 / p) ≤ (∑ (i : ι), (edist (f i) (g i) + edist (g i) (h i)) ^ p) ^ (1 / p) : begin apply ennreal.rpow_le_rpow _ (one_div_nonneg.2 $ le_of_lt pos), refine finset.sum_le_sum (λ i hi, _), exact ennreal.rpow_le_rpow (edist_triangle _ _ _) (le_trans zero_le_one hp) end ... ≤ (∑ (i : ι), edist (f i) (g i) ^ p) ^ (1 / p) + (∑ (i : ι), edist (g i) (h i) ^ p) ^ (1 / p) : ennreal.Lp_add_le _ _ _ hp } /-- Endowing the space `pi_Lp p hp α` with the `L^p` edistance. This definition is not satisfactory, as it does not register the fact that the topology and the uniform structure coincide with the product one. Therefore, we do not register it as an instance. Using this as a temporary emetric space instance, we will show that the uniform structure is equal (but not defeq) to the product one, and then register an instance in which we replace the uniform structure by the product one using this emetric space and `emetric_space.replace_uniformity`. -/ def emetric_aux : emetric_space (pi_Lp p hp α) := { eq_of_edist_eq_zero := λ f g hfg, begin have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, letI h := pseudo_emetric_aux p hp α, have h : edist f g = (∑ (i : ι), (edist (f i) (g i)) ^ p) ^ (1/p) := rfl, simp [h, ennreal.rpow_eq_zero_iff, pos, asymm pos, finset.sum_eq_zero_iff_of_nonneg] at hfg, exact funext hfg end, ..pseudo_emetric_aux p hp α } local attribute [instance] pi_Lp.emetric_aux pi_Lp.pseudo_emetric_aux lemma lipschitz_with_equiv : lipschitz_with 1 (pi_Lp.equiv p hp β) := begin have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, have cancel : p * (1/p) = 1 := mul_div_cancel' 1 (ne_of_gt pos), assume x y, simp only [edist, forall_prop_of_true, one_mul, finset.mem_univ, finset.sup_le_iff, ennreal.coe_one], assume i, calc edist (x i) (y i) = (edist (x i) (y i) ^ p) ^ (1/p) : by simp [← ennreal.rpow_mul, cancel, -one_div] ... ≤ (∑ (i : ι), edist (x i) (y i) ^ p) ^ (1 / p) : begin apply ennreal.rpow_le_rpow _ (one_div_nonneg.2 $ le_of_lt pos), exact finset.single_le_sum (λ i hi, (bot_le : (0 : ℝ≥0∞) ≤ _)) (finset.mem_univ i) end end lemma antilipschitz_with_equiv : antilipschitz_with ((fintype.card ι : ℝ≥0) ^ (1/p)) (pi_Lp.equiv p hp β) := begin have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, have nonneg : 0 ≤ 1 / p := one_div_nonneg.2 (le_of_lt pos), have cancel : p * (1/p) = 1 := mul_div_cancel' 1 (ne_of_gt pos), assume x y, simp [edist, -one_div], calc (∑ (i : ι), edist (x i) (y i) ^ p) ^ (1 / p) ≤ (∑ (i : ι), edist (pi_Lp.equiv p hp β x) (pi_Lp.equiv p hp β y) ^ p) ^ (1 / p) : begin apply ennreal.rpow_le_rpow _ nonneg, apply finset.sum_le_sum (λ i hi, _), apply ennreal.rpow_le_rpow _ (le_of_lt pos), exact finset.le_sup (finset.mem_univ i) end ... = (((fintype.card ι : ℝ≥0)) ^ (1/p) : ℝ≥0) * edist (pi_Lp.equiv p hp β x) (pi_Lp.equiv p hp β y) : begin simp only [nsmul_eq_mul, finset.card_univ, ennreal.rpow_one, finset.sum_const, ennreal.mul_rpow_of_nonneg _ _ nonneg, ←ennreal.rpow_mul, cancel], have : (fintype.card ι : ℝ≥0∞) = (fintype.card ι : ℝ≥0) := (ennreal.coe_nat (fintype.card ι)).symm, rw [this, ennreal.coe_rpow_of_nonneg _ nonneg] end end lemma aux_uniformity_eq : 𝓤 (pi_Lp p hp β) = @uniformity _ (Pi.uniform_space _) := begin have A : uniform_inducing (pi_Lp.equiv p hp β) := (antilipschitz_with_equiv p hp β).uniform_inducing (lipschitz_with_equiv p hp β).uniform_continuous, have : (λ (x : pi_Lp p hp β × pi_Lp p hp β), ((pi_Lp.equiv p hp β) x.fst, (pi_Lp.equiv p hp β) x.snd)) = id, by ext i; refl, rw [← A.comap_uniformity, this, comap_id] end end /-! ### Instances on finite `L^p` products -/ instance uniform_space [∀ i, uniform_space (β i)] : uniform_space (pi_Lp p hp β) := Pi.uniform_space _ variable [fintype ι] /-- pseudoemetric space instance on the product of finitely many pseudoemetric spaces, using the `L^p` pseudoedistance, and having as uniformity the product uniformity. -/ instance [∀ i, pseudo_emetric_space (β i)] : pseudo_emetric_space (pi_Lp p hp β) := (pseudo_emetric_aux p hp β).replace_uniformity (aux_uniformity_eq p hp β).symm /-- emetric space instance on the product of finitely many emetric spaces, using the `L^p` edistance, and having as uniformity the product uniformity. -/ instance [∀ i, emetric_space (α i)] : emetric_space (pi_Lp p hp α) := (emetric_aux p hp α).replace_uniformity (aux_uniformity_eq p hp α).symm protected lemma edist {p : ℝ} {hp : 1 ≤ p} {β : ι → Type*} [∀ i, pseudo_emetric_space (β i)] (x y : pi_Lp p hp β) : edist x y = (∑ (i : ι), (edist (x i) (y i)) ^ p) ^ (1/p) := rfl /-- pseudometric space instance on the product of finitely many psuedometric spaces, using the `L^p` distance, and having as uniformity the product uniformity. -/ instance [∀ i, pseudo_metric_space (β i)] : pseudo_metric_space (pi_Lp p hp β) := begin /- we construct the instance from the pseudo emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, refine pseudo_emetric_space.to_pseudo_metric_space_of_dist (λf g, (∑ (i : ι), (dist (f i) (g i)) ^ p) ^ (1/p)) (λ f g, _) (λ f g, _), { simp [pi_Lp.edist, ennreal.rpow_eq_top_iff, asymm pos, pos, ennreal.sum_eq_top_iff, edist_ne_top] }, { have A : ∀ (i : ι), i ∈ (finset.univ : finset ι) → edist (f i) (g i) ^ p < ⊤ := λ i hi, by simp [lt_top_iff_ne_top, edist_ne_top, le_of_lt pos], simp [dist, -one_div, pi_Lp.edist, ← ennreal.to_real_rpow, ennreal.to_real_sum A, dist_edist] } end /-- metric space instance on the product of finitely many metric spaces, using the `L^p` distance, and having as uniformity the product uniformity. -/ instance [∀ i, metric_space (α i)] : metric_space (pi_Lp p hp α) := begin /- we construct the instance from the emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, refine emetric_space.to_metric_space_of_dist (λf g, (∑ (i : ι), (dist (f i) (g i)) ^ p) ^ (1/p)) (λ f g, _) (λ f g, _), { simp [pi_Lp.edist, ennreal.rpow_eq_top_iff, asymm pos, pos, ennreal.sum_eq_top_iff, edist_ne_top] }, { have A : ∀ (i : ι), i ∈ (finset.univ : finset ι) → edist (f i) (g i) ^ p < ⊤ := λ i hi, by simp [lt_top_iff_ne_top, edist_ne_top, le_of_lt pos], simp [dist, -one_div, pi_Lp.edist, ← ennreal.to_real_rpow, ennreal.to_real_sum A, dist_edist] } end protected lemma dist {p : ℝ} {hp : 1 ≤ p} {β : ι → Type*} [∀ i, pseudo_metric_space (β i)] (x y : pi_Lp p hp β) : dist x y = (∑ (i : ι), (dist (x i) (y i)) ^ p) ^ (1/p) := rfl /-- seminormed group instance on the product of finitely many normed groups, using the `L^p` norm. -/ instance semi_normed_group [∀i, semi_normed_group (β i)] : semi_normed_group (pi_Lp p hp β) := { norm := λf, (∑ (i : ι), norm (f i) ^ p) ^ (1/p), dist_eq := λ x y, by { simp [pi_Lp.dist, dist_eq_norm, sub_eq_add_neg] }, .. pi.add_comm_group } /-- normed group instance on the product of finitely many normed groups, using the `L^p` norm. -/ instance normed_group [∀i, normed_group (α i)] : normed_group (pi_Lp p hp α) := { ..pi_Lp.semi_normed_group p hp α } lemma norm_eq {p : ℝ} {hp : 1 ≤ p} {β : ι → Type*} [∀i, semi_normed_group (β i)] (f : pi_Lp p hp β) : ∥f∥ = (∑ (i : ι), ∥f i∥ ^ p) ^ (1/p) := rfl lemma norm_eq_of_nat {p : ℝ} {hp : 1 ≤ p} {β : ι → Type*} [∀i, semi_normed_group (β i)] (n : ℕ) (h : p = n) (f : pi_Lp p hp β) : ∥f∥ = (∑ (i : ι), ∥f i∥ ^ n) ^ (1/(n : ℝ)) := by simp [norm_eq, h, real.sqrt_eq_rpow, ←real.rpow_nat_cast] variables (𝕜 : Type*) [normed_field 𝕜] /-- The product of finitely many seminormed spaces is a seminormed space, with the `L^p` norm. -/ instance semi_normed_space [∀i, semi_normed_group (β i)] [∀i, semi_normed_space 𝕜 (β i)] : semi_normed_space 𝕜 (pi_Lp p hp β) := { norm_smul_le := begin assume c f, have : p * (1 / p) = 1 := mul_div_cancel' 1 (ne_of_gt (lt_of_lt_of_le zero_lt_one hp)), simp only [pi_Lp.norm_eq, norm_smul, mul_rpow, norm_nonneg, ←finset.mul_sum, pi.smul_apply], rw [mul_rpow (rpow_nonneg_of_nonneg (norm_nonneg _) _), ← rpow_mul (norm_nonneg _), this, rpow_one], exact finset.sum_nonneg (λ i hi, rpow_nonneg_of_nonneg (norm_nonneg _) _) end, .. pi.module ι β 𝕜 } /-- The product of finitely many normed spaces is a normed space, with the `L^p` norm. -/ instance normed_space [∀i, normed_group (α i)] [∀i, normed_space 𝕜 (α i)] : normed_space 𝕜 (pi_Lp p hp α) := { ..pi_Lp.semi_normed_space p hp α 𝕜 } /- Register simplification lemmas for the applications of `pi_Lp` elements, as the usual lemmas for Pi types will not trigger. -/ variables {𝕜 p hp α} [∀i, semi_normed_group (β i)] [∀i, semi_normed_space 𝕜 (β i)] (c : 𝕜) (x y : pi_Lp p hp β) (i : ι) @[simp] lemma add_apply : (x + y) i = x i + y i := rfl @[simp] lemma sub_apply : (x - y) i = x i - y i := rfl @[simp] lemma smul_apply : (c • x) i = c • x i := rfl @[simp] lemma neg_apply : (-x) i = - (x i) := rfl end pi_Lp
0328172ddbae8a6f3951beac7e39004b46ca2a5a
e898bfefd5cb60a60220830c5eba68cab8d02c79
/uexp/src/uexp/rules/ex2sigmod92.lean
8827760e641faebe3a8648b2dd5c9023cbaf89d2
[ "BSD-2-Clause" ]
permissive
kkpapa/Cosette
9ed09e2dc4c1ecdef815c30b5501f64a7383a2ce
fda8fdbbf0de6c1be9b4104b87bbb06cede46329
refs/heads/master
1,584,573,128,049
1,526,370,422,000
1,526,370,422,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,139
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..UDP import ..canonize import ..cosette_tactics set_option profiler true open Expr open Proj open Pred open SQL variable i1000 : const datatypes.int theorem rule : forall (Γ scm_itm scm_itp : Schema) (rel_itm : relation scm_itm) (rel_itp : relation scm_itp) (itm_itemno : Column datatypes.int scm_itm) (itm_type : Column datatypes.int scm_itm) (itp_itemno : Column datatypes.int scm_itp) (itp_np : Column datatypes.int scm_itp) (ik : isKey itm_itemno rel_itm), denoteSQL (SELECT1 (combine (right⋅left⋅right) (combine (right⋅right⋅itm_type) (right⋅right⋅itm_itemno))) FROM1 (product (DISTINCT (SELECT1 (combine (right⋅itp_itemno) (right⋅itp_np)) FROM1 (table rel_itp) WHERE (castPred (combine (right⋅itp_np) (e2p (constantExpr i1000))) predicates.gt))) (table rel_itm)) WHERE (equal (uvariable (right⋅left⋅left)) (uvariable (right⋅right⋅itm_itemno))) : SQL Γ _) = denoteSQL (DISTINCT (SELECT1 (combine (right⋅left⋅itp_np) (combine (right⋅right⋅itm_type) (right⋅right⋅itm_itemno))) FROM1 (product (table rel_itp) (table rel_itm)) WHERE (and (castPred (combine (right⋅left⋅itp_np) (e2p (constantExpr i1000))) predicates.gt) (equal (uvariable (right⋅left⋅itp_itemno)) (uvariable (right⋅right⋅itm_itemno))))) : SQL Γ _) := begin intros, unfold_all_denotations, funext, simp, canonize, sorry end
7f12b22079631c2517cf7453074079c9a81b4b2d
46125763b4dbf50619e8846a1371029346f4c3db
/src/ring_theory/localization.lean
8834fc012acef7a28add664adc3c5581bf3d8693
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
27,092
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin -/ import tactic.ring data.quot data.equiv.algebra ring_theory.ideal_operations group_theory.submonoid universes u v namespace localization variables (α : Type u) [comm_ring α] (S : set α) [is_submonoid S] def r (x y : α × S) : Prop := ∃ t ∈ S, ((x.2 : α) * y.1 - y.2 * x.1) * t = 0 local infix ≈ := r α S section variables {α S} theorem r_of_eq {a₀ a₁ : α × S} (h : (a₀.2 : α) * a₁.1 = a₁.2 * a₀.1) : a₀ ≈ a₁ := ⟨1, is_submonoid.one_mem S, by rw [h, sub_self, mul_one]⟩ end theorem refl (x : α × S) : x ≈ x := r_of_eq rfl theorem symm (x y : α × S) : x ≈ y → y ≈ x := λ ⟨t, hts, ht⟩, ⟨t, hts, by rw [← neg_sub, ← neg_mul_eq_neg_mul, ht, neg_zero]⟩ theorem trans : ∀ (x y z : α × S), x ≈ y → y ≈ z → x ≈ z := λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨t, hts, ht⟩ ⟨t', hts', ht'⟩, ⟨s₂ * t' * t, is_submonoid.mul_mem (is_submonoid.mul_mem hs₂ hts') hts, calc (s₁ * r₃ - s₃ * r₁) * (s₂ * t' * t) = t' * s₃ * ((s₁ * r₂ - s₂ * r₁) * t) + t * s₁ * ((s₂ * r₃ - s₃ * r₂) * t') : by ring ... = 0 : by simp only [subtype.coe_mk] at ht ht'; rw [ht, ht']; simp⟩ instance : setoid (α × S) := ⟨r α S, refl α S, symm α S, trans α S⟩ end localization /-- The localization of a ring at a submonoid: the elements of the submonoid become invertible in the localization.-/ def localization (α : Type u) [comm_ring α] (S : set α) [is_submonoid S] := quotient $ localization.setoid α S namespace localization variables (α : Type u) [comm_ring α] (S : set α) [is_submonoid S] instance : has_add (localization α S) := ⟨quotient.lift₂ (λ x y : α × S, (⟦⟨x.2 * y.1 + y.2 * x.1, x.2 * y.2⟩⟧ : localization α S)) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨r₄, s₄, hs₄⟩ ⟨t₅, hts₅, ht₅⟩ ⟨t₆, hts₆, ht₆⟩, quotient.sound ⟨t₆ * t₅, is_submonoid.mul_mem hts₆ hts₅, calc (s₁ * s₂ * (s₃ * r₄ + s₄ * r₃) - s₃ * s₄ * (s₁ * r₂ + s₂ * r₁)) * (t₆ * t₅) = s₁ * s₃ * ((s₂ * r₄ - s₄ * r₂) * t₆) * t₅ + s₂ * s₄ * ((s₁ * r₃ - s₃ * r₁) * t₅) * t₆ : by ring ... = 0 : by simp only [subtype.coe_mk] at ht₅ ht₆; rw [ht₆, ht₅]; simp⟩⟩ instance : has_neg (localization α S) := ⟨quotient.lift (λ x : α × S, (⟦⟨-x.1, x.2⟩⟧ : localization α S)) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨t, hts, ht⟩, quotient.sound ⟨t, hts, calc (s₁ * -r₂ - s₂ * -r₁) * t = -((s₁ * r₂ - s₂ * r₁) * t) : by ring ... = 0 : by simp only [subtype.coe_mk] at ht; rw ht; simp⟩⟩ instance : has_mul (localization α S) := ⟨quotient.lift₂ (λ x y : α × S, (⟦⟨x.1 * y.1, x.2 * y.2⟩⟧ : localization α S)) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨r₄, s₄, hs₄⟩ ⟨t₅, hts₅, ht₅⟩ ⟨t₆, hts₆, ht₆⟩, quotient.sound ⟨t₆ * t₅, is_submonoid.mul_mem hts₆ hts₅, calc ((s₁ * s₂) * (r₃ * r₄) - (s₃ * s₄) * (r₁ * r₂)) * (t₆ * t₅) = t₆ * ((s₁ * r₃ - s₃ * r₁) * t₅) * r₂ * s₄ + t₅ * ((s₂ * r₄ - s₄ * r₂) * t₆) * r₃ * s₁ : by ring ... = 0 : by simp only [subtype.coe_mk] at ht₅ ht₆; rw [ht₅, ht₆]; simp⟩⟩ variables {α S} def mk (r : α) (s : S) : localization α S := ⟦(r, s)⟧ /-- The natural map from the ring to the localization.-/ def of (r : α) : localization α S := mk r 1 instance : comm_ring (localization α S) := by refine { add := has_add.add, add_assoc := λ m n k, quotient.induction_on₃ m n k _, zero := of 0, zero_add := quotient.ind _, add_zero := quotient.ind _, neg := has_neg.neg, add_left_neg := quotient.ind _, add_comm := quotient.ind₂ _, mul := has_mul.mul, mul_assoc := λ m n k, quotient.induction_on₃ m n k _, one := of 1, one_mul := quotient.ind _, mul_one := quotient.ind _, left_distrib := λ m n k, quotient.induction_on₃ m n k _, right_distrib := λ m n k, quotient.induction_on₃ m n k _, mul_comm := quotient.ind₂ _ }; { intros, try {rcases a with ⟨r₁, s₁, hs₁⟩}, try {rcases b with ⟨r₂, s₂, hs₂⟩}, try {rcases c with ⟨r₃, s₃, hs₃⟩}, refine (quotient.sound $ r_of_eq _), simp only [is_submonoid.coe_mul, is_submonoid.coe_one, subtype.coe_mk], ring } instance : inhabited (localization α S) := ⟨0⟩ instance of.is_ring_hom : is_ring_hom (of : α → localization α S) := { map_add := λ x y, quotient.sound $ by simp [add_comm], map_mul := λ x y, quotient.sound $ by simp [add_comm], map_one := rfl } variables {S} instance : has_coe_t α (localization α S) := ⟨of⟩ -- note [use has_coe_t] instance coe.is_ring_hom : is_ring_hom (coe : α → localization α S) := localization.of.is_ring_hom /-- The natural map from the submonoid to the unit group of the localization.-/ def to_units (s : S) : units (localization α S) := { val := s, inv := mk 1 s, val_inv := quotient.sound $ r_of_eq $ mul_assoc _ _ _, inv_val := quotient.sound $ r_of_eq $ show s.val * 1 * 1 = 1 * (1 * s.val), by simp } @[simp] lemma to_units_coe (s : S) : ((to_units s) : localization α S) = ((s : α) : localization α S) := rfl section variables (α S) (x y : α) (n : ℕ) @[simp] lemma of_zero : (of 0 : localization α S) = 0 := rfl @[simp] lemma of_one : (of 1 : localization α S) = 1 := rfl @[simp] lemma of_add : (of (x + y) : localization α S) = of x + of y := by apply is_ring_hom.map_add @[simp] lemma of_sub : (of (x - y) : localization α S) = of x - of y := by apply is_ring_hom.map_sub @[simp] lemma of_mul : (of (x * y) : localization α S) = of x * of y := by apply is_ring_hom.map_mul @[simp] lemma of_neg : (of (-x) : localization α S) = -of x := by apply is_ring_hom.map_neg @[simp] lemma of_pow : (of (x ^ n) : localization α S) = (of x) ^ n := by apply is_semiring_hom.map_pow @[simp] lemma of_is_unit' (s ∈ S) : is_unit (of s : localization α S) := is_unit_unit $ to_units ⟨s, ‹s ∈ S›⟩ @[simp] lemma of_is_unit (s : S) : is_unit (of s : localization α S) := is_unit_unit $ to_units s @[simp] lemma coe_zero : ((0 : α) : localization α S) = 0 := rfl @[simp] lemma coe_one : ((1 : α) : localization α S) = 1 := rfl @[simp] lemma coe_add : (↑(x + y) : localization α S) = x + y := of_add _ _ _ _ @[simp] lemma coe_sub : (↑(x - y) : localization α S) = x - y := of_sub _ _ _ _ @[simp] lemma coe_mul : (↑(x * y) : localization α S) = x * y := of_mul _ _ _ _ @[simp] lemma coe_neg : (↑(-x) : localization α S) = -x := of_neg _ _ _ @[simp] lemma coe_pow : (↑(x ^ n) : localization α S) = x ^ n := of_pow _ _ _ _ @[simp] lemma coe_is_unit' (s ∈ S) : is_unit ((s : α) : localization α S) := of_is_unit' _ _ _ ‹s ∈ S› @[simp] lemma coe_is_unit (s : S) : is_unit ((s : α) : localization α S) := of_is_unit _ _ _ end lemma mk_self {x : α} {hx : x ∈ S} : (mk x ⟨x, hx⟩ : localization α S) = 1 := quotient.sound ⟨1, is_submonoid.one_mem S, by simp only [subtype.coe_mk, is_submonoid.coe_one, mul_one, one_mul, sub_self]⟩ lemma mk_self' {s : S} : (mk s s : localization α S) = 1 := by cases s; exact mk_self lemma mk_self'' {s : S} : (mk s.1 s : localization α S) = 1 := mk_self' -- This lemma does not apply with simp, since (mk r s) simplifies to (r * s⁻¹). -- However, it could apply with dsimp. @[simp, nolint simp_nf] lemma coe_mul_mk (x y : α) (s : S) : ↑x * mk y s = mk (x * y) s := quotient.sound $ r_of_eq $ by rw one_mul lemma mk_eq_mul_mk_one (r : α) (s : S) : mk r s = r * mk 1 s := by rw [coe_mul_mk, mul_one] -- This lemma does not apply with simp, since (mk r s) simplifies to (r * s⁻¹). -- However, it could apply with dsimp. @[simp, nolint simp_nf] lemma mk_mul_mk (x y : α) (s t : S) : mk x s * mk y t = mk (x * y) (s * t) := rfl lemma mk_mul_cancel_left (r : α) (s : S) : mk (↑s * r) s = r := by rw [mk_eq_mul_mk_one, mul_comm ↑s, coe_mul, mul_assoc, ← mk_eq_mul_mk_one, mk_self', mul_one] lemma mk_mul_cancel_right (r : α) (s : S) : mk (r * s) s = r := by rw [mul_comm, mk_mul_cancel_left] @[simp] lemma mk_eq (r : α) (s : S) : mk r s = r * ((to_units s)⁻¹ : units _) := quotient.sound $ by simp @[elab_as_eliminator] protected theorem induction_on {C : localization α S → Prop} (x : localization α S) (ih : ∀ r s, C (mk r s : localization α S)) : C x := by rcases x with ⟨r, s⟩; exact ih r s section variables {β : Type v} [comm_ring β] {T : set β} [is_submonoid T] (f : α → β) [is_ring_hom f] @[elab_with_expected_type] def lift' (g : S → units β) (hg : ∀ s, (g s : β) = f s) (x : localization α S) : β := quotient.lift_on x (λ p, f p.1 * ((g p.2)⁻¹ : units β)) $ λ ⟨r₁, s₁⟩ ⟨r₂, s₂⟩ ⟨t, hts, ht⟩, show f r₁ * ↑(g s₁)⁻¹ = f r₂ * ↑(g s₂)⁻¹, from calc f r₁ * ↑(g s₁)⁻¹ = (f r₁ * g s₂ + ((g s₁ * f r₂ - g s₂ * f r₁) * g ⟨t, hts⟩) * ↑(g ⟨t, hts⟩)⁻¹) * ↑(g s₁)⁻¹ * ↑(g s₂)⁻¹ : by simp only [hg, subtype.coe_mk, (is_ring_hom.map_mul f).symm, (is_ring_hom.map_sub f).symm, ht, is_ring_hom.map_zero f, zero_mul, add_zero]; rw [is_ring_hom.map_mul f, ← hg, mul_right_comm, mul_assoc (f r₁), ← units.coe_mul, mul_inv_self]; rw [units.coe_one, mul_one] ... = f r₂ * ↑(g s₂)⁻¹ : by rw [mul_assoc, mul_assoc, ← units.coe_mul, mul_inv_self, units.coe_one, mul_one, mul_comm ↑(g s₂), add_sub_cancel'_right]; rw [mul_comm ↑(g s₁), ← mul_assoc, mul_assoc (f r₂), ← units.coe_mul, mul_inv_self, units.coe_one, mul_one] instance lift'.is_ring_hom (g : S → units β) (hg : ∀ s, (g s : β) = f s) : is_ring_hom (localization.lift' f g hg) := { map_one := have g 1 = 1, from units.ext (by rw hg; exact is_ring_hom.map_one f), show f 1 * ↑(g 1)⁻¹ = 1, by rw [this, one_inv, units.coe_one, mul_one, is_ring_hom.map_one f], map_mul := λ x y, localization.induction_on x $ λ r₁ s₁, localization.induction_on y $ λ r₂ s₂, have g (s₁ * s₂) = g s₁ * g s₂, from units.ext (by simp only [hg, units.coe_mul]; exact is_ring_hom.map_mul f), show _ * ↑(g (_ * _))⁻¹ = (_ * _) * (_ * _), by simp only [subtype.coe_mk, mul_one, one_mul, subtype.coe_eta, this, mul_inv_rev]; rw [is_ring_hom.map_mul f, units.coe_mul, ← mul_assoc, ← mul_assoc]; simp only [mul_right_comm], map_add := λ x y, localization.induction_on x $ λ r₁ s₁, localization.induction_on y $ λ r₂ s₂, have g (s₁ * s₂) = g s₁ * g s₂, from units.ext (by simp only [hg, units.coe_mul]; exact is_ring_hom.map_mul f), show _ * ↑(g (_ * _))⁻¹ = _ * _ + _ * _, by simp only [subtype.coe_mk, mul_one, one_mul, subtype.coe_eta, this, mul_inv_rev]; simp only [is_ring_hom.map_mul f, is_ring_hom.map_add f, add_mul, (hg _).symm]; simp only [mul_assoc, mul_comm, mul_left_comm, (units.coe_mul _ _).symm]; rw [mul_inv_cancel_left, mul_left_comm, ← mul_assoc, mul_inv_cancel_right, add_comm] } noncomputable def lift (h : ∀ s ∈ S, is_unit (f s)) : localization α S → β := localization.lift' f (λ s, classical.some $ h s.1 s.2) (λ s, by rw [← classical.some_spec (h s.1 s.2)]; refl) instance lift.is_ring_hom (h : ∀ s ∈ S, is_unit (f s)) : is_ring_hom (lift f h) := lift'.is_ring_hom _ _ _ -- This lemma does not apply with simp, since (mk r s) simplifies to (r * s⁻¹). -- However, it could apply with dsimp. @[simp, nolint simp_nf] lemma lift'_mk (g : S → units β) (hg : ∀ s, (g s : β) = f s) (r : α) (s : S) : lift' f g hg (mk r s) = f r * ↑(g s)⁻¹ := rfl @[simp] lemma lift'_of (g : S → units β) (hg : ∀ s, (g s : β) = f s) (a : α) : lift' f g hg (of a) = f a := have g 1 = 1, from units.ext_iff.2 $ by simp [hg, is_ring_hom.map_one f], by simp [lift', quotient.lift_on_beta, of, mk, this] @[simp] lemma lift'_coe (g : S → units β) (hg : ∀ s, (g s : β) = f s) (a : α) : lift' f g hg a = f a := lift'_of _ _ _ _ @[simp] lemma lift_of (h : ∀ s ∈ S, is_unit (f s)) (a : α) : lift f h (of a) = f a := lift'_of _ _ _ _ @[simp] lemma lift_coe (h : ∀ s ∈ S, is_unit (f s)) (a : α) : lift f h a = f a := lift'_of _ _ _ _ @[simp] lemma lift'_comp_of (g : S → units β) (hg : ∀ s, (g s : β) = f s) : lift' f g hg ∘ of = f := funext $ λ a, lift'_of _ _ _ a @[simp] lemma lift_comp_of (h : ∀ s ∈ S, is_unit (f s)) : lift f h ∘ of = f := lift'_comp_of _ _ _ @[simp] lemma lift'_apply_coe (f : localization α S → β) [is_ring_hom f] (g : S → units β) (hg : ∀ s, (g s : β) = f s) : lift' (λ a : α, f a) g hg = f := have g = (λ s, (units.map' f : units (localization α S) → units β) (to_units s)), from funext $ λ x, units.ext $ (hg x).symm ▸ rfl, funext $ λ x, localization.induction_on x (λ r s, by subst this; rw [lift'_mk, ← (units.map' f).map_inv, units.coe_map']; simp [is_ring_hom.map_mul f]) @[simp] lemma lift_apply_coe (f : localization α S → β) [is_ring_hom f] : lift (λ a : α, f a) (λ s hs, is_unit.map' f (is_unit_unit (to_units ⟨s, hs⟩))) = f := by rw [lift, lift'_apply_coe] /-- Function extensionality for localisations: two functions are equal if they agree on elements that are coercions.-/ protected lemma funext (f g : localization α S → β) [is_ring_hom f] [is_ring_hom g] (h : ∀ a : α, f a = g a) : f = g := begin rw [← lift_apply_coe f, ← lift_apply_coe g], congr' 1, exact funext h end variables {α S T} def map (hf : ∀ s ∈ S, f s ∈ T) : localization α S → localization β T := lift' (of ∘ f) (to_units ∘ subtype.map f hf) (λ s, rfl) instance map.is_ring_hom (hf : ∀ s ∈ S, f s ∈ T) : is_ring_hom (map f hf) := lift'.is_ring_hom _ _ _ @[simp] lemma map_of (hf : ∀ s ∈ S, f s ∈ T) (a : α) : map f hf (of a) = of (f a) := lift'_of _ _ _ _ @[simp] lemma map_coe (hf : ∀ s ∈ S, f s ∈ T) (a : α) : map f hf a = (f a) := lift'_of _ _ _ _ @[simp] lemma map_comp_of (hf : ∀ s ∈ S, f s ∈ T) : map f hf ∘ of = of ∘ f := funext $ λ a, map_of _ _ _ @[simp] lemma map_id : map id (λ s (hs : s ∈ S), hs) = id := localization.funext _ _ $ map_coe _ _ lemma map_comp_map {γ : Type*} [comm_ring γ] (hf : ∀ s ∈ S, f s ∈ T) (U : set γ) [is_submonoid U] (g : β → γ) [is_ring_hom g] (hg : ∀ t ∈ T, g t ∈ U) : map g hg ∘ map f hf = map (λ x, g (f x)) (λ s hs, hg _ (hf _ hs)) := localization.funext _ _ $ by simp lemma map_map {γ : Type*} [comm_ring γ] (hf : ∀ s ∈ S, f s ∈ T) (U : set γ) [is_submonoid U] (g : β → γ) [is_ring_hom g] (hg : ∀ t ∈ T, g t ∈ U) (x) : map g hg (map f hf x) = map (λ x, g (f x)) (λ s hs, hg _ (hf _ hs)) x := congr_fun (map_comp_map _ _ _ _ _) x def equiv_of_equiv (h₁ : α ≃+* β) (h₂ : h₁ '' S = T) : localization α S ≃+* localization β T := { to_fun := map h₁ $ λ s hs, h₂ ▸ set.mem_image_of_mem _ hs, inv_fun := map h₁.symm $ λ t ht, by simp [h₁.image_eq_preimage, set.preimage, set.ext_iff, *] at *, left_inv := λ _, by simp only [map_map, h₁.symm_apply_apply]; erw map_id; refl, right_inv := λ _, by simp only [map_map, h₁.apply_symm_apply]; erw map_id; refl, map_mul' := λ _ _, is_ring_hom.map_mul _, map_add' := λ _ _, is_ring_hom.map_add _ } end section away variables {β : Type v} [comm_ring β] (f : α → β) [is_ring_hom f] @[reducible] def away (x : α) := localization α (powers x) @[simp] def away.inv_self (x : α) : away x := mk 1 ⟨x, 1, pow_one x⟩ @[elab_with_expected_type] noncomputable def away.lift {x : α} (hfx : is_unit (f x)) : away x → β := localization.lift' f (λ s, classical.some hfx ^ classical.some s.2) $ λ s, by rw [units.coe_pow, ← classical.some_spec hfx, ← is_semiring_hom.map_pow f, classical.some_spec s.2]; refl instance away.lift.is_ring_hom {x : α} (hfx : is_unit (f x)) : is_ring_hom (localization.away.lift f hfx) := lift'.is_ring_hom _ _ _ @[simp] lemma away.lift_of {x : α} (hfx : is_unit (f x)) (a : α) : away.lift f hfx (of a) = f a := lift'_of _ _ _ _ @[simp] lemma away.lift_coe {x : α} (hfx : is_unit (f x)) (a : α) : away.lift f hfx a = f a := lift'_of _ _ _ _ @[simp] lemma away.lift_comp_of {x : α} (hfx : is_unit (f x)) : away.lift f hfx ∘ of = f := lift'_comp_of _ _ _ noncomputable def away_to_away_right (x y : α) : away x → away (x * y) := localization.away.lift coe $ is_unit_of_mul_one x (y * away.inv_self (x * y)) $ by rw [away.inv_self, coe_mul_mk, coe_mul_mk, mul_one, mk_self] instance away_to_away_right.is_ring_hom (x y : α) : is_ring_hom (away_to_away_right x y) := away.lift.is_ring_hom _ _ end away section at_prime variables (P : ideal α) [hp : ideal.is_prime P] include hp instance prime.is_submonoid : is_submonoid (-P : set α) := { one_mem := P.ne_top_iff_one.1 hp.1, mul_mem := λ x y hnx hny hxy, or.cases_on (hp.2 hxy) hnx hny } @[reducible] def at_prime := localization α (-P) instance at_prime.local_ring : local_ring (at_prime P) := local_of_nonunits_ideal (λ hze, let ⟨t, hts, ht⟩ := quotient.exact hze in hts $ have htz : t = 0, by simpa using ht, suffices (0:α) ∈ P, by rwa htz, P.zero_mem) (begin rintro ⟨⟨r₁, s₁, hs₁⟩⟩ ⟨⟨r₂, s₂, hs₂⟩⟩ hx hy hu, rcases is_unit_iff_exists_inv.1 hu with ⟨⟨⟨r₃, s₃, hs₃⟩⟩, hz⟩, rcases quotient.exact hz with ⟨t, hts, ht⟩, simp at ht, have : ∀ {r s hs}, (⟦⟨r, s, hs⟩⟧ : at_prime P) ∈ nonunits (at_prime P) → r ∈ P, { haveI := classical.dec, exact λ r s hs, not_imp_comm.1 (λ nr, is_unit_iff_exists_inv.2 ⟨⟦⟨s, r, nr⟩⟧, quotient.sound $ r_of_eq $ by simp [mul_comm]⟩) }, have hr₃ := (hp.mem_or_mem_of_mul_eq_zero ht).resolve_right hts, have := (ideal.add_mem_iff_left _ _).1 hr₃, { exact not_or (mt hp.mem_or_mem (not_or hs₁ hs₂)) hs₃ (hp.mem_or_mem this) }, { exact P.neg_mem (P.mul_mem_right (P.add_mem (P.mul_mem_left (this hy)) (P.mul_mem_left (this hx)))) } end) end at_prime variable (α) def non_zero_divisors : set α := {x | ∀ z, z * x = 0 → z = 0} instance non_zero_divisors.is_submonoid : is_submonoid (non_zero_divisors α) := { one_mem := λ z hz, by rwa mul_one at hz, mul_mem := λ x₁ x₂ hx₁ hx₂ z hz, have z * x₁ * x₂ = 0, by rwa mul_assoc, hx₁ z $ hx₂ (z * x₁) this } @[simp] lemma non_zero_divisors_one_val : (1 : non_zero_divisors α).val = 1 := rfl /-- The field of fractions of an integral domain.-/ @[reducible] def fraction_ring := localization α (non_zero_divisors α) namespace fraction_ring open function variables {β : Type u} [integral_domain β] [decidable_eq β] lemma eq_zero_of_ne_zero_of_mul_eq_zero {x y : β} : x ≠ 0 → y * x = 0 → y = 0 := λ hnx hxy, or.resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx lemma mem_non_zero_divisors_iff_ne_zero {x : β} : x ∈ non_zero_divisors β ↔ x ≠ 0 := ⟨λ hm hz, zero_ne_one (hm 1 $ by rw [hz, one_mul]).symm, λ hnx z, eq_zero_of_ne_zero_of_mul_eq_zero hnx⟩ variable (β) def inv_aux (x : β × (non_zero_divisors β)) : fraction_ring β := if h : x.1 = 0 then 0 else ⟦⟨x.2, x.1, mem_non_zero_divisors_iff_ne_zero.mpr h⟩⟧ instance : has_inv (fraction_ring β) := ⟨quotient.lift (inv_aux β) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨t, hts, ht⟩, begin have hrs : s₁ * r₂ = 0 + s₂ * r₁, from sub_eq_iff_eq_add.1 (hts _ ht), by_cases hr₁ : r₁ = 0; by_cases hr₂ : r₂ = 0; simp [hr₁, hr₂] at hrs; simp only [inv_aux, hr₁, hr₂, dif_pos, dif_neg, not_false_iff, subtype.coe_mk, quotient.eq], { exfalso, exact mem_non_zero_divisors_iff_ne_zero.mp hs₁ hrs }, { exfalso, exact mem_non_zero_divisors_iff_ne_zero.mp hs₂ hrs }, { apply r_of_eq, simpa [mul_comm] using hrs.symm } end⟩ lemma mk_inv {r s} : (mk r s : fraction_ring β)⁻¹ = if h : r = 0 then 0 else ⟦⟨s, r, mem_non_zero_divisors_iff_ne_zero.mpr h⟩⟧ := rfl lemma mk_inv' : ∀ (x : β × (non_zero_divisors β)), (⟦x⟧⁻¹ : fraction_ring β) = if h : x.1 = 0 then 0 else ⟦⟨x.2.val, x.1, mem_non_zero_divisors_iff_ne_zero.mpr h⟩⟧ | ⟨r,s,hs⟩ := rfl instance : decidable_eq (fraction_ring β) := @quotient.decidable_eq (β × non_zero_divisors β) (localization.setoid β (non_zero_divisors β)) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩, show decidable (∃ t ∈ non_zero_divisors β, (s₁ * r₂ - s₂ * r₁) * t = 0), from decidable_of_iff (s₁ * r₂ - s₂ * r₁ = 0) ⟨λ H, ⟨1, λ y, (mul_one y).symm ▸ id, H.symm ▸ zero_mul _⟩, λ ⟨t, ht1, ht2⟩, or.resolve_right (mul_eq_zero.1 ht2) $ λ ht, one_ne_zero (ht1 1 ((one_mul t).symm ▸ ht))⟩ instance : field (fraction_ring β) := by refine { inv := has_inv.inv, zero_ne_one := λ hzo, let ⟨t, hts, ht⟩ := quotient.exact hzo in zero_ne_one (by simpa using hts _ ht : 0 = 1), mul_inv_cancel := quotient.ind _, inv_zero := dif_pos rfl, .. localization.comm_ring }; { intros x hnx, rcases x with ⟨x, z, hz⟩, have : x ≠ 0, from assume hx, hnx (quotient.sound $ r_of_eq $ by simp [hx]), simp only [has_inv.inv, inv_aux, quotient.lift_beta, dif_neg this], exact (quotient.sound $ r_of_eq $ by simp [mul_comm]) } @[simp, nolint simp_nf] -- takes a crazy amount of time simplify lhs lemma mk_eq_div {r s} : (mk r s : fraction_ring β) = (r / s : fraction_ring β) := show _ = _ * dite (s.1 = 0) _ _, by rw [dif_neg (mem_non_zero_divisors_iff_ne_zero.mp s.2)]; exact localization.mk_eq_mul_mk_one _ _ variables {β} @[simp] lemma mk_eq_div' (x : β × (non_zero_divisors β)) : (⟦x⟧ : fraction_ring β) = ((x.1) / ((x.2).val) : fraction_ring β) := by erw ← mk_eq_div; cases x; refl lemma eq_zero_of (x : β) (h : (of x : fraction_ring β) = 0) : x = 0 := begin rcases quotient.exact h with ⟨t, ht, ht'⟩, simpa [mem_non_zero_divisors_iff_ne_zero.mp ht] using ht' end lemma of.injective : function.injective (of : β → fraction_ring β) := (is_add_group_hom.injective_iff _).mpr eq_zero_of section map open function is_ring_hom variables {A : Type u} [integral_domain A] [decidable_eq A] variables {B : Type v} [integral_domain B] [decidable_eq B] variables (f : A → B) [is_ring_hom f] def map (hf : injective f) : fraction_ring A → fraction_ring B := localization.map f $ λ s h, by rw [mem_non_zero_divisors_iff_ne_zero, ← map_zero f, ne.def, hf.eq_iff]; exact mem_non_zero_divisors_iff_ne_zero.1 h @[simp] lemma map_of (hf : injective f) (a : A) : map f hf (of a) = of (f a) := localization.map_of _ _ _ @[simp] lemma map_coe (hf : injective f) (a : A) : map f hf a = f a := localization.map_coe _ _ _ @[simp] lemma map_comp_of (hf : injective f) : map f hf ∘ (of : A → fraction_ring A) = (of : B → fraction_ring B) ∘ f := localization.map_comp_of _ _ instance map.is_ring_hom (hf : injective f) : is_ring_hom (map f hf) := localization.map.is_ring_hom _ _ def equiv_of_equiv (h : A ≃+* B) : fraction_ring A ≃+* fraction_ring B := localization.equiv_of_equiv h begin ext b, rw [h.image_eq_preimage, set.preimage, set.mem_set_of_eq, mem_non_zero_divisors_iff_ne_zero, mem_non_zero_divisors_iff_ne_zero, ne.def], exact h.symm.map_ne_zero_iff end end map end fraction_ring section ideals theorem map_comap (J : ideal (localization α S)) : ideal.map coe (ideal.comap (coe : α → localization α S) J) = J := le_antisymm (ideal.map_le_iff_le_comap.2 (le_refl _)) $ λ x, localization.induction_on x $ λ r s hJ, (submodule.mem_coe _).2 $ mul_one r ▸ coe_mul_mk r 1 s ▸ (ideal.mul_mem_right _ $ ideal.mem_map_of_mem $ have _ := @ideal.mul_mem_left (localization α S) _ _ s _ hJ, by rwa [coe_coe, coe_mul_mk, mk_mul_cancel_left] at this) def le_order_embedding : ((≤) : ideal (localization α S) → ideal (localization α S) → Prop) ≼o ((≤) : ideal α → ideal α → Prop) := { to_fun := λ J, ideal.comap coe J, inj := function.injective_of_left_inverse (map_comap α), ord := λ J₁ J₂, ⟨ideal.comap_mono, λ hJ, map_comap α J₁ ▸ map_comap α J₂ ▸ ideal.map_mono hJ⟩ } end ideals section module /-! ### `module` section Localizations form an algebra over `α` induced by the embedding `coe : α → localization α S`. -/ set_option class.instance_max_depth 50 variables (α S) instance : algebra α (localization α S) := algebra.of_ring_hom coe (is_ring_hom.of_semiring coe) lemma of_smul (c x : α) : (of (c • x) : localization α S) = c • of x := by { simp, refl } lemma coe_smul (c x : α) : (coe (c • x) : localization α S) = c • coe x := of_smul α S c x lemma coe_mul_eq_smul (c : α) (x : localization α S) : coe c * x = c • x := rfl lemma mul_coe_eq_smul (c : α) (x : localization α S) : x * coe c = c • x := mul_comm x (coe c) /-- The embedding `coe : α → localization α S` induces a linear map. -/ def lin_coe : α →ₗ[α] localization α S := ⟨coe, coe_add α S, coe_smul α S⟩ @[simp] lemma lin_coe_apply (a : α) : lin_coe α S a = coe a := rfl instance coe_submodules : has_coe (ideal α) (submodule α (localization α S)) := ⟨submodule.map (lin_coe _ _)⟩ @[simp] lemma of_id (a : α) : (algebra.of_id α (localization α S) : α → localization α S) a = ↑a := rfl end module section is_integer /-- `a : localization α S` is an integer if it is an element of the original ring `α` -/ def is_integer (S : set α) [is_submonoid S] (a : localization α S) : Prop := a ∈ set.range (coe : α → localization α S) lemma is_integer_coe (a : α) : is_integer α S a := ⟨a, rfl⟩ lemma is_integer_add {a b} (ha : is_integer α S a) (hb : is_integer α S b) : is_integer α S (a + b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' + b', rw [coe_add, ha, hb] end lemma is_integer_mul {a b} (ha : is_integer α S a) (hb : is_integer α S b) : is_integer α S (a * b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' * b', rw [coe_mul, ha, hb] end set_option class.instance_max_depth 50 lemma is_integer_smul {a : α} {b} (hb : is_integer α S b) : is_integer α S (a • b) := begin rcases hb with ⟨b', hb⟩, use a * b', rw [←hb, ←coe_smul, smul_eq_mul] end end is_integer end localization
faa4d2cee94c8e6ef007e1b84e3d882c82efab86
e151e9053bfd6d71740066474fc500a087837323
/src/hott/algebra/ordered_ring.lean
7a0df989b3bf0cb70b742f74e13b069c640f67d1
[ "Apache-2.0" ]
permissive
daniel-carranza/hott3
15bac2d90589dbb952ef15e74b2837722491963d
913811e8a1371d3a5751d7d32ff9dec8aa6815d9
refs/heads/master
1,610,091,349,670
1,596,222,336,000
1,596,222,336,000
241,957,822
0
0
Apache-2.0
1,582,222,839,000
1,582,222,838,000
null
UTF-8
Lean
false
false
30,298
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Here an "ordered_ring" is partially ordered ring, which is ordered with respect to both a weak order and an associated strict order. Our numeric structures (int, rat, and real) will be instances of "linear_ordered_comm_ring". This development is modeled after Isabelle's library. -/ import .ordered_group .ring universes u v w hott_theory set_option old_structure_cmd true namespace hott open algebra variable {A : Type _} namespace algebra @[hott] private def absurd_a_lt_a {B : Type _} {a : A} [s : strict_order A] (H : a < a) : B := absurd H (lt.irrefl a) /- semiring structures -/ @[hott] structure ordered_semiring (A : Type _) extends semiring A, ordered_mul_cancel_comm_monoid A renaming mul→add mul_assoc→add_assoc one→zero one_mul→zero_add mul_one→add_zero mul_comm→add_comm mul_left_cancel→add_left_cancel mul_right_cancel→add_right_cancel mul_le_mul_left→add_le_add_left mul_lt_mul_left→add_lt_add_left le_of_mul_le_mul_left→le_of_add_le_add_left lt_of_mul_lt_mul_left→lt_of_add_lt_add_left := (mul_le_mul_of_nonneg_left: Πa b c, le a b → le zero c → le (mul c a) (mul c b)) (mul_le_mul_of_nonneg_right: Πa b c, le a b → le zero c → le (mul a c) (mul b c)) (mul_lt_mul_of_pos_left: Πa b c, lt a b → lt zero c → lt (mul c a) (mul c b)) (mul_lt_mul_of_pos_right: Πa b c, lt a b → lt zero c → lt (mul a c) (mul b c)) -- /- we make it a class now (and not as part of the structure) to avoid -- ordered_semiring.to_ordered_mul_cancel_comm_monoid to be an instance -/ attribute [class] ordered_semiring @[hott, instance, reducible] def add_ab_group_of_ordered_semiring (A : Type _) [H : ordered_semiring A] : semiring A := @ordered_semiring.to_semiring A H @[hott, instance, reducible] def monoid_of_ordered_semiring (A : Type _) [H : ordered_semiring A] : ordered_cancel_comm_monoid A := @ordered_semiring.to_ordered_mul_cancel_comm_monoid A H section variable [s : ordered_semiring A] variables (a b c d e : A) include s @[hott] def mul_le_mul_of_nonneg_left {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : c * a ≤ c * b := ordered_semiring.mul_le_mul_of_nonneg_left _ _ _ _ Hab Hc @[hott] def mul_le_mul_of_nonneg_right {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : a * c ≤ b * c := ordered_semiring.mul_le_mul_of_nonneg_right _ _ _ _ Hab Hc @[hott] theorem mul_le_mul {a b c d : A} (Hac : a ≤ c) (Hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right Hac nn_b ... ≤ c * d : mul_le_mul_of_nonneg_left Hbd nn_c @[hott] theorem mul_nonneg {a b : A} (Ha : a ≥ 0) (Hb : b ≥ 0) : a * b ≥ 0 := begin have H : 0 * b ≤ a * b, from mul_le_mul_of_nonneg_right Ha Hb, rwr zero_mul at H, exact H end @[hott] theorem mul_nonpos_of_nonneg_of_nonpos {a b : A} (Ha : a ≥ 0) (Hb : b ≤ 0) : a * b ≤ 0 := begin have H : a * b ≤ a * 0, from mul_le_mul_of_nonneg_left Hb Ha, rwr mul_zero at H, exact H end @[hott] theorem mul_nonpos_of_nonpos_of_nonneg {a b : A} (Ha : a ≤ 0) (Hb : b ≥ 0) : a * b ≤ 0 := begin have H : a * b ≤ 0 * b, from mul_le_mul_of_nonneg_right Ha Hb, rwr zero_mul at H, exact H end @[hott] def mul_lt_mul_of_pos_left {a b c : A} (Hab : a < b) (Hc : 0 < c) : c * a < c * b := ordered_semiring.mul_lt_mul_of_pos_left _ _ _ _ Hab Hc @[hott] def mul_lt_mul_of_pos_right {a b c : A} (Hab : a < b) (Hc : 0 < c) : a * c < b * c := ordered_semiring.mul_lt_mul_of_pos_right _ _ _ _ Hab Hc -- TODO: once again, there are variations @[hott] theorem mul_lt_mul {a b c d : A} (Hac : a < c) (Hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right Hac pos_b ... ≤ c * d : mul_le_mul_of_nonneg_left Hbd nn_c @[hott] def mul_pos {a b : A} (Ha : a > 0) (Hb : b > 0) : a * b > 0 := begin have H : 0 * b < a * b, from mul_lt_mul_of_pos_right Ha Hb, rwr zero_mul at H, exact H end @[hott] def mul_neg_of_pos_of_neg {a b : A} (Ha : a > 0) (Hb : b < 0) : a * b < 0 := begin have H : a * b < a * 0, from mul_lt_mul_of_pos_left Hb Ha, rwr mul_zero at H, exact H end @[hott] def mul_neg_of_neg_of_pos {a b : A} (Ha : a < 0) (Hb : b > 0) : a * b < 0 := begin have H : a * b < 0 * b, from mul_lt_mul_of_pos_right Ha Hb, rwr zero_mul at H, exact H end end @[hott, class] structure linear_ordered_semiring (A : Type _) extends ordered_semiring A, linear_strong_order_pair A := (zero_lt_one : lt zero one) section variable [s : linear_ordered_semiring A] variables {a b c : A} include s @[hott] theorem zero_lt_one : 0 < (1:A) := linear_ordered_semiring.zero_lt_one A @[hott] theorem lt_of_mul_lt_mul_left (H : c * a < c * b) (Hc : c ≥ 0) : a < b := lt_of_not_ge (assume H1 : b ≤ a, have H2 : c * b ≤ c * a, from mul_le_mul_of_nonneg_left H1 Hc, not_lt_of_ge H2 H) @[hott] theorem lt_of_mul_lt_mul_right (H : a * c < b * c) (Hc : c ≥ 0) : a < b := lt_of_not_ge (assume H1 : b ≤ a, have H2 : b * c ≤ a * c, from mul_le_mul_of_nonneg_right H1 Hc, not_lt_of_ge H2 H) @[hott] theorem le_of_mul_le_mul_left (H : c * a ≤ c * b) (Hc : c > 0) : a ≤ b := le_of_not_gt (assume H1 : b < a, have H2 : c * b < c * a, from mul_lt_mul_of_pos_left H1 Hc, not_le_of_gt H2 H) @[hott] theorem le_of_mul_le_mul_right (H : a * c ≤ b * c) (Hc : c > 0) : a ≤ b := le_of_not_gt (assume H1 : b < a, have H2 : b * c < a * c, from mul_lt_mul_of_pos_right H1 Hc, not_le_of_gt H2 H) @[hott] theorem le_iff_mul_le_mul_left (a b : A) {c : A} (H : c > 0) : a ≤ b ↔ c * a ≤ c * b := iff.intro (assume H', mul_le_mul_of_nonneg_left H' (le_of_lt H)) (assume H', le_of_mul_le_mul_left H' H) @[hott] theorem le_iff_mul_le_mul_right (a b : A) {c : A} (H : c > 0) : a ≤ b ↔ a * c ≤ b * c := iff.intro (assume H', mul_le_mul_of_nonneg_right H' (le_of_lt H)) (assume H', le_of_mul_le_mul_right H' H) @[hott] theorem pos_of_mul_pos_left (H : 0 < a * b) (H1 : 0 ≤ a) : 0 < b := lt_of_not_ge (assume H2 : b ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonneg_of_nonpos H1 H2, not_lt_of_ge H3 H) @[hott] theorem pos_of_mul_pos_right (H : 0 < a * b) (H1 : 0 ≤ b) : 0 < a := lt_of_not_ge (assume H2 : a ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonpos_of_nonneg H2 H1, not_lt_of_ge H3 H) @[hott] theorem nonneg_of_mul_nonneg_left (H : 0 ≤ a * b) (H1 : 0 < a) : 0 ≤ b := le_of_not_gt (assume H2 : b < 0, not_le_of_gt (mul_neg_of_pos_of_neg H1 H2) H) @[hott] theorem nonneg_of_mul_nonneg_right (H : 0 ≤ a * b) (H1 : 0 < b) : 0 ≤ a := le_of_not_gt (assume H2 : a < 0, not_le_of_gt (mul_neg_of_neg_of_pos H2 H1) H) @[hott] theorem neg_of_mul_neg_left (H : a * b < 0) (H1 : 0 ≤ a) : b < 0 := lt_of_not_ge (assume H2 : b ≥ 0, not_lt_of_ge (mul_nonneg H1 H2) H) @[hott] theorem neg_of_mul_neg_right (H : a * b < 0) (H1 : 0 ≤ b) : a < 0 := lt_of_not_ge (assume H2 : a ≥ 0, not_lt_of_ge (mul_nonneg H2 H1) H) @[hott] theorem nonpos_of_mul_nonpos_left (H : a * b ≤ 0) (H1 : 0 < a) : b ≤ 0 := le_of_not_gt (assume H2 : b > 0, not_le_of_gt (mul_pos H1 H2) H) @[hott] theorem nonpos_of_mul_nonpos_right (H : a * b ≤ 0) (H1 : 0 < b) : a ≤ 0 := le_of_not_gt (assume H2 : a > 0, not_le_of_gt (mul_pos H2 H1) H) end @[hott, class] structure decidable_linear_ordered_semiring (A : Type _) extends linear_ordered_semiring A, decidable_linear_order A /- ring structures -/ @[hott] structure ordered_ring (A : Type _) extends ring A, ordered_mul_ab_group A renaming mul→add mul_assoc→add_assoc one→zero one_mul→zero_add mul_one→add_zero inv→neg mul_left_inv→add_left_inv mul_comm→add_comm mul_le_mul_left→add_le_add_left mul_lt_mul_left→add_lt_add_left, zero_ne_one_class A := (mul_nonneg : Πa b, le zero a → le zero b → le zero (mul a b)) (mul_pos : Πa b, lt zero a → lt zero b → lt zero (mul a b)) -- /- we make it a class now (and not as part of the structure) to avoid -- ordered_ring.to_ordered_mul_ab_group to be an instance -/ attribute [class] ordered_ring @[hott, instance, reducible] def add_ab_group_of_ordered_ring (A : Type _) [H : ordered_ring A] : ring A := @ordered_ring.to_ring A H @[hott, instance, reducible] def monoid_of_ordered_ring (A : Type _) [H : ordered_ring A] : ordered_ab_group A := @ordered_ring.to_ordered_mul_ab_group A H @[hott, instance, reducible] def zero_ne_one_class_of_ordered_ring (A : Type _) [H : ordered_ring A] : zero_ne_one_class A := @ordered_ring.to_zero_ne_one_class A H @[hott] def ordered_ring.mul_le_mul_of_nonneg_left [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : c * a ≤ c * b := have H1 : 0 ≤ b - a, from sub_nonneg_of_le Hab, have H2 : 0 ≤ c * (b - a), from ordered_ring.mul_nonneg _ _ _ Hc H1, begin rwr mul_sub_left_distrib at H2, exact (iff.mp (sub_nonneg_iff_le _ _) H2) end @[hott] def ordered_ring.mul_le_mul_of_nonneg_right [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : a * c ≤ b * c := have H1 : 0 ≤ b - a, from iff.elim_right (sub_nonneg_iff_le _ _) Hab, have H2 : 0 ≤ (b - a) * c, from ordered_ring.mul_nonneg _ _ _ H1 Hc, begin rwr mul_sub_right_distrib at H2, exact le_of_sub_nonneg H2 end @[hott] def ordered_ring.mul_lt_mul_of_pos_left [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : c * a < c * b := have H1 : 0 < b - a, from iff.elim_right (sub_pos_iff_lt _ _) Hab, have H2 : 0 < c * (b - a), from ordered_ring.mul_pos _ _ _ Hc H1, begin rwr mul_sub_left_distrib at H2, exact (iff.mp (sub_pos_iff_lt _ _) H2) end @[hott] def ordered_ring.mul_lt_mul_of_pos_right [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : a * c < b * c := have H1 : 0 < b - a, from iff.elim_right (sub_pos_iff_lt _ _) Hab, have H2 : 0 < (b - a) * c, from ordered_ring.mul_pos _ _ _ H1 Hc, begin rwr mul_sub_right_distrib at H2, exact (lt_of_sub_pos H2) end @[hott, instance, reducible] def ordered_ring.to_ordered_semiring [s : ordered_ring A] : ordered_semiring A := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A _, add_right_cancel := @add.right_cancel A _, le_of_add_le_add_left := @le_of_add_le_add_left A _, mul_le_mul_of_nonneg_left := @ordered_ring.mul_le_mul_of_nonneg_left A _, mul_le_mul_of_nonneg_right := @ordered_ring.mul_le_mul_of_nonneg_right A _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left A _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right A _, lt_of_add_lt_add_left := @lt_of_add_lt_add_left A _, ..s } section variable [s : ordered_ring A] variables {a b c : A} include s @[hott] theorem mul_le_mul_of_nonpos_left (H : b ≤ a) (Hc : c ≤ 0) : c * a ≤ c * b := have Hc' : -c ≥ 0, from iff.mpr (neg_nonneg_iff_nonpos _) Hc, have H1 : -c * b ≤ -c * a, from mul_le_mul_of_nonneg_left H Hc', have H2 : -(c * b) ≤ -(c * a), begin rwr [←neg_mul_eq_neg_mul, ←neg_mul_eq_neg_mul] at H1, exact H1 end, le_of_neg_le_neg H2 @[hott] theorem mul_le_mul_of_nonpos_right (H : b ≤ a) (Hc : c ≤ 0) : a * c ≤ b * c := have Hc' : -c ≥ 0, from iff.mpr (neg_nonneg_iff_nonpos _) Hc, have H1 : b * -c ≤ a * -c, from mul_le_mul_of_nonneg_right H Hc', have H2 : -(b * c) ≤ -(a * c), begin rwr [←neg_mul_eq_mul_neg, ←neg_mul_eq_mul_neg] at H1, exact H1 end, le_of_neg_le_neg H2 @[hott] theorem mul_nonneg_of_nonpos_of_nonpos (Ha : a ≤ 0) (Hb : b ≤ 0) : 0 ≤ a * b := begin have H : 0 * b ≤ a * b, from mul_le_mul_of_nonpos_right Ha Hb, rwr zero_mul at H, exact H end @[hott] def mul_lt_mul_of_neg_left (H : b < a) (Hc : c < 0) : c * a < c * b := have Hc' : -c > 0, from iff.mpr (neg_pos_iff_neg _) Hc, have H1 : -c * b < -c * a, from mul_lt_mul_of_pos_left H Hc', have H2 : -(c * b) < -(c * a), begin rwr [←neg_mul_eq_neg_mul, ←neg_mul_eq_neg_mul] at H1, exact H1 end, lt_of_neg_lt_neg H2 @[hott] def mul_lt_mul_of_neg_right (H : b < a) (Hc : c < 0) : a * c < b * c := have Hc' : -c > 0, from iff.mpr (neg_pos_iff_neg _) Hc, have H1 : b * -c < a * -c, from mul_lt_mul_of_pos_right H Hc', have H2 : -(b * c) < -(a * c), begin rwr [←neg_mul_eq_mul_neg, ←neg_mul_eq_mul_neg] at H1, exact H1 end, lt_of_neg_lt_neg H2 @[hott] def mul_pos_of_neg_of_neg (Ha : a < 0) (Hb : b < 0) : 0 < a * b := begin have H : 0 * b < a * b, from mul_lt_mul_of_neg_right Ha Hb, rwr zero_mul at H, exact H end end -- TODO: we can eliminate mul_pos_of_pos, but now it is not worth the effort to redeclare the -- class instance @[hott, class] structure linear_ordered_ring (A : Type _) extends ordered_ring A, linear_strong_order_pair A := (zero_lt_one : lt zero one) @[hott, instance, reducible] def linear_ordered_ring.to_linear_ordered_semiring [s : linear_ordered_ring A] : linear_ordered_semiring A := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A _, add_right_cancel := @add.right_cancel A _, le_of_add_le_add_left := @le_of_add_le_add_left A _, mul_le_mul_of_nonneg_left := @mul_le_mul_of_nonneg_left A _, mul_le_mul_of_nonneg_right := @mul_le_mul_of_nonneg_right A _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left A _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right A _, le_total := linear_ordered_ring.le_total, lt_of_add_lt_add_left := @lt_of_add_lt_add_left A _, ..s } @[hott, class] structure linear_ordered_comm_ring (A : Type _) extends linear_ordered_ring A, comm_monoid A @[hott] def linear_ordered_comm_ring.eq_zero_sum_eq_zero_of_mul_eq_zero [s : linear_ordered_comm_ring A] {a b : A} (H : a * b = 0) : a = 0 ⊎ b = 0 := lt.by_cases (assume Ha : 0 < a, lt.by_cases (assume Hb : 0 < b, begin have H1 : 0 < a * b, from mul_pos Ha Hb, rwr H at H1, apply absurd_a_lt_a H1 end) (assume Hb : 0 = b, sum.inr (Hb⁻¹)) (assume Hb : 0 > b, begin have H1 : 0 > a * b, from mul_neg_of_pos_of_neg Ha Hb, rwr H at H1, apply absurd_a_lt_a H1 end)) (assume Ha : 0 = a, sum.inl (Ha⁻¹)) (assume Ha : 0 > a, lt.by_cases (assume Hb : 0 < b, begin have H1 : 0 > a * b, from mul_neg_of_neg_of_pos Ha Hb, rwr H at H1, apply absurd_a_lt_a H1 end) (assume Hb : 0 = b, sum.inr (Hb⁻¹)) (assume Hb : 0 > b, begin have H1 : 0 < a * b, from mul_pos_of_neg_of_neg Ha Hb, rwr H at H1, apply absurd_a_lt_a H1 end)) -- Linearity implies no zero divisors. Doesn't need commutativity. @[hott, instance, reducible] def linear_ordered_comm_ring.to_integral_domain [s : linear_ordered_comm_ring A] : integral_domain A := { eq_zero_sum_eq_zero_of_mul_eq_zero := @linear_ordered_comm_ring.eq_zero_sum_eq_zero_of_mul_eq_zero A s, ..s } section variable [s : linear_ordered_ring A] variables (a b c : A) include s @[hott] theorem mul_self_nonneg : a * a ≥ 0 := sum.elim (le.total 0 a) (assume H : a ≥ 0, mul_nonneg H H) (assume H : a ≤ 0, mul_nonneg_of_nonpos_of_nonpos H H) @[hott] theorem zero_le_one : 0 ≤ (1:A) := by rwr [←one_mul (1 : A)]; exact mul_self_nonneg 1 @[hott] theorem pos_prod_pos_sum_neg_prod_neg_of_mul_pos {a b : A} (Hab : a * b > 0) : (a > 0 × b > 0) ⊎ (a < 0 × b < 0) := lt.by_cases (assume Ha : 0 < a, lt.by_cases (assume Hb : 0 < b, sum.inl (pair Ha Hb)) (assume Hb : 0 = b, begin rwr [←Hb, mul_zero] at Hab, apply absurd_a_lt_a Hab end) (assume Hb : b < 0, absurd Hab (lt.asymm (mul_neg_of_pos_of_neg Ha Hb)))) (assume Ha : 0 = a, begin rwr [←Ha, zero_mul] at Hab, apply absurd_a_lt_a Hab end) (assume Ha : a < 0, lt.by_cases (assume Hb : 0 < b, absurd Hab (lt.asymm (mul_neg_of_neg_of_pos Ha Hb))) (assume Hb : 0 = b, begin rwr [←Hb, mul_zero] at Hab, apply absurd_a_lt_a Hab end) (assume Hb : b < 0, sum.inr (pair Ha Hb))) @[hott] theorem gt_of_mul_lt_mul_neg_left {a b c : A} (H : c * a < c * b) (Hc : c ≤ 0) : a > b := have nhc : -c ≥ 0, from neg_nonneg_of_nonpos Hc, have H2 : -(c * b) < -(c * a), from iff.mpr (neg_lt_neg_iff_lt _ _) H, have H3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : by rwr neg_mul_eq_neg_mul ... < -(c * a) : H2 ... = (-c) * a : by rwr neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left H3 nhc @[hott] theorem zero_gt_neg_one : - 1 < (0:A) := by rwr ←neg_zero; exact neg_lt_neg zero_lt_one @[hott] theorem le_of_mul_le_of_ge_one {a b c : A} (H : a * c ≤ b) (Hb : b ≥ 0) (Hc : c ≥ 1) : a ≤ b := have H' : a * c ≤ b * c, from calc a * c ≤ b : H ... = b * 1 : by rwr mul_one ... ≤ b * c : mul_le_mul_of_nonneg_left Hc Hb, le_of_mul_le_mul_right H' (lt_of_lt_of_le zero_lt_one Hc) @[hott] theorem nonneg_le_nonneg_of_squares_le {a b : A} (Ha : a ≥ 0) (Hb : b ≥ 0) (H : a * a ≤ b * b) : a ≤ b := begin apply le_of_not_gt, intro Hab, let Hposa := lt_of_le_of_lt Hb Hab, let H' := calc b * b ≤ a * b : mul_le_mul_of_nonneg_right (le_of_lt Hab) Hb ... < a * a : mul_lt_mul_of_pos_left Hab Hposa, apply (not_le_of_gt H') H end end /- TODO: Isabelle's library has all kinds of cancelation rules for the simplifier. Search on mult_le_cancel_right1 in Rings.thy. -/ @[hott] structure decidable_linear_ordered_comm_ring (A : Type _) extends linear_ordered_comm_ring A, decidable_linear_ordered_mul_ab_group A renaming mul→add mul_assoc→add_assoc one→zero one_mul→zero_add mul_one→add_zero inv→neg mul_left_inv→add_left_inv mul_comm→add_comm mul_le_mul_left→add_le_add_left mul_lt_mul_left→add_lt_add_left /- we make it a class now (and not as part of the structure) to avoid ordered_semiring.to_ordered_mul_cancel_comm_monoid to be an instance -/ attribute [class] decidable_linear_ordered_comm_ring @[hott, instance, reducible] def linear_ordered_comm_ring_of_decidable_linear_ordered_comm_ring (A : Type _) [H : decidable_linear_ordered_comm_ring A] : linear_ordered_comm_ring A := @decidable_linear_ordered_comm_ring.to_linear_ordered_comm_ring A H @[hott, instance, reducible] def decidable_linear_ordered_ab_group_of_decidable_linear_ordered_comm_ring (A : Type _) [H : decidable_linear_ordered_comm_ring A] : decidable_linear_ordered_ab_group A := @decidable_linear_ordered_comm_ring.to_decidable_linear_ordered_mul_ab_group A H section variable [s : decidable_linear_ordered_comm_ring A] variables {a b c : A} include s @[hott] def sign (a : A) : A := lt.cases a 0 (- 1) 0 1 @[hott] theorem sign_of_neg (H : a < 0) : sign a = - 1 := lt.cases_of_lt H @[hott] theorem sign_zero : sign 0 = (0:A) := lt.cases_of_eq rfl @[hott] theorem sign_of_pos (H : a > 0) : sign a = 1 := lt.cases_of_gt H @[hott] theorem sign_one : sign 1 = (1:A) := sign_of_pos zero_lt_one @[hott] theorem sign_neg_one : sign (- 1) = -(1:A) := sign_of_neg (neg_neg_of_pos zero_lt_one) @[hott] theorem sign_sign (a : A) : sign (sign a) = sign a := lt.by_cases (assume H : a > 0, calc sign (sign a) = sign 1 : by rwr (sign_of_pos H) ... = 1 : by rwr sign_one ... = sign a : by rwr (sign_of_pos H)) (assume H : 0 = a, calc sign (sign a) = sign (sign 0) : by rwr H ... = sign 0 : by rwr ap sign sign_zero ... = sign a : by rwr ←H) (assume H : a < 0, calc sign (sign a) = sign (- 1) : by rwr (sign_of_neg H) ... = - 1 : by rwr sign_neg_one ... = sign a : by rwr (sign_of_neg H)) @[hott] theorem pos_of_sign_eq_one (H : sign a = 1) : a > 0 := lt.by_cases (assume H1 : 0 < a, H1) (assume H1 : 0 = a, begin rwr [←H1, sign_zero] at H, apply absurd H zero_ne_one end) (assume H1 : 0 > a, have H2 : - 1 = 1 :> A, from (sign_of_neg H1)⁻¹ ⬝ H, absurd ((eq_zero_of_neg_eq H2)⁻¹ᵖ) zero_ne_one) @[hott] theorem eq_zero_of_sign_eq_zero (H : sign a = 0) : a = 0 := lt.by_cases (assume H1 : 0 < a, absurd (H⁻¹ ⬝ sign_of_pos H1) zero_ne_one) (assume H1 : 0 = a, H1⁻¹) (assume H1 : 0 > a, have H2 : 0 = - 1 :> A, from H⁻¹ ⬝ sign_of_neg H1, have H3 : 1 = 0 :> A, from eq_neg_of_eq_neg H2 ⬝ neg_zero, absurd (H3⁻¹) zero_ne_one) @[hott] theorem neg_of_sign_eq_neg_one (H : sign a = - 1) : a < 0 := lt.by_cases (assume H1 : 0 < a, have H2 : - 1 = 1 :> A, from H⁻¹ ⬝ (sign_of_pos H1), absurd ((eq_zero_of_neg_eq H2)⁻¹) zero_ne_one) (assume H1 : 0 = a, have H2 : 0 = - 1 :> A, begin rwr [←H1, sign_zero] at H, exact H end, have H3 : 1 = 0 :> A, from eq_neg_of_eq_neg H2 ⬝ neg_zero, absurd (H3⁻¹) zero_ne_one) (assume H1 : 0 > a, H1) @[hott] theorem sign_neg (a : A) : sign (-a) = -(sign a) := lt.by_cases (assume H1 : 0 < a, calc sign (-a) = - 1 : sign_of_neg (neg_neg_of_pos H1) ... = -(sign a) : by rwr (sign_of_pos H1)) (assume H1 : 0 = a, calc sign (-a) = sign (-0) : by rwr ←H1 ... = sign 0 : by rwr neg_zero ... = 0 : by rwr sign_zero ... = -0 : by rwr neg_zero ... = -(sign 0) : by rwr sign_zero ... = -(sign a) : by rwr ←H1) (assume H1 : 0 > a, calc sign (-a) = 1 : sign_of_pos (neg_pos_of_neg H1) ... = -(- 1) : by rwr neg_neg ... = -(sign a) : by rwr sign_of_neg H1) @[hott] theorem sign_mul (a b : A) : sign (a * b) = sign a * sign b := hott.algebra.lt.by_cases (assume z_lt_a : 0 < a, lt.by_cases (assume z_lt_b : 0 < b, by rwr [sign_of_pos z_lt_a, sign_of_pos z_lt_b, sign_of_pos (mul_pos z_lt_a z_lt_b), one_mul]) (assume z_eq_b : 0 = b, by rwr [←z_eq_b, mul_zero, sign_zero, mul_zero]) (assume z_gt_b : 0 > b, by rwr [sign_of_pos z_lt_a, sign_of_neg z_gt_b, sign_of_neg (mul_neg_of_pos_of_neg z_lt_a z_gt_b), one_mul])) (assume z_eq_a : 0 = a, by rwr [←z_eq_a, zero_mul, sign_zero, zero_mul]) (assume z_gt_a : 0 > a, lt.by_cases (assume z_lt_b : 0 < b, by rwr [sign_of_neg z_gt_a, sign_of_pos z_lt_b, sign_of_neg (mul_neg_of_neg_of_pos z_gt_a z_lt_b), mul_one]) (assume z_eq_b : 0 = b, by rwr [←z_eq_b, mul_zero, sign_zero, mul_zero]) (assume z_gt_b : 0 > b, by rwr [sign_of_neg z_gt_a, sign_of_neg z_gt_b, sign_of_pos (mul_pos_of_neg_of_neg z_gt_a z_gt_b), neg_mul_neg, one_mul])) @[hott] theorem abs_eq_sign_mul (a : A) : abs a = sign a * a := lt.by_cases (assume H1 : 0 < a, calc abs a = a : abs_of_pos H1 ... = 1 * a : by rwr one_mul ... = sign a * a : by rwr (sign_of_pos H1)) (assume H1 : 0 = a, calc abs a = abs 0 : by rwr ←H1 ... = 0 : abs_zero ... = 0 * a : by rwr zero_mul ... = sign 0 * a : by rwr sign_zero ... = sign a * a : by rwr ←H1) (assume H1 : a < 0, calc abs a = -a : abs_of_neg H1 ... = - 1 * a : by rwr neg_eq_neg_one_mul ... = sign a * a : by rwr (sign_of_neg H1)) @[hott] theorem eq_sign_mul_abs (a : A) : a = sign a * abs a := lt.by_cases (assume H1 : 0 < a, calc a = abs a : by rwr abs_of_pos H1 ... = 1 * abs a : by rwr one_mul ... = sign a * abs a : by rwr (sign_of_pos H1)) (assume H1 : 0 = a, calc a = 0 : H1⁻¹ ... = 0 * abs a : by rwr zero_mul ... = sign 0 * abs a : by rwr sign_zero ... = sign a * abs a : by rwr H1) (assume H1 : a < 0, calc a = -(-a) : by rwr neg_neg ... = -abs a : by rwr (abs_of_neg H1) ... = - 1 * abs a : by rwr neg_eq_neg_one_mul ... = sign a * abs a : by rwr (sign_of_neg H1)) -- @[hott] theorem abs_dvd_iff (a b : A) : abs a ∣ b ↔ a ∣ b := -- abs.by_cases iff.rfl (neg_dvd_iff_dvd _ _) -- @[hott] theorem abs_dvd_of_dvd {a b : A} : a ∣ b → abs a ∣ b := -- iff.mpr !abs_dvd_iff -- @[hott] theorem dvd_abs_iff (a b : A) : a ∣ abs b ↔ a ∣ b := -- abs.by_cases iff.rfl !dvd_neg_iff_dvd -- @[hott] theorem dvd_abs_of_dvd {a b : A} : a ∣ b → a ∣ abs b := -- iff.mpr !dvd_abs_iff -- @[hott] theorem abs_mul (a b : A) : abs (a * b) = abs a * abs b := -- sum.elim (le.total 0 a) -- (assume H1 : 0 ≤ a, -- sum.elim (le.total 0 b) -- (assume H2 : 0 ≤ b, -- calc -- abs (a * b) = a * b : abs_of_nonneg (mul_nonneg H1 H2) -- ... = abs a * b : by rwr (abs_of_nonneg H1) -- ... = abs a * abs b : by rwr (abs_of_nonneg H2)) -- (assume H2 : b ≤ 0, -- calc -- abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonneg_of_nonpos H1 H2) -- ... = a * -b : by rwr neg_mul_eq_mul_neg -- ... = abs a * -b : by rwr (abs_of_nonneg H1) -- ... = abs a * abs b : by rwr (abs_of_nonpos H2))) -- (assume H1 : a ≤ 0, -- sum.elim (le.total 0 b) -- (assume H2 : 0 ≤ b, -- calc -- abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonpos_of_nonneg H1 H2) -- ... = -a * b : by rwr neg_mul_eq_neg_mul -- ... = abs a * b : by rwr (abs_of_nonpos H1) -- ... = abs a * abs b : by rwr (abs_of_nonneg H2)) -- (assume H2 : b ≤ 0, -- calc -- abs (a * b) = a * b : abs_of_nonneg (mul_nonneg_of_nonpos_of_nonpos H1 H2) -- ... = -a * -b : by rwr neg_mul_neg -- ... = abs a * -b : by rwr (abs_of_nonpos H1) -- ... = abs a * abs b : by rwr (abs_of_nonpos H2))) -- @[hott] theorem abs_mul_abs_self (a : A) : abs a * abs a = a * a := -- abs.by_cases rfl !neg_mul_neg -- @[hott] theorem abs_mul_self (a : A) : abs (a * a) = a * a := -- by rwr [abs_mul, abs_mul_abs_self] -- @[hott] theorem sub_le_of_abs_sub_le_left (H : abs (a - b) ≤ c) : b - c ≤ a := -- if Hz : 0 ≤ a - b then -- (calc -- a ≥ b : (iff.mp (sub_nonneg_iff_le _ _)) Hz -- ... ≥ b - c : sub_le_of_nonneg _ (le.trans !abs_nonneg H)) -- else -- (have Habs : b - a ≤ c, by rwr [abs_of_neg (lt_of_not_ge Hz), neg_sub] at H; apply H, -- have Habs' : b ≤ c + a, from (iff.mpr !le_add_iff_sub_right_le) Habs, -- (iff.mp !le_add_iff_sub_left_le) Habs') -- @[hott] theorem sub_le_of_abs_sub_le_right (H : abs (a - b) ≤ c) : a - c ≤ b := -- sub_le_of_abs_sub_le_left (!abs_sub ▸ H) -- @[hott] theorem sub_lt_of_abs_sub_lt_left (H : abs (a - b) < c) : b - c < a := -- if Hz : 0 ≤ a - b then -- (calc -- a ≥ b : (iff.mp (sub_nonneg_iff_le _ _)) Hz -- ... > b - c : sub_lt_of_pos _ (lt_of_le_of_lt !abs_nonneg H)) -- else -- (have Habs : b - a < c, by rwr [abs_of_neg (lt_of_not_ge Hz), neg_sub] at H; apply H, -- have Habs' : b < c + a, from lt_add_of_sub_lt_right Habs, -- sub_lt_left_of_lt_add Habs') -- @[hott] theorem sub_lt_of_abs_sub_lt_right (H : abs (a - b) < c) : a - c < b := -- sub_lt_of_abs_sub_lt_left (!abs_sub ▸ H) -- @[hott] theorem abs_sub_square (a b : A) : abs (a - b) * abs (a - b) = a * a + b * b - (1 + 1) * a * b := -- begin -- rwr [abs_mul_abs_self, *mul_sub_left_distrib, *mul_sub_right_distrib, -- sub_eq_add_neg (a*b), sub_add_eq_sub_sub, sub_neg_eq_add, *right_distrib, sub_add_eq_sub_sub, *one_mul, -- *add.assoc, {_ + b * b}add.comm, *sub_eq_add_neg], -- rwr [{a*a + b*b}add.comm], -- rwr [mul.comm b a, *add.assoc] -- end -- @[hott] theorem abs_abs_sub_abs_le_abs_sub (a b : A) : abs (abs a - abs b) ≤ abs (a - b) := -- begin -- apply nonneg_le_nonneg_of_squares_le, -- repeat apply abs_nonneg, -- rwr [*abs_sub_square, *abs_abs, *abs_mul_abs_self], -- apply sub_le_sub_left, -- rwr *mul.assoc, -- apply mul_le_mul_of_nonneg_left, -- rwr ←abs_mul, -- apply le_abs_self, -- apply le_of_lt, -- apply add_pos, -- apply zero_lt_one, -- apply zero_lt_one -- end end /- TODO: Multiplication and one, starting with mult_right_le_one_le. -/ -- namespace norm_num -- @[hott] theorem pos_bit0_helper [s : linear_ordered_semiring A] (a : A) (H : a > 0) : bit0 a > 0 := -- by rwr ↑bit0; apply add_pos H H -- @[hott] theorem nonneg_bit0_helper [s : linear_ordered_semiring A] (a : A) (H : a ≥ 0) : bit0 a ≥ 0 := -- by rwr ↑bit0; apply add_nonneg H H -- @[hott] theorem pos_bit1_helper [s : linear_ordered_semiring A] (a : A) (H : a ≥ 0) : bit1 a > 0 := -- begin -- rwr ↑bit1, -- apply add_pos_of_nonneg_of_pos, -- apply nonneg_bit0_helper _ H, -- apply zero_lt_one -- end -- @[hott] theorem nonneg_bit1_helper [s : linear_ordered_semiring A] (a : A) (H : a ≥ 0) : bit1 a ≥ 0 := -- by apply le_of_lt; apply pos_bit1_helper _ H -- @[hott] theorem nonzero_of_pos_helper [s : linear_ordered_semiring A] (a : A) (H : a > 0) : a ≠ 0 := -- ne_of_gt H -- @[hott] theorem nonzero_of_neg_helper [s : linear_ordered_ring A] (a : A) (H : a ≠ 0) : -a ≠ 0 := -- begin intro Ha, apply H, apply eq_of_neg_eq_neg, rwr neg_zero, exact Ha end -- end norm_num end algebra end hott
ad5d8112057836ec2b27d94dd6bc5d354ef901c5
6fbf10071e62af7238f2de8f9aa83d55d8763907
/answers/exam1-key.lean
d91767f5741510babae99a9d067c6770d5620c83
[]
no_license
HasanMukati/uva-cs-dm-s19
ee5aad4568a3ca330c2738ed579c30e1308b03b0
3e7177682acdb56a2d16914e0344c10335583dcf
refs/heads/master
1,596,946,213,130
1,568,221,949,000
1,568,221,949,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,562
lean
/- POINTS: Welcome to the first CS2102 exam. The exam has 12 questions. Points for each question are as indicated, for a total of 100 points. READ CAREFULLY: If you are unable to answer a question in a way that Lean accepts as syntactically correct, *comment out your malformed answer*. Otherwise an error in your answer can cause Lean not to recognize correct answers to other questions. If you are sure an answer is correct but Lean is not accepting it, look for problems in the preceding logic. Do not change or delete any of the questions. WHAT TO DO: Complete the exam by following the instructions for each question. Save your file then upload the completed and saved file to Collab. You have 75 minutes from the start of the exam to the time where it must be uploaded to Collab. OPEN NOTES: You may use the class notes for this exam, whether provided to you by the instructors or taken by you (or for you). STRICTLY INDIVIDUAL EFFORT: This is a strictly individual exam, taken under the honor system. Do not communicate with anyone except for the instructor about the content of this exam, by any means, until you are sure that each person you are communicating with has already completed the test. -/ /- 1. (5 points) What is the type of function1 (just below)? Give you answer by replacing the hole (underscore) in the subsequent definition with your answer. -/ def function1 (f: ℕ → ℕ) (g: ℕ → ℕ) := λ (x: ℕ), 3 #check function1 def function1_type : Type := (ℕ → ℕ) → (ℕ → ℕ) → ℕ → ℕ /- 2. (10 points) Define three equivalent functions, called product1, product2, and product3. Each must take two natural numbers as its arguments and return their product. Define the first version using C-style notation, the second using a lambda abstraction, and the third using a tactic script. -/ -- Answer below: -- ANSWER -- C-style here def product1 (n m : ℕ) : ℕ := n * m -- Lambda abstraction here def product2: ℕ → ℕ → ℕ := λ n m, n * m -- Tactic script here def product3: ℕ → ℕ → ℕ := begin intros n m, exact n * m, end /- 3. (5 points) Given the definition of product1, what function is (product1 5)? Answer by replacing the hole in the following definition with a lambda abstraction. -/ def product1_5 := λ m, 5 * m /- 4. (5 points) Which of the following properties does "product1_5" have? Answer by placing a Y (for yes, it has this property), or N (for no, it doesn't have this property), BEFORE the name of each property, just after the dash. -- ANSWER - Y injective - N surjective - N one-to-many - N strictly partial - N bijective -/ /- 5. (5 points) Complete the proof of the following conjecture, that (product1 4 6) = 24. Fill in the proposition to be proved in the first hole (underscore) and a proof in the second hole. -/ -- ANSWER example : (product1 4 6) = 24 := rfl /- 6. (10 points) State and prove the proposition that, for any natural numbers, a, b, and c, if b = a, then if c = b, then a = c. Fill in the holes in the following example accordingly, replacing the underscores first with a formal statement of the proposition, and then a proof of it, respectively. -/ -- Complete by replacing the hole with a proof: example: ∀ a b c: ℕ, b = a → c = b → a = c := begin intros a b c, assume ba cb, have ab := eq.symm ba, have bc := eq.symm cb, exact eq.trans ab bc end /- 7. (10 points) In the context of the following assumptions, use "example" to formally state and prove the proposition that "Jane is nice." -/ axiom Person : Type axioms Jill Jane : Person axiom IsNice : Person → Prop axiom JillIsNice : IsNice Jill axiom JillIsJane : Jill = Jane -- Fill in the holes with your proposition and proof example : IsNice Jane := eq.subst JillIsJane JillIsNice /- 8. (10 points) Use "example" to prove that true ∧ true is true. Give two proofs, the first using a term-style proof, the second using a tactic script. -/ -- Your answers here -- either one of the following would be ok example : true ∧ true → true := λ tt, tt.left example : true ∧ true := and.intro true.intro true.intro /- 9. (10 points) Define a function, called exfalso, that takes a proof of false as an argument, and that returns a proof of 3 = 7 as a result. -/ -- ANSWER def exfalse (f : false) : 3 = 7 := false.elim f /- 10. (10 points) Formally state and prove the proposition, that, for any propositions, A, B, and C, A ∧ B ∧ C → C ∧ A ∧ B. You may write the proof in any style you wish. One way to do it would be to define a function that takes the propositions, A, B, and C, and a proof of the premise as its arguments and that returns a proof of the conclusion as a result. You might also use a tactic script. -/ -- ANSWER example : ∀ A B C : Prop, A ∧ B ∧ C → C ∧ A ∧ B := begin intros A B C, assume h, have a := h.left, have bc := h.right, have b := bc.left, have c := bc.right, have ab := and.intro a b, exact and.intro c ab, end /- 11. (10 points) Formally (in Lean), prove that if A, B, and C are any propositions, and if C is true, then A ∧ B ∧ C → B ∧ A. -/ -- Complete the following by replacing _ with a proof: example: ∀(A B C: Prop), C → (A ∧ B ∧ C → B ∧ A) := begin intros A B C, assume c, assume abc, have a := abc.left, have b := abc.right.left, exact and.intro b a, end /- 12. (10 points) Define a predicate, gt5, that is true for all and only for natural numbers greater than 5. You may use the expression, n > 5, in your answer. Then fill in the hole in the following definition with the type of the term (gt5 4). -/ -- ANSWER def gt5 : ℕ → Prop := λ n, n > 5 -- ANSWER #check gt5 4 def type_of_gt5_4 := Prop /- 13. EXTRA CREDIT 5 points Give brief natural-language (in English) rendition of the following formal propositions. ∃ n, m : ℕ, isPrime n ∧ isPrime m ∧ m = n + 2 Answer: There are natural numbers, n and m, such that both n and m are prime and m is just two larger than n. (Note: such a pair of prime numbers is called a "prime pair" in the mathematical literature.) If by isPrime we mean the ordinary concept of primeness from basic arithmetic, then the second proposition is true. Prove it by giving values for n and m that satisfy the predicate along with a very brief argument that the two numbers do actually satisfy the predicate. Answer: n = 5 m = 7 Argument: Both 5 and 7 are prime (obvious) and 7 is two larger than 5 (also trivial). -/
d57d51d563f2928bc93181db56f9e78e450aaffa
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_1813.lean
1e1f1071f861e77e2ccb9c9904e4b1c2b96a751e
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
466
lean
variables p q r : Prop -- BEGIN example (h : p ∨ q) (k₁ : p → r) (k₂ : q → r) : r := begin -- By or elim. on `h`, it suffices -- 1. to show `r` on the assumption `h₁ : p` and -- 2. to show `r` on the assumption `h₂ : q`. cases h with h₁ h₂, { show r, from k₁ h₁, }, -- We show `r` by implication elimination on `k₁` and `h₁`. { show r, from k₂ h₂, }, -- We show `r` by implication elimination on `k₂` and `h₂`. end -- END
0f67e9cf62304bccba0bb8ef5154beb082ad19e3
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0603.lean
7da401961e49710a3ba3efbe56bbfd37c0f047b7
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
113
lean
variables (f : ℕ → ℕ) (k : ℕ) example (h₁ : f 0 = 0) (h₂ : k = 0) : f k = 0 := by rw [h₂, h₁]
5efa5cb3946a1618e0cab6b9d5a92ebe8e8f718c
94e33a31faa76775069b071adea97e86e218a8ee
/src/tactic/congrm.lean
887620cf228d6c1bd888b4878b7640a70e21a830
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
5,084
lean
/- Copyright (c) 2022 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Damiano Testa -/ import tactic.interactive /-! `congrm`: `congr` with pattern-matching `congrm e` gives to the use the functionality of using `congr` with an expression `e` "guiding" `congr` through the matching. This allows more flexibility than `congr' n`, which enters uniformly through `n` iterations. Instead, we can guide the matching deeper on some parts of the expression and stop earlier on other parts. -/ namespace tactic /-- For each element of `list congr_arg_kind` that is `eq`, add a pair `(g, pat)` to the final list. Otherwise, discard an appropriate number of initial terms from each list (possibly none from the first) and repeat. `pat` is the given pattern-piece at the appropriate location, extracted from the last `list expr`. It appears to be the list of arguments of a function application. `g` is possibly the proof of an equality? It is extracted from the first `list expr`. -/ private meta def extract_subgoals : list expr → list congr_arg_kind → list expr → tactic (list (expr × expr)) | (_ :: _ :: g :: prf_args) (congr_arg_kind.eq :: kinds) (pat :: pat_args) := (λ rest, (g, pat) :: rest) <$> extract_subgoals prf_args kinds pat_args | (_ :: prf_args) (congr_arg_kind.fixed :: kinds) (_ :: pat_args) := extract_subgoals prf_args kinds pat_args | prf_args (congr_arg_kind.fixed_no_param :: kinds) (_ :: pat_args) := extract_subgoals prf_args kinds pat_args | (_ :: _ :: prf_args) (congr_arg_kind.cast :: kinds) (_ :: pat_args) := extract_subgoals prf_args kinds pat_args | _ _ [] := pure [] | _ _ _ := fail "unsupported congr lemma" /-- `equate_with_pattern_core pat` solves a single goal of the form `lhs = rhs` (assuming that `lhs` and `rhs` are unifiable with `pat`) by applying congruence lemmas until `pat` is a metavariable. Returns the list of metavariables for the new subgoals at the leafs. Calls `set_goals []` at the end. -/ meta def equate_with_pattern_core : expr → tactic (list expr) | pat := (applyc ``subsingleton.elim >> pure []) <|> (applyc ``rfl >> pure []) <|> if pat.is_mvar || pat.get_delayed_abstraction_locals.is_some then do try $ applyc ``_root_.propext, get_goals <* set_goals [] else match pat with | expr.app _ _ := do cl ← mk_specialized_congr_lemma pat, H_congr_lemma ← assertv `H_congr_lemma cl.type cl.proof, [prf] ← get_goals, apply H_congr_lemma <|> fail "could not apply congr_lemma", all_goals' $ try $ clear H_congr_lemma, -- given the `set_goals []` that follows, is this needed? set_goals [], prf ← instantiate_mvars prf, subgoals ← extract_subgoals prf.get_app_args cl.arg_kinds pat.get_app_args, subgoals ← subgoals.mmap (λ ⟨subgoal, subpat⟩, do set_goals [subgoal], equate_with_pattern_core subpat), pure subgoals.join | expr.lam _ _ _ body := do applyc ``_root_.funext, x ← intro pat.binding_name, equate_with_pattern_core $ body.instantiate_var x | expr.pi _ _ _ codomain := do applyc ``_root_.pi_congr, x ← intro pat.binding_name, equate_with_pattern_core $ codomain.instantiate_var x | _ := do pat ← pp pat, fail $ to_fmt "unsupported pattern:\n" ++ pat end /-- `equate_with_pattern pat` solves a single goal of the form `lhs = rhs` (assuming that `lhs` and `rhs` are unifiable with `pat`) by applying congruence lemmas until `pat` is a metavariable. The subgoals for the leafs are prepended to the goals. --/ meta def equate_with_pattern (pat : expr) : tactic unit := do congr_subgoals ← solve1 (equate_with_pattern_core pat), gs ← get_goals, set_goals $ congr_subgoals ++ gs end tactic namespace tactic.interactive open tactic interactive setup_tactic_parser /-- Assume that the goal is of the form `lhs = rhs` or `lhs ↔ rhs`. `congrm e` takes an expression `e` containing placeholders `_` and scans `e, lhs, rhs` in parallel. It matches both `lhs` and `rhs` to the pattern `e`, and produces one goal for each placeholder, stating that the corresponding subexpressions in `lhs` and `rhs` are equal. Examples: ```lean example {a b c d : ℕ} : nat.pred a.succ * (d + (c + a.pred)) = nat.pred b.succ * (b + (c + d.pred)) := begin congrm nat.pred (nat.succ _) * (_ + _), /- Goals left: ⊢ a = b ⊢ d = b ⊢ c + a.pred = c + d.pred -/ sorry, sorry, sorry, end example {a b : ℕ} (h : a = b) : (λ y : ℕ, ∀ z, a + a = z) = (λ x, ∀ z, b + a = z) := begin congrm λ x, ∀ w, _ + a = w, -- produces one goal for the underscore: ⊢ a = b exact h, end ``` -/ meta def congrm (arg : parse texpr) : tactic unit := do try $ applyc ``_root_.eq.to_iff, `(@eq %%ty _ _) ← target | fail "congrm: goal must be an equality or iff", ta ← to_expr ``((%%arg : %%ty)) tt ff, equate_with_pattern ta add_tactic_doc { name := "congrm", category := doc_category.tactic, decl_names := [`tactic.interactive.congrm], tags := ["congruence"] } end tactic.interactive
3248d740ddaf2c208c1ac4df146814c87f9f1ad8
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Elab/Import.lean
002c8a8d45c93202bfd73bfcda177928d64332f0
[ "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
2,517
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Parser.Module import Lean.Data.Json namespace Lean.Elab def headerToImports (header : Syntax) : List Import := let imports := if header[0].isNone then [{ module := `Init : Import }] else [] imports ++ header[1].getArgs.toList.map fun stx => -- `stx` is of the form `(Module.import "import" "runtime"? id) let runtime := !stx[1].isNone let id := stx[2].getId { module := id, runtimeOnly := runtime } def processHeader (header : Syntax) (opts : Options) (messages : MessageLog) (inputCtx : Parser.InputContext) (trustLevel : UInt32 := 0) : IO (Environment × MessageLog) := do try let env ← importModules (headerToImports header) opts trustLevel pure (env, messages) catch e => let env ← mkEmptyEnvironment let spos := header.getPos?.getD 0 let pos := inputCtx.fileMap.toPosition spos pure (env, messages.add { fileName := inputCtx.fileName, data := toString e, pos := pos }) def parseImports (input : String) (fileName : Option String := none) : IO (List Import × Position × MessageLog) := do let fileName := fileName.getD "<input>" let inputCtx := Parser.mkInputContext input fileName let (header, parserState, messages) ← Parser.parseHeader inputCtx pure (headerToImports header, inputCtx.fileMap.toPosition parserState.pos, messages) @[export lean_print_imports] def printImports (input : String) (fileName : Option String) : IO Unit := do let (deps, _, _) ← parseImports input fileName for dep in deps do let fname ← findOLean dep.module IO.println fname deriving instance ToJson for Import structure PrintImportResult where imports? : Option (Array Import) := none errors : Array String := #[] deriving ToJson structure PrintImportsResult where imports : Array PrintImportResult deriving ToJson @[export lean_print_imports_json] def printImportsJson (fileNames : Array String) : IO Unit := do let rs ← fileNames.mapM fun fn => do try let (deps, _, msgs) ← parseImports (← IO.FS.readFile ⟨fn⟩) fn if msgs.hasErrors then return { errors := (← msgs.toList.toArray.mapM (·.toString)) } else return { imports? := some deps.toArray } catch e => return { errors := #[e.toString] } IO.println (toJson { imports := rs : PrintImportsResult }) end Lean.Elab
9c800a8f39f7bb67c2d1c867718ec6ee50ff4bc2
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/analysis/topology/uniform_space.lean
710833c9e4b7d9f8b207bf50e9480e916d0e0203
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
84,405
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot Theory of uniform spaces. Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * completeness * completion (on Cauchy filters instead of Cauchy sequences) * extension of uniform continuous functions to complete spaces * uniform contiunuity & embedding * totally bounded * totally bounded ∧ complete → compact One reason to directly formalize uniform spaces is foundational: we define ℝ as a completion of ℚ. The central concept of uniform spaces is its uniformity: a filter relating two elements of the space. This filter is reflexive, symmetric and transitive. So a set (i.e. a relation) in this filter represents a 'distance': it is reflexive, symmetric and the uniformity contains a set for which the `triangular` rule holds. The formalization is mostly based on the books: N. Bourbaki: General Topology I. M. James: Topologies and Uniformities A major difference is that this formalization is heavily based on the filter library. -/ import order.filter data.quot analysis.topology.topological_space analysis.topology.continuity open set lattice filter classical local attribute [instance] prop_decidable set_option eqn_compiler.zeta true universes u section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type*} := {p : α × α | p.1 = p.2} @[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s := by simp [subset_def]; exact forall_congr (λ a, by simp) /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} @[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)} {x y : α} : (x, y) ∈ comp_rel r₁ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, comp_rel (f x) (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ comp_rel s t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : comp_rel id_rel r = r := set.ext $ assume ⟨a, b⟩, by simp lemma comp_rel_assoc {r s t : set (α×α)} : comp_rel (comp_rel r s) t = comp_rel r (comp_rel s t) := by ext p; cases p; simp only [mem_comp_rel]; tauto /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : principal id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, comp_rel s s) ≤ uniformity) def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r ∈ U.sets) x, (x, x) ∈ r) (symm : ∀ r ∈ U.sets, {p | prod.swap p ∈ r} ∈ U.sets) (comp : ∀ r ∈ U.sets, ∃ t ∈ U.sets, comp_rel t t ⊆ r) : uniform_space.core α := ⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm, begin intros r ru, rw [mem_lift'_sets], exact comp _ ru, apply monotone_comp_rel; exact monotone_id, end⟩ /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity.sets, is_open_univ := by simp; intro; exact univ_mem_sets, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt}, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := have u₁ = u₂, from h, by simp [*] /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity.sets)) @[pattern] def uniform_space.mk' {α} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀s:set α, t.is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity.sets)) : uniform_space α := ⟨c, is_open_uniformity⟩ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.refl _ } def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.refl _ } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] @[extensionality] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h := have u₁ = u₂, from uniform_space.core_eq h, have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this], by simp [*] lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl section uniform_space variables [uniform_space α] /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity : filter (α × α) := (@uniform_space.to_core α _).uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ (@uniformity α _).sets) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : principal id_rel ≤ @uniformity α _ := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ (@uniformity α _).sets) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) uniformity ≤ uniformity := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : uniformity.lift' (λs:set (α×α), comp_rel s s) ≤ uniformity := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto prod.swap (@uniformity α _) uniformity := symm_le_uniformity lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ_, (a, a)) f uniformity := assume s hs, show {x | (a, a) ∈ s} ∈ f.sets, from univ_mem_sets' $ assume b, refl_mem_uniformity hs lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, comp_rel t t ⊆ s := have s ∈ (uniformity.lift' (λt:set (α×α), comp_rel t t)).sets, from comp_le_uniformity hs, (mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ (@uniformity α _).sets, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem_sets hs this, assume a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ comp_rel t t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : uniformity ≤ (@prod.swap α α) <$> uniformity := by rw [map_swap_eq_comap_swap]; from map_le_iff_le_comap.1 tendsto_swap_uniformity lemma uniformity_eq_symm : uniformity = (@prod.swap α α) <$> uniformity := le_antisymm uniformity_le_symm symm_le_uniformity theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : uniformity.lift (λs, g (preimage prod.swap s)) ≤ f) : uniformity.lift g ≤ f := calc uniformity.lift g ≤ (filter.map prod.swap (@uniformity α _)).lift g : lift_mono uniformity_le_symm (le_refl _) ... ≤ _ : by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f): uniformity.lift (λs, f (comp_rel s s)) ≤ uniformity.lift f := calc uniformity.lift (λs, f (comp_rel s s)) = (uniformity.lift' (λs:set (α×α), comp_rel s s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ uniformity.lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s)) ≤ uniformity := calc uniformity.lift' (λd, comp_rel d (comp_rel d d)) = uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s (comp_rel t t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (principal ∘ comp_rel s) $ monotone_comp (monotone_comp_rel monotone_const monotone_id) monotone_principal ... = uniformity.lift' (λs:set(α×α), comp_rel s s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ uniformity : comp_le_uniformity lemma mem_nhds_uniformity_iff {x : α} {s : set α} : (s ∈ (nhds x).sets) ↔ ({p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets) := ⟨ begin simp [mem_nhds_sets_iff, is_open_uniformity], exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_sets_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets}, assume x' hx', refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'), by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b), have hp : (x', b) ∈ t, from hax' ▸ hp', have (b, b') ∈ t, from hab ▸ hp'', have (x', b') ∈ comp_rel t t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma nhds_eq_comap_uniformity {x : α} : nhds x = uniformity.comap (prod.mk x) := by ext s; rw [mem_nhds_uniformity_iff, mem_comap_sets]; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, uniformity.sets_of_superset h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp]) lemma nhds_eq_uniformity {x : α} : nhds x = uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ s}) := begin ext s, rw [mem_lift'_sets], tactic.swap, apply monotone_preimage, simp [mem_nhds_uniformity_iff], exact ⟨assume h, ⟨_, h, assume y h, h rfl⟩, assume ⟨t, h₁, h₂⟩, uniformity.sets_of_superset h₁ $ assume ⟨x', y⟩ hp (eq : x' = x), h₂ $ show (x, y) ∈ t, from eq ▸ hp⟩ end lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) : {y : α | (x, y) ∈ s} ∈ (nhds x).sets := have nhds x ≤ principal {y : α | (x, y) ∈ s}, by rw [nhds_eq_uniformity]; exact infi_le_of_le s (infi_le _ h), by simp at this; assumption lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) : {x : α | (x, y) ∈ s} ∈ (nhds y).sets := mem_nhds_left _ (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (nhds a) uniformity := assume s, mem_nhds_right a lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (nhds a) uniformity := assume s, mem_nhds_left a lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_comp monotone_preimage $ monotone_comp monotone_preimage monotone_principal) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> uniformity).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ monotone_comp monotone_preimage hg ... = _ : by simp [image_swap_eq_preimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : filter.prod (nhds a) (nhds b) = uniformity.lift (λs:set (α×α), uniformity.lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := begin rw [prod_def], show (nhds a).lift (λs:set α, (nhds b).lift (λt:set α, principal (set.prod s t))) = _, rw [lift_nhds_right], apply congr_arg, funext s, rw [lift_nhds_left], refl, exact monotone_comp (monotone_prod monotone_const monotone_id) monotone_principal, exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : nhds (a, b) = uniformity.lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ (@uniformity α _).sets) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $ show cl_d ∈ (nhds (x, y)).sets, begin rw [nhds_eq_uniformity_prod, mem_lift'_sets], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d∈(@uniformity α _).sets, comp_rel d (comp_rel t d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (nhds (a, b) ⊓ principal t ≠ ⊥) : by simp [closure_eq_nhds] ... ↔ (((@prod.swap α α) <$> uniformity).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) uniformity).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by refl ... ↔ (uniformity.lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ principal t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_preimage_swap, function.comp], exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s∈(@uniformity α _).sets, ∃x, x ∈ set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t) : begin rw [lift'_inf_principal_eq, lift'_neq_bot_iff], apply forall_congr, intro s, rw [ne_empty_iff_exists_mem], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀s∈(@uniformity α _).sets, (a, b) ∈ comp_rel s (comp_rel t s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : (@uniformity α _) = uniformity.lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure) (calc uniformity.lift' closure ≤ uniformity.lift' (λd, comp_rel d (comp_rel d d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ uniformity : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : (@uniformity α _) = uniformity.lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ assume x, assume : x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ (@uniformity α _).sets, by filter_upwards [hs] this, by simp [this]) (assume s hs, (uniformity.lift' interior).sets_of_superset (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : interior s ∈ (@uniformity α _).sets := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed [uniform_space α] {s : set (α×α)} (h : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, is_closed t ∧ t ⊆ s := have s ∈ ((@uniformity α _).lift' closure).sets, by rwa [uniformity_eq_uniformity_closure] at h, have ∃t∈(@uniformity α _).sets, closure t ⊆ s, by rwa [mem_lift'_sets] at this; apply closure_mono, let ⟨t, ht, hst⟩ := this in ⟨closure t, uniformity.sets_of_superset ht subset_closure, is_closed_closure, hst⟩ /- uniform continuity -/ def uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) uniformity uniformity theorem uniform_continuous_def [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ (@uniformity β _).sets, {x : α × α | (f x.1, f x.2) ∈ r} ∈ (@uniformity α _).sets := iff.rfl lemma uniform_continuous_id : uniform_continuous (@id α) := by simp [uniform_continuous]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := @tendsto_const_uniformity _ _ _ b uniformity lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (g ∘ f) := hf.comp hg def uniform_embedding [uniform_space β] (f : α → β) := function.injective f ∧ comap (λx:α×α, (f x.1, f x.2)) uniformity = uniformity theorem uniform_embedding_def [uniform_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ ∀ s, s ∈ (@uniformity α _).sets ↔ ∃ t ∈ (@uniformity β _).sets, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s := by rw [uniform_embedding, eq_comm, filter.ext_iff]; simp [subset_def] theorem uniform_embedding_def' [uniform_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ s, s ∈ (@uniformity α _).sets → ∃ t ∈ (@uniformity β _).sets, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s := by simp [uniform_embedding_def, uniform_continuous_def]; exact ⟨λ ⟨I, H⟩, ⟨I, λ s su, (H _).2 ⟨s, su, λ x y, id⟩, λ s, (H s).1⟩, λ ⟨I, H₁, H₂⟩, ⟨I, λ s, ⟨H₂ s, λ ⟨t, tu, h⟩, sets_of_superset _ (H₁ t tu) (λ ⟨a, b⟩, h a b)⟩⟩⟩ lemma uniform_embedding.uniform_continuous [uniform_space β] {f : α → β} (hf : uniform_embedding f) : uniform_continuous f := (uniform_embedding_def'.1 hf).2.1 lemma uniform_embedding.uniform_continuous_iff [uniform_space β] [uniform_space γ] {f : α → β} {g : β → γ} (hg : uniform_embedding g) : uniform_continuous f ↔ uniform_continuous (g ∘ f) := by simp [uniform_continuous, tendsto]; rw [← hg.2, ← map_le_iff_le_comap, filter.map_map] lemma uniform_embedding.dense_embedding [uniform_space β] {f : α → β} (h : uniform_embedding f) (hd : ∀x, x ∈ closure (range f)) : dense_embedding f := { dense := hd, inj := h.left, induced := begin intro a, simp [h.right.symm, nhds_eq_uniformity], rw [comap_lift'_eq, comap_lift'_eq2], refl, exact monotone_preimage, exact monotone_preimage end } lemma uniform_continuous.continuous [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_tendsto.mpr $ assume a, calc map f (nhds a) ≤ (map (λp:α×α, (f p.1, f p.2)) uniformity).lift' (λs:set (β×β), {y | (f a, y) ∈ s}) : begin rw [nhds_eq_uniformity, map_lift'_eq, map_lift'_eq2], exact (lift'_mono' $ assume s hs b ⟨a', (ha' : (_, a') ∈ s), a'_eq⟩, ⟨(a, a'), ha', show (f a, f a') = (f a, b), from a'_eq ▸ rfl⟩), exact monotone_preimage, exact monotone_preimage end ... ≤ nhds (f a) : by rw [nhds_eq_uniformity]; exact lift'_mono hf (le_refl _) lemma closure_image_mem_nhds_of_uniform_embedding [uniform_space α] [uniform_space β] {s : set (α×α)} {e : α → β} (b : β) (he₁ : uniform_embedding e) (he₂ : dense_embedding e) (hs : s ∈ (@uniformity α _).sets) : ∃a, closure (e '' {a' | (a, a') ∈ s}) ∈ (nhds b).sets := have s ∈ (comap (λp:α×α, (e p.1, e p.2)) $ uniformity).sets, from he₁.right.symm ▸ hs, let ⟨t₁, ht₁u, ht₁⟩ := this in have ht₁ : ∀p:α×α, (e p.1, e p.2) ∈ t₁ → p ∈ s, from ht₁, let ⟨t₂, ht₂u, ht₂s, ht₂c⟩ := comp_symm_of_uniformity ht₁u in let ⟨t, htu, hts, htc⟩ := comp_symm_of_uniformity ht₂u in have preimage e {b' | (b, b') ∈ t₂} ∈ (comap e $ nhds b).sets, from preimage_mem_comap $ mem_nhds_left b ht₂u, let ⟨a, (ha : (b, e a) ∈ t₂)⟩ := inhabited_of_mem_sets (he₂.comap_nhds_neq_bot) this in have ∀b' (s' : set (β × β)), (b, b') ∈ t → s' ∈ (@uniformity β _).sets → {y : β | (b', y) ∈ s'} ∩ e '' {a' : α | (a, a') ∈ s} ≠ ∅, from assume b' s' hb' hs', have preimage e {b'' | (b', b'') ∈ s' ∩ t} ∈ (comap e $ nhds b').sets, from preimage_mem_comap $ mem_nhds_left b' $ inter_mem_sets hs' htu, let ⟨a₂, ha₂s', ha₂t⟩ := inhabited_of_mem_sets (he₂.comap_nhds_neq_bot) this in have (e a, e a₂) ∈ t₁, from ht₂c $ prod_mk_mem_comp_rel (ht₂s ha) $ htc $ prod_mk_mem_comp_rel hb' ha₂t, have e a₂ ∈ {b'':β | (b', b'') ∈ s'} ∩ e '' {a' | (a, a') ∈ s}, from ⟨ha₂s', mem_image_of_mem _ $ ht₁ (a, a₂) this⟩, ne_empty_of_mem this, have ∀b', (b, b') ∈ t → nhds b' ⊓ principal (e '' {a' | (a, a') ∈ s}) ≠ ⊥, begin intros b' hb', rw [nhds_eq_uniformity, lift'_inf_principal_eq, lift'_neq_bot_iff], exact assume s, this b' s hb', exact monotone_inter monotone_preimage monotone_const end, have ∀b', (b, b') ∈ t → b' ∈ closure (e '' {a' | (a, a') ∈ s}), from assume b' hb', by rw [closure_eq_nhds]; exact this b' hb', ⟨a, (nhds b).sets_of_superset (mem_nhds_left b htu) this⟩ /-- A filter `f` is Cauchy if for every entourage `r`, there exists an `s ∈ f` such that `s × s ⊆ r`. This is a generalization of Cauchy sequences, because if `a : ℕ → α` then the filter of sets containing cofinitely many of the `a n` is Cauchy iff `a` is a Cauchy sequence. -/ def cauchy (f : filter α) := f ≠ ⊥ ∧ filter.prod f f ≤ uniformity lemma cauchy_iff [uniform_space α] {f : filter α} : cauchy f ↔ (f ≠ ⊥ ∧ (∀s∈(@uniformity α _).sets, ∃t∈f.sets, set.prod t t ⊆ s)) := and_congr (iff.refl _) $ forall_congr $ assume s, forall_congr $ assume hs, mem_prod_same_iff lemma cauchy_downwards {f g : filter α} (h_c : cauchy f) (hg : g ≠ ⊥) (h_le : g ≤ f) : cauchy g := ⟨hg, le_trans (filter.prod_mono h_le h_le) h_c.right⟩ lemma cauchy_nhds {a : α} : cauchy (nhds a) := ⟨nhds_neq_bot, calc filter.prod (nhds a) (nhds a) = uniformity.lift (λs:set (α×α), uniformity.lift' (λt:set(α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (a, y) ∈ t})) : nhds_nhds_eq_uniformity_uniformity_prod ... ≤ uniformity.lift' (λs:set (α×α), comp_rel s s) : le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le_of_le hs $ principal_mono.mpr $ assume ⟨x, y⟩ ⟨(hx : (x, a) ∈ s), (hy : (a, y) ∈ s)⟩, ⟨a, hx, hy⟩ ... ≤ uniformity : comp_le_uniformity⟩ lemma cauchy_pure {a : α} : cauchy (pure a) := cauchy_downwards cauchy_nhds (show principal {a} ≠ ⊥, by simp) (pure_le_nhds a) lemma le_nhds_of_cauchy_adhp {f : filter α} {x : α} (hf : cauchy f) (adhs : f ⊓ nhds x ≠ ⊥) : f ≤ nhds x := have ∀s∈f.sets, x ∈ closure s, begin intros s hs, simp [closure_eq_nhds, inf_comm], exact assume h', adhs $ bot_unique $ h' ▸ inf_le_inf (by simp; exact hs) (le_refl _) end, calc f ≤ f.lift' (λs:set α, {y | x ∈ closure s ∧ y ∈ closure s}) : le_infi $ assume s, le_infi $ assume hs, begin rw [←forall_sets_neq_empty_iff_neq_bot] at adhs, simp [this s hs], exact mem_sets_of_superset hs subset_closure end ... ≤ f.lift' (λs:set α, {y | (x, y) ∈ closure (set.prod s s)}) : by simp [closure_prod_eq]; exact le_refl _ ... = (filter.prod f f).lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : begin rw [prod_same_eq], rw [lift'_lift'_assoc], exact monotone_prod monotone_id monotone_id, exact monotone_comp (assume s t h x h', closure_mono h h') monotone_preimage end ... ≤ uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : lift'_mono hf.right (le_refl _) ... = (uniformity.lift' closure).lift' (λs:set (α×α), {y | (x, y) ∈ s}) : begin rw [lift'_lift'_assoc], exact assume s t h, closure_mono h, exact monotone_preimage end ... = uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ s}) : by rw [←uniformity_eq_uniformity_closure] ... = nhds x : by rw [nhds_eq_uniformity] lemma le_nhds_iff_adhp_of_cauchy {f : filter α} {x : α} (hf : cauchy f) : f ≤ nhds x ↔ f ⊓ nhds x ≠ ⊥ := ⟨assume h, (inf_of_le_left h).symm ▸ hf.left, le_nhds_of_cauchy_adhp hf⟩ lemma cauchy_map [uniform_space β] {f : filter α} {m : α → β} (hm : uniform_continuous m) (hf : cauchy f) : cauchy (map m f) := ⟨have f ≠ ⊥, from hf.left, by simp; assumption, calc filter.prod (map m f) (map m f) = map (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_map_map_eq ... ≤ map (λp:α×α, (m p.1, m p.2)) uniformity : map_mono hf.right ... ≤ uniformity : hm⟩ lemma cauchy_comap [uniform_space β] {f : filter β} {m : α → β} (hm : comap (λp:α×α, (m p.1, m p.2)) uniformity ≤ uniformity) (hf : cauchy f) (hb : comap m f ≠ ⊥) : cauchy (comap m f) := ⟨hb, calc filter.prod (comap m f) (comap m f) = comap (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_comap_comap_eq ... ≤ comap (λp:α×α, (m p.1, m p.2)) uniformity : comap_mono hf.right ... ≤ uniformity : hm⟩ /- separated uniformity -/ /-- The separation relation is the intersection of all entourages. Two points which are related by the separation relation are "indistinguishable" according to the uniform structure. -/ protected def separation_rel (α : Type u) [u : uniform_space α] := ⋂₀ (@uniformity α _).sets lemma separated_equiv : equivalence (λx y, (x, y) ∈ separation_rel α) := ⟨assume x, assume s, refl_mem_uniformity, assume x y, assume h (s : set (α×α)) hs, have preimage prod.swap s ∈ (@uniformity α _).sets, from symm_le_uniformity hs, h _ this, assume x y z (hxy : (x, y) ∈ separation_rel α) (hyz : (y, z) ∈ separation_rel α) s (hs : s ∈ (@uniformity α _).sets), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ protected def separation_setoid (α : Type u) [u : uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ separation_rel α, separated_equiv⟩ @[class] def separated (α : Type u) [uniform_space α] := separation_rel α = id_rel theorem separated_def {α : Type u} [uniform_space α] : separated α ↔ ∀ x y, (∀ r ∈ (@uniformity α _).sets, (x, y) ∈ r) → x = y := by simp [separated, id_rel_subset.2 separated_equiv.1, subset.antisymm_iff]; simp [subset_def, separation_rel] theorem separated_def' {α : Type u} [uniform_space α] : separated α ↔ ∀ x y, x ≠ y → ∃ r ∈ (@uniformity α _).sets, (x, y) ∉ r := separated_def.trans $ forall_congr $ λ x, forall_congr $ λ y, by rw ← not_imp_not; simp [classical.not_forall] instance separated_t2 [s : separated α] : t2_space α := ⟨assume x y, assume h : x ≠ y, let ⟨d, hd, (hxy : (x, y) ∉ d)⟩ := separated_def'.1 s x y h in let ⟨d', hd', (hd'd' : comp_rel d' d' ⊆ d)⟩ := comp_mem_uniformity_sets hd in have {y | (x, y) ∈ d'} ∈ (nhds x).sets, from mem_nhds_left x hd', let ⟨u, hu₁, hu₂, hu₃⟩ := mem_nhds_sets_iff.mp this in have {x | (x, y) ∈ d'} ∈ (nhds y).sets, from mem_nhds_right y hd', let ⟨v, hv₁, hv₂, hv₃⟩ := mem_nhds_sets_iff.mp this in have u ∩ v = ∅, from eq_empty_of_subset_empty $ assume z ⟨(h₁ : z ∈ u), (h₂ : z ∈ v)⟩, have (x, y) ∈ comp_rel d' d', from ⟨z, hu₁ h₁, hv₁ h₂⟩, hxy $ hd'd' this, ⟨u, v, hu₂, hv₂, hu₃, hv₃, this⟩⟩ instance separated_regular [separated α] : regular_space α := { regular := λs a hs ha, have -s ∈ (nhds a).sets, from mem_nhds_sets hs ha, have {p : α × α | p.1 = a → p.2 ∈ -s} ∈ uniformity.sets, from mem_nhds_uniformity_iff.mp this, let ⟨d, hd, h⟩ := comp_mem_uniformity_sets this in let e := {y:α| (a, y) ∈ d} in have hae : a ∈ closure e, from subset_closure $ refl_mem_uniformity hd, have set.prod (closure e) (closure e) ⊆ comp_rel d (comp_rel (set.prod e e) d), begin rw [←closure_prod_eq, closure_eq_inter_uniformity], change (⨅d' ∈ uniformity.sets, _) ≤ comp_rel d (comp_rel _ d), exact (infi_le_of_le d $ infi_le_of_le hd $ le_refl _) end, have e_subset : closure e ⊆ -s, from assume a' ha', let ⟨x, (hx : (a, x) ∈ d), y, ⟨hx₁, hx₂⟩, (hy : (y, _) ∈ d)⟩ := @this ⟨a, a'⟩ ⟨hae, ha'⟩ in have (a, a') ∈ comp_rel d d, from ⟨y, hx₂, hy⟩, h this rfl, have closure e ∈ (nhds a).sets, from (nhds a).sets_of_superset (mem_nhds_left a hd) subset_closure, have nhds a ⊓ principal (-closure e) = ⊥, from (@inf_eq_bot_iff_le_compl _ _ _ (principal (- closure e)) (principal (closure e)) (by simp [principal_univ, union_comm]) (by simp)).mpr (by simp [this]), ⟨- closure e, is_closed_closure, assume x h₁ h₂, @e_subset x h₂ h₁, this⟩, ..separated_t2 } /-- A set `s` is totally bounded if for every entourage `d` there is a finite set of points `t` such that every element of `s` is `d`-near to some element of `t`. -/ def totally_bounded (s : set α) : Prop := ∀d ∈ (@uniformity α _).sets, ∃t : set α, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) theorem totally_bounded_iff_subset {s : set α} : totally_bounded s ↔ ∀d ∈ (@uniformity α _).sets, ∃t ⊆ s, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) := ⟨λ H d hd, begin rcases comp_symm_of_uniformity hd with ⟨r, hr, rs, rd⟩, rcases H r hr with ⟨k, fk, ks⟩, let u := {y ∈ k | ∃ x, x ∈ s ∧ (x, y) ∈ r}, let f : u → α := λ x, classical.some x.2.2, have : ∀ x : u, f x ∈ s ∧ (f x, x.1) ∈ r := λ x, classical.some_spec x.2.2, refine ⟨range f, _, _, _⟩, { exact range_subset_iff.2 (λ x, (this x).1) }, { have : finite u := finite_subset fk (λ x h, h.1), exact ⟨@set.fintype_range _ _ _ _ this.fintype⟩ }, { intros x xs, have := ks xs, simp at this, rcases this with ⟨y, hy, xy⟩, let z : coe_sort u := ⟨y, hy, x, xs, xy⟩, simp, exact ⟨_, ⟨_, z.2, rfl⟩, rd $ mem_comp_rel.2 ⟨_, xy, rs (this z).2⟩⟩ } end, λ H d hd, let ⟨t, _, ht⟩ := H d hd in ⟨t, ht⟩⟩ lemma totally_bounded_subset [uniform_space α] {s₁ s₂ : set α} (hs : s₁ ⊆ s₂) (h : totally_bounded s₂) : totally_bounded s₁ := assume d hd, let ⟨t, ht₁, ht₂⟩ := h d hd in ⟨t, ht₁, subset.trans hs ht₂⟩ lemma totally_bounded_closure [uniform_space α] {s : set α} (h : totally_bounded s) : totally_bounded (closure s) := assume t ht, let ⟨t', ht', hct', htt'⟩ := mem_uniformity_is_closed ht, ⟨c, hcf, hc⟩ := h t' ht' in ⟨c, hcf, calc closure s ⊆ closure (⋃ (y : α) (H : y ∈ c), {x : α | (x, y) ∈ t'}) : closure_mono hc ... = _ : closure_eq_of_is_closed $ is_closed_Union hcf $ assume i hi, continuous_iff_is_closed.mp (continuous_id.prod_mk continuous_const) _ hct' ... ⊆ _ : bUnion_subset $ assume i hi, subset.trans (assume x, @htt' (x, i)) (subset_bUnion_of_mem hi)⟩ lemma totally_bounded_image [uniform_space α] [uniform_space β] {f : α → β} {s : set α} (hf : uniform_continuous f) (hs : totally_bounded s) : totally_bounded (f '' s) := assume t ht, have {p:α×α | (f p.1, f p.2) ∈ t} ∈ (@uniformity α _).sets, from hf ht, let ⟨c, hfc, hct⟩ := hs _ this in ⟨f '' c, finite_image f hfc, begin simp [image_subset_iff], simp [subset_def] at hct, intros x hx, simp [-mem_image], exact let ⟨i, hi, ht⟩ := hct x hx in ⟨f i, mem_image_of_mem f hi, ht⟩ end⟩ lemma totally_bounded_preimage [uniform_space α] [uniform_space β] {f : α → β} {s : set β} (hf : uniform_embedding f) (hs : totally_bounded s) : totally_bounded (f ⁻¹' s) := λ t ht, begin rw ← hf.2 at ht, rcases mem_comap_sets.2 ht with ⟨t', ht', ts⟩, rcases totally_bounded_iff_subset.1 (totally_bounded_subset (image_preimage_subset f s) hs) _ ht' with ⟨c, cs, hfc, hct⟩, refine ⟨f ⁻¹' c, finite_preimage hf.1 hfc, λ x h, _⟩, have := hct (mem_image_of_mem f h), simp at this ⊢, rcases this with ⟨z, zc, zt⟩, rcases cs zc with ⟨y, yc, rfl⟩, exact ⟨y, zc, ts (by exact zt)⟩ end lemma cauchy_of_totally_bounded_of_ultrafilter {s : set α} {f : filter α} (hs : totally_bounded s) (hf : ultrafilter f) (h : f ≤ principal s) : cauchy f := ⟨hf.left, assume t ht, let ⟨t', ht'₁, ht'_symm, ht'_t⟩ := comp_symm_of_uniformity ht in let ⟨i, hi, hs_union⟩ := hs t' ht'₁ in have (⋃y∈i, {x | (x,y) ∈ t'}) ∈ f.sets, from mem_sets_of_superset (le_principal_iff.mp h) hs_union, have ∃y∈i, {x | (x,y) ∈ t'} ∈ f.sets, from mem_of_finite_Union_ultrafilter hf hi this, let ⟨y, hy, hif⟩ := this in have set.prod {x | (x,y) ∈ t'} {x | (x,y) ∈ t'} ⊆ comp_rel t' t', from assume ⟨x₁, x₂⟩ ⟨(h₁ : (x₁, y) ∈ t'), (h₂ : (x₂, y) ∈ t')⟩, ⟨y, h₁, ht'_symm h₂⟩, (filter.prod f f).sets_of_superset (prod_mem_prod hif hif) (subset.trans this ht'_t)⟩ lemma totally_bounded_iff_filter {s : set α} : totally_bounded s ↔ (∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c) := ⟨assume : totally_bounded s, assume f hf hs, ⟨ultrafilter_of f, ultrafilter_of_le, cauchy_of_totally_bounded_of_ultrafilter this (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hs)⟩, assume h : ∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c, assume d hd, classical.by_contradiction $ assume hs, have hd_cover : ∀{t:set α}, finite t → ¬ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}), by simpa using hs, let f := ⨅t:{t : set α // finite t}, principal (s \ (⋃y∈t.val, {x | (x,y) ∈ d})), ⟨a, ha⟩ := @exists_mem_of_ne_empty α s (assume h, hd_cover finite_empty $ h.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩ (assume ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, ⟨⟨t₁ ∪ t₂, finite_union ht₁ ht₂⟩, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inl, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inr⟩) (assume ⟨t, ht⟩, by simp [diff_eq_empty]; exact hd_cover ht), have f ≤ principal s, from infi_le_of_le ⟨∅, finite_empty⟩ $ by simp; exact subset.refl s, let ⟨c, (hc₁ : c ≤ f), (hc₂ : cauchy c)⟩ := h f ‹f ≠ ⊥› this, ⟨m, hm, (hmd : set.prod m m ⊆ d)⟩ := (@mem_prod_same_iff α c d).mp $ hc₂.right hd in have c ≤ principal s, from le_trans ‹c ≤ f› this, have m ∩ s ∈ c.sets, from inter_mem_sets hm $ le_principal_iff.mp this, let ⟨y, hym, hys⟩ := inhabited_of_mem_sets hc₂.left this in let ys := (⋃y'∈({y}:set α), {x | (x, y') ∈ d}) in have m ⊆ ys, from assume y' hy', show y' ∈ (⋃y'∈({y}:set α), {x | (x, y') ∈ d}), by simp; exact @hmd (y', y) ⟨hy', hym⟩, have c ≤ principal (s - ys), from le_trans hc₁ $ infi_le_of_le ⟨{y}, finite_singleton _⟩ $ le_refl _, have (s - ys) ∩ (m ∩ s) ∈ c.sets, from inter_mem_sets (le_principal_iff.mp this) ‹m ∩ s ∈ c.sets›, have ∅ ∈ c.sets, from c.sets_of_superset this $ assume x ⟨⟨hxs, hxys⟩, hxm, _⟩, hxys $ ‹m ⊆ ys› hxm, hc₂.left $ empty_in_sets_eq_bot.mp this⟩ lemma totally_bounded_iff_ultrafilter {s : set α} : totally_bounded s ↔ (∀f, ultrafilter f → f ≤ principal s → cauchy f) := ⟨assume hs f, cauchy_of_totally_bounded_of_ultrafilter hs, assume h, totally_bounded_iff_filter.mpr $ assume f hf hfs, have cauchy (ultrafilter_of f), from h (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs), ⟨ultrafilter_of f, ultrafilter_of_le, this⟩⟩ lemma compact_of_totally_bounded_complete {s : set α} (ht : totally_bounded s) (hc : ∀{f:filter α}, cauchy f → f ≤ principal s → ∃x∈s, f ≤ nhds x) : compact s := begin rw [compact_iff_ultrafilter_le_nhds], rw [totally_bounded_iff_ultrafilter] at ht, exact assume f hf hfs, hc (ht _ hf hfs) hfs end /-- A complete space is defined here using uniformities. A uniform space is complete if every Cauchy filter converges. -/ class complete_space (α : Type u) [uniform_space α] : Prop := (complete : ∀{f:filter α}, cauchy f → ∃x, f ≤ nhds x) theorem le_nhds_lim_of_cauchy {α} [uniform_space α] [complete_space α] [inhabited α] {f : filter α} (hf : cauchy f) : f ≤ nhds (lim f) := lim_spec (complete_space.complete hf) lemma complete_of_is_closed [complete_space α] {s : set α} {f : filter α} (h : is_closed s) (hf : cauchy f) (hfs : f ≤ principal s) : ∃x∈s, f ≤ nhds x := let ⟨x, hx⟩ := complete_space.complete hf in have x ∈ s, from is_closed_iff_nhds.mp h x $ neq_bot_of_le_neq_bot hf.left $ le_inf hx hfs, ⟨x, this, hx⟩ lemma compact_of_totally_bounded_is_closed [complete_space α] {s : set α} (ht : totally_bounded s) (hc : is_closed s) : compact s := @compact_of_totally_bounded_complete α _ s ht $ assume f, complete_of_is_closed hc lemma complete_space_extension [uniform_space β] {m : β → α} (hm : uniform_embedding m) (dense : ∀x, x ∈ closure (range m)) (h : ∀f:filter β, cauchy f → ∃x:α, map m f ≤ nhds x) : complete_space α := ⟨assume (f : filter α), assume hf : cauchy f, let p : set (α × α) → set α → set α := λs t, {y : α| ∃x:α, x ∈ t ∧ (x, y) ∈ s}, g := uniformity.lift (λs, f.lift' (p s)) in have mp₀ : monotone p, from assume a b h t s ⟨x, xs, xa⟩, ⟨x, xs, h xa⟩, have mp₁ : ∀{s}, monotone (p s), from assume s a b h x ⟨y, ya, yxs⟩, ⟨y, h ya, yxs⟩, have f ≤ g, from le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, le_principal_iff.mpr $ mem_sets_of_superset ht $ assume x hx, ⟨x, hx, refl_mem_uniformity hs⟩, have g ≠ ⊥, from neq_bot_of_le_neq_bot hf.left this, have comap m g ≠ ⊥, from comap_neq_bot $ assume t ht, let ⟨t', ht', ht_mem⟩ := (mem_lift_sets $ monotone_lift' monotone_const mp₀).mp ht in let ⟨t'', ht'', ht'_sub⟩ := (mem_lift'_sets mp₁).mp ht_mem in let ⟨x, (hx : x ∈ t'')⟩ := inhabited_of_mem_sets hf.left ht'' in have h₀ : nhds x ⊓ principal (range m) ≠ ⊥, by simp [closure_eq_nhds] at dense; exact dense x, have h₁ : {y | (x, y) ∈ t'} ∈ (nhds x ⊓ principal (range m)).sets, from @mem_inf_sets_of_left α (nhds x) (principal (range m)) _ $ mem_nhds_left x ht', have h₂ : range m ∈ (nhds x ⊓ principal (range m)).sets, from @mem_inf_sets_of_right α (nhds x) (principal (range m)) _ $ subset.refl _, have {y | (x, y) ∈ t'} ∩ range m ∈ (nhds x ⊓ principal (range m)).sets, from @inter_mem_sets α (nhds x ⊓ principal (range m)) _ _ h₁ h₂, let ⟨y, xyt', b, b_eq⟩ := inhabited_of_mem_sets h₀ this in ⟨b, b_eq.symm ▸ ht'_sub ⟨x, hx, xyt'⟩⟩, have cauchy g, from ⟨‹g ≠ ⊥›, assume s hs, let ⟨s₁, hs₁, (comp_s₁ : comp_rel s₁ s₁ ⊆ s)⟩ := comp_mem_uniformity_sets hs, ⟨s₂, hs₂, (comp_s₂ : comp_rel s₂ s₂ ⊆ s₁)⟩ := comp_mem_uniformity_sets hs₁, ⟨t, ht, (prod_t : set.prod t t ⊆ s₂)⟩ := mem_prod_same_iff.mp (hf.right hs₂) in have hg₁ : p (preimage prod.swap s₁) t ∈ g.sets, from mem_lift (symm_le_uniformity hs₁) $ @mem_lift' α α f _ t ht, have hg₂ : p s₂ t ∈ g.sets, from mem_lift hs₂ $ @mem_lift' α α f _ t ht, have hg : set.prod (p (preimage prod.swap s₁) t) (p s₂ t) ∈ (filter.prod g g).sets, from @prod_mem_prod α α _ _ g g hg₁ hg₂, (filter.prod g g).sets_of_superset hg (assume ⟨a, b⟩ ⟨⟨c₁, c₁t, hc₁⟩, ⟨c₂, c₂t, hc₂⟩⟩, have (c₁, c₂) ∈ set.prod t t, from ⟨c₁t, c₂t⟩, comp_s₁ $ prod_mk_mem_comp_rel hc₁ $ comp_s₂ $ prod_mk_mem_comp_rel (prod_t this) hc₂)⟩, have cauchy (filter.comap m g), from cauchy_comap (le_of_eq hm.right) ‹cauchy g› (by assumption), let ⟨x, (hx : map m (filter.comap m g) ≤ nhds x)⟩ := h _ this in have map m (filter.comap m g) ⊓ nhds x ≠ ⊥, from (le_nhds_iff_adhp_of_cauchy (cauchy_map hm.uniform_continuous this)).mp hx, have g ⊓ nhds x ≠ ⊥, from neq_bot_of_le_neq_bot this (inf_le_inf (assume s hs, ⟨s, hs, subset.refl _⟩) (le_refl _)), ⟨x, calc f ≤ g : by assumption ... ≤ nhds x : le_nhds_of_cauchy_adhp ‹cauchy g› this⟩⟩ /- separation space -/ section separation_space local attribute [instance] separation_setoid instance {α : Type u} [u : uniform_space α] : uniform_space (quotient (separation_setoid α)) := { to_topological_space := u.to_topological_space.coinduced (λx, ⟦x⟧), uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity, refl := assume s hs ⟨a, b⟩ (h : a = b), have ∀a:α, (a, a) ∈ preimage (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) s, from assume a, refl_mem_uniformity hs, h ▸ quotient.induction_on a this, symm := tendsto_map' $ by simp [prod.swap, (∘)]; exact tendsto_swap_uniformity.comp tendsto_map, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity).lift' (λs, comp_rel s s) = uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ assume s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin simp at a_eq, simp at b_eq, have h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] }, have h : (a₂, b₁) ∈ separation_rel α := quotient.exact h, simp [function.comp, set.image, comp_rel, and.comm, and.left_comm, and.assoc], exact ⟨a₁, a_eq.left, b₂, b_eq.right, a₂, ha, b₁, h s hs, hb⟩ end ... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity : map_mono comp_le_uniformity3, is_open_uniformity := assume s, have ∀a, ⟦a⟧ ∈ s → ({p:α×α | p.1 = a → ⟦p.2⟧ ∈ s} ∈ (@uniformity α _).sets ↔ {p:α×α | p.1 ≈ a → ⟦p.2⟧ ∈ s} ∈ (@uniformity α _).sets), from assume a ha, ⟨assume h, let ⟨t, ht, hts⟩ := comp_mem_uniformity_sets h in have hts : ∀{a₁ a₂}, (a, a₁) ∈ t → (a₁, a₂) ∈ t → ⟦a₂⟧ ∈ s, from assume a₁ a₂ ha₁ ha₂, @hts (a, a₂) ⟨a₁, ha₁, ha₂⟩ rfl, have ht' : ∀{a₁ a₂}, a₁ ≈ a₂ → (a₁, a₂) ∈ t, from assume a₁ a₂ h, sInter_subset_of_mem ht h, uniformity.sets_of_superset ht $ assume ⟨a₁, a₂⟩ h₁ h₂, hts (ht' $ setoid.symm h₂) h₁, assume h, uniformity.sets_of_superset h $ by simp {contextual := tt}⟩, begin simp [topological_space.coinduced, u.is_open_uniformity, uniformity, forall_quotient_iff], exact ⟨λh a ha, (this a ha).mp $ h a ha, λh a ha, (this a ha).mpr $ h a ha⟩ end } lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_refl _ lemma comap_quotient_le_uniformity : comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity ≤ uniformity := assume t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (@uniformity α _).sets_of_superset hs $ assume x hx, ⟨x, hx, rfl⟩, assume ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma comap_quotient_eq_uniformity : comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity = uniformity := le_antisymm comap_quotient_le_uniformity le_comap_map lemma complete_space_separation [h : complete_space α] : complete_space (quotient (separation_setoid α)) := ⟨assume f, assume hf : cauchy f, have cauchy (comap (λx, ⟦x⟧) f), from cauchy_comap comap_quotient_le_uniformity hf $ comap_neq_bot_of_surj hf.left $ assume b, quotient.exists_rep _, let ⟨x, (hx : comap (λx, ⟦x⟧) f ≤ nhds x)⟩ := complete_space.complete this in ⟨⟦x⟧, calc f ≤ map (λx, ⟦x⟧) (comap (λx, ⟦x⟧) f) : le_map_comap $ assume b, quotient.exists_rep _ ... ≤ map (λx, ⟦x⟧) (nhds x) : map_mono hx ... ≤ _ : continuous_iff_tendsto.mp uniform_continuous_quotient_mk.continuous _⟩⟩ lemma separated_separation [h : complete_space α] : separated (quotient (separation_setoid α)) := set.ext $ assume ⟨a, b⟩, quotient.induction_on₂ a b $ assume a b, ⟨assume h, have a ≈ b, from assume s hs, have s ∈ (comap (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity).sets, from comap_quotient_le_uniformity hs, let ⟨t, ht, hts⟩ := this in hts begin dsimp, exact h t ht end, show ⟦a⟧ = ⟦b⟧, from quotient.sound this, assume heq : ⟦a⟧ = ⟦b⟧, assume h hs, heq ▸ refl_mem_uniformity hs⟩ variables [uniform_space β] [uniform_space γ] lemma uniform_continuous_quotient {f : quotient (separation_setoid α) → β} (hf : uniform_continuous (λx, f ⟦x⟧)) : uniform_continuous f := hf lemma uniform_continuous_quotient_lift {f : α → β} {h : ∀a b, (a, b) ∈ separation_rel α → f a = f b} (hf : uniform_continuous f) : uniform_continuous (λa, quotient.lift f h a) := uniform_continuous_quotient hf lemma uniformity_quotient : @uniformity (quotient (separation_setoid α)) _ = uniformity.map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) := rfl lemma separated_of_uniform_continuous {f : α → β} (H : uniform_continuous f) {x y : α} (h : x ≈ y) : f x ≈ f y := assume _ h', h _ (H h') lemma eq_of_separated_of_uniform_continuous [separated β] {f : α → β} (H : uniform_continuous f) {x y : α} (h : x ≈ y) : f x = f y := separated_def.1 (by apply_instance) _ _ $ separated_of_uniform_continuous H h end separation_space section uniform_extension variables [uniform_space β] [uniform_space γ] {e : β → α} (h_e : uniform_embedding e) (h_dense : ∀x, x ∈ closure (range e)) {f : β → γ} (h_f : uniform_continuous f) local notation `ψ` := (h_e.dense_embedding h_dense).extend f lemma uniformly_extend_of_emb [cγ : complete_space γ] [sγ : separated γ] {b : β} : ψ (e b) = f b := dense_embedding.extend_e_eq _ $ continuous_iff_tendsto.mp h_f.continuous b lemma uniformly_extend_exists [complete_space γ] [sγ : separated γ] {a : α} : ∃c, tendsto f (comap e (nhds a)) (nhds c) := let de := (h_e.dense_embedding h_dense) in have cauchy (nhds a), from cauchy_nhds, have cauchy (comap e (nhds a)), from cauchy_comap (le_of_eq h_e.right) this de.comap_nhds_neq_bot, have cauchy (map f (comap e (nhds a))), from cauchy_map h_f this, complete_space.complete this lemma uniformly_extend_spec [complete_space γ] [sγ : separated γ] {a : α} : tendsto f (comap e (nhds a)) (nhds (ψ a)) := @lim_spec _ (id _) _ _ $ uniformly_extend_exists h_e h_dense h_f lemma uniform_continuous_uniformly_extend [cγ : complete_space γ] [sγ : separated γ] : uniform_continuous ψ := assume d hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in have h_pnt : ∀{a m}, m ∈ (nhds a).sets → ∃c, c ∈ f '' preimage e m ∧ (c, ψ a) ∈ s ∧ (ψ a, c) ∈ s, from assume a m hm, have nb : map f (comap e (nhds a)) ≠ ⊥, from map_ne_bot (h_e.dense_embedding h_dense).comap_nhds_neq_bot, have (f '' preimage e m) ∩ ({c | (c, ψ a) ∈ s } ∩ {c | (ψ a, c) ∈ s }) ∈ (map f (comap e (nhds a))).sets, from inter_mem_sets (image_mem_map $ preimage_mem_comap $ hm) (uniformly_extend_spec h_e h_dense h_f $ inter_mem_sets (mem_nhds_right _ hs) (mem_nhds_left _ hs)), inhabited_of_mem_sets nb this, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ (@uniformity β _).sets, from h_f hs, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ (comap (λx:β×β, (e x.1, e x.2)) uniformity).sets, by rwa [h_e.right.symm] at this, let ⟨t, ht, ts⟩ := this in show preimage (λp:(α×α), (ψ p.1, ψ p.2)) d ∈ uniformity.sets, from (@uniformity α _).sets_of_superset (interior_mem_uniformity ht) $ assume ⟨x₁, x₂⟩ hx_t, have nhds (x₁, x₂) ≤ principal (interior t), from is_open_iff_nhds.mp is_open_interior (x₁, x₂) hx_t, have interior t ∈ (filter.prod (nhds x₁) (nhds x₂)).sets, by rwa [nhds_prod_eq, le_principal_iff] at this, let ⟨m₁, hm₁, m₂, hm₂, (hm : set.prod m₁ m₂ ⊆ interior t)⟩ := mem_prod_iff.mp this in let ⟨a, ha₁, _, ha₂⟩ := h_pnt hm₁ in let ⟨b, hb₁, hb₂, _⟩ := h_pnt hm₂ in have set.prod (preimage e m₁) (preimage e m₂) ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s, from calc _ ⊆ preimage (λp:(β×β), (e p.1, e p.2)) (interior t) : preimage_mono hm ... ⊆ preimage (λp:(β×β), (e p.1, e p.2)) t : preimage_mono interior_subset ... ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s : ts, have set.prod (f '' preimage e m₁) (f '' preimage e m₂) ⊆ s, from calc set.prod (f '' preimage e m₁) (f '' preimage e m₂) = (λp:(β×β), (f p.1, f p.2)) '' (set.prod (preimage e m₁) (preimage e m₂)) : prod_image_image_eq ... ⊆ (λp:(β×β), (f p.1, f p.2)) '' preimage (λp:(β×β), (f p.1, f p.2)) s : mono_image this ... ⊆ s : image_subset_iff.mpr $ subset.refl _, have (a, b) ∈ s, from @this (a, b) ⟨ha₁, hb₁⟩, hs_comp $ show (ψ x₁, ψ x₂) ∈ comp_rel s (comp_rel s s), from ⟨a, ha₂, ⟨b, this, hb₂⟩⟩ end uniform_extension end uniform_space end /-- Space of Cauchy filters This is essentially the completion of a uniform space. The embeddings are the neighbourhood filters. This space is not minimal, the separated uniform space (i.e. quotiented on the intersection of all entourages) is necessary for this. -/ def Cauchy (α : Type u) [uniform_space α] : Type u := { f : filter α // cauchy f } namespace Cauchy section parameters {α : Type u} [uniform_space α] def gen (s : set (α × α)) : set (Cauchy α × Cauchy α) := {p | s ∈ (filter.prod (p.1.val) (p.2.val)).sets } lemma monotone_gen : monotone gen := monotone_set_of $ assume p, @monotone_mem_sets (α×α) (filter.prod (p.1.val) (p.2.val)) private lemma symm_gen : map prod.swap (uniformity.lift' gen) ≤ uniformity.lift' gen := calc map prod.swap (uniformity.lift' gen) = uniformity.lift' (λs:set (α×α), {p | s ∈ (filter.prod (p.2.val) (p.1.val)).sets }) : begin delta gen, simp [map_lift'_eq, monotone_set_of, monotone_mem_sets, function.comp, image_swap_eq_preimage_swap] end ... ≤ uniformity.lift' gen : uniformity_lift_le_swap (monotone_comp (monotone_set_of $ assume p, @monotone_mem_sets (α×α) ((filter.prod ((p.2).val) ((p.1).val)))) monotone_principal) begin have h := λ(p:Cauchy α×Cauchy α), @filter.prod_comm _ _ (p.2.val) (p.1.val), simp [function.comp, h], exact le_refl _ end private lemma comp_rel_gen_gen_subset_gen_comp_rel {s t : set (α×α)} : comp_rel (gen s) (gen t) ⊆ (gen (comp_rel s t) : set (Cauchy α × Cauchy α)) := assume ⟨f, g⟩ ⟨h, h₁, h₂⟩, let ⟨t₁, (ht₁ : t₁ ∈ f.val.sets), t₂, (ht₂ : t₂ ∈ h.val.sets), (h₁ : set.prod t₁ t₂ ⊆ s)⟩ := mem_prod_iff.mp h₁ in let ⟨t₃, (ht₃ : t₃ ∈ h.val.sets), t₄, (ht₄ : t₄ ∈ g.val.sets), (h₂ : set.prod t₃ t₄ ⊆ t)⟩ := mem_prod_iff.mp h₂ in have t₂ ∩ t₃ ∈ h.val.sets, from inter_mem_sets ht₂ ht₃, let ⟨x, xt₂, xt₃⟩ := inhabited_of_mem_sets (h.property.left) this in (filter.prod f.val g.val).sets_of_superset (prod_mem_prod ht₁ ht₄) (assume ⟨a, b⟩ ⟨(ha : a ∈ t₁), (hb : b ∈ t₄)⟩, ⟨x, h₁ (show (a, x) ∈ set.prod t₁ t₂, from ⟨ha, xt₂⟩), h₂ (show (x, b) ∈ set.prod t₃ t₄, from ⟨xt₃, hb⟩)⟩) private lemma comp_gen : (uniformity.lift' gen).lift' (λs, comp_rel s s) ≤ uniformity.lift' gen := calc (uniformity.lift' gen).lift' (λs, comp_rel s s) = uniformity.lift' (λs, comp_rel (gen s) (gen s)) : begin rw [lift'_lift'_assoc], exact monotone_gen, exact (monotone_comp_rel monotone_id monotone_id) end ... ≤ uniformity.lift' (λs, gen $ comp_rel s s) : lift'_mono' $ assume s hs, comp_rel_gen_gen_subset_gen_comp_rel ... = (uniformity.lift' $ λs:set(α×α), comp_rel s s).lift' gen : begin rw [lift'_lift'_assoc], exact (monotone_comp_rel monotone_id monotone_id), exact monotone_gen end ... ≤ uniformity.lift' gen : lift'_mono comp_le_uniformity (le_refl _) instance completion_space : uniform_space (Cauchy α) := uniform_space.of_core { uniformity := uniformity.lift' gen, refl := principal_le_lift' $ assume s hs ⟨a, b⟩ (a_eq_b : a = b), a_eq_b ▸ a.property.right hs, symm := symm_gen, comp := comp_gen } theorem mem_uniformity {s : set (Cauchy α × Cauchy α)} : s ∈ (@uniformity (Cauchy α) _).sets ↔ ∃ t ∈ (@uniformity α _).sets, gen t ⊆ s := mem_lift'_sets monotone_gen theorem mem_uniformity' {s : set (Cauchy α × Cauchy α)} : s ∈ (@uniformity (Cauchy α) _).sets ↔ ∃ t ∈ (@uniformity α _).sets, ∀ f g : Cauchy α, t ∈ (filter.prod f.1 g.1).sets → (f, g) ∈ s := mem_uniformity.trans $ bex_congr $ λ t h, prod.forall /-- Embedding of `α` into its completion -/ def pure_cauchy (a : α) : Cauchy α := ⟨pure a, cauchy_pure⟩ lemma uniform_embedding_pure_cauchy : uniform_embedding (pure_cauchy : α → Cauchy α) := ⟨assume a₁ a₂ h, have (pure_cauchy a₁).val = (pure_cauchy a₂).val, from congr_arg _ h, have {a₁} = ({a₂} : set α), from principal_eq_iff_eq.mp this, by simp at this; assumption, have (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) = id, from funext $ assume s, set.ext $ assume ⟨a₁, a₂⟩, by simp [preimage, gen, pure_cauchy, prod_principal_principal], calc comap (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) (uniformity.lift' gen) = uniformity.lift' (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) : comap_lift'_eq monotone_gen ... = uniformity : by simp [this]⟩ lemma pure_cauchy_dense : ∀x, x ∈ closure (range pure_cauchy) := assume f, have h_ex : ∀s∈(@uniformity (Cauchy α) _).sets, ∃y:α, (f, pure_cauchy y) ∈ s, from assume s hs, let ⟨t'', ht''₁, (ht''₂ : gen t'' ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht'₁, ht'₂⟩ := comp_mem_uniformity_sets ht''₁ in have t' ∈ (filter.prod (f.val) (f.val)).sets, from f.property.right ht'₁, let ⟨t, ht, (h : set.prod t t ⊆ t')⟩ := mem_prod_same_iff.mp this in let ⟨x, (hx : x ∈ t)⟩ := inhabited_of_mem_sets f.property.left ht in have t'' ∈ (filter.prod f.val (pure x)).sets, from mem_prod_iff.mpr ⟨t, ht, {y:α | (x, y) ∈ t'}, assume y, begin simp, intro h, simp [h], exact refl_mem_uniformity ht'₁ end, assume ⟨a, b⟩ ⟨(h₁ : a ∈ t), (h₂ : (x, b) ∈ t')⟩, ht'₂ $ prod_mk_mem_comp_rel (@h (a, x) ⟨h₁, hx⟩) h₂⟩, ⟨x, ht''₂ $ by dsimp [gen]; exact this⟩, begin simp [closure_eq_nhds, nhds_eq_uniformity, lift'_inf_principal_eq, set.inter_comm], exact (lift'_neq_bot_iff $ monotone_inter monotone_const monotone_preimage).mpr (assume s hs, let ⟨y, hy⟩ := h_ex s hs in have pure_cauchy y ∈ range pure_cauchy ∩ {y : Cauchy α | (f, y) ∈ s}, from ⟨mem_range_self y, hy⟩, ne_empty_of_mem this) end instance : complete_space (Cauchy α) := complete_space_extension uniform_embedding_pure_cauchy pure_cauchy_dense $ assume f hf, let f' : Cauchy α := ⟨f, hf⟩ in have map pure_cauchy f ≤ uniformity.lift' (preimage (prod.mk f')), from le_lift' $ assume s hs, let ⟨t, ht₁, (ht₂ : gen t ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht', (h : set.prod t' t' ⊆ t)⟩ := mem_prod_same_iff.mp (hf.right ht₁) in have t' ⊆ { y : α | (f', pure_cauchy y) ∈ gen t }, from assume x hx, (filter.prod f (pure x)).sets_of_superset (prod_mem_prod ht' $ mem_pure hx) h, f.sets_of_superset ht' $ subset.trans this (preimage_mono ht₂), ⟨f', by simp [nhds_eq_uniformity]; assumption⟩ end section local attribute [instance] separation_setoid lemma injective_separated_pure_cauchy {α : Type*} [uniform_space α] [s : separated α] : function.injective (λa:α, ⟦pure_cauchy a⟧) | a b h := separated_def.1 s _ _ $ assume s hs, let ⟨t, ht, hts⟩ := by rw [← (@uniform_embedding_pure_cauchy α _).right, filter.mem_comap_sets] at hs; exact hs in have (pure_cauchy a, pure_cauchy b) ∈ t, from quotient.exact h t ht, @hts (a, b) this end end Cauchy instance nonempty_Cauchy {α : Type u} [h : nonempty α] [uniform_space α] : nonempty (Cauchy α) := h.rec_on $ assume a, nonempty.intro $ Cauchy.pure_cauchy a instance inhabited_Cauchy {α : Type u} [inhabited α] [uniform_space α] : inhabited (Cauchy α) := ⟨Cauchy.pure_cauchy $ default α⟩ section constructions variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} instance : partial_order (uniform_space α) := { le := λt s, s.uniformity ≤ t.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₂ h₁, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, @le_trans _ _ c.uniformity b.uniformity a.uniformity h₂ h₁ } instance : has_Sup (uniform_space α) := ⟨assume s, uniform_space.of_core { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma le_Sup {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : t ≤ Sup tt := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma Sup_le {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t' ≤ t) : Sup tt ≤ t := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_bot (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_top (uniform_space α) := ⟨{ to_topological_space := ⊤, uniformity := principal id_rel, refl := le_refl _, symm := by simp [tendsto]; apply subset.refl, comp := begin rw [lift'_principal], {simp}, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩ instance : complete_lattice (uniform_space α) := { sup := λa b, Sup {a, b}, le_sup_left := assume a b, le_Sup $ by simp, le_sup_right := assume a b, le_Sup $ by simp, sup_le := assume a b c h₁ h₂, Sup_le $ assume t', begin simp, intro h, cases h with h h, repeat { subst h; assumption } end, inf := λa b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := assume a b c h₁ h₂, le_Sup ⟨h₁, h₂⟩, inf_le_left := assume a b, Sup_le $ assume x ⟨ha, hb⟩, ha, inf_le_right := assume a b, Sup_le $ assume x ⟨ha, hb⟩, hb, top := ⊤, le_top := assume u, u.refl, bot := ⊥, bot_le := assume a, show a.uniformity ≤ ⊤, from le_top, Sup := Sup, le_Sup := assume s u, le_Sup, Sup_le := assume s u, Sup_le, Inf := λtt, Sup {t | ∀t'∈tt, t ≤ t'}, le_Inf := assume s a hs, le_Sup hs, Inf_le := assume s a ha, Sup_le $ assume u hs, hs _ ha, ..uniform_space.partial_order } lemma supr_uniformity {ι : Sort*} {u : ι → uniform_space α} : (supr u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, a = u i), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : a = u i)⟩, ha.symm ▸ infi_le _ _) lemma sup_uniformity {u v : uniform_space α} : (u ⊔ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊔ v) = (⨆i (h : i = u ∨ i = v), i), by simp [supr_or, supr_sup_eq], calc (u ⊔ v).uniformity = ((⨆i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp [supr_uniformity, infi_or, infi_inf_eq] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊤⟩ /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl), symm := by simp [tendsto_comap_iff, prod.swap, (∘)]; exact tendsto_comap.comp tendsto_swap_uniformity, comp := le_trans begin rw [comap_lift'_eq, comap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (comap_mono u.comp), is_open_uniformity := λ s, begin change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp [is_open_iff_nhds, nhds_induced_eq_comap, mem_nhds_uniformity_iff, filter.comap, and_comm], refine ball_congr (λ x hx, ⟨_, _⟩), { rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩, rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) }, { rintro ⟨t, ht, hts⟩, exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl, mem_nhds_uniformity_iff.1 $ mem_nhds_left _ ht⟩ } end } lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id := by ext u ; dsimp [uniform_space.comap] ; rw [prod.id_prod, filter.comap_id] lemma uniform_space.comap_comap_comp {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} : uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) := by ext ; dsimp [uniform_space.comap] ; rw filter.comap_comap_comp lemma uniform_continuous_iff {α β} [uα : uniform_space α] [uβ : uniform_space β] (f : α → β) : uniform_continuous f ↔ uβ.comap f ≤ uα := filter.map_le_iff_le_comap lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.comap f u) u f := tendsto_comap theorem to_topological_space_comap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.comap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := eq_of_nhds_eq_nhds $ assume a, begin simp [nhds_induced_eq_comap, nhds_eq_uniformity, nhds_eq_uniformity], change comap f (uniformity.lift' (preimage (λb, (f a, b)))) = (u.uniformity.comap (λp:α×α, (f p.1, f p.2))).lift' (preimage (λa', (a, a'))), rw [comap_lift'_eq monotone_preimage, comap_lift'_eq2 monotone_preimage], exact rfl end lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g := tendsto_comap_iff.2 h lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ assume a, by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _) lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := rfl lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := bot_unique $ assume s hs, classical.by_cases (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊥) (assume : s ≠ ∅, let ⟨x, hx⟩ := exists_mem_of_ne_empty this in have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl, this.symm ▸ @is_open_univ _ ⊥) lemma to_topological_space_supr {ι : Sort*} {u : ι → uniform_space α} : @uniform_space.to_topological_space α (supr u) = (⨆i, @uniform_space.to_topological_space α (u i)) := classical.by_cases (assume h : nonempty ι, eq_of_nhds_eq_nhds $ assume a, begin rw [nhds_supr, nhds_eq_uniformity], change _ = (supr u).uniformity.lift' (preimage $ prod.mk a), begin rw [supr_uniformity, lift'_infi], exact (congr_arg _ $ funext $ assume i, @nhds_eq_uniformity α (u i) a), exact h, exact assume a b, rfl end end) (assume : ¬ nonempty ι, le_antisymm (have supr u = ⊥, from bot_unique $ supr_le $ assume i, (this ⟨i⟩).elim, have @uniform_space.to_topological_space _ (supr u) = ⊥, from this.symm ▸ to_topological_space_bot, this.symm ▸ bot_le) (supr_le $ assume i, to_topological_space_mono $ le_supr _ _)) lemma to_topological_space_Sup {s : set (uniform_space α)} : @uniform_space.to_topological_space α (Sup s) = (⨆i∈s, @uniform_space.to_topological_space α i) := begin rw [Sup_eq_supr, to_topological_space_supr], apply congr rfl, funext x, exact to_topological_space_supr end lemma to_topological_space_sup {u v : uniform_space α} : @uniform_space.to_topological_space α (u ⊔ v) = @uniform_space.to_topological_space α u ⊔ @uniform_space.to_topological_space α v := ord_continuous_sup $ assume s, to_topological_space_Sup instance : uniform_space empty := ⊤ instance : uniform_space unit := ⊤ instance : uniform_space bool := ⊤ instance : uniform_space ℕ := ⊤ instance : uniform_space ℤ := ⊤ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.comap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : (@uniformity (subtype p) _) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) uniformity := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_comap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_comap' hf lemma tendsto_of_uniform_continuous_subtype [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ (nhds a).sets) : tendsto f (nhds a) (nhds (f a)) := by rw [(@map_nhds_subtype_val_eq α _ s a (mem_of_nhds ha) ha).symm]; exact tendsto_map' (continuous_iff_tendsto.mp hf.continuous _) instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.comap prod.fst ⊔ u₂.comap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.comap prod.fst ⊔ u₂.comap prod.snd).to_topological_space : by rw [to_topological_space_sup, to_topological_space_comap, to_topological_space_comap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) theorem uniformity_prod [uniform_space α] [uniform_space β] : @uniformity (α × β) _ = uniformity.comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓ uniformity.comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) := sup_uniformity lemma uniform_embedding_subtype_emb {α : Type*} {β : Type*} [uniform_space α] [uniform_space β] (p : α → Prop) {e : α → β} (ue : uniform_embedding e) (de : dense_embedding e) : uniform_embedding (de.subtype_emb p) := ⟨(de.subtype p).inj, by simp [comap_comap_comp, (∘), dense_embedding.subtype_emb, uniformity_subtype, ue.right.symm]⟩ lemma uniform_extend_subtype {α : Type*} {β : Type*} {γ : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [complete_space γ] [inhabited γ] [separated γ] {p : α → Prop} {e : α → β} {f : α → γ} {b : β} {s : set α} (hf : uniform_continuous (λx:subtype p, f x.val)) (he : uniform_embedding e) (hd : ∀x:β, x ∈ closure (range e)) (hb : closure (e '' s) ∈ (nhds b).sets) (hs : is_closed s) (hp : ∀x∈s, p x) : ∃c, tendsto f (comap e (nhds b)) (nhds c) := have de : dense_embedding e, from he.dense_embedding hd, have de' : dense_embedding (de.subtype_emb p), by exact de.subtype p, have ue' : uniform_embedding (de.subtype_emb p), from uniform_embedding_subtype_emb _ he de, have b ∈ closure (e '' {x | p x}), from (closure_mono $ mono_image $ hp) (mem_of_nhds hb), let ⟨c, (hc : tendsto (f ∘ subtype.val) (comap (de.subtype_emb p) (nhds ⟨b, this⟩)) (nhds c))⟩ := uniformly_extend_exists ue' de'.dense hf in begin rw [nhds_subtype_eq_comap] at hc, simp [comap_comap_comp] at hc, change (tendsto (f ∘ @subtype.val α p) (comap (e ∘ @subtype.val α p) (nhds b)) (nhds c)) at hc, rw [←comap_comap_comp] at hc, existsi c, apply tendsto_comap'' s _ _ hc, exact ⟨_, hb, assume x, begin change e x ∈ (closure (e '' s)) → x ∈ s, rw [←closure_induced, closure_eq_nhds], dsimp, rw [nhds_induced_eq_comap, de.induced], change x ∈ {x | nhds x ⊓ principal s ≠ ⊥} → x ∈ s, rw [←closure_eq_nhds, closure_eq_of_is_closed hs], exact id, exact de.inj end⟩, exact (assume x hx, ⟨⟨x, hp x hx⟩, rfl⟩) end /- 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 -/ lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : @uniformity (α×β) _ = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (filter.prod uniformity uniformity) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_comap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap_comp, comap_comap_comp] lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ (@uniformity α _).sets) (hb : b ∈ (@uniformity β _).sets) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _).sets := by rw [uniformity_prod]; exact inter_mem_inf_sets (preimage_mem_comap ha) (preimage_mem_comap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) uniformity uniformity := le_trans (map_mono (@le_sup_left (uniform_space (α×β)) _ _ _)) map_comap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) uniformity uniformity := le_trans (map_mono (@le_sup_right (uniform_space (α×β)) _ _ _)) map_comap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd variables [uniform_space α] [uniform_space β] [uniform_space γ] lemma uniform_continuous.prod_mk {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) : uniform_continuous (λ a, f (a,b)) := uniform_continuous.comp (uniform_continuous.prod_mk uniform_continuous_id uniform_continuous_const) h lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) : uniform_continuous (λ b, f (a,b)) := uniform_continuous.comp (uniform_continuous.prod_mk uniform_continuous_const uniform_continuous_id) h instance complete_space.prod [complete_space α] [complete_space β] : complete_space (α × β) := { complete := λ f hf, let ⟨x1, hx1⟩ := complete_space.complete $ cauchy_map uniform_continuous_fst hf in let ⟨x2, hx2⟩ := complete_space.complete $ cauchy_map uniform_continuous_snd hf in ⟨(x1, x2), by rw [nhds_prod_eq, filter.prod_def]; from filter.le_lift (λ s hs, filter.le_lift' $ λ t ht, have H1 : prod.fst ⁻¹' s ∈ f.sets := hx1 hs, have H2 : prod.snd ⁻¹' t ∈ f.sets := hx2 ht, filter.inter_mem_sets H1 H2)⟩ } lemma uniform_embedding.prod {α' : Type*} {β' : Type*} [uniform_space α] [uniform_space β] [uniform_space α'] [uniform_space β'] {e₁ : α → α'} {e₂ : β → β'} (h₁ : uniform_embedding e₁) (h₂ : uniform_embedding e₂) : uniform_embedding (λp:α×β, (e₁ p.1, e₂ p.2)) := ⟨assume ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, by simp [prod.mk.inj_iff]; exact assume eq₁ eq₂, ⟨h₁.left eq₁, h₂.left eq₂⟩, by simp [(∘), uniformity_prod, h₁.right.symm, h₂.right.symm, comap_inf, comap_comap_comp]⟩ lemma to_topological_space_prod [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl section separation_space local attribute [instance] separation_setoid lemma uniform_continuous_quotient_lift₂ [uniform_space γ] {f : α → β → γ} {h : ∀a c b d, (a, b) ∈ separation_rel α → (c, d) ∈ separation_rel β → f a c = f b d} (hf : uniform_continuous (λp:α×β, f p.1 p.2)) : uniform_continuous (λp:_×_, quotient.lift₂ f h p.1 p.2) := begin rw [uniform_continuous, uniformity_prod_eq_prod, uniformity_quotient, uniformity_quotient, filter.prod_map_map_eq, filter.tendsto_map'_iff, filter.tendsto_map'_iff], rwa [uniform_continuous, uniformity_prod_eq_prod, filter.tendsto_map'_iff] at hf end lemma separation_prod {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) ≈ (a₂, b₂) ↔ a₁ ≈ a₂ ∧ b₁ ≈ b₂ := begin split ; intro h, { exact ⟨separated_of_uniform_continuous uniform_continuous_fst h, separated_of_uniform_continuous uniform_continuous_snd h⟩ }, { rcases h with ⟨eqv_α, eqv_β⟩, intros r r_in, rw uniformity_prod at r_in, rcases r_in with ⟨t_α, ⟨r_α, r_α_in, h_α⟩, t_β, ⟨r_β, r_β_in, h_β⟩, H⟩, let p_α := λ (p : (α × β) × α × β), ((p.fst).fst, (p.snd).fst), let p_β := λ (p : (α × β) × α × β), ((p.fst).snd, (p.snd).snd), have key_α : p_α ((a₁, b₁), (a₂, b₂)) ∈ r_α, by simp[p_α, eqv_α r_α r_α_in], have key_β : p_β ((a₁, b₁), (a₂, b₂)) ∈ r_β, by simp[p_β, eqv_β r_β r_β_in], exact H ⟨h_α key_α, h_β key_β⟩ }, end instance separated.prod [separated α] [separated β] : separated (α × β) := separated_def.2 $ assume x y H, prod.ext (eq_of_separated_of_uniform_continuous uniform_continuous_fst H) (eq_of_separated_of_uniform_continuous uniform_continuous_snd H) end separation_space end constructions lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α} (hs : compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ n ∈ (@uniformity α _).sets, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i := begin let u := λ n, {x | ∃ i (m ∈ (@uniformity α _).sets), {y | (x, y) ∈ comp_rel m n} ⊆ c i}, have hu₁ : ∀ n ∈ (@uniformity α _).sets, is_open (u n), { refine λ n hn, is_open_uniformity.2 _, rintro x ⟨i, m, hm, h⟩, rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩, apply uniformity.sets_of_superset hm', rintros ⟨x, y⟩ hp rfl, refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩, dsimp at hz ⊢, rw comp_rel_assoc, exact ⟨y, hp, hz⟩ }, have hu₂ : s ⊆ ⋃ n ∈ (@uniformity α _).sets, u n, { intros x hx, rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩, rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩, exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ }, rcases compact_elim_finite_subcover_image hs hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩, refine ⟨_, Inter_mem_sets b_fin bu, λ x hx, _⟩, rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩, refine ⟨i, λ y hy, h _⟩, exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy) end lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ n ∈ (@uniformity α _).sets, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma hs (by simpa) hc₂
6460a4d8023b24cb8e53203a11f4422ababb194b
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_rec_eq.lean
35354ceb66d7f14ad0415d52b716441a6dc41a15
[ "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
402
lean
open nat lemma addz [simp] : ∀ a : nat, a + 0 = a := sorry lemma zadd [simp] : ∀ a : nat, 0 + a = a := sorry lemma adds [simp] : ∀ a b : nat, a + succ b = succ (a + b) := sorry lemma sadd [simp] : ∀ a b : nat, succ a + b = succ (a + b) := sorry definition comm : ∀ a b : nat, a + b = b + a | a 0 := by simp | a (succ n) := assert a + n = n + a, from !comm, by simp
dd73aa562d84ac4df669c66b43a6f363f60c054e
2c41ae31b2b771ad5646ad880201393f5269a7f0
/Lean/Qualities/CyberCapable.lean
7add5735fc9e649fb4ae4bd0be7aa5dc847570d6
[]
no_license
kevinsullivan/Boehm
926f25bc6f1a8b6bd47d333d936fdfc278228312
55208395bff20d48a598b7fa33a4d55a2447a9cf
refs/heads/master
1,586,127,134,302
1,488,252,326,000
1,488,252,326,000
32,836,930
0
0
null
null
null
null
UTF-8
Lean
false
false
689
lean
-- Cyber Capable /- [CyberCapable] is parameterized by an instance of type [SystemType], and it's a sub-attribute to [MissionEffective]. An instance of type [SystemType] is deemed [CyberCapable] if and only if all the requirements are satisfied. -/ import SystemModel.System inductive CyberCapable (sys_type: SystemType): Prop | intro : (exists cyberCapable: sys_type ^.Contexts -> sys_type ^.Phases -> sys_type ^.Stakeholders -> @SystemInstance sys_type -> Prop, forall c: sys_type ^.Contexts, forall p: sys_type ^.Phases, forall s: sys_type ^.Stakeholders, forall st: @SystemInstance sys_type, cyberCapable c p s st) -> CyberCapable
d598b82fd8f3a831b598c62f5930047af3fb08a3
618003631150032a5676f229d13a079ac875ff77
/src/ring_theory/polynomial.lean
283d52c3b9ef28c7eba000d6cc10531b01131164
[ "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
18,587
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Ring-theoretic supplement of data.polynomial. Main result: Hilbert basis theorem, that if a ring is noetherian then so is its polynomial ring. -/ import data.mv_polynomial import ring_theory.noetherian noncomputable theory local attribute [instance, priority 100] classical.prop_decidable universes u v w namespace polynomial variables (R : Type u) [comm_ring R] /-- The `R`-submodule of `R[X]` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := ⨅ k : ℕ, ⨅ h : ↑k > n, (lcoeff R k).ker /-- The `R`-submodule of `R[X]` consisting of polynomials of degree < `n`. -/ def degree_lt (n : ℕ) : submodule R (polynomial R) := ⨅ k : ℕ, ⨅ h : k ≥ n, (lcoeff R k).ker variable {R} theorem mem_degree_le {n : with_bot ℕ} {f : polynomial R} : f ∈ degree_le R n ↔ degree f ≤ n := by simp only [degree_le, submodule.mem_infi, degree_le_iff_coeff_zero, linear_map.mem_ker]; refl @[mono] theorem degree_le_mono {m n : with_bot ℕ} (H : m ≤ n) : degree_le R m ≤ degree_le R n := λ f hf, mem_degree_le.2 (le_trans (mem_degree_le.1 hf) H) theorem degree_le_eq_span_X_pow {n : ℕ} : degree_le R n = submodule.span R ↑((finset.range (n+1)).image (λ n, X^n) : finset (polynomial R)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_le.1 hp, rw [← finsupp.sum_single p, finsupp.sum], refine submodule.sum_mem _ (λ k hk, _), show monomial _ _ ∈ _, have := with_bot.coe_le_coe.1 (finset.sup_le_iff.1 hp k hk), rw [single_eq_C_mul_X, C_mul'], refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $ finset.mem_image.2 ⟨_, finset.mem_range.2 (nat.lt_succ_of_le this), rfl⟩) }, rw [submodule.span_le, finset.coe_image, set.image_subset_iff], intros k hk, apply mem_degree_le.2, apply le_trans (degree_X_pow_le _) (with_bot.coe_le_coe.2 $ nat.le_of_lt_succ $ finset.mem_range.1 hk) end theorem mem_degree_lt {n : ℕ} {f : polynomial R} : f ∈ degree_lt R n ↔ degree f < n := by { simp_rw [degree_lt, submodule.mem_infi, linear_map.mem_ker, degree, finset.sup_lt_iff (with_bot.bot_lt_coe n), finsupp.mem_support_iff, with_bot.some_eq_coe, with_bot.coe_lt_coe, lt_iff_not_ge', ne, not_imp_not], refl } @[mono] theorem degree_lt_mono {m n : ℕ} (H : m ≤ n) : degree_lt R m ≤ degree_lt R n := λ f hf, mem_degree_lt.2 (lt_of_lt_of_le (mem_degree_lt.1 hf) $ with_bot.coe_le_coe.2 H) theorem degree_lt_eq_span_X_pow {n : ℕ} : degree_lt R n = submodule.span R ↑((finset.range n).image (λ n, X^n) : finset (polynomial R)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_lt.1 hp, rw [← finsupp.sum_single p, finsupp.sum], refine submodule.sum_mem _ (λ k hk, _), show monomial _ _ ∈ _, have := with_bot.coe_lt_coe.1 ((finset.sup_lt_iff $ with_bot.bot_lt_coe n).1 hp k hk), rw [single_eq_C_mul_X, C_mul'], refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $ finset.mem_image.2 ⟨_, finset.mem_range.2 this, rfl⟩) }, rw [submodule.span_le, finset.coe_image, set.image_subset_iff], intros k hk, apply mem_degree_lt.2, exact lt_of_le_of_lt (degree_X_pow_le _) (with_bot.coe_lt_coe.2 $ finset.mem_range.1 hk) end /-- Given a polynomial, return the polynomial whose coefficients are in the ring closure of the original coefficients. -/ def restriction (p : polynomial R) : polynomial (ring.closure (↑p.frange : set R)) := ⟨p.support, λ i, ⟨p.to_fun i, if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem else ring.subset_closure $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩, λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩ @[simp] theorem coeff_restriction {p : polynomial R} {n : ℕ} : ↑(coeff (restriction p) n) = coeff p n := rfl @[simp] theorem coeff_restriction' {p : polynomial R} {n : ℕ} : (coeff (restriction p) n).1 = coeff p n := rfl @[simp] theorem degree_restriction {p : polynomial R} : (restriction p).degree = p.degree := rfl @[simp] theorem nat_degree_restriction {p : polynomial R} : (restriction p).nat_degree = p.nat_degree := rfl @[simp] theorem monic_restriction {p : polynomial R} : monic (restriction p) ↔ monic p := ⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩ @[simp] theorem restriction_zero : restriction (0 : polynomial R) = 0 := rfl @[simp] theorem restriction_one : restriction (1 : polynomial R) = 1 := ext $ λ i, subtype.eq $ by rw [coeff_restriction', coeff_one, coeff_one]; split_ifs; refl variables {S : Type v} [comm_ring S] {f : R → S} {x : S} theorem eval₂_restriction {p : polynomial R} : eval₂ f x p = eval₂ (f ∘ subtype.val) x p.restriction := rfl section to_subring variables (p : polynomial R) (T : set R) [is_subring T] /-- Given a polynomial `p` and a subring `T` that contains the coefficients of `p`, return the corresponding polynomial whose coefficients are in `T. -/ def to_subring (hp : ↑p.frange ⊆ T) : polynomial T := ⟨p.support, λ i, ⟨p.to_fun i, if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem else hp $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩, λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩ variables (hp : ↑p.frange ⊆ T) include hp @[simp] theorem coeff_to_subring {n : ℕ} : ↑(coeff (to_subring p T hp) n) = coeff p n := rfl @[simp] theorem coeff_to_subring' {n : ℕ} : (coeff (to_subring p T hp) n).1 = coeff p n := rfl @[simp] theorem degree_to_subring : (to_subring p T hp).degree = p.degree := rfl @[simp] theorem nat_degree_to_subring : (to_subring p T hp).nat_degree = p.nat_degree := rfl @[simp] theorem monic_to_subring : monic (to_subring p T hp) ↔ monic p := ⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩ omit hp @[simp] theorem to_subring_zero : to_subring (0 : polynomial R) T (set.empty_subset _) = 0 := rfl @[simp] theorem to_subring_one : to_subring (1 : polynomial R) T (set.subset.trans (finset.coe_subset.2 finsupp.frange_single) (finset.singleton_subset_set_iff.2 is_submonoid.one_mem)) = 1 := ext $ λ i, subtype.eq $ by rw [coeff_to_subring', coeff_one, coeff_one]; split_ifs; refl end to_subring variables (T : set R) [is_subring T] /-- Given a polynomial whose coefficients are in some subring, return the corresponding polynomial whose coefificents are in the ambient ring. -/ def of_subring (p : polynomial T) : polynomial R := ⟨p.support, subtype.val ∘ p.to_fun, λ n, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ h, congr_arg subtype.val h, λ h, subtype.eq h⟩)⟩ @[simp] theorem frange_of_subring {p : polynomial T} : ↑(p.of_subring T).frange ⊆ T := λ y H, let ⟨hy, x, hx⟩ := finsupp.mem_frange.1 H in hx ▸ (p.to_fun x).2 end polynomial variables {R : Type u} {σ : Type v} [comm_ring R] namespace ideal open polynomial /-- Transport an ideal of `R[X]` to an `R`-submodule of `R[X]`. -/ def of_polynomial (I : ideal (polynomial R)) : submodule R (polynomial R) := { carrier := I.carrier, zero := I.zero_mem, add := λ _ _, I.add_mem, smul := λ c x H, by rw [← C_mul']; exact submodule.smul_mem _ _ H } variables {I : ideal (polynomial R)} theorem mem_of_polynomial (x) : x ∈ I.of_polynomial ↔ x ∈ I := iff.rfl variables (I) /-- Given an ideal `I` of `R[X]`, make the `R`-submodule of `I` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := degree_le R n ⊓ I.of_polynomial /-- Given an ideal `I` of `R[X]`, make the ideal in `R` of leading coefficients of polynomials in `I` with degree ≤ `n`. -/ def leading_coeff_nth (n : ℕ) : ideal R := (I.degree_le n).map $ lcoeff R n theorem mem_leading_coeff_nth (n : ℕ) (x) : x ∈ I.leading_coeff_nth n ↔ ∃ p ∈ I, degree p ≤ n ∧ leading_coeff p = x := begin simp only [leading_coeff_nth, degree_le, submodule.mem_map, lcoeff_apply, submodule.mem_inf, mem_degree_le], split, { rintro ⟨p, ⟨hpdeg, hpI⟩, rfl⟩, cases lt_or_eq_of_le hpdeg with hpdeg hpdeg, { refine ⟨0, I.zero_mem, bot_le, _⟩, rw [leading_coeff_zero, eq_comm], exact coeff_eq_zero_of_degree_lt hpdeg }, { refine ⟨p, hpI, le_of_eq hpdeg, _⟩, rw [leading_coeff, nat_degree, hpdeg], refl } }, { rintro ⟨p, hpI, hpdeg, rfl⟩, have : nat_degree p + (n - nat_degree p) = n, { exact nat.add_sub_cancel' (nat_degree_le_of_degree_le hpdeg) }, refine ⟨p * X ^ (n - nat_degree p), ⟨_, I.mul_mem_right hpI⟩, _⟩, { apply le_trans (degree_mul_le _ _) _, apply le_trans (add_le_add' (degree_le_nat_degree) (degree_X_pow_le _)) _, rw [← with_bot.coe_add, this], exact le_refl _ }, { rw [leading_coeff, ← coeff_mul_X_pow p (n - nat_degree p), this] } } end theorem mem_leading_coeff_nth_zero (x) : x ∈ I.leading_coeff_nth 0 ↔ C x ∈ I := (mem_leading_coeff_nth _ _ _).trans ⟨λ ⟨p, hpI, hpdeg, hpx⟩, by rwa [← hpx, leading_coeff, nat.eq_zero_of_le_zero (nat_degree_le_of_degree_le hpdeg), ← eq_C_of_degree_le_zero hpdeg], λ hx, ⟨C x, hx, degree_C_le, leading_coeff_C x⟩⟩ theorem leading_coeff_nth_mono {m n : ℕ} (H : m ≤ n) : I.leading_coeff_nth m ≤ I.leading_coeff_nth n := begin intros r hr, simp only [submodule.mem_coe, mem_leading_coeff_nth] at hr ⊢, rcases hr with ⟨p, hpI, hpdeg, rfl⟩, refine ⟨p * X ^ (n - m), I.mul_mem_right hpI, _, leading_coeff_mul_X_pow⟩, refine le_trans (degree_mul_le _ _) _, refine le_trans (add_le_add' hpdeg (degree_X_pow_le _)) _, rw [← with_bot.coe_add, nat.add_sub_cancel' H], exact le_refl _ end /-- Given an ideal `I` in `R[X]`, make the ideal in `R` of the leading coefficients in `I`. -/ def leading_coeff : ideal R := ⨆ n : ℕ, I.leading_coeff_nth n theorem mem_leading_coeff (x) : x ∈ I.leading_coeff ↔ ∃ p ∈ I, polynomial.leading_coeff p = x := begin rw [leading_coeff, submodule.mem_supr_of_directed], simp only [mem_leading_coeff_nth], { split, { rintro ⟨i, p, hpI, hpdeg, rfl⟩, exact ⟨p, hpI, rfl⟩ }, rintro ⟨p, hpI, rfl⟩, exact ⟨nat_degree p, p, hpI, degree_le_nat_degree, rfl⟩ }, intros i j, exact ⟨i + j, I.leading_coeff_nth_mono (nat.le_add_right _ _), I.leading_coeff_nth_mono (nat.le_add_left _ _)⟩ end theorem is_fg_degree_le [is_noetherian_ring R] (n : ℕ) : submodule.fg (I.degree_le n) := is_noetherian_submodule_left.1 (is_noetherian_of_fg_of_noetherian _ ⟨_, degree_le_eq_span_X_pow.symm⟩) _ end ideal /-- Hilbert basis theorem: a polynomial ring over a noetherian ring is a noetherian ring. -/ protected theorem polynomial.is_noetherian_ring [is_noetherian_ring R] : is_noetherian_ring (polynomial R) := ⟨assume I : ideal (polynomial R), let L := I.leading_coeff in let M := well_founded.min (is_noetherian_iff_well_founded.1 (by apply_instance)) (set.range I.leading_coeff_nth) ⟨_, ⟨0, rfl⟩⟩ in have hm : M ∈ set.range I.leading_coeff_nth := well_founded.min_mem _ _ _, let ⟨N, HN⟩ := hm, ⟨s, hs⟩ := I.is_fg_degree_le N in have hm2 : ∀ k, I.leading_coeff_nth k ≤ M := λ k, or.cases_on (le_or_lt k N) (λ h, HN ▸ I.leading_coeff_nth_mono h) (λ h x hx, classical.by_contradiction $ λ hxm, have ¬M < I.leading_coeff_nth k, by refine well_founded.not_lt_min (well_founded_submodule_gt _ _) _ _ _; exact ⟨k, rfl⟩, this ⟨HN ▸ I.leading_coeff_nth_mono (le_of_lt h), λ H, hxm (H hx)⟩), have hs2 : ∀ {x}, x ∈ I.degree_le N → x ∈ ideal.span (↑s : set (polynomial R)), from hs ▸ λ x hx, submodule.span_induction hx (λ _ hx, ideal.subset_span hx) (ideal.zero_mem _) (λ _ _, ideal.add_mem _) (λ c f hf, f.C_mul' c ▸ ideal.mul_mem_left _ hf), ⟨s, le_antisymm (ideal.span_le.2 $ λ x hx, have x ∈ I.degree_le N, from hs ▸ submodule.subset_span hx, this.2) $ begin change I ≤ ideal.span ↑s, intros p hp, generalize hn : p.nat_degree = k, induction k using nat.strong_induction_on with k ih generalizing p, cases le_or_lt k N, { subst k, refine hs2 ⟨polynomial.mem_degree_le.2 (le_trans polynomial.degree_le_nat_degree $ with_bot.coe_le_coe.2 h), hp⟩ }, { have hp0 : p ≠ 0, { rintro rfl, cases hn, exact nat.not_lt_zero _ h }, have : (0 : R) ≠ 1, { intro h, apply hp0, ext i, refine (mul_one _).symm.trans _, rw [← h, mul_zero], refl }, haveI : nonzero R := ⟨this⟩, have : p.leading_coeff ∈ I.leading_coeff_nth N, { rw HN, exact hm2 k ((I.mem_leading_coeff_nth _ _).2 ⟨_, hp, hn ▸ polynomial.degree_le_nat_degree, rfl⟩) }, rw I.mem_leading_coeff_nth at this, rcases this with ⟨q, hq, hdq, hlqp⟩, have hq0 : q ≠ 0, { intro H, rw [← polynomial.leading_coeff_eq_zero] at H, rw [hlqp, polynomial.leading_coeff_eq_zero] at H, exact hp0 H }, have h1 : p.degree = (q * polynomial.X ^ (k - q.nat_degree)).degree, { rw [polynomial.degree_mul_eq', polynomial.degree_X_pow], rw [polynomial.degree_eq_nat_degree hp0, polynomial.degree_eq_nat_degree hq0], rw [← with_bot.coe_add, nat.add_sub_cancel', hn], { refine le_trans (polynomial.nat_degree_le_of_degree_le hdq) (le_of_lt h) }, rw [polynomial.leading_coeff_X_pow, mul_one], exact mt polynomial.leading_coeff_eq_zero.1 hq0 }, have h2 : p.leading_coeff = (q * polynomial.X ^ (k - q.nat_degree)).leading_coeff, { rw [← hlqp, polynomial.leading_coeff_mul_X_pow] }, have := polynomial.degree_sub_lt h1 hp0 h2, rw [polynomial.degree_eq_nat_degree hp0] at this, rw ← sub_add_cancel p (q * polynomial.X ^ (k - q.nat_degree)), refine (ideal.span ↑s).add_mem _ ((ideal.span ↑s).mul_mem_right _), { by_cases hpq : p - q * polynomial.X ^ (k - q.nat_degree) = 0, { rw hpq, exact ideal.zero_mem _ }, refine ih _ _ (I.sub_mem hp (I.mul_mem_right hq)) rfl, rwa [polynomial.degree_eq_nat_degree hpq, with_bot.coe_lt_coe, hn] at this }, exact hs2 ⟨polynomial.mem_degree_le.2 hdq, hq⟩ } end⟩⟩ attribute [instance] polynomial.is_noetherian_ring namespace mv_polynomial lemma is_noetherian_ring_fin_0 [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial (fin 0) R) := is_noetherian_ring_of_ring_equiv R ((mv_polynomial.pempty_ring_equiv R).symm.trans (mv_polynomial.ring_equiv_of_equiv _ fin_zero_equiv'.symm)) theorem is_noetherian_ring_fin [is_noetherian_ring R] : ∀ {n : ℕ}, is_noetherian_ring (mv_polynomial (fin n) R) | 0 := is_noetherian_ring_fin_0 | (n+1) := @is_noetherian_ring_of_ring_equiv (polynomial (mv_polynomial (fin n) R)) _ _ _ (mv_polynomial.fin_succ_equiv _ n).symm (@polynomial.is_noetherian_ring (mv_polynomial (fin n) R) _ (is_noetherian_ring_fin)) /-- The multivariate polynomial ring in finitely many variables over a noetherian ring is itself a noetherian ring. -/ instance is_noetherian_ring [fintype σ] [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial σ R) := trunc.induction_on (fintype.equiv_fin σ) $ λ e, @is_noetherian_ring_of_ring_equiv (mv_polynomial (fin (fintype.card σ)) R) _ _ _ (mv_polynomial.ring_equiv_of_equiv _ e.symm) is_noetherian_ring_fin lemma is_integral_domain_fin_zero (R : Type u) [comm_ring R] (hR : is_integral_domain R) : is_integral_domain (mv_polynomial (fin 0) R) := ring_equiv.is_integral_domain R hR ((ring_equiv_of_equiv R fin_zero_equiv').trans (mv_polynomial.pempty_ring_equiv R)) /-- Auxilliary lemma: Multivariate polynomials over an integral domain with variables indexed by `fin n` form an integral domain. This fact is proven inductively, and then used to prove the general case without any finiteness hypotheses. See `mv_polynomial.integral_domain` for the general case. -/ lemma is_integral_domain_fin (R : Type u) [comm_ring R] (hR : is_integral_domain R) : ∀ (n : ℕ), is_integral_domain (mv_polynomial (fin n) R) | 0 := is_integral_domain_fin_zero R hR | (n+1) := ring_equiv.is_integral_domain (polynomial (mv_polynomial (fin n) R)) (is_integral_domain_fin n).polynomial (mv_polynomial.fin_succ_equiv _ n) lemma is_integral_domain_fintype (R : Type u) (σ : Type v) [comm_ring R] [fintype σ] (hR : is_integral_domain R) : is_integral_domain (mv_polynomial σ R) := trunc.induction_on (fintype.equiv_fin σ) $ λ e, @ring_equiv.is_integral_domain _ (mv_polynomial (fin $ fintype.card σ) R) _ _ (mv_polynomial.is_integral_domain_fin _ hR _) (ring_equiv_of_equiv R e) /-- Auxilliary definition: Multivariate polynomials in finitely many variables over an integral domain form an integral domain. This fact is proven by transport of structure from the `mv_polynomial.integral_domain_fin`, and then used to prove the general case without finiteness hypotheses. See `mv_polynomial.integral_domain` for the general case. -/ def integral_domain_fintype (R : Type u) (σ : Type v) [integral_domain R] [fintype σ] : integral_domain (mv_polynomial σ R) := @is_integral_domain.to_integral_domain _ _ $ mv_polynomial.is_integral_domain_fintype R σ $ integral_domain.to_is_integral_domain R protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {R : Type u} [integral_domain R] {σ : Type v} (p q : mv_polynomial σ R) (h : p * q = 0) : p = 0 ∨ q = 0 := begin obtain ⟨s, p, rfl⟩ := exists_finset_rename p, obtain ⟨t, q, rfl⟩ := exists_finset_rename q, have : p.rename (subtype.map id (finset.subset_union_left s t) : {x // x ∈ s} → {x // x ∈ s ∪ t}) * q.rename (subtype.map id (finset.subset_union_right s t)) = 0, { apply injective_rename _ subtype.val_injective, simpa using h }, letI := mv_polynomial.integral_domain_fintype R {x // x ∈ (s ∪ t)}, rw mul_eq_zero at this, cases this; [left, right], all_goals { simpa using congr_arg (rename subtype.val) this } end /-- The multivariate polynomial ring over an integral domain is an integral domain. -/ instance {R : Type u} {σ : Type v} [integral_domain R] : integral_domain (mv_polynomial σ R) := { eq_zero_or_eq_zero_of_mul_eq_zero := mv_polynomial.eq_zero_or_eq_zero_of_mul_eq_zero, zero_ne_one := begin intro H, have : eval₂ id (λ s, (0:R)) (0 : mv_polynomial σ R) = eval₂ id (λ s, (0:R)) (1 : mv_polynomial σ R), { congr, exact H }, simpa, end, .. (by apply_instance : comm_ring (mv_polynomial σ R)) } end mv_polynomial
713d51a190af02c8f306fcbefadc8c97c9921a81
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/slow/list_elab2.lean
cfd3d20ab185de003c255a81cdd12a7e94de7afb
[ "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
6,590
lean
---------------------------------------------------------------------------------------------------- --- Copyright (c) 2014 Parikshit Khanna. All rights reserved. --- Released under Apache 2.0 license as described in the file LICENSE. --- Authors: Parikshit Khanna, Jeremy Avigad ---------------------------------------------------------------------------------------------------- -- Theory list -- =========== -- -- Basic properties of lists. import logic data.nat -- import congr open nat algebra -- open congr open eq.ops eq inductive list (T : Type) : Type := | nil {} : list T | cons : T → list T → list T definition refl := @eq.refl namespace list -- Type -- ---- infixr `::` := cons section variable {T : Type} theorem list_induction_on {P : list T → Prop} (l : list T) (Hnil : P nil) (Hind : forall x : T, forall l : list T, forall H : P l, P (cons x l)) : P l := list.rec Hnil Hind l theorem list_cases_on {P : list T → Prop} (l : list T) (Hnil : P nil) (Hcons : forall x : T, forall l : list T, P (cons x l)) : P l := list_induction_on l Hnil (take x l IH, Hcons x l) notation `[` l:(foldr `,` (h t, cons h t) nil) `]` := l -- Concat -- ------ definition concat (s t : list T) : list T := list.rec t (fun x : T, fun l : list T, fun u : list T, cons x u) s infixl `++` := concat theorem nil_concat (t : list T) : nil ++ t = t := refl _ theorem cons_concat (x : T) (s t : list T) : (x :: s) ++ t = x :: (s ++ t) := refl _ theorem concat_nil (t : list T) : t ++ nil = t := list_induction_on t (refl _) (take (x : T) (l : list T) (H : concat l nil = l), H ▸ (refl (cons x (concat l nil)))) attribute concat [reducible] theorem concat_nil2 (t : list T) : t ++ nil = t := list_induction_on t (refl _) (take (x : T) (l : list T) (H : concat l nil = l), -- H ▸ (refl (cons x (concat l nil)))) H ▸ (refl (concat (cons x l) nil))) theorem concat_assoc (s t u : list T) : s ++ t ++ u = s ++ (t ++ u) := list_induction_on s (refl _) (take x l, assume H : concat (concat l t) u = concat l (concat t u), H ▸ refl _) theorem concat_assoc2 (s t u : list T) : s ++ t ++ u = s ++ (t ++ u) := list_induction_on s (refl _) (take x l, assume H : concat (concat l t) u = concat l (concat t u), calc concat (concat (cons x l) t) u = cons x (concat (concat l t) u) : refl _ ... = concat (cons x l) (concat t u) : { H }) theorem concat_assoc3 (s t u : list T) : s ++ t ++ u = s ++ (t ++ u) := list_induction_on s (refl _) (take x l, assume H : concat (concat l t) u = concat l (concat t u), calc concat (concat (cons x l) t) u = cons x (concat l (concat t u)) : { H } ... = concat (cons x l) (concat t u) : refl _) theorem concat_assoc4 (s t u : list T) : s ++ t ++ u = s ++ (t ++ u) := list_induction_on s (refl _) (take x l, assume H : concat (concat l t) u = concat l (concat t u), calc concat (concat (cons x l) t) u = cons x (concat (concat l t) u) : refl _ ... = cons x (concat l (concat t u)) : { H } ... = concat (cons x l) (concat t u) : refl _) -- Length -- ------ definition length : list T → ℕ := list.rec 0 (fun x l m, succ m) -- TODO: cannot replace zero by 0 theorem length_nil : length (@nil T) = zero := refl _ theorem length_cons (x : T) (t : list T) : length (x :: t) = succ (length t) := refl _ theorem length_concat (s t : list T) : length (s ++ t) = length s + length t := list_induction_on s (calc length (concat nil t) = length t : refl _ ... = 0 + length t : {symm !zero_add} ... = length (@nil T) + length t : refl _) (take x s, assume H : length (concat s t) = length s + length t, calc length (concat (cons x s) t ) = succ (length (concat s t)) : refl _ ... = succ (length s + length t) : { H } ... = succ (length s) + length t : {symm !succ_add} ... = length (cons x s) + length t : refl _) -- Reverse -- ------- definition reverse : list T → list T := list.rec nil (fun x l r, r ++ [x]) theorem reverse_nil : reverse (@nil T) = nil := refl _ theorem reverse_cons (x : T) (l : list T) : reverse (x :: l) = (reverse l) ++ (cons x nil) := refl _ -- opaque_hint (hiding reverse) theorem reverse_concat (s t : list T) : reverse (s ++ t) = (reverse t) ++ (reverse s) := list_induction_on s (calc reverse (concat nil t) = reverse t : { nil_concat _ } ... = concat (reverse t) nil : symm (concat_nil _) ... = concat (reverse t) (reverse nil) : {symm (reverse_nil)}) (take x l, assume H : reverse (concat l t) = concat (reverse t) (reverse l), calc reverse (concat (cons x l) t) = concat (reverse (concat l t)) (cons x nil) : refl _ ... = concat (concat (reverse t) (reverse l)) (cons x nil) : { H } ... = concat (reverse t) (concat (reverse l) (cons x nil)) : concat_assoc _ _ _ ... = concat (reverse t) (reverse (cons x l)) : refl _) -- -- add_rewrite length_nil length_cons theorem reverse_reverse (l : list T) : reverse (reverse l) = l := list_induction_on l (refl _) (take x l', assume H: reverse (reverse l') = l', show reverse (reverse (cons x l')) = cons x l', from calc reverse (reverse (cons x l')) = concat (reverse (cons x nil)) (reverse (reverse l')) : {reverse_concat _ _} ... = cons x l' : {H}) -- Append -- ------ -- TODO: define reverse from append definition append (x : T) : list T → list T := list.rec (x :: nil) (fun y l l', y :: l') theorem append_nil (x : T) : append x nil = [x] := refl _ theorem append_cons (x : T) (y : T) (l : list T) : append x (y :: l) = y :: (append x l) := refl _ theorem append_eq_concat (x : T) (l : list T) : append x l = l ++ [x] := list_induction_on l (refl _) (take y l, assume P : append x l = concat l [x], P ▸ refl _) theorem append_eq_reverse_cons (x : T) (l : list T) : append x l = reverse (x :: reverse l) := list_induction_on l (calc append x nil = [x] : (refl _) ... = concat nil [x] : {symm (nil_concat _)} ... = concat (reverse nil) [x] : {symm (reverse_nil)} ... = reverse [x] : {symm (reverse_cons _ _)} ... = reverse (x :: (reverse nil)) : {symm (reverse_nil)}) (take y l', assume H : append x l' = reverse (x :: reverse l'), calc append x (y :: l') = (y :: l') ++ [ x ] : append_eq_concat _ _ ... = concat (reverse (reverse (y :: l'))) [ x ] : {symm (reverse_reverse _)} ... = reverse (x :: (reverse (y :: l'))) : refl _) end end list
309e2f0616ac14684155a07f1b0eb171e998a8ec
618003631150032a5676f229d13a079ac875ff77
/src/algebra/category/Group/images.lean
32c082b6430a4dfce7ecb433fc1111e355e6df30
[ "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
2,647
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Group /-! # The category of commutative additive groups has images. -/ open category_theory open category_theory.limits universe u namespace AddCommGroup variables {G H : AddCommGroup.{0}} (f : G ⟶ H) local attribute [ext] subtype.eq' section -- implementation details of `has_image` for AddCommGroup; use the API, not these /-- the image of a morphism in AddCommGroup is just the bundling of `set.range f` -/ def image : AddCommGroup := AddCommGroup.of (set.range f) /-- the inclusion of `image f` into the target -/ def image.ι : image f ⟶ H := f.range_subtype_val instance : mono (image.ι f) := concrete_category.mono_of_injective (image.ι f) subtype.val_injective /-- the corestriction map to the image -/ def factor_thru_image : G ⟶ image f := add_monoid_hom.range_factorization f lemma image.fac : factor_thru_image f ≫ image.ι f = f := by { ext, refl, } local attribute [simp] image.fac variables {f} /-- the universal property for the image factorisation -/ noncomputable def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I := { to_fun := (λ x, F'.e (classical.indefinite_description _ x.2).1 : image f → F'.I), map_zero' := begin haveI := F'.m_mono, apply injective_of_mono F'.m, change (F'.e ≫ F'.m) _ = _, rw [F'.fac, add_monoid_hom.map_zero], convert (classical.indefinite_description (λ y, f y = 0) _).2, end, map_add' := begin intros x y, haveI := F'.m_mono, apply injective_of_mono F'.m, rw [add_monoid_hom.map_add], change (F'.e ≫ F'.m) _ = (F'.e ≫ F'.m) _ + (F'.e ≫ F'.m) _, rw [F'.fac], rw (classical.indefinite_description (λ z, f z = _) _).2, rw (classical.indefinite_description (λ z, f z = _) _).2, rw (classical.indefinite_description (λ z, f z = _) _).2, refl, end, } lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ι f := begin ext x, change (F'.e ≫ F'.m) _ = _, rw [F'.fac, (classical.indefinite_description _ x.2).2], refl, end end /-- the factorisation of any morphism in AddCommGroup through a mono. -/ def mono_factorisation : mono_factorisation f := { I := image f, m := image.ι f, e := factor_thru_image f } noncomputable instance : has_image f := { F := mono_factorisation f, is_image := { lift := image.lift, lift_fac' := image.lift_fac } } noncomputable instance : has_images.{0} AddCommGroup.{0} := { has_image := infer_instance } end AddCommGroup
a26c04e96c8da586cf995e0b99bc0f63d4f471ff
7b681d6cc18477cf6b60470d9782923d3ea63915
/W3-proof.lean
dd3d7c01cc945d670e640bd7b7dc447b3990d73a
[]
no_license
osoulim/LEAN
a7458f597abbe5c36ebbb3f36eab29a4c60f5140
5e0dc240e86e392fdab4b2ffdcc3174c0cce7b66
refs/heads/master
1,591,850,481,195
1,561,547,647,000
1,561,547,647,000
193,852,039
0
0
null
null
null
null
UTF-8
Lean
false
false
313
lean
-- ∀x A(x) -> (∀x B(x) -> ∀y(A(y) ∧ B(y))) variable U: Type variables A B: U -> Prop example : (∀ x, A x) -> (∀ x, B x) -> (∀ x, A x ∧ B x) := assume hA: ∀ x, A x, assume hB: ∀ x, B x, assume y, have pAy: A y, from hA y, have pBy: B y, from hB y, show A y ∧ B y, from and.intro pAy pBy
de25a6bf5475c2e818f4a2f127edea9383877a08
1b8f093752ba748c5ca0083afef2959aaa7dace5
/src/category_theory/examples/TopRing.lean
62d1b93018e45270cbf9d95f739884a188ebfcc5
[]
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
927
lean
import category_theory.category import analysis.topology.topological_structures universes u open category_theory namespace category_theory.examples structure TopRing := {β : Type u} [Ring : comm_ring β] [Top : topological_space β] [TopRing : topological_ring β] instance TopRing_comm_ring (R : TopRing) : comm_ring R.β := R.Ring instance TopRing_topological_space (R : TopRing) : topological_space R.β := R.Top instance TopRing_topological_ring (R : TopRing) : topological_ring R.β := R.TopRing instance : category TopRing := { hom := λ R S, {f : R.β → S.β // is_ring_hom f ∧ continuous f }, id := λ R, ⟨id, by obviously⟩, comp := λ R S T f g, ⟨g.val ∘ f.val, begin -- TODO automate cases f, cases g, cases f_property, cases g_property, split, dsimp, resetI, apply_instance, dsimp, apply continuous.comp ; assumption end⟩ } end category_theory.examples
1d9c443a67a07a614414da22ba271dc6b6adb502
ecea1a568b8a7bdfef1206845f7dc2e62b85b6b3
/tests/lean/run/check_constants.lean
d437e202ccddd256aa568c47445e7cf3c19e8728
[ "Apache-2.0" ]
permissive
ndcroos/lean
b1b6de42ee4d3ded05829373e505e09614d4acdf
6919d231413705c892eec02bdacd7d7d916524c8
refs/heads/master
1,625,911,732,192
1,507,549,407,000
1,507,549,407,000
106,106,359
0
0
null
1,507,388,410,000
1,507,388,410,000
null
UTF-8
Lean
false
false
15,025
lean
-- DO NOT EDIT, automatically generated file, generator scripts/gen_constants_cpp.py import smt system.io open tactic meta def script_check_id (n : name) : tactic unit := do env ← get_env, (env^.get n >> return ()) <|> (guard $ env^.is_namespace n) <|> (attribute.get_instances n >> return ()) <|> fail ("identifier '" ++ to_string n ++ "' is not a constant, namespace nor attribute") run_cmd script_check_id `abs run_cmd script_check_id `absurd run_cmd script_check_id `acc.cases_on run_cmd script_check_id `acc.rec run_cmd script_check_id `add_comm_group run_cmd script_check_id `add_comm_semigroup run_cmd script_check_id `add_group run_cmd script_check_id `add_monoid run_cmd script_check_id `and run_cmd script_check_id `and.elim_left run_cmd script_check_id `and.elim_right run_cmd script_check_id `and.intro run_cmd script_check_id `and.rec run_cmd script_check_id `and.cases_on run_cmd script_check_id `auto_param run_cmd script_check_id `bit0 run_cmd script_check_id `bit1 run_cmd script_check_id `bin_tree.empty run_cmd script_check_id `bin_tree.leaf run_cmd script_check_id `bin_tree.node run_cmd script_check_id `bool run_cmd script_check_id `bool.ff run_cmd script_check_id `bool.tt run_cmd script_check_id `combinator.K run_cmd script_check_id `cast run_cmd script_check_id `cast_heq run_cmd script_check_id `char run_cmd script_check_id `char.of_nat run_cmd script_check_id `char.of_nat_ne_of_ne run_cmd script_check_id `classical.prop_decidable run_cmd script_check_id `classical.type_decidable_eq run_cmd script_check_id `coe run_cmd script_check_id `coe_fn run_cmd script_check_id `coe_sort run_cmd script_check_id `coe_to_lift run_cmd script_check_id `congr run_cmd script_check_id `congr_arg run_cmd script_check_id `congr_fun run_cmd script_check_id `decidable run_cmd script_check_id `decidable.to_bool run_cmd script_check_id `distrib run_cmd script_check_id `dite run_cmd script_check_id `id run_cmd script_check_id `empty run_cmd script_check_id `Exists run_cmd script_check_id `eq run_cmd script_check_id `eq.cases_on run_cmd script_check_id `eq.drec run_cmd script_check_id `eq.mp run_cmd script_check_id `eq.mpr run_cmd script_check_id `eq.rec run_cmd script_check_id `eq.refl run_cmd script_check_id `eq.subst run_cmd script_check_id `eq.symm run_cmd script_check_id `eq.trans run_cmd script_check_id `eq_of_heq run_cmd script_check_id `eq_rec_heq run_cmd script_check_id `eq_true_intro run_cmd script_check_id `eq_false_intro run_cmd script_check_id `eq_self_iff_true run_cmd script_check_id `expr run_cmd script_check_id `expr.subst run_cmd script_check_id `format run_cmd script_check_id `false run_cmd script_check_id `false_of_true_iff_false run_cmd script_check_id `false_of_true_eq_false run_cmd script_check_id `true_eq_false_of_false run_cmd script_check_id `false.rec run_cmd script_check_id `field run_cmd script_check_id `fin.mk run_cmd script_check_id `fin.ne_of_vne run_cmd script_check_id `forall_congr run_cmd script_check_id `forall_congr_eq run_cmd script_check_id `forall_not_of_not_exists run_cmd script_check_id `funext run_cmd script_check_id `ge run_cmd script_check_id `gt run_cmd script_check_id `has_add run_cmd script_check_id `has_add.add run_cmd script_check_id `andthen run_cmd script_check_id `has_bind.and_then run_cmd script_check_id `has_bind.bind run_cmd script_check_id `has_bind.seq run_cmd script_check_id `has_div run_cmd script_check_id `has_div.div run_cmd script_check_id `has_emptyc.emptyc run_cmd script_check_id `has_mod.mod run_cmd script_check_id `has_mul run_cmd script_check_id `has_mul.mul run_cmd script_check_id `has_insert.insert run_cmd script_check_id `has_inv run_cmd script_check_id `has_inv.inv run_cmd script_check_id `has_le run_cmd script_check_id `has_le.le run_cmd script_check_id `has_lt run_cmd script_check_id `has_lt.lt run_cmd script_check_id `has_neg run_cmd script_check_id `has_neg.neg run_cmd script_check_id `has_one run_cmd script_check_id `has_one.one run_cmd script_check_id `has_orelse.orelse run_cmd script_check_id `has_sep.sep run_cmd script_check_id `has_sizeof run_cmd script_check_id `has_sizeof.mk run_cmd script_check_id `has_sub run_cmd script_check_id `has_sub.sub run_cmd script_check_id `has_to_format run_cmd script_check_id `has_repr run_cmd script_check_id `has_well_founded run_cmd script_check_id `has_well_founded.r run_cmd script_check_id `has_well_founded.wf run_cmd script_check_id `has_zero run_cmd script_check_id `has_zero.zero run_cmd script_check_id `has_coe_t run_cmd script_check_id `heq run_cmd script_check_id `heq.refl run_cmd script_check_id `heq.symm run_cmd script_check_id `heq.trans run_cmd script_check_id `heq_of_eq run_cmd script_check_id `hole_command run_cmd script_check_id `id_locked run_cmd script_check_id `id_rhs run_cmd script_check_id `if_neg run_cmd script_check_id `if_pos run_cmd script_check_id `iff run_cmd script_check_id `iff_false_intro run_cmd script_check_id `iff.intro run_cmd script_check_id `iff.mp run_cmd script_check_id `iff.mpr run_cmd script_check_id `iff.refl run_cmd script_check_id `iff.symm run_cmd script_check_id `iff.trans run_cmd script_check_id `iff_true_intro run_cmd script_check_id `imp_congr run_cmd script_check_id `imp_congr_eq run_cmd script_check_id `imp_congr_ctx run_cmd script_check_id `imp_congr_ctx_eq run_cmd script_check_id `implies run_cmd script_check_id `implies_of_if_neg run_cmd script_check_id `implies_of_if_pos run_cmd script_check_id `int run_cmd script_check_id `int.has_add run_cmd script_check_id `int.has_mul run_cmd script_check_id `int.has_sub run_cmd script_check_id `int.has_div run_cmd script_check_id `int.has_le run_cmd script_check_id `int.has_lt run_cmd script_check_id `int.has_neg run_cmd script_check_id `int.has_mod run_cmd script_check_id `int.bit0_nonneg run_cmd script_check_id `int.bit1_nonneg run_cmd script_check_id `int.one_nonneg run_cmd script_check_id `int.zero_nonneg run_cmd script_check_id `int.bit0_pos run_cmd script_check_id `int.bit1_pos run_cmd script_check_id `int.one_pos run_cmd script_check_id `int.nat_abs_zero run_cmd script_check_id `int.nat_abs_one run_cmd script_check_id `int.nat_abs_bit0_step run_cmd script_check_id `int.nat_abs_bit1_nonneg_step run_cmd script_check_id `int.ne_of_nat_ne_nonneg_case run_cmd script_check_id `int.ne_neg_of_ne run_cmd script_check_id `int.neg_ne_of_pos run_cmd script_check_id `int.ne_neg_of_pos run_cmd script_check_id `int.neg_ne_zero_of_ne run_cmd script_check_id `int.zero_ne_neg_of_ne run_cmd script_check_id `int.decidable_linear_ordered_comm_group run_cmd script_check_id `interactive.param_desc run_cmd script_check_id `interactive.parse run_cmd script_check_id `io run_cmd script_check_id `io.interface run_cmd script_check_id `is_associative run_cmd script_check_id `is_associative.assoc run_cmd script_check_id `is_commutative run_cmd script_check_id `is_commutative.comm run_cmd script_check_id `ite run_cmd script_check_id `lean.parser run_cmd script_check_id `lean.parser.pexpr run_cmd script_check_id `lean.parser.tk run_cmd script_check_id `left_distrib run_cmd script_check_id `left_comm run_cmd script_check_id `le_refl run_cmd script_check_id `linear_ordered_ring run_cmd script_check_id `linear_ordered_semiring run_cmd script_check_id `list run_cmd script_check_id `list.nil run_cmd script_check_id `list.cons run_cmd script_check_id `match_failed run_cmd script_check_id `monad run_cmd script_check_id `monad_fail run_cmd script_check_id `monoid run_cmd script_check_id `mul_one run_cmd script_check_id `mul_zero run_cmd script_check_id `mul_zero_class run_cmd script_check_id `name.anonymous run_cmd script_check_id `name.mk_numeral run_cmd script_check_id `name.mk_string run_cmd script_check_id `nat run_cmd script_check_id `nat.succ run_cmd script_check_id `nat.zero run_cmd script_check_id `nat.has_zero run_cmd script_check_id `nat.has_one run_cmd script_check_id `nat.has_add run_cmd script_check_id `nat.add run_cmd script_check_id `nat.cases_on run_cmd script_check_id `nat.bit0_ne run_cmd script_check_id `nat.bit0_ne_bit1 run_cmd script_check_id `nat.bit0_ne_zero run_cmd script_check_id `nat.bit0_ne_one run_cmd script_check_id `nat.bit1_ne run_cmd script_check_id `nat.bit1_ne_bit0 run_cmd script_check_id `nat.bit1_ne_zero run_cmd script_check_id `nat.bit1_ne_one run_cmd script_check_id `nat.zero_ne_one run_cmd script_check_id `nat.zero_ne_bit0 run_cmd script_check_id `nat.zero_ne_bit1 run_cmd script_check_id `nat.one_ne_zero run_cmd script_check_id `nat.one_ne_bit0 run_cmd script_check_id `nat.one_ne_bit1 run_cmd script_check_id `nat.bit0_lt run_cmd script_check_id `nat.bit1_lt run_cmd script_check_id `nat.bit0_lt_bit1 run_cmd script_check_id `nat.bit1_lt_bit0 run_cmd script_check_id `nat.zero_lt_one run_cmd script_check_id `nat.zero_lt_bit1 run_cmd script_check_id `nat.zero_lt_bit0 run_cmd script_check_id `nat.one_lt_bit0 run_cmd script_check_id `nat.one_lt_bit1 run_cmd script_check_id `nat.le_of_lt run_cmd script_check_id `nat.le_refl run_cmd script_check_id `ne run_cmd script_check_id `neq_of_not_iff run_cmd script_check_id `norm_num.add1 run_cmd script_check_id `norm_num.add1_bit0 run_cmd script_check_id `norm_num.add1_bit1_helper run_cmd script_check_id `norm_num.add1_one run_cmd script_check_id `norm_num.add1_zero run_cmd script_check_id `norm_num.add_div_helper run_cmd script_check_id `norm_num.bin_add_zero run_cmd script_check_id `norm_num.bin_zero_add run_cmd script_check_id `norm_num.bit0_add_bit0_helper run_cmd script_check_id `norm_num.bit0_add_bit1_helper run_cmd script_check_id `norm_num.bit0_add_one run_cmd script_check_id `norm_num.bit1_add_bit0_helper run_cmd script_check_id `norm_num.bit1_add_bit1_helper run_cmd script_check_id `norm_num.bit1_add_one_helper run_cmd script_check_id `norm_num.div_add_helper run_cmd script_check_id `norm_num.div_eq_div_helper run_cmd script_check_id `norm_num.div_helper run_cmd script_check_id `norm_num.div_mul_helper run_cmd script_check_id `norm_num.mk_cong run_cmd script_check_id `norm_num.mul_bit0_helper run_cmd script_check_id `norm_num.mul_bit1_helper run_cmd script_check_id `norm_num.mul_div_helper run_cmd script_check_id `norm_num.neg_add_neg_helper run_cmd script_check_id `norm_num.neg_add_pos_helper1 run_cmd script_check_id `norm_num.neg_add_pos_helper2 run_cmd script_check_id `norm_num.neg_mul_neg_helper run_cmd script_check_id `norm_num.neg_mul_pos_helper run_cmd script_check_id `norm_num.neg_neg_helper run_cmd script_check_id `norm_num.neg_zero_helper run_cmd script_check_id `norm_num.nonneg_bit0_helper run_cmd script_check_id `norm_num.nonneg_bit1_helper run_cmd script_check_id `norm_num.nonzero_of_div_helper run_cmd script_check_id `norm_num.nonzero_of_neg_helper run_cmd script_check_id `norm_num.nonzero_of_pos_helper run_cmd script_check_id `norm_num.one_add_bit0 run_cmd script_check_id `norm_num.one_add_bit1_helper run_cmd script_check_id `norm_num.one_add_one run_cmd script_check_id `norm_num.pos_add_neg_helper run_cmd script_check_id `norm_num.pos_bit0_helper run_cmd script_check_id `norm_num.pos_bit1_helper run_cmd script_check_id `norm_num.pos_mul_neg_helper run_cmd script_check_id `norm_num.sub_nat_zero_helper run_cmd script_check_id `norm_num.sub_nat_pos_helper run_cmd script_check_id `norm_num.subst_into_div run_cmd script_check_id `norm_num.subst_into_prod run_cmd script_check_id `norm_num.subst_into_subtr run_cmd script_check_id `norm_num.subst_into_sum run_cmd script_check_id `not run_cmd script_check_id `not_of_iff_false run_cmd script_check_id `not_of_eq_false run_cmd script_check_id `of_eq_true run_cmd script_check_id `of_iff_true run_cmd script_check_id `opt_param run_cmd script_check_id `or run_cmd script_check_id `inout_param run_cmd script_check_id `punit run_cmd script_check_id `punit.star run_cmd script_check_id `prod.mk run_cmd script_check_id `pprod run_cmd script_check_id `pprod.mk run_cmd script_check_id `pprod.fst run_cmd script_check_id `pprod.snd run_cmd script_check_id `propext run_cmd script_check_id `to_pexpr run_cmd script_check_id `quot.mk run_cmd script_check_id `quot.lift run_cmd script_check_id `real run_cmd script_check_id `real.of_int run_cmd script_check_id `real.to_int run_cmd script_check_id `real.is_int run_cmd script_check_id `real.has_neg run_cmd script_check_id `real.has_div run_cmd script_check_id `real.has_add run_cmd script_check_id `real.has_mul run_cmd script_check_id `real.has_sub run_cmd script_check_id `real.has_lt run_cmd script_check_id `real.has_le run_cmd script_check_id `reflected run_cmd script_check_id `reflected.subst run_cmd script_check_id `repr run_cmd script_check_id `rfl run_cmd script_check_id `right_distrib run_cmd script_check_id `ring run_cmd script_check_id `scope_trace run_cmd script_check_id `set_of run_cmd script_check_id `semiring run_cmd script_check_id `psigma run_cmd script_check_id `psigma.cases_on run_cmd script_check_id `psigma.mk run_cmd script_check_id `psigma.fst run_cmd script_check_id `psigma.snd run_cmd script_check_id `singleton run_cmd script_check_id `sizeof run_cmd script_check_id `smt.array run_cmd script_check_id `smt.select run_cmd script_check_id `smt.store run_cmd script_check_id `smt.prove run_cmd script_check_id `string run_cmd script_check_id `string.empty run_cmd script_check_id `string.str run_cmd script_check_id `string.empty_ne_str run_cmd script_check_id `string.str_ne_empty run_cmd script_check_id `string.str_ne_str_left run_cmd script_check_id `string.str_ne_str_right run_cmd script_check_id `subsingleton run_cmd script_check_id `subsingleton.elim run_cmd script_check_id `subsingleton.helim run_cmd script_check_id `subtype run_cmd script_check_id `subtype.mk run_cmd script_check_id `subtype.val run_cmd script_check_id `subtype.rec run_cmd script_check_id `psum run_cmd script_check_id `psum.cases_on run_cmd script_check_id `psum.inl run_cmd script_check_id `psum.inr run_cmd script_check_id `tactic run_cmd script_check_id `tactic.try run_cmd script_check_id `tactic.triv run_cmd script_check_id `thunk run_cmd script_check_id `to_fmt run_cmd script_check_id `trans_rel_left run_cmd script_check_id `trans_rel_right run_cmd script_check_id `true run_cmd script_check_id `true.intro run_cmd script_check_id `unification_hint run_cmd script_check_id `unification_hint.mk run_cmd script_check_id `unit run_cmd script_check_id `unit.cases_on run_cmd script_check_id `unit.star run_cmd script_check_id `unsafe_monad_from_pure_bind run_cmd script_check_id `user_attribute run_cmd script_check_id `user_attribute.parse_reflect run_cmd script_check_id `vm_monitor run_cmd script_check_id `partial_order run_cmd script_check_id `well_founded.fix run_cmd script_check_id `well_founded.fix_eq run_cmd script_check_id `well_founded_tactics run_cmd script_check_id `well_founded_tactics.default run_cmd script_check_id `well_founded_tactics.rel_tac run_cmd script_check_id `well_founded_tactics.dec_tac run_cmd script_check_id `xor run_cmd script_check_id `zero_le_one run_cmd script_check_id `zero_lt_one run_cmd script_check_id `zero_mul
cac5b74cde7f8bf6a16206ee36bdd59613953aa5
4727251e0cd73359b15b664c3170e5d754078599
/src/data/real/ennreal.lean
6c3306acf2d9a9ee82914a04ff10ba68f38df24d
[ "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
76,937
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import data.real.nnreal /-! # Extended non-negative reals We define `ennreal = ℝ≥0∞ := with_top ℝ≥0` to be the type of extended nonnegative real numbers, i.e., the interval `[0, +∞]`. This type is used as the codomain of a `measure_theory.measure`, and of the extended distance `edist` in a `emetric_space`. In this file we define some algebraic operations and a linear order on `ℝ≥0∞` and prove basic properties of these operations, order, and conversions to/from `ℝ`, `ℝ≥0`, and `ℕ`. ## Main definitions * `ℝ≥0∞`: the extended nonnegative real numbers `[0, ∞]`; defined as `with_top ℝ≥0`; it is equipped with the following structures: - coercion from `ℝ≥0` defined in the natural way; - the natural structure of a complete dense linear order: `↑p ≤ ↑q ↔ p ≤ q` and `∀ a, a ≤ ∞`; - `a + b` is defined so that `↑p + ↑q = ↑(p + q)` for `(p q : ℝ≥0)` and `a + ∞ = ∞ + a = ∞`; - `a * b` is defined so that `↑p * ↑q = ↑(p * q)` for `(p q : ℝ≥0)`, `0 * ∞ = ∞ * 0 = 0`, and `a * ∞ = ∞ * a = ∞` for `a ≠ 0`; - `a - b` is defined as the minimal `d` such that `a ≤ d + b`; this way we have `↑p - ↑q = ↑(p - q)`, `∞ - ↑p = ∞`, `↑p - ∞ = ∞ - ∞ = 0`; note that there is no negation, only subtraction; - `a⁻¹` is defined as `Inf {b | 1 ≤ a * b}`. This way we have `(↑p)⁻¹ = ↑(p⁻¹)` for `p : ℝ≥0`, `p ≠ 0`, `0⁻¹ = ∞`, and `∞⁻¹ = 0`. - `a / b` is defined as `a * b⁻¹`. The addition and multiplication defined this way together with `0 = ↑0` and `1 = ↑1` turn `ℝ≥0∞` into a canonically ordered commutative semiring of characteristic zero. * Coercions to/from other types: - coercion `ℝ≥0 → ℝ≥0∞` is defined as `has_coe`, so one can use `(p : ℝ≥0)` in a context that expects `a : ℝ≥0∞`, and Lean will apply `coe` automatically; - `ennreal.to_nnreal` sends `↑p` to `p` and `∞` to `0`; - `ennreal.to_real := coe ∘ ennreal.to_nnreal` sends `↑p`, `p : ℝ≥0` to `(↑p : ℝ)` and `∞` to `0`; - `ennreal.of_real := coe ∘ real.to_nnreal` sends `x : ℝ` to `↑⟨max x 0, _⟩` - `ennreal.ne_top_equiv_nnreal` is an equivalence between `{a : ℝ≥0∞ // a ≠ 0}` and `ℝ≥0`. ## Implementation notes We define a `can_lift ℝ≥0∞ ℝ≥0` instance, so one of the ways to prove theorems about an `ℝ≥0∞` number `a` is to consider the cases `a = ∞` and `a ≠ ∞`, and use the tactic `lift a to ℝ≥0 using ha` in the second case. This instance is even more useful if one already has `ha : a ≠ ∞` in the context, or if we have `(f : α → ℝ≥0∞) (hf : ∀ x, f x ≠ ∞)`. ## Notations * `ℝ≥0∞`: the type of the extended nonnegative real numbers; * `ℝ≥0`: the type of nonnegative real numbers `[0, ∞)`; defined in `data.real.nnreal`; * `∞`: a localized notation in `ℝ≥0∞` for `⊤ : ℝ≥0∞`. -/ open classical set open_locale classical big_operators nnreal variables {α : Type*} {β : Type*} /-- The extended nonnegative real numbers. This is usually denoted [0, ∞], and is relevant as the codomain of a measure. -/ @[derive [ has_zero, add_comm_monoid, canonically_ordered_comm_semiring, complete_linear_order, densely_ordered, nontrivial, canonically_linear_ordered_add_monoid, has_sub, has_ordered_sub, linear_ordered_add_comm_monoid_with_top]] def ennreal := with_top ℝ≥0 localized "notation `ℝ≥0∞` := ennreal" in ennreal localized "notation `∞` := (⊤ : ennreal)" in ennreal namespace ennreal variables {a b c d : ℝ≥0∞} {r p q : ℝ≥0} -- TODO: why are the two covariant instances necessary? why aren't they inferred? instance covariant_class_mul_le : covariant_class ℝ≥0∞ ℝ≥0∞ (*) (≤) := canonically_ordered_comm_semiring.to_covariant_mul_le instance covariant_class_add_le : covariant_class ℝ≥0∞ ℝ≥0∞ (+) (≤) := ordered_add_comm_monoid.to_covariant_class_left ℝ≥0∞ instance : inhabited ℝ≥0∞ := ⟨0⟩ instance : has_coe ℝ≥0 ℝ≥0∞ := ⟨ option.some ⟩ instance : can_lift ℝ≥0∞ ℝ≥0 := { coe := coe, cond := λ r, r ≠ ∞, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } @[simp] lemma none_eq_top : (none : ℝ≥0∞) = ∞ := rfl @[simp] lemma some_eq_coe (a : ℝ≥0) : (some a : ℝ≥0∞) = (↑a : ℝ≥0∞) := rfl /-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/ protected def to_nnreal : ℝ≥0∞ → ℝ≥0 | (some r) := r | none := 0 /-- `to_real x` returns `x` if it is real, `0` otherwise. -/ protected def to_real (a : ℝ≥0∞) : real := coe (a.to_nnreal) /-- `of_real x` returns `x` if it is nonnegative, `0` otherwise. -/ protected noncomputable def of_real (r : real) : ℝ≥0∞ := coe (real.to_nnreal r) @[simp, norm_cast] lemma to_nnreal_coe : (r : ℝ≥0∞).to_nnreal = r := rfl @[simp] lemma coe_to_nnreal : ∀{a:ℝ≥0∞}, a ≠ ∞ → ↑(a.to_nnreal) = a | (some r) h := rfl | none h := (h rfl).elim @[simp] lemma of_real_to_real {a : ℝ≥0∞} (h : a ≠ ∞) : ennreal.of_real (a.to_real) = a := by simp [ennreal.to_real, ennreal.of_real, h] @[simp] lemma to_real_of_real {r : ℝ} (h : 0 ≤ r) : ennreal.to_real (ennreal.of_real r) = r := by simp [ennreal.to_real, ennreal.of_real, real.coe_to_nnreal _ h] lemma to_real_of_real' {r : ℝ} : ennreal.to_real (ennreal.of_real r) = max r 0 := rfl lemma coe_to_nnreal_le_self : ∀{a:ℝ≥0∞}, ↑(a.to_nnreal) ≤ a | (some r) := by rw [some_eq_coe, to_nnreal_coe]; exact le_rfl | none := le_top lemma coe_nnreal_eq (r : ℝ≥0) : (r : ℝ≥0∞) = ennreal.of_real r := by { rw [ennreal.of_real, real.to_nnreal], cases r with r h, congr, dsimp, rw max_eq_left h } lemma of_real_eq_coe_nnreal {x : ℝ} (h : 0 ≤ x) : ennreal.of_real x = @coe ℝ≥0 ℝ≥0∞ _ (⟨x, h⟩ : ℝ≥0) := by { rw [coe_nnreal_eq], refl } @[simp] lemma of_real_coe_nnreal : ennreal.of_real p = p := (coe_nnreal_eq p).symm @[simp, norm_cast] lemma coe_zero : ↑(0 : ℝ≥0) = (0 : ℝ≥0∞) := rfl @[simp, norm_cast] lemma coe_one : ↑(1 : ℝ≥0) = (1 : ℝ≥0∞) := rfl @[simp] lemma to_real_nonneg {a : ℝ≥0∞} : 0 ≤ a.to_real := by simp [ennreal.to_real] @[simp] lemma top_to_nnreal : ∞.to_nnreal = 0 := rfl @[simp] lemma top_to_real : ∞.to_real = 0 := rfl @[simp] lemma one_to_real : (1 : ℝ≥0∞).to_real = 1 := rfl @[simp] lemma one_to_nnreal : (1 : ℝ≥0∞).to_nnreal = 1 := rfl @[simp] lemma coe_to_real (r : ℝ≥0) : (r : ℝ≥0∞).to_real = r := rfl @[simp] lemma zero_to_nnreal : (0 : ℝ≥0∞).to_nnreal = 0 := rfl @[simp] lemma zero_to_real : (0 : ℝ≥0∞).to_real = 0 := rfl @[simp] lemma of_real_zero : ennreal.of_real (0 : ℝ) = 0 := by simp [ennreal.of_real]; refl @[simp] lemma of_real_one : ennreal.of_real (1 : ℝ) = (1 : ℝ≥0∞) := by simp [ennreal.of_real] lemma of_real_to_real_le {a : ℝ≥0∞} : ennreal.of_real (a.to_real) ≤ a := if ha : a = ∞ then ha.symm ▸ le_top else le_of_eq (of_real_to_real ha) lemma forall_ennreal {p : ℝ≥0∞ → Prop} : (∀a, p a) ↔ (∀r:ℝ≥0, p r) ∧ p ∞ := ⟨assume h, ⟨assume r, h _, h _⟩, assume ⟨h₁, h₂⟩ a, match a with some r := h₁ _ | none := h₂ end⟩ lemma forall_ne_top {p : ℝ≥0∞ → Prop} : (∀ a ≠ ∞, p a) ↔ ∀ r : ℝ≥0, p r := option.ball_ne_none lemma exists_ne_top {p : ℝ≥0∞ → Prop} : (∃ a ≠ ∞, p a) ↔ ∃ r : ℝ≥0, p r := option.bex_ne_none lemma to_nnreal_eq_zero_iff (x : ℝ≥0∞) : x.to_nnreal = 0 ↔ x = 0 ∨ x = ∞ := ⟨begin cases x, { simp [none_eq_top] }, { rintro (rfl : x = 0), exact or.inl rfl }, end, by rintro (h | h); simp [h]⟩ lemma to_real_eq_zero_iff (x : ℝ≥0∞) : x.to_real = 0 ↔ x = 0 ∨ x = ∞ := by simp [ennreal.to_real, to_nnreal_eq_zero_iff] @[simp] lemma coe_ne_top : (r : ℝ≥0∞) ≠ ∞ := with_top.coe_ne_top @[simp] lemma top_ne_coe : ∞ ≠ (r : ℝ≥0∞) := with_top.top_ne_coe @[simp] lemma of_real_ne_top {r : ℝ} : ennreal.of_real r ≠ ∞ := by simp [ennreal.of_real] @[simp] lemma of_real_lt_top {r : ℝ} : ennreal.of_real r < ∞ := lt_top_iff_ne_top.2 of_real_ne_top @[simp] lemma top_ne_of_real {r : ℝ} : ∞ ≠ ennreal.of_real r := by simp [ennreal.of_real] @[simp] lemma zero_ne_top : 0 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_zero : ∞ ≠ 0 := top_ne_coe @[simp] lemma one_ne_top : 1 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_one : ∞ ≠ 1 := top_ne_coe @[simp, norm_cast] lemma coe_eq_coe : (↑r : ℝ≥0∞) = ↑q ↔ r = q := with_top.coe_eq_coe @[simp, norm_cast] lemma coe_le_coe : (↑r : ℝ≥0∞) ≤ ↑q ↔ r ≤ q := with_top.coe_le_coe @[simp, norm_cast] lemma coe_lt_coe : (↑r : ℝ≥0∞) < ↑q ↔ r < q := with_top.coe_lt_coe lemma coe_mono : monotone (coe : ℝ≥0 → ℝ≥0∞) := λ _ _, coe_le_coe.2 @[simp, norm_cast] lemma coe_eq_zero : (↑r : ℝ≥0∞) = 0 ↔ r = 0 := coe_eq_coe @[simp, norm_cast] lemma zero_eq_coe : 0 = (↑r : ℝ≥0∞) ↔ 0 = r := coe_eq_coe @[simp, norm_cast] lemma coe_eq_one : (↑r : ℝ≥0∞) = 1 ↔ r = 1 := coe_eq_coe @[simp, norm_cast] lemma one_eq_coe : 1 = (↑r : ℝ≥0∞) ↔ 1 = r := coe_eq_coe @[simp, norm_cast] lemma coe_nonneg : 0 ≤ (↑r : ℝ≥0∞) ↔ 0 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_pos : 0 < (↑r : ℝ≥0∞) ↔ 0 < r := coe_lt_coe lemma coe_ne_zero : (r : ℝ≥0∞) ≠ 0 ↔ r ≠ 0 := not_congr coe_eq_coe @[simp, norm_cast] lemma coe_add : ↑(r + p) = (r + p : ℝ≥0∞) := with_top.coe_add @[simp, norm_cast] lemma coe_mul : ↑(r * p) = (r * p : ℝ≥0∞) := with_top.coe_mul @[simp, norm_cast] lemma coe_bit0 : (↑(bit0 r) : ℝ≥0∞) = bit0 r := coe_add @[simp, norm_cast] lemma coe_bit1 : (↑(bit1 r) : ℝ≥0∞) = bit1 r := by simp [bit1] lemma coe_two : ((2:ℝ≥0) : ℝ≥0∞) = 2 := by norm_cast protected lemma zero_lt_one : 0 < (1 : ℝ≥0∞) := canonically_ordered_comm_semiring.zero_lt_one @[simp] lemma one_lt_two : (1 : ℝ≥0∞) < 2 := coe_one ▸ coe_two ▸ by exact_mod_cast (@one_lt_two ℕ _ _) lemma one_le_two : (1 : ℝ≥0∞) ≤ 2 := one_lt_two.le @[simp] lemma zero_lt_two : (0:ℝ≥0∞) < 2 := lt_trans ennreal.zero_lt_one one_lt_two lemma two_ne_zero : (2:ℝ≥0∞) ≠ 0 := (ne_of_lt zero_lt_two).symm lemma two_ne_top : (2:ℝ≥0∞) ≠ ∞ := coe_two ▸ coe_ne_top /-- `(1 : ℝ≥0∞) ≤ 1`, recorded as a `fact` for use with `Lp` spaces. -/ instance _root_.fact_one_le_one_ennreal : fact ((1 : ℝ≥0∞) ≤ 1) := ⟨le_rfl⟩ /-- `(1 : ℝ≥0∞) ≤ 2`, recorded as a `fact` for use with `Lp` spaces. -/ instance _root_.fact_one_le_two_ennreal : fact ((1 : ℝ≥0∞) ≤ 2) := ⟨ennreal.coe_le_coe.2 (show (1 : ℝ≥0) ≤ 2, by norm_num)⟩ /-- `(1 : ℝ≥0∞) ≤ ∞`, recorded as a `fact` for use with `Lp` spaces. -/ instance _root_.fact_one_le_top_ennreal : fact ((1 : ℝ≥0∞) ≤ ∞) := ⟨le_top⟩ /-- The set of numbers in `ℝ≥0∞` that are not equal to `∞` is equivalent to `ℝ≥0`. -/ def ne_top_equiv_nnreal : {a | a ≠ ∞} ≃ ℝ≥0 := { to_fun := λ x, ennreal.to_nnreal x, inv_fun := λ x, ⟨x, coe_ne_top⟩, left_inv := λ ⟨x, hx⟩, subtype.eq $ coe_to_nnreal hx, right_inv := λ x, to_nnreal_coe } lemma cinfi_ne_top [has_Inf α] (f : ℝ≥0∞ → α) : (⨅ x : {x // x ≠ ∞}, f x) = ⨅ x : ℝ≥0, f x := eq.symm $ ne_top_equiv_nnreal.symm.surjective.infi_congr _$ λ x, rfl lemma infi_ne_top [complete_lattice α] (f : ℝ≥0∞ → α) : (⨅ x ≠ ∞, f x) = ⨅ x : ℝ≥0, f x := by rw [infi_subtype', cinfi_ne_top] lemma csupr_ne_top [has_Sup α] (f : ℝ≥0∞ → α) : (⨆ x : {x // x ≠ ∞}, f x) = ⨆ x : ℝ≥0, f x := @cinfi_ne_top αᵒᵈ _ _ lemma supr_ne_top [complete_lattice α] (f : ℝ≥0∞ → α) : (⨆ x ≠ ∞, f x) = ⨆ x : ℝ≥0, f x := @infi_ne_top αᵒᵈ _ _ lemma infi_ennreal {α : Type*} [complete_lattice α] {f : ℝ≥0∞ → α} : (⨅ n, f n) = (⨅ n : ℝ≥0, f n) ⊓ f ∞ := le_antisymm (le_inf (le_infi $ assume i, infi_le _ _) (infi_le _ _)) (le_infi $ forall_ennreal.2 ⟨λ r, inf_le_of_left_le $ infi_le _ _, inf_le_right⟩) lemma supr_ennreal {α : Type*} [complete_lattice α] {f : ℝ≥0∞ → α} : (⨆ n, f n) = (⨆ n : ℝ≥0, f n) ⊔ f ∞ := @infi_ennreal αᵒᵈ _ _ @[simp] lemma add_top : a + ∞ = ∞ := add_top _ @[simp] lemma top_add : ∞ + a = ∞ := top_add _ /-- Coercion `ℝ≥0 → ℝ≥0∞` as a `ring_hom`. -/ def of_nnreal_hom : ℝ≥0 →+* ℝ≥0∞ := ⟨coe, coe_one, λ _ _, coe_mul, coe_zero, λ _ _, coe_add⟩ @[simp] lemma coe_of_nnreal_hom : ⇑of_nnreal_hom = coe := rfl section actions /-- A `mul_action` over `ℝ≥0∞` restricts to a `mul_action` over `ℝ≥0`. -/ noncomputable instance {M : Type*} [mul_action ℝ≥0∞ M] : mul_action ℝ≥0 M := mul_action.comp_hom M of_nnreal_hom.to_monoid_hom lemma smul_def {M : Type*} [mul_action ℝ≥0∞ M] (c : ℝ≥0) (x : M) : c • x = (c : ℝ≥0∞) • x := rfl instance {M N : Type*} [mul_action ℝ≥0∞ M] [mul_action ℝ≥0∞ N] [has_scalar M N] [is_scalar_tower ℝ≥0∞ M N] : is_scalar_tower ℝ≥0 M N := { smul_assoc := λ r, (smul_assoc (r : ℝ≥0∞) : _)} instance smul_comm_class_left {M N : Type*} [mul_action ℝ≥0∞ N] [has_scalar M N] [smul_comm_class ℝ≥0∞ M N] : smul_comm_class ℝ≥0 M N := { smul_comm := λ r, (smul_comm (r : ℝ≥0∞) : _)} instance smul_comm_class_right {M N : Type*} [mul_action ℝ≥0∞ N] [has_scalar M N] [smul_comm_class M ℝ≥0∞ N] : smul_comm_class M ℝ≥0 N := { smul_comm := λ m r, (smul_comm m (r : ℝ≥0∞) : _)} /-- A `distrib_mul_action` over `ℝ≥0∞` restricts to a `distrib_mul_action` over `ℝ≥0`. -/ noncomputable instance {M : Type*} [add_monoid M] [distrib_mul_action ℝ≥0∞ M] : distrib_mul_action ℝ≥0 M := distrib_mul_action.comp_hom M of_nnreal_hom.to_monoid_hom /-- A `module` over `ℝ≥0∞` restricts to a `module` over `ℝ≥0`. -/ noncomputable instance {M : Type*} [add_comm_monoid M] [module ℝ≥0∞ M] : module ℝ≥0 M := module.comp_hom M of_nnreal_hom /-- An `algebra` over `ℝ≥0∞` restricts to an `algebra` over `ℝ≥0`. -/ noncomputable instance {A : Type*} [semiring A] [algebra ℝ≥0∞ A] : algebra ℝ≥0 A := { smul := (•), commutes' := λ r x, by simp [algebra.commutes], smul_def' := λ r x, by simp [←algebra.smul_def (r : ℝ≥0∞) x, smul_def], to_ring_hom := ((algebra_map ℝ≥0∞ A).comp (of_nnreal_hom : ℝ≥0 →+* ℝ≥0∞)) } -- verify that the above produces instances we might care about noncomputable example : algebra ℝ≥0 ℝ≥0∞ := infer_instance noncomputable example : distrib_mul_action ℝ≥0ˣ ℝ≥0∞ := infer_instance lemma coe_smul {R} (r : R) (s : ℝ≥0) [has_scalar R ℝ≥0] [has_scalar R ℝ≥0∞] [is_scalar_tower R ℝ≥0 ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ≥0∞] : (↑(r • s) : ℝ≥0∞) = r • ↑s := by rw [←smul_one_smul ℝ≥0 r (s: ℝ≥0∞), smul_def, smul_eq_mul, ←ennreal.coe_mul, smul_mul_assoc, one_mul] end actions @[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → ℝ≥0) (a : α) : ((s.indicator f a : ℝ≥0) : ℝ≥0∞) = s.indicator (λ x, f x) a := (of_nnreal_hom : ℝ≥0 →+ ℝ≥0∞).map_indicator _ _ _ @[simp, norm_cast] lemma coe_pow (n : ℕ) : (↑(r^n) : ℝ≥0∞) = r^n := of_nnreal_hom.map_pow r n @[simp] lemma add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := with_top.add_eq_top @[simp] lemma add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := with_top.add_lt_top lemma to_nnreal_add {r₁ r₂ : ℝ≥0∞} (h₁ : r₁ ≠ ∞) (h₂ : r₂ ≠ ∞) : (r₁ + r₂).to_nnreal = r₁.to_nnreal + r₂.to_nnreal := by { lift r₁ to ℝ≥0 using h₁, lift r₂ to ℝ≥0 using h₂, refl } lemma not_lt_top {x : ℝ≥0∞} : ¬ x < ∞ ↔ x = ∞ := by rw [lt_top_iff_ne_top, not_not] lemma add_ne_top : a + b ≠ ∞ ↔ a ≠ ∞ ∧ b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using add_lt_top lemma mul_top : a * ∞ = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.mul_top h } end lemma top_mul : ∞ * a = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.top_mul h } end @[simp] lemma top_mul_top : ∞ * ∞ = ∞ := with_top.top_mul_top lemma top_pow {n:ℕ} (h : 0 < n) : ∞^n = ∞ := nat.le_induction (pow_one _) (λ m hm hm', by rw [pow_succ, hm', top_mul_top]) _ (nat.succ_le_of_lt h) lemma mul_eq_top : a * b = ∞ ↔ (a ≠ 0 ∧ b = ∞) ∨ (a = ∞ ∧ b ≠ 0) := with_top.mul_eq_top_iff lemma mul_lt_top : a ≠ ∞ → b ≠ ∞ → a * b < ∞ := with_top.mul_lt_top lemma mul_ne_top : a ≠ ∞ → b ≠ ∞ → a * b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using mul_lt_top lemma lt_top_of_mul_ne_top_left (h : a * b ≠ ∞) (hb : b ≠ 0) : a < ∞ := lt_top_iff_ne_top.2 $ λ ha, h $ mul_eq_top.2 (or.inr ⟨ha, hb⟩) lemma lt_top_of_mul_ne_top_right (h : a * b ≠ ∞) (ha : a ≠ 0) : b < ∞ := lt_top_of_mul_ne_top_left (by rwa [mul_comm]) ha lemma mul_lt_top_iff {a b : ℝ≥0∞} : a * b < ∞ ↔ (a < ∞ ∧ b < ∞) ∨ a = 0 ∨ b = 0 := begin split, { intro h, rw [← or_assoc, or_iff_not_imp_right, or_iff_not_imp_right], intros hb ha, exact ⟨lt_top_of_mul_ne_top_left h.ne hb, lt_top_of_mul_ne_top_right h.ne ha⟩ }, { rintro (⟨ha, hb⟩|rfl|rfl); [exact mul_lt_top ha.ne hb.ne, simp, simp] } end lemma mul_self_lt_top_iff {a : ℝ≥0∞} : a * a < ⊤ ↔ a < ⊤ := by { rw [ennreal.mul_lt_top_iff, and_self, or_self, or_iff_left_iff_imp], rintro rfl, norm_num } lemma mul_pos_iff : 0 < a * b ↔ 0 < a ∧ 0 < b := canonically_ordered_comm_semiring.mul_pos lemma mul_pos (ha : a ≠ 0) (hb : b ≠ 0) : 0 < a * b := mul_pos_iff.2 ⟨pos_iff_ne_zero.2 ha, pos_iff_ne_zero.2 hb⟩ @[simp] lemma pow_eq_top_iff {n : ℕ} : a ^ n = ∞ ↔ a = ∞ ∧ n ≠ 0 := begin induction n with n ihn, { simp }, rw [pow_succ, mul_eq_top, ihn], fsplit, { rintro (⟨-,rfl,h0⟩|⟨rfl,h0⟩); exact ⟨rfl, n.succ_ne_zero⟩ }, { rintro ⟨rfl, -⟩, exact or.inr ⟨rfl, pow_ne_zero n top_ne_zero⟩ } end lemma pow_eq_top (n : ℕ) (h : a ^ n = ∞) : a = ∞ := (pow_eq_top_iff.1 h).1 lemma pow_ne_top (h : a ≠ ∞) {n:ℕ} : a^n ≠ ∞ := mt (pow_eq_top n) h lemma pow_lt_top : a < ∞ → ∀ n:ℕ, a^n < ∞ := by simpa only [lt_top_iff_ne_top] using pow_ne_top @[simp, norm_cast] lemma coe_finset_sum {s : finset α} {f : α → ℝ≥0} : ↑(∑ a in s, f a) = (∑ a in s, f a : ℝ≥0∞) := of_nnreal_hom.map_sum f s @[simp, norm_cast] lemma coe_finset_prod {s : finset α} {f : α → ℝ≥0} : ↑(∏ a in s, f a) = ((∏ a in s, f a) : ℝ≥0∞) := of_nnreal_hom.map_prod f s section order @[simp] lemma bot_eq_zero : (⊥ : ℝ≥0∞) = 0 := rfl @[simp] lemma coe_lt_top : coe r < ∞ := with_top.coe_lt_top r @[simp] lemma not_top_le_coe : ¬ ∞ ≤ ↑r := with_top.not_top_le_coe r @[simp, norm_cast] lemma one_le_coe_iff : (1:ℝ≥0∞) ≤ ↑r ↔ 1 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_le_one_iff : ↑r ≤ (1:ℝ≥0∞) ↔ r ≤ 1 := coe_le_coe @[simp, norm_cast] lemma coe_lt_one_iff : (↑p : ℝ≥0∞) < 1 ↔ p < 1 := coe_lt_coe @[simp, norm_cast] lemma one_lt_coe_iff : 1 < (↑p : ℝ≥0∞) ↔ 1 < p := coe_lt_coe @[simp, norm_cast] lemma coe_nat (n : ℕ) : ((n : ℝ≥0) : ℝ≥0∞) = n := with_top.coe_nat n @[simp] lemma of_real_coe_nat (n : ℕ) : ennreal.of_real n = n := by simp [ennreal.of_real] @[simp] lemma nat_ne_top (n : ℕ) : (n : ℝ≥0∞) ≠ ∞ := with_top.nat_ne_top n @[simp] lemma top_ne_nat (n : ℕ) : ∞ ≠ n := with_top.top_ne_nat n @[simp] lemma one_lt_top : 1 < ∞ := coe_lt_top @[simp, norm_cast] lemma to_nnreal_nat (n : ℕ) : (n : ℝ≥0∞).to_nnreal = n := by conv_lhs { rw [← ennreal.coe_nat n, ennreal.to_nnreal_coe] } @[simp, norm_cast] lemma to_real_nat (n : ℕ) : (n : ℝ≥0∞).to_real = n := by conv_lhs { rw [← ennreal.of_real_coe_nat n, ennreal.to_real_of_real (nat.cast_nonneg _)] } lemma le_coe_iff : a ≤ ↑r ↔ (∃p:ℝ≥0, a = p ∧ p ≤ r) := with_top.le_coe_iff lemma coe_le_iff : ↑r ≤ a ↔ (∀p:ℝ≥0, a = p → r ≤ p) := with_top.coe_le_iff lemma lt_iff_exists_coe : a < b ↔ (∃p:ℝ≥0, a = p ∧ ↑p < b) := with_top.lt_iff_exists_coe lemma to_real_le_coe_of_le_coe {a : ℝ≥0∞} {b : ℝ≥0} (h : a ≤ b) : a.to_real ≤ b := show ↑a.to_nnreal ≤ ↑b, begin have : ↑a.to_nnreal = a := ennreal.coe_to_nnreal (lt_of_le_of_lt h coe_lt_top).ne, rw ← this at h, exact_mod_cast h end @[simp, norm_cast] lemma coe_finset_sup {s : finset α} {f : α → ℝ≥0} : ↑(s.sup f) = s.sup (λ x, (f x : ℝ≥0∞)) := finset.comp_sup_eq_sup_comp_of_is_total _ coe_mono rfl lemma pow_le_pow {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := begin cases a, { cases m, { rw eq_bot_iff.mpr h, exact le_rfl }, { rw [none_eq_top, top_pow (nat.succ_pos m)], exact le_top } }, { rw [some_eq_coe, ← coe_pow, ← coe_pow, coe_le_coe], exact pow_le_pow (by simpa using ha) h } end lemma one_le_pow_of_one_le (ha : 1 ≤ a) (n : ℕ) : 1 ≤ a ^ n := by simpa using pow_le_pow ha (zero_le n) @[simp] lemma max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 := by simp only [nonpos_iff_eq_zero.symm, max_le_iff] @[simp] lemma max_zero_left : max 0 a = a := max_eq_right (zero_le a) @[simp] lemma max_zero_right : max a 0 = a := max_eq_left (zero_le a) @[simp] lemma sup_eq_max : a ⊔ b = max a b := rfl protected lemma pow_pos : 0 < a → ∀ n : ℕ, 0 < a^n := canonically_ordered_comm_semiring.pow_pos protected lemma pow_ne_zero : a ≠ 0 → ∀ n : ℕ, a^n ≠ 0 := by simpa only [pos_iff_ne_zero] using ennreal.pow_pos @[simp] lemma not_lt_zero : ¬ a < 0 := by simp protected lemma le_of_add_le_add_left : a ≠ ∞ → a + b ≤ a + c → b ≤ c := with_top.le_of_add_le_add_left protected lemma le_of_add_le_add_right : a ≠ ∞ → b + a ≤ c + a → b ≤ c := with_top.le_of_add_le_add_right protected lemma add_lt_add_left : a ≠ ∞ → b < c → a + b < a + c := with_top.add_lt_add_left protected lemma add_lt_add_right : a ≠ ∞ → b < c → b + a < c + a := with_top.add_lt_add_right protected lemma add_le_add_iff_left : a ≠ ∞ → (a + b ≤ a + c ↔ b ≤ c) := with_top.add_le_add_iff_left protected lemma add_le_add_iff_right : a ≠ ∞ → (b + a ≤ c + a ↔ b ≤ c) := with_top.add_le_add_iff_right protected lemma add_lt_add_iff_left : a ≠ ∞ → (a + b < a + c ↔ b < c) := with_top.add_lt_add_iff_left protected lemma add_lt_add_iff_right : a ≠ ∞ → (b + a < c + a ↔ b < c) := with_top.add_lt_add_iff_right protected lemma add_lt_add_of_le_of_lt : a ≠ ∞ → a ≤ b → c < d → a + c < b + d := with_top.add_lt_add_of_le_of_lt protected lemma add_lt_add_of_lt_of_le : c ≠ ∞ → a < b → c ≤ d → a + c < b + d := with_top.add_lt_add_of_lt_of_le instance contravariant_class_add_lt : contravariant_class ℝ≥0∞ ℝ≥0∞ (+) (<) := with_top.contravariant_class_add_lt lemma lt_add_right (ha : a ≠ ∞) (hb : b ≠ 0) : a < a + b := by rwa [← pos_iff_ne_zero, ←ennreal.add_lt_add_iff_left ha, add_zero] at hb lemma le_of_forall_pos_le_add : ∀{a b : ℝ≥0∞}, (∀ε : ℝ≥0, 0 < ε → b < ∞ → a ≤ b + ε) → a ≤ b | a none h := le_top | none (some a) h := have ∞ ≤ ↑a + ↑(1:ℝ≥0), from h 1 zero_lt_one coe_lt_top, by rw [← coe_add] at this; exact (not_top_le_coe this).elim | (some a) (some b) h := by simp only [none_eq_top, some_eq_coe, coe_add.symm, coe_le_coe, coe_lt_top, true_implies_iff] at *; exact nnreal.le_of_forall_pos_le_add h lemma lt_iff_exists_rat_btwn : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < real.to_nnreal q ∧ (real.to_nnreal q:ℝ≥0∞) < b) := ⟨λ h, begin rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩, rcases exists_between h with ⟨c, pc, cb⟩, rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩, rcases (nnreal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩, exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩ end, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_real_btwn : a < b ↔ (∃r:ℝ, 0 ≤ r ∧ a < ennreal.of_real r ∧ (ennreal.of_real r:ℝ≥0∞) < b) := ⟨λ h, let ⟨q, q0, aq, qb⟩ := ennreal.lt_iff_exists_rat_btwn.1 h in ⟨q, rat.cast_nonneg.2 q0, aq, qb⟩, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_nnreal_btwn : a < b ↔ (∃r:ℝ≥0, a < r ∧ (r : ℝ≥0∞) < b) := with_top.lt_iff_exists_coe_btwn lemma lt_iff_exists_add_pos_lt : a < b ↔ (∃ r : ℝ≥0, 0 < r ∧ a + r < b) := begin refine ⟨λ hab, _, λ ⟨r, rpos, hr⟩, lt_of_le_of_lt (le_self_add) hr⟩, cases a, { simpa using hab }, rcases lt_iff_exists_real_btwn.1 hab with ⟨c, c_nonneg, ac, cb⟩, let d : ℝ≥0 := ⟨c, c_nonneg⟩, have ad : a < d, { rw of_real_eq_coe_nnreal c_nonneg at ac, exact coe_lt_coe.1 ac }, refine ⟨d-a, tsub_pos_iff_lt.2 ad, _⟩, rw [some_eq_coe, ← coe_add], convert cb, have : real.to_nnreal c = d, by { rw [← nnreal.coe_eq, real.coe_to_nnreal _ c_nonneg], refl }, rw [add_comm, this], exact tsub_add_cancel_of_le ad.le end lemma coe_nat_lt_coe {n : ℕ} : (n : ℝ≥0∞) < r ↔ ↑n < r := ennreal.coe_nat n ▸ coe_lt_coe lemma coe_lt_coe_nat {n : ℕ} : (r : ℝ≥0∞) < n ↔ r < n := ennreal.coe_nat n ▸ coe_lt_coe @[simp, norm_cast] lemma coe_nat_lt_coe_nat {m n : ℕ} : (m : ℝ≥0∞) < n ↔ m < n := ennreal.coe_nat n ▸ coe_nat_lt_coe.trans nat.cast_lt lemma coe_nat_ne_top {n : ℕ} : (n : ℝ≥0∞) ≠ ∞ := ennreal.coe_nat n ▸ coe_ne_top lemma coe_nat_mono : strict_mono (coe : ℕ → ℝ≥0∞) := λ _ _, coe_nat_lt_coe_nat.2 @[simp, norm_cast] lemma coe_nat_le_coe_nat {m n : ℕ} : (m : ℝ≥0∞) ≤ n ↔ m ≤ n := coe_nat_mono.le_iff_le instance : char_zero ℝ≥0∞ := ⟨coe_nat_mono.injective⟩ protected lemma exists_nat_gt {r : ℝ≥0∞} (h : r ≠ ∞) : ∃n:ℕ, r < n := begin lift r to ℝ≥0 using h, rcases exists_nat_gt r with ⟨n, hn⟩, exact ⟨n, coe_lt_coe_nat.2 hn⟩, end lemma add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d := begin lift a to ℝ≥0 using ne_top_of_lt ac, lift b to ℝ≥0 using ne_top_of_lt bd, cases c, { simp }, cases d, { simp }, simp only [← coe_add, some_eq_coe, coe_lt_coe] at *, exact add_lt_add ac bd end @[norm_cast] lemma coe_min : ((min r p:ℝ≥0):ℝ≥0∞) = min r p := coe_mono.map_min @[norm_cast] lemma coe_max : ((max r p:ℝ≥0):ℝ≥0∞) = max r p := coe_mono.map_max lemma le_of_top_imp_top_of_to_nnreal_le {a b : ℝ≥0∞} (h : a = ⊤ → b = ⊤) (h_nnreal : a ≠ ⊤ → b ≠ ⊤ → a.to_nnreal ≤ b.to_nnreal) : a ≤ b := begin by_cases ha : a = ⊤, { rw h ha, exact le_top, }, by_cases hb : b = ⊤, { rw hb, exact le_top, }, rw [←coe_to_nnreal hb, ←coe_to_nnreal ha, coe_le_coe], exact h_nnreal ha hb, end end order section complete_lattice lemma coe_Sup {s : set ℝ≥0} : bdd_above s → (↑(Sup s) : ℝ≥0∞) = (⨆a∈s, ↑a) := with_top.coe_Sup lemma coe_Inf {s : set ℝ≥0} : s.nonempty → (↑(Inf s) : ℝ≥0∞) = (⨅a∈s, ↑a) := with_top.coe_Inf @[simp] lemma top_mem_upper_bounds {s : set ℝ≥0∞} : ∞ ∈ upper_bounds s := assume x hx, le_top lemma coe_mem_upper_bounds {s : set ℝ≥0} : ↑r ∈ upper_bounds ((coe : ℝ≥0 → ℝ≥0∞) '' s) ↔ r ∈ upper_bounds s := by simp [upper_bounds, ball_image_iff, -mem_image, *] {contextual := tt} end complete_lattice section mul @[mono] lemma mul_le_mul : a ≤ b → c ≤ d → a * c ≤ b * d := mul_le_mul' @[mono] lemma mul_lt_mul (ac : a < c) (bd : b < d) : a * b < c * d := begin rcases lt_iff_exists_nnreal_btwn.1 ac with ⟨a', aa', a'c⟩, lift a to ℝ≥0 using ne_top_of_lt aa', rcases lt_iff_exists_nnreal_btwn.1 bd with ⟨b', bb', b'd⟩, lift b to ℝ≥0 using ne_top_of_lt bb', norm_cast at *, calc ↑(a * b) < ↑(a' * b') : coe_lt_coe.2 (mul_lt_mul' aa'.le bb' (zero_le _) ((zero_le a).trans_lt aa')) ... = ↑a' * ↑b' : coe_mul ... ≤ c * d : mul_le_mul a'c.le b'd.le end lemma mul_left_mono : monotone ((*) a) := λ b c, mul_le_mul le_rfl lemma mul_right_mono : monotone (λ x, x * a) := λ b c h, mul_le_mul h le_rfl lemma pow_strict_mono {n : ℕ} (hn : n ≠ 0) : strict_mono (λ (x : ℝ≥0∞), x^n) := begin assume x y hxy, obtain ⟨n, rfl⟩ := nat.exists_eq_succ_of_ne_zero hn, induction n with n IH, { simp only [hxy, pow_one] }, { simp only [pow_succ _ n.succ, mul_lt_mul hxy (IH (nat.succ_pos _).ne')] } end lemma max_mul : max a b * c = max (a * c) (b * c) := mul_right_mono.map_max lemma mul_max : a * max b c = max (a * b) (a * c) := mul_left_mono.map_max lemma mul_eq_mul_left : a ≠ 0 → a ≠ ∞ → (a * b = a * c ↔ b = c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm, nnreal.mul_eq_mul_left] {contextual := tt}, end lemma mul_eq_mul_right : c ≠ 0 → c ≠ ∞ → (a * c = b * c ↔ a = b) := mul_comm c a ▸ mul_comm c b ▸ mul_eq_mul_left lemma mul_le_mul_left : a ≠ 0 → a ≠ ∞ → (a * b ≤ a * c ↔ b ≤ c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm] {contextual := tt}, assume h, exact mul_le_mul_left (pos_iff_ne_zero.2 h) end lemma mul_le_mul_right : c ≠ 0 → c ≠ ∞ → (a * c ≤ b * c ↔ a ≤ b) := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left lemma mul_lt_mul_left : a ≠ 0 → a ≠ ∞ → (a * b < a * c ↔ b < c) := λ h0 ht, by simp only [mul_le_mul_left h0 ht, lt_iff_le_not_le] lemma mul_lt_mul_right : c ≠ 0 → c ≠ ∞ → (a * c < b * c ↔ a < b) := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_left end mul section cancel /-- An element `a` is `add_le_cancellable` if `a + b ≤ a + c` implies `b ≤ c` for all `b` and `c`. This is true in `ℝ≥0∞` for all elements except `∞`. -/ lemma add_le_cancellable_iff_ne {a : ℝ≥0∞} : add_le_cancellable a ↔ a ≠ ∞ := begin split, { rintro h rfl, refine ennreal.zero_lt_one.not_le (h _), simp, }, { rintro h b c hbc, apply ennreal.le_of_add_le_add_left h hbc } end /-- This lemma has an abbreviated name because it is used frequently. -/ lemma cancel_of_ne {a : ℝ≥0∞} (h : a ≠ ∞) : add_le_cancellable a := add_le_cancellable_iff_ne.mpr h /-- This lemma has an abbreviated name because it is used frequently. -/ lemma cancel_of_lt {a : ℝ≥0∞} (h : a < ∞) : add_le_cancellable a := cancel_of_ne h.ne /-- This lemma has an abbreviated name because it is used frequently. -/ lemma cancel_of_lt' {a b : ℝ≥0∞} (h : a < b) : add_le_cancellable a := cancel_of_ne h.ne_top /-- This lemma has an abbreviated name because it is used frequently. -/ lemma cancel_coe {a : ℝ≥0} : add_le_cancellable (a : ℝ≥0∞) := cancel_of_ne coe_ne_top lemma add_right_inj (h : a ≠ ∞) : a + b = a + c ↔ b = c := (cancel_of_ne h).inj lemma add_left_inj (h : a ≠ ∞) : b + a = c + a ↔ b = c := (cancel_of_ne h).inj_left end cancel section sub lemma sub_eq_Inf {a b : ℝ≥0∞} : a - b = Inf {d | a ≤ d + b} := le_antisymm (le_Inf $ λ c, tsub_le_iff_right.mpr) $ Inf_le le_tsub_add /-- This is a special case of `with_top.coe_sub` in the `ennreal` namespace -/ lemma coe_sub : (↑(r - p) : ℝ≥0∞) = ↑r - ↑p := with_top.coe_sub /-- This is a special case of `with_top.top_sub_coe` in the `ennreal` namespace -/ lemma top_sub_coe : ∞ - ↑r = ∞ := with_top.top_sub_coe /-- This is a special case of `with_top.sub_top` in the `ennreal` namespace -/ lemma sub_top : a - ∞ = 0 := with_top.sub_top lemma sub_eq_top_iff : a - b = ∞ ↔ a = ∞ ∧ b ≠ ∞ := by { cases a; cases b; simp [← with_top.coe_sub] } lemma sub_ne_top (ha : a ≠ ∞) : a - b ≠ ∞ := mt sub_eq_top_iff.mp $ mt and.left ha protected lemma sub_eq_of_eq_add (hb : b ≠ ∞) : a = c + b → a - b = c := (cancel_of_ne hb).tsub_eq_of_eq_add protected lemma eq_sub_of_add_eq (hc : c ≠ ∞) : a + c = b → a = b - c := (cancel_of_ne hc).eq_tsub_of_add_eq protected lemma sub_eq_of_eq_add_rev (hb : b ≠ ∞) : a = b + c → a - b = c := (cancel_of_ne hb).tsub_eq_of_eq_add_rev lemma sub_eq_of_add_eq (hb : b ≠ ∞) (hc : a + b = c) : c - b = a := ennreal.sub_eq_of_eq_add hb hc.symm @[simp] protected lemma add_sub_cancel_left (ha : a ≠ ∞) : a + b - a = b := (cancel_of_ne ha).add_tsub_cancel_left @[simp] protected lemma add_sub_cancel_right (hb : b ≠ ∞) : a + b - b = a := (cancel_of_ne hb).add_tsub_cancel_right protected lemma lt_add_of_sub_lt_left (h : a ≠ ∞ ∨ b ≠ ∞) : a - b < c → a < b + c := begin obtain rfl | hb := eq_or_ne b ∞, { rw [top_add, lt_top_iff_ne_top], exact λ _, h.resolve_right (not_not.2 rfl) }, { exact (cancel_of_ne hb).lt_add_of_tsub_lt_left } end protected lemma lt_add_of_sub_lt_right (h : a ≠ ∞ ∨ c ≠ ∞) : a - c < b → a < b + c := add_comm c b ▸ ennreal.lt_add_of_sub_lt_left h lemma le_sub_of_add_le_left (ha : a ≠ ∞) : a + b ≤ c → b ≤ c - a := (cancel_of_ne ha).le_tsub_of_add_le_left lemma le_sub_of_add_le_right (hb : b ≠ ∞) : a + b ≤ c → a ≤ c - b := (cancel_of_ne hb).le_tsub_of_add_le_right protected lemma sub_lt_of_lt_add (hac : c ≤ a) (h : a < b + c) : a - c < b := ((cancel_of_lt' $ hac.trans_lt h).tsub_lt_iff_right hac).mpr h protected lemma sub_lt_iff_lt_right (hb : b ≠ ∞) (hab : b ≤ a) : a - b < c ↔ a < c + b := (cancel_of_ne hb).tsub_lt_iff_right hab protected lemma sub_lt_self (ha : a ≠ ∞) (ha₀ : a ≠ 0) (hb : b ≠ 0) : a - b < a := (cancel_of_ne ha).tsub_lt_self (pos_iff_ne_zero.2 ha₀) (pos_iff_ne_zero.2 hb) protected lemma sub_lt_self_iff (ha : a ≠ ∞) : a - b < a ↔ 0 < a ∧ 0 < b := (cancel_of_ne ha).tsub_lt_self_iff lemma sub_lt_of_sub_lt (h₂ : c ≤ a) (h₃ : a ≠ ∞ ∨ b ≠ ∞) (h₁ : a - b < c) : a - c < b := ennreal.sub_lt_of_lt_add h₂ (add_comm c b ▸ ennreal.lt_add_of_sub_lt_right h₃ h₁) lemma sub_sub_cancel (h : a ≠ ∞) (h2 : b ≤ a) : a - (a - b) = b := (cancel_of_ne $ sub_ne_top h).tsub_tsub_cancel_of_le h2 lemma sub_right_inj {a b c : ℝ≥0∞} (ha : a ≠ ∞) (hb : b ≤ a) (hc : c ≤ a) : a - b = a - c ↔ b = c := (cancel_of_ne ha).tsub_right_inj (cancel_of_ne $ ne_top_of_le_ne_top ha hb) (cancel_of_ne $ ne_top_of_le_ne_top ha hc) hb hc lemma sub_mul (h : 0 < b → b < a → c ≠ ∞) : (a - b) * c = a * c - b * c := begin cases le_or_lt a b with hab hab, { simp [hab, mul_right_mono hab] }, rcases eq_or_lt_of_le (zero_le b) with rfl|hb, { simp }, exact (cancel_of_ne $ mul_ne_top hab.ne_top (h hb hab)).tsub_mul end lemma mul_sub (h : 0 < c → c < b → a ≠ ∞) : a * (b - c) = a * b - a * c := by { simp only [mul_comm a], exact sub_mul h } end sub section sum open finset /-- A product of finite numbers is still finite -/ lemma prod_lt_top {s : finset α} {f : α → ℝ≥0∞} (h : ∀ a ∈ s, f a ≠ ∞) : (∏ a in s, f a) < ∞ := with_top.prod_lt_top h /-- A sum of finite numbers is still finite -/ lemma sum_lt_top {s : finset α} {f : α → ℝ≥0∞} (h : ∀ a ∈ s, f a ≠ ∞) : ∑ a in s, f a < ∞ := with_top.sum_lt_top h /-- A sum of finite numbers is still finite -/ lemma sum_lt_top_iff {s : finset α} {f : α → ℝ≥0∞} : ∑ a in s, f a < ∞ ↔ (∀ a ∈ s, f a < ∞) := with_top.sum_lt_top_iff /-- A sum of numbers is infinite iff one of them is infinite -/ lemma sum_eq_top_iff {s : finset α} {f : α → ℝ≥0∞} : (∑ x in s, f x) = ∞ ↔ (∃ a ∈ s, f a = ∞) := with_top.sum_eq_top_iff lemma lt_top_of_sum_ne_top {s : finset α} {f : α → ℝ≥0∞} (h : (∑ x in s, f x) ≠ ∞) {a : α} (ha : a ∈ s) : f a < ∞ := sum_lt_top_iff.1 h.lt_top a ha /-- seeing `ℝ≥0∞` as `ℝ≥0` does not change their sum, unless one of the `ℝ≥0∞` is infinity -/ lemma to_nnreal_sum {s : finset α} {f : α → ℝ≥0∞} (hf : ∀a∈s, f a ≠ ∞) : ennreal.to_nnreal (∑ a in s, f a) = ∑ a in s, ennreal.to_nnreal (f a) := begin rw [← coe_eq_coe, coe_to_nnreal, coe_finset_sum, sum_congr rfl], { intros x hx, exact (coe_to_nnreal (hf x hx)).symm }, { exact (sum_lt_top hf).ne } end /-- seeing `ℝ≥0∞` as `real` does not change their sum, unless one of the `ℝ≥0∞` is infinity -/ lemma to_real_sum {s : finset α} {f : α → ℝ≥0∞} (hf : ∀ a ∈ s, f a ≠ ∞) : ennreal.to_real (∑ a in s, f a) = ∑ a in s, ennreal.to_real (f a) := by { rw [ennreal.to_real, to_nnreal_sum hf, nnreal.coe_sum], refl } lemma of_real_sum_of_nonneg {s : finset α} {f : α → ℝ} (hf : ∀ i, i ∈ s → 0 ≤ f i) : ennreal.of_real (∑ i in s, f i) = ∑ i in s, ennreal.of_real (f i) := begin simp_rw [ennreal.of_real, ←coe_finset_sum, coe_eq_coe], exact real.to_nnreal_sum_of_nonneg hf, end theorem sum_lt_sum_of_nonempty {s : finset α} (hs : s.nonempty) {f g : α → ℝ≥0∞} (Hlt : ∀ i ∈ s, f i < g i) : ∑ i in s, f i < ∑ i in s, g i := begin induction hs using finset.nonempty.cons_induction with a a s as hs IH, { simp [Hlt _ (finset.mem_singleton_self _)] }, { simp only [as, finset.sum_cons, not_false_iff], exact ennreal.add_lt_add (Hlt _ (finset.mem_cons_self _ _)) (IH (λ i hi, Hlt _ (finset.mem_cons.2 $ or.inr hi))) } end theorem exists_le_of_sum_le {s : finset α} (hs : s.nonempty) {f g : α → ℝ≥0∞} (Hle : ∑ i in s, f i ≤ ∑ i in s, g i) : ∃ i ∈ s, f i ≤ g i := begin contrapose! Hle, apply ennreal.sum_lt_sum_of_nonempty hs Hle, end end sum section interval variables {x y z : ℝ≥0∞} {ε ε₁ ε₂ : ℝ≥0∞} {s : set ℝ≥0∞} protected lemma Ico_eq_Iio : (Ico 0 y) = (Iio y) := Ico_bot lemma mem_Iio_self_add : x ≠ ∞ → ε ≠ 0 → x ∈ Iio (x + ε) := assume xt ε0, lt_add_right xt ε0 lemma mem_Ioo_self_sub_add : x ≠ ∞ → x ≠ 0 → ε₁ ≠ 0 → ε₂ ≠ 0 → x ∈ Ioo (x - ε₁) (x + ε₂) := assume xt x0 ε0 ε0', ⟨ennreal.sub_lt_self xt x0 ε0, lt_add_right xt ε0'⟩ end interval section bit @[simp] lemma bit0_inj : bit0 a = bit0 b ↔ a = b := ⟨λh, begin rcases (lt_trichotomy a b) with h₁| h₂| h₃, { exact (absurd h (ne_of_lt (add_lt_add h₁ h₁))) }, { exact h₂ }, { exact (absurd h.symm (ne_of_lt (add_lt_add h₃ h₃))) } end, λh, congr_arg _ h⟩ @[simp] lemma bit0_eq_zero_iff : bit0 a = 0 ↔ a = 0 := by simpa only [bit0_zero] using @bit0_inj a 0 @[simp] lemma bit0_eq_top_iff : bit0 a = ∞ ↔ a = ∞ := by rw [bit0, add_eq_top, or_self] @[simp] lemma bit1_inj : bit1 a = bit1 b ↔ a = b := ⟨λh, begin unfold bit1 at h, rwa [add_left_inj, bit0_inj] at h, simp [lt_top_iff_ne_top] end, λh, congr_arg _ h⟩ @[simp] lemma bit1_ne_zero : bit1 a ≠ 0 := by unfold bit1; simp @[simp] lemma bit1_eq_one_iff : bit1 a = 1 ↔ a = 0 := by simpa only [bit1_zero] using @bit1_inj a 0 @[simp] lemma bit1_eq_top_iff : bit1 a = ∞ ↔ a = ∞ := by unfold bit1; rw add_eq_top; simp end bit section inv noncomputable theory instance : has_inv ℝ≥0∞ := ⟨λa, Inf {b | 1 ≤ a * b}⟩ instance : div_inv_monoid ℝ≥0∞ := { inv := has_inv.inv, .. (infer_instance : monoid ℝ≥0∞) } @[simp] lemma inv_zero : (0 : ℝ≥0∞)⁻¹ = ∞ := show Inf {b : ℝ≥0∞ | 1 ≤ 0 * b} = ∞, by simp; refl @[simp] lemma inv_top : ∞⁻¹ = 0 := bot_unique $ le_of_forall_le_of_dense $ λ a (h : a > 0), Inf_le $ by simp [*, ne_of_gt h, top_mul] @[simp, norm_cast] lemma coe_inv (hr : r ≠ 0) : (↑r⁻¹ : ℝ≥0∞) = (↑r)⁻¹ := le_antisymm (le_Inf $ assume b (hb : 1 ≤ ↑r * b), coe_le_iff.2 $ by rintros b rfl; rwa [← coe_mul, ← coe_one, coe_le_coe, ← nnreal.inv_le hr] at hb) (Inf_le $ by simp; rw [← coe_mul, mul_inv_cancel hr]; exact le_refl 1) lemma coe_inv_le : (↑r⁻¹ : ℝ≥0∞) ≤ (↑r)⁻¹ := if hr : r = 0 then by simp only [hr, inv_zero, coe_zero, le_top] else by simp only [coe_inv hr, le_rfl] @[norm_cast] lemma coe_inv_two : ((2⁻¹ : ℝ≥0) : ℝ≥0∞) = 2⁻¹ := by rw [coe_inv (ne_of_gt _root_.zero_lt_two), coe_two] @[simp, norm_cast] lemma coe_div (hr : r ≠ 0) : (↑(p / r) : ℝ≥0∞) = p / r := by rw [div_eq_mul_inv, div_eq_mul_inv, coe_mul, coe_inv hr] lemma div_zero (h : a ≠ 0) : a / 0 = ∞ := by simp [div_eq_mul_inv, h] @[simp] lemma inv_one : (1 : ℝ≥0∞)⁻¹ = 1 := by simpa only [coe_inv one_ne_zero, coe_one] using coe_eq_coe.2 inv_one @[simp] lemma div_one {a : ℝ≥0∞} : a / 1 = a := by rw [div_eq_mul_inv, inv_one, mul_one] protected lemma inv_pow {n : ℕ} : (a^n)⁻¹ = (a⁻¹)^n := begin by_cases a = 0; cases a; cases n; simp [*, none_eq_top, some_eq_coe, zero_pow, top_pow, nat.zero_lt_succ] at *, rw [← coe_inv h, ← coe_pow, ← coe_inv (pow_ne_zero _ h), ← inv_pow₀, coe_pow] end instance : has_involutive_inv ℝ≥0∞ := { inv := has_inv.inv, inv_inv := λ a, by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe, -coe_inv, (coe_inv _).symm] at * } @[simp] lemma inv_eq_top : a⁻¹ = ∞ ↔ a = 0 := inv_zero ▸ inv_inj lemma inv_ne_top : a⁻¹ ≠ ∞ ↔ a ≠ 0 := by simp @[simp] lemma inv_lt_top {x : ℝ≥0∞} : x⁻¹ < ∞ ↔ 0 < x := by { simp only [lt_top_iff_ne_top, inv_ne_top, pos_iff_ne_zero] } lemma div_lt_top {x y : ℝ≥0∞} (h1 : x ≠ ∞) (h2 : y ≠ 0) : x / y < ∞ := mul_lt_top h1 (inv_ne_top.mpr h2) @[simp] lemma inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ := inv_top ▸ inv_inj lemma inv_ne_zero : a⁻¹ ≠ 0 ↔ a ≠ ∞ := by simp lemma mul_inv {a b : ℝ≥0∞} (ha : a ≠ 0 ∨ b ≠ ∞) (hb : a ≠ ∞ ∨ b ≠ 0) : (a * b)⁻¹ = a⁻¹ * b⁻¹ := begin induction b using with_top.rec_top_coe, { simp at ha, simp [ha], }, induction a using with_top.rec_top_coe, { simp at hb, simp [hb] }, by_cases h'a : a = 0, { simp only [h'a, with_top.top_mul, ennreal.inv_zero, ennreal.coe_ne_top, zero_mul, ne.def, not_false_iff, ennreal.coe_zero, ennreal.inv_eq_zero] }, by_cases h'b : b = 0, { simp only [h'b, ennreal.inv_zero, ennreal.coe_ne_top, with_top.mul_top, ne.def, not_false_iff, mul_zero, ennreal.coe_zero, ennreal.inv_eq_zero] }, rw [← ennreal.coe_mul, ← ennreal.coe_inv, ← ennreal.coe_inv h'a, ← ennreal.coe_inv h'b, ← ennreal.coe_mul, nnreal.mul_inv, mul_comm], simp [h'a, h'b], end @[simp] lemma inv_pos : 0 < a⁻¹ ↔ a ≠ ∞ := pos_iff_ne_zero.trans inv_ne_zero @[simp] lemma inv_lt_inv : a⁻¹ < b⁻¹ ↔ b < a := begin cases a; cases b; simp only [some_eq_coe, none_eq_top, inv_top], { simp only [lt_irrefl] }, { exact inv_pos.trans lt_top_iff_ne_top.symm }, { simp only [not_lt_zero, not_top_lt] }, { cases eq_or_lt_of_le (zero_le a) with ha ha, { subst a, simp }, cases eq_or_lt_of_le (zero_le b) with hb hb, { subst b, simp [pos_iff_ne_zero, lt_top_iff_ne_top, inv_ne_top] }, { rw [← coe_inv (ne_of_gt ha), ← coe_inv (ne_of_gt hb), coe_lt_coe, coe_lt_coe], simp only [nnreal.coe_lt_coe.symm] at *, exact inv_lt_inv ha hb } } end lemma inv_lt_iff_inv_lt : a⁻¹ < b ↔ b⁻¹ < a := by simpa only [inv_inv] using @inv_lt_inv a b⁻¹ lemma lt_inv_iff_lt_inv : a < b⁻¹ ↔ b < a⁻¹ := by simpa only [inv_inv] using @inv_lt_inv a⁻¹ b @[simp, priority 1100] -- higher than le_inv_iff_mul_le lemma inv_le_inv : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by simp only [le_iff_lt_or_eq, inv_lt_inv, inv_inj, eq_comm] lemma inv_le_iff_inv_le : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by simpa only [inv_inv] using @inv_le_inv a b⁻¹ lemma le_inv_iff_le_inv : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by simpa only [inv_inv] using @inv_le_inv a⁻¹ b @[simp] lemma inv_le_one : a⁻¹ ≤ 1 ↔ 1 ≤ a := inv_le_iff_inv_le.trans $ by rw inv_one lemma one_le_inv : 1 ≤ a⁻¹ ↔ a ≤ 1 := le_inv_iff_le_inv.trans $ by rw inv_one @[simp] lemma inv_lt_one : a⁻¹ < 1 ↔ 1 < a := inv_lt_iff_inv_lt.trans $ by rw [inv_one] /-- The inverse map `λ x, x⁻¹` is an order isomorphism between `ℝ≥0∞` and its `order_dual` -/ @[simps apply] def _root_.order_iso.inv_ennreal : ℝ≥0∞ ≃o ℝ≥0∞ᵒᵈ := { to_fun := λ x, x⁻¹, inv_fun := λ x, x⁻¹, map_rel_iff' := λ a b, ennreal.inv_le_inv, ..equiv.inv ℝ≥0∞ } @[simp] lemma _root_.order_iso.inv_ennreal_symm_apply : order_iso.inv_ennreal.symm a = a⁻¹ := rfl lemma pow_le_pow_of_le_one {n m : ℕ} (ha : a ≤ 1) (h : n ≤ m) : a ^ m ≤ a ^ n := begin rw [←inv_inv a, ← ennreal.inv_pow, ← @ennreal.inv_pow a⁻¹, inv_le_inv], exact pow_le_pow (one_le_inv.2 ha) h end @[simp] lemma div_top : a / ∞ = 0 := by rw [div_eq_mul_inv, inv_top, mul_zero] @[simp] lemma top_div_coe : ∞ / p = ∞ := by simp [div_eq_mul_inv, top_mul] lemma top_div_of_ne_top (h : a ≠ ∞) : ∞ / a = ∞ := by { lift a to ℝ≥0 using h, exact top_div_coe } lemma top_div_of_lt_top (h : a < ∞) : ∞ / a = ∞ := top_div_of_ne_top h.ne lemma top_div : ∞ / a = if a = ∞ then 0 else ∞ := by by_cases a = ∞; simp [top_div_of_ne_top, *] @[simp] lemma zero_div : 0 / a = 0 := zero_mul a⁻¹ lemma div_eq_top : a / b = ∞ ↔ (a ≠ 0 ∧ b = 0) ∨ (a = ∞ ∧ b ≠ ∞) := by simp [div_eq_mul_inv, ennreal.mul_eq_top] lemma le_div_iff_mul_le (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : a ≤ c / b ↔ a * b ≤ c := begin cases b, { simp at ht, split, { assume ha, simp at ha, simp [ha] }, { contrapose, assume ha, simp at ha, have : a * ∞ = ∞, by simp [ennreal.mul_eq_top, ha], simp [this, ht] } }, rcases eq_or_ne b 0 with (rfl | hb), { simp at h0, have : c / 0 = ∞, by simp [div_eq_top, h0], simp [this] }, { have : (b : ℝ≥0∞) ≠ 0, by simp [hb], rw [← ennreal.mul_le_mul_left this coe_ne_top], suffices : ↑b * a ≤ (↑b * ↑b⁻¹) * c ↔ a * ↑b ≤ c, { simpa [some_eq_coe, div_eq_mul_inv, hb, mul_left_comm, mul_comm, mul_assoc] }, rw [← coe_mul, mul_inv_cancel hb, coe_one, one_mul, mul_comm] }, end lemma div_le_iff_le_mul (hb0 : b ≠ 0 ∨ c ≠ ∞) (hbt : b ≠ ∞ ∨ c ≠ 0) : a / b ≤ c ↔ a ≤ c * b := begin suffices : a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹, by simpa [div_eq_mul_inv], refine (le_div_iff_mul_le _ _).symm; simpa end lemma lt_div_iff_mul_lt (hb0 : b ≠ 0 ∨ c ≠ ∞) (hbt : b ≠ ∞ ∨ c ≠ 0) : c < a / b ↔ c * b < a := lt_iff_lt_of_le_iff_le (div_le_iff_le_mul hb0 hbt) lemma div_le_of_le_mul (h : a ≤ b * c) : a / c ≤ b := begin by_cases h0 : c = 0, { have : a = 0, by simpa [h0] using h, simp [*] }, by_cases hinf : c = ∞, by simp [hinf], exact (div_le_iff_le_mul (or.inl h0) (or.inl hinf)).2 h end lemma div_le_of_le_mul' (h : a ≤ b * c) : a / b ≤ c := div_le_of_le_mul $ mul_comm b c ▸ h lemma mul_le_of_le_div (h : a ≤ b / c) : a * c ≤ b := begin rcases _root_.em (c = 0 ∧ b = 0 ∨ c = ∞ ∧ b = ∞) with (⟨rfl, rfl⟩|⟨rfl, rfl⟩)|H, { rw [mul_zero], exact le_rfl }, { exact le_top }, { simp only [not_or_distrib, not_and_distrib] at H, rwa ← le_div_iff_mul_le H.1 H.2 } end lemma mul_le_of_le_div' (h : a ≤ b / c) : c * a ≤ b := mul_comm a c ▸ mul_le_of_le_div h protected lemma div_lt_iff (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : c / b < a ↔ c < a * b := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le h0 ht lemma mul_lt_of_lt_div (h : a < b / c) : a * c < b := by { contrapose! h, exact ennreal.div_le_of_le_mul h } lemma mul_lt_of_lt_div' (h : a < b / c) : c * a < b := mul_comm a c ▸ mul_lt_of_lt_div h lemma inv_le_iff_le_mul : (b = ∞ → a ≠ 0) → (a = ∞ → b ≠ 0) → (a⁻¹ ≤ b ↔ 1 ≤ a * b) := begin cases a; cases b; simp [none_eq_top, some_eq_coe, mul_top, top_mul] {contextual := tt}, by_cases a = 0; simp [*, -coe_mul, coe_mul.symm, -coe_inv, (coe_inv _).symm, nnreal.inv_le] end @[simp] lemma le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 := begin cases b, { by_cases a = 0; simp [*, none_eq_top, mul_top] }, by_cases b = 0; simp [*, some_eq_coe, le_div_iff_mul_le], suffices : a ≤ 1 / b ↔ a * b ≤ 1, { simpa [div_eq_mul_inv, h] }, exact le_div_iff_mul_le (or.inl (mt coe_eq_coe.1 h)) (or.inl coe_ne_top) end lemma div_le_div {a b c d : ℝ≥0∞} (hab : a ≤ b) (hdc : d ≤ c) : a / c ≤ b / d := div_eq_mul_inv b d ▸ div_eq_mul_inv a c ▸ ennreal.mul_le_mul hab (ennreal.inv_le_inv.mpr hdc) lemma mul_inv_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a * a⁻¹ = 1 := begin lift a to ℝ≥0 using ht, norm_cast at *, exact mul_inv_cancel h0 end lemma inv_mul_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a⁻¹ * a = 1 := mul_comm a a⁻¹ ▸ mul_inv_cancel h0 ht lemma eq_inv_of_mul_eq_one_left (h : a * b = 1) : a = b⁻¹ := begin rcases eq_or_ne b ∞ with rfl|hb, { have : false, by simpa [left_ne_zero_of_mul_eq_one h] using h, exact this.elim }, { rw [← mul_one a, ← mul_inv_cancel (right_ne_zero_of_mul_eq_one h) hb, ← mul_assoc, h, one_mul] } end lemma mul_le_iff_le_inv {a b r : ℝ≥0∞} (hr₀ : r ≠ 0) (hr₁ : r ≠ ∞) : (r * a ≤ b ↔ a ≤ r⁻¹ * b) := by rw [← @ennreal.mul_le_mul_left _ a _ hr₀ hr₁, ← mul_assoc, mul_inv_cancel hr₀ hr₁, one_mul] lemma le_of_forall_nnreal_lt {x y : ℝ≥0∞} (h : ∀ r : ℝ≥0, ↑r < x → ↑r ≤ y) : x ≤ y := begin refine le_of_forall_ge_of_dense (λ r hr, _), lift r to ℝ≥0 using ne_top_of_lt hr, exact h r hr end lemma le_of_forall_pos_nnreal_lt {x y : ℝ≥0∞} (h : ∀ r : ℝ≥0, 0 < r → ↑r < x → ↑r ≤ y) : x ≤ y := le_of_forall_nnreal_lt $ λ r hr, (zero_le r).eq_or_lt.elim (λ h, h ▸ zero_le _) (λ h0, h r h0 hr) lemma eq_top_of_forall_nnreal_le {x : ℝ≥0∞} (h : ∀ r : ℝ≥0, ↑r ≤ x) : x = ∞ := top_unique $ le_of_forall_nnreal_lt $ λ r hr, h r lemma add_div : (a + b) / c = a / c + b / c := right_distrib a b (c⁻¹) lemma div_add_div_same {a b c : ℝ≥0∞} : a / c + b / c = (a + b) / c := add_div.symm lemma div_self (h0 : a ≠ 0) (hI : a ≠ ∞) : a / a = 1 := mul_inv_cancel h0 hI -- *TODO* this should surely be called div_mul_cancel? lemma mul_div_cancel (h0 : a ≠ 0) (hI : a ≠ ∞) : (b / a) * a = b := by rw [div_eq_mul_inv, mul_assoc, inv_mul_cancel h0 hI, mul_one] lemma mul_div_cancel' (h0 : a ≠ 0) (hI : a ≠ ∞) : a * (b / a) = b := by rw [mul_comm, mul_div_cancel h0 hI] lemma mul_div_le : a * (b / a) ≤ b := begin by_cases h0 : a = 0, { simp [h0] }, by_cases hI : a = ∞, { simp [hI] }, rw mul_div_cancel' h0 hI, exact le_refl b end lemma inv_two_add_inv_two : (2:ℝ≥0∞)⁻¹ + 2⁻¹ = 1 := by rw [← two_mul, ← div_eq_mul_inv, div_self two_ne_zero two_ne_top] lemma inv_three_add_inv_three : (3 : ℝ≥0∞)⁻¹ + 3⁻¹ +3⁻¹ = 1 := begin rw [show (3 : ℝ≥0∞)⁻¹ + 3⁻¹ + 3⁻¹ = 3 * 3⁻¹, by ring, ← div_eq_mul_inv, ennreal.div_self]; simp, end @[simp] lemma add_halves (a : ℝ≥0∞) : a / 2 + a / 2 = a := by rw [div_eq_mul_inv, ← mul_add, inv_two_add_inv_two, mul_one] @[simp] lemma add_thirds (a : ℝ≥0∞) : a / 3 + a / 3 + a / 3 = a := by rw [div_eq_mul_inv, ← mul_add, ← mul_add, inv_three_add_inv_three, mul_one] @[simp] lemma div_zero_iff : a / b = 0 ↔ a = 0 ∨ b = ∞ := by simp [div_eq_mul_inv] @[simp] lemma div_pos_iff : 0 < a / b ↔ a ≠ 0 ∧ b ≠ ∞ := by simp [pos_iff_ne_zero, not_or_distrib] lemma half_pos {a : ℝ≥0∞} (h : a ≠ 0) : 0 < a / 2 := by simp [h] lemma one_half_lt_one : (2⁻¹:ℝ≥0∞) < 1 := inv_lt_one.2 $ one_lt_two lemma half_lt_self {a : ℝ≥0∞} (hz : a ≠ 0) (ht : a ≠ ∞) : a / 2 < a := begin lift a to ℝ≥0 using ht, have h : (2 : ℝ≥0∞) = ((2 : ℝ≥0) : ℝ≥0∞), from rfl, have h' : (2 : ℝ≥0) ≠ 0, from _root_.two_ne_zero', rw [h, ← coe_div h', coe_lt_coe], -- `norm_cast` fails to apply `coe_div` norm_cast at hz, exact nnreal.half_lt_self hz end lemma half_le_self : a / 2 ≤ a := le_add_self.trans_eq (add_halves _) lemma sub_half (h : a ≠ ∞) : a - a / 2 = a / 2 := begin lift a to ℝ≥0 using h, exact sub_eq_of_add_eq (mul_ne_top coe_ne_top $ by simp) (add_halves a) end @[simp] lemma one_sub_inv_two : (1:ℝ≥0∞) - 2⁻¹ = 2⁻¹ := by simpa only [div_eq_mul_inv, one_mul] using sub_half one_ne_top lemma exists_inv_nat_lt {a : ℝ≥0∞} (h : a ≠ 0) : ∃n:ℕ, (n:ℝ≥0∞)⁻¹ < a := inv_inv a ▸ by simp only [inv_lt_inv, ennreal.exists_nat_gt (inv_ne_top.2 h)] lemma exists_nat_pos_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n > 0, b < (n : ℕ) * a := begin have : b / a ≠ ∞, from mul_ne_top hb (inv_ne_top.2 ha), refine (ennreal.exists_nat_gt this).imp (λ n hn, _), have : 0 < (n : ℝ≥0∞), from (zero_le _).trans_lt hn, refine ⟨coe_nat_lt_coe_nat.1 this, _⟩, rwa [← ennreal.div_lt_iff (or.inl ha) (or.inr hb)] end lemma exists_nat_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n : ℕ, b < n * a := (exists_nat_pos_mul_gt ha hb).imp $ λ n, Exists.snd lemma exists_nat_pos_inv_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ((n : ℕ) : ℝ≥0∞)⁻¹ * a < b := begin rcases exists_nat_pos_mul_gt hb ha with ⟨n, npos, hn⟩, have : (n : ℝ≥0∞) ≠ 0 := nat.cast_ne_zero.2 npos.lt.ne', use [n, npos], rwa [← one_mul b, ← inv_mul_cancel this coe_nat_ne_top, mul_assoc, mul_lt_mul_left (inv_ne_zero.2 coe_nat_ne_top) (inv_ne_top.2 this)] end lemma exists_nnreal_pos_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ↑(n : ℝ≥0) * a < b := begin rcases exists_nat_pos_inv_mul_lt ha hb with ⟨n, npos : 0 < n, hn⟩, use (n : ℝ≥0)⁻¹, simp [*, npos.ne', zero_lt_one] end lemma exists_inv_two_pow_lt (ha : a ≠ 0) : ∃ n : ℕ, 2⁻¹ ^ n < a := begin rcases exists_inv_nat_lt ha with ⟨n, hn⟩, simp only [← ennreal.inv_pow], refine ⟨n, lt_trans (inv_lt_inv.2 _) hn⟩, norm_cast, exact n.lt_two_pow end @[simp, norm_cast] lemma coe_zpow (hr : r ≠ 0) (n : ℤ) : (↑(r^n) : ℝ≥0∞) = r^n := begin cases n, { simp only [int.of_nat_eq_coe, coe_pow, zpow_coe_nat] }, { have : r ^ n.succ ≠ 0 := pow_ne_zero (n+1) hr, simp only [zpow_neg_succ_of_nat, coe_inv this, coe_pow] } end lemma zpow_pos (ha : a ≠ 0) (h'a : a ≠ ∞) (n : ℤ) : 0 < a ^ n := begin cases n, { exact ennreal.pow_pos ha.bot_lt n }, { simp only [h'a, pow_eq_top_iff, zpow_neg_succ_of_nat, ne.def, not_false_iff, inv_pos, false_and] } end lemma zpow_lt_top (ha : a ≠ 0) (h'a : a ≠ ∞) (n : ℤ) : a ^ n < ∞ := begin cases n, { exact ennreal.pow_lt_top h'a.lt_top _ }, { simp only [ennreal.pow_pos ha.bot_lt (n + 1), zpow_neg_succ_of_nat, inv_lt_top] } end lemma exists_mem_Ico_zpow {x y : ℝ≥0∞} (hx : x ≠ 0) (h'x : x ≠ ∞) (hy : 1 < y) (h'y : y ≠ ⊤) : ∃ n : ℤ, x ∈ Ico (y ^ n) (y ^ (n + 1)) := begin lift x to ℝ≥0 using h'x, lift y to ℝ≥0 using h'y, have A : y ≠ 0, by simpa only [ne.def, coe_eq_zero] using (ennreal.zero_lt_one.trans hy).ne', obtain ⟨n, hn, h'n⟩ : ∃ n : ℤ, y ^ n ≤ x ∧ x < y ^ (n + 1), { refine nnreal.exists_mem_Ico_zpow _ (one_lt_coe_iff.1 hy), simpa only [ne.def, coe_eq_zero] using hx }, refine ⟨n, _, _⟩, { rwa [← ennreal.coe_zpow A, ennreal.coe_le_coe] }, { rwa [← ennreal.coe_zpow A, ennreal.coe_lt_coe] } end lemma exists_mem_Ioc_zpow {x y : ℝ≥0∞} (hx : x ≠ 0) (h'x : x ≠ ∞) (hy : 1 < y) (h'y : y ≠ ⊤) : ∃ n : ℤ, x ∈ Ioc (y ^ n) (y ^ (n + 1)) := begin lift x to ℝ≥0 using h'x, lift y to ℝ≥0 using h'y, have A : y ≠ 0, by simpa only [ne.def, coe_eq_zero] using (ennreal.zero_lt_one.trans hy).ne', obtain ⟨n, hn, h'n⟩ : ∃ n : ℤ, y ^ n < x ∧ x ≤ y ^ (n + 1), { refine nnreal.exists_mem_Ioc_zpow _ (one_lt_coe_iff.1 hy), simpa only [ne.def, coe_eq_zero] using hx }, refine ⟨n, _, _⟩, { rwa [← ennreal.coe_zpow A, ennreal.coe_lt_coe] }, { rwa [← ennreal.coe_zpow A, ennreal.coe_le_coe] } end lemma Ioo_zero_top_eq_Union_Ico_zpow {y : ℝ≥0∞} (hy : 1 < y) (h'y : y ≠ ⊤) : Ioo (0 : ℝ≥0∞) (∞ : ℝ≥0∞) = ⋃ (n : ℤ), Ico (y^n) (y^(n+1)) := begin ext x, simp only [mem_Union, mem_Ioo, mem_Ico], split, { rintros ⟨hx, h'x⟩, exact exists_mem_Ico_zpow hx.ne' h'x.ne hy h'y }, { rintros ⟨n, hn, h'n⟩, split, { apply lt_of_lt_of_le _ hn, exact ennreal.zpow_pos (ennreal.zero_lt_one.trans hy).ne' h'y _ }, { apply lt_trans h'n _, exact ennreal.zpow_lt_top (ennreal.zero_lt_one.trans hy).ne' h'y _ } } end lemma zpow_le_of_le {x : ℝ≥0∞} (hx : 1 ≤ x) {a b : ℤ} (h : a ≤ b) : x ^ a ≤ x ^ b := begin induction a with a a; induction b with b b, { simp only [int.of_nat_eq_coe, zpow_coe_nat], apply pow_le_pow hx (int.le_of_coe_nat_le_coe_nat h), }, { apply absurd h (not_le_of_gt _), exact lt_of_lt_of_le (int.neg_succ_lt_zero _) (int.of_nat_nonneg _) }, { simp only [zpow_neg_succ_of_nat, int.of_nat_eq_coe, zpow_coe_nat], refine le_trans (inv_le_one.2 _) _; apply ennreal.one_le_pow_of_one_le hx, }, { simp only [zpow_neg_succ_of_nat], apply inv_le_inv.2, { apply pow_le_pow hx, have : -(↑(a+1) : ℤ) ≤ -(↑(b+1) : ℤ), from h, have h' := le_of_neg_le_neg this, apply int.le_of_coe_nat_le_coe_nat h' }, repeat { apply pow_pos (lt_of_lt_of_le zero_lt_one hx) } } end lemma monotone_zpow {x : ℝ≥0∞} (hx : 1 ≤ x) : monotone ((^) x : ℤ → ℝ≥0∞) := λ a b h, zpow_le_of_le hx h lemma zpow_add {x : ℝ≥0∞} (hx : x ≠ 0) (h'x : x ≠ ∞) (m n : ℤ) : x ^ (m + n) = x ^ m * x ^ n := begin lift x to ℝ≥0 using h'x, replace hx : x ≠ 0, by simpa only [ne.def, coe_eq_zero] using hx, simp only [← coe_zpow hx, zpow_add₀ hx, coe_mul] end end inv section real lemma to_real_add (ha : a ≠ ∞) (hb : b ≠ ∞) : (a+b).to_real = a.to_real + b.to_real := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, refl end lemma to_real_sub_of_le {a b : ℝ≥0∞} (h : b ≤ a) (ha : a ≠ ∞): (a - b).to_real = a.to_real - b.to_real := begin lift b to ℝ≥0 using ne_top_of_le_ne_top ha h, lift a to ℝ≥0 using ha, simp only [← ennreal.coe_sub, ennreal.coe_to_real, nnreal.coe_sub (ennreal.coe_le_coe.mp h)], end lemma le_to_real_sub {a b : ℝ≥0∞} (hb : b ≠ ∞) : a.to_real - b.to_real ≤ (a - b).to_real := begin lift b to ℝ≥0 using hb, cases a, { simp }, { simp only [some_eq_coe, ←coe_sub, nnreal.sub_def, real.coe_to_nnreal', coe_to_real], exact le_max_left _ _ } end lemma to_real_add_le : (a+b).to_real ≤ a.to_real + b.to_real := if ha : a = ∞ then by simp only [ha, top_add, top_to_real, zero_add, to_real_nonneg] else if hb : b = ∞ then by simp only [hb, add_top, top_to_real, add_zero, to_real_nonneg] else le_of_eq (to_real_add ha hb) lemma of_real_add {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) : ennreal.of_real (p + q) = ennreal.of_real p + ennreal.of_real q := by rw [ennreal.of_real, ennreal.of_real, ennreal.of_real, ← coe_add, coe_eq_coe, real.to_nnreal_add hp hq] lemma of_real_add_le {p q : ℝ} : ennreal.of_real (p + q) ≤ ennreal.of_real p + ennreal.of_real q := coe_le_coe.2 real.to_nnreal_add_le @[simp] lemma to_real_le_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real ≤ b.to_real ↔ a ≤ b := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, norm_cast end lemma to_real_mono (hb : b ≠ ∞) (h : a ≤ b) : a.to_real ≤ b.to_real := (to_real_le_to_real (h.trans_lt (lt_top_iff_ne_top.2 hb)).ne hb).2 h @[simp] lemma to_real_lt_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real < b.to_real ↔ a < b := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, norm_cast end lemma to_real_strict_mono (hb : b ≠ ∞) (h : a < b) : a.to_real < b.to_real := (to_real_lt_to_real (h.trans (lt_top_iff_ne_top.2 hb)).ne hb).2 h lemma to_nnreal_mono (hb : b ≠ ∞) (h : a ≤ b) : a.to_nnreal ≤ b.to_nnreal := by simpa [←ennreal.coe_le_coe, hb, (h.trans_lt hb.lt_top).ne] @[simp] lemma to_nnreal_le_to_nnreal (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_nnreal ≤ b.to_nnreal ↔ a ≤ b := begin refine ⟨_, to_nnreal_mono hb⟩, { intro h, have key := ennreal.coe_le_coe.mpr h, rwa [coe_to_nnreal ha, coe_to_nnreal hb] at key, }, end lemma to_nnreal_strict_mono (hb : b ≠ ∞) (h : a < b) : a.to_nnreal < b.to_nnreal := by simpa [←ennreal.coe_lt_coe, hb, (h.trans hb.lt_top).ne] @[simp] lemma to_nnreal_lt_to_nnreal (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_nnreal < b.to_nnreal ↔ a < b := begin refine ⟨_, to_nnreal_strict_mono hb⟩, { intro h, have key := ennreal.coe_lt_coe.mpr h, rwa [coe_to_nnreal ha, coe_to_nnreal hb] at key, }, end lemma to_real_max (hr : a ≠ ∞) (hp : b ≠ ∞) : ennreal.to_real (max a b) = max (ennreal.to_real a) (ennreal.to_real b) := (le_total a b).elim (λ h, by simp only [h, (ennreal.to_real_le_to_real hr hp).2 h, max_eq_right]) (λ h, by simp only [h, (ennreal.to_real_le_to_real hp hr).2 h, max_eq_left]) lemma to_nnreal_pos_iff : 0 < a.to_nnreal ↔ (0 < a ∧ a < ∞) := begin cases a, { simp [none_eq_top] }, { simp [some_eq_coe] } end lemma to_nnreal_pos {a : ℝ≥0∞} (ha₀ : a ≠ 0) (ha_top : a ≠ ∞) : 0 < a.to_nnreal := to_nnreal_pos_iff.mpr ⟨bot_lt_iff_ne_bot.mpr ha₀, lt_top_iff_ne_top.mpr ha_top⟩ lemma to_real_pos_iff : 0 < a.to_real ↔ (0 < a ∧ a < ∞):= (nnreal.coe_pos).trans to_nnreal_pos_iff lemma to_real_pos {a : ℝ≥0∞} (ha₀ : a ≠ 0) (ha_top : a ≠ ∞) : 0 < a.to_real := to_real_pos_iff.mpr ⟨bot_lt_iff_ne_bot.mpr ha₀, lt_top_iff_ne_top.mpr ha_top⟩ lemma of_real_le_of_real {p q : ℝ} (h : p ≤ q) : ennreal.of_real p ≤ ennreal.of_real q := by simp [ennreal.of_real, real.to_nnreal_le_to_nnreal h] lemma of_real_le_of_le_to_real {a : ℝ} {b : ℝ≥0∞} (h : a ≤ ennreal.to_real b) : ennreal.of_real a ≤ b := (of_real_le_of_real h).trans of_real_to_real_le @[simp] lemma of_real_le_of_real_iff {p q : ℝ} (h : 0 ≤ q) : ennreal.of_real p ≤ ennreal.of_real q ↔ p ≤ q := by rw [ennreal.of_real, ennreal.of_real, coe_le_coe, real.to_nnreal_le_to_nnreal_iff h] @[simp] lemma of_real_lt_of_real_iff {p q : ℝ} (h : 0 < q) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, real.to_nnreal_lt_to_nnreal_iff h] lemma of_real_lt_of_real_iff_of_nonneg {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, real.to_nnreal_lt_to_nnreal_iff_of_nonneg hp] @[simp] lemma of_real_pos {p : ℝ} : 0 < ennreal.of_real p ↔ 0 < p := by simp [ennreal.of_real] @[simp] lemma of_real_eq_zero {p : ℝ} : ennreal.of_real p = 0 ↔ p ≤ 0 := by simp [ennreal.of_real] @[simp] lemma zero_eq_of_real {p : ℝ} : 0 = ennreal.of_real p ↔ p ≤ 0 := eq_comm.trans of_real_eq_zero alias ennreal.of_real_eq_zero ↔ _ ennreal.of_real_of_nonpos lemma of_real_sub (p : ℝ) (hq : 0 ≤ q) : ennreal.of_real (p - q) = ennreal.of_real p - ennreal.of_real q := begin obtain h | h := le_total p q, { rw [of_real_of_nonpos (sub_nonpos_of_le h), tsub_eq_zero_of_le (of_real_le_of_real h)] }, refine ennreal.eq_sub_of_add_eq of_real_ne_top _, rw [←of_real_add (sub_nonneg_of_le h) hq, sub_add_cancel], end lemma of_real_le_iff_le_to_real {a : ℝ} {b : ℝ≥0∞} (hb : b ≠ ∞) : ennreal.of_real a ≤ b ↔ a ≤ ennreal.to_real b := begin lift b to ℝ≥0 using hb, simpa [ennreal.of_real, ennreal.to_real] using real.to_nnreal_le_iff_le_coe end lemma of_real_lt_iff_lt_to_real {a : ℝ} {b : ℝ≥0∞} (ha : 0 ≤ a) (hb : b ≠ ∞) : ennreal.of_real a < b ↔ a < ennreal.to_real b := begin lift b to ℝ≥0 using hb, simpa [ennreal.of_real, ennreal.to_real] using real.to_nnreal_lt_iff_lt_coe ha end lemma le_of_real_iff_to_real_le {a : ℝ≥0∞} {b : ℝ} (ha : a ≠ ∞) (hb : 0 ≤ b) : a ≤ ennreal.of_real b ↔ ennreal.to_real a ≤ b := begin lift a to ℝ≥0 using ha, simpa [ennreal.of_real, ennreal.to_real] using real.le_to_nnreal_iff_coe_le hb end lemma to_real_le_of_le_of_real {a : ℝ≥0∞} {b : ℝ} (hb : 0 ≤ b) (h : a ≤ ennreal.of_real b) : ennreal.to_real a ≤ b := have ha : a ≠ ∞, from ne_top_of_le_ne_top of_real_ne_top h, (le_of_real_iff_to_real_le ha hb).1 h lemma lt_of_real_iff_to_real_lt {a : ℝ≥0∞} {b : ℝ} (ha : a ≠ ∞) : a < ennreal.of_real b ↔ ennreal.to_real a < b := begin lift a to ℝ≥0 using ha, simpa [ennreal.of_real, ennreal.to_real] using real.lt_to_nnreal_iff_coe_lt end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real (p * q) = (ennreal.of_real p) * (ennreal.of_real q) := by { simp only [ennreal.of_real, coe_mul.symm, coe_eq_coe], exact real.to_nnreal_mul hp } lemma of_real_pow {p : ℝ} (hp : 0 ≤ p) (n : ℕ) : ennreal.of_real (p ^ n) = ennreal.of_real p ^ n := by rw [of_real_eq_coe_nnreal hp, ← coe_pow, ← of_real_coe_nnreal, nnreal.coe_pow, nnreal.coe_mk] lemma of_real_inv_of_pos {x : ℝ} (hx : 0 < x) : (ennreal.of_real x)⁻¹ = ennreal.of_real x⁻¹ := by rw [ennreal.of_real, ennreal.of_real, ←@coe_inv (real.to_nnreal x) (by simp [hx]), coe_eq_coe, real.to_nnreal_inv.symm] lemma of_real_div_of_pos {x y : ℝ} (hy : 0 < y) : ennreal.of_real (x / y) = ennreal.of_real x / ennreal.of_real y := by rw [div_eq_inv_mul, div_eq_mul_inv, of_real_mul (inv_nonneg.2 hy.le), of_real_inv_of_pos hy, mul_comm] lemma to_real_of_real_mul (c : ℝ) (a : ℝ≥0∞) (h : 0 ≤ c) : ennreal.to_real ((ennreal.of_real c) * a) = c * ennreal.to_real a := begin cases a, { simp only [none_eq_top, ennreal.to_real, top_to_nnreal, nnreal.coe_zero, mul_zero, mul_top], by_cases h' : c ≤ 0, { rw [if_pos], { simp }, { convert of_real_zero, exact le_antisymm h' h } }, { rw [if_neg], refl, rw [of_real_eq_zero], assumption } }, { simp only [ennreal.to_real, ennreal.to_nnreal], simp only [some_eq_coe, ennreal.of_real, coe_mul.symm, to_nnreal_coe, nnreal.coe_mul], congr, apply real.coe_to_nnreal, exact h } end @[simp] lemma to_nnreal_mul_top (a : ℝ≥0∞) : ennreal.to_nnreal (a * ∞) = 0 := begin by_cases h : a = 0, { rw [h, zero_mul, zero_to_nnreal] }, { rw [mul_top, if_neg h, top_to_nnreal] } end @[simp] lemma to_nnreal_top_mul (a : ℝ≥0∞) : ennreal.to_nnreal (∞ * a) = 0 := by rw [mul_comm, to_nnreal_mul_top] @[simp] lemma to_real_mul_top (a : ℝ≥0∞) : ennreal.to_real (a * ∞) = 0 := by rw [ennreal.to_real, to_nnreal_mul_top, nnreal.coe_zero] @[simp] lemma to_real_top_mul (a : ℝ≥0∞) : ennreal.to_real (∞ * a) = 0 := by { rw mul_comm, exact to_real_mul_top _ } lemma to_real_eq_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : ennreal.to_real a = ennreal.to_real b ↔ a = b := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, simp only [coe_eq_coe, nnreal.coe_eq, coe_to_real], end lemma to_real_smul (r : ℝ≥0) (s : ℝ≥0∞) : (r • s).to_real = r • s.to_real := begin induction s using with_top.rec_top_coe, { rw [show r • ∞ = (r : ℝ≥0∞) * ∞, by refl], simp only [ennreal.to_real_mul_top, ennreal.top_to_real, smul_zero] }, { rw [← coe_smul, ennreal.coe_to_real, ennreal.coe_to_real], refl } end protected lemma trichotomy (p : ℝ≥0∞) : p = 0 ∨ p = ∞ ∨ 0 < p.to_real := begin rcases eq_or_lt_of_le (bot_le : 0 ≤ p) with (rfl : 0 = p) | (hp : 0 < p), { simp }, rcases eq_or_lt_of_le (le_top : p ≤ ⊤) with rfl | hp', { simp }, simp [ennreal.to_real_pos_iff, hp, hp'], end protected lemma trichotomy₂ {p q : ℝ≥0∞} (hpq : p ≤ q) : (p = 0 ∧ q = 0) ∨ (p = 0 ∧ q = ∞) ∨ (p = 0 ∧ 0 < q.to_real) ∨ (p = ∞ ∧ q = ∞) ∨ (0 < p.to_real ∧ q = ∞) ∨ (0 < p.to_real ∧ 0 < q.to_real ∧ p.to_real ≤ q.to_real) := begin rcases eq_or_lt_of_le (bot_le : 0 ≤ p) with (rfl : 0 = p) | (hp : 0 < p), { simpa using q.trichotomy }, rcases eq_or_lt_of_le (le_top : q ≤ ∞) with rfl | hq, { simpa using p.trichotomy }, repeat { right }, have hq' : 0 < q := lt_of_lt_of_le hp hpq, have hp' : p < ∞ := lt_of_le_of_lt hpq hq, simp [ennreal.to_real_le_to_real hp'.ne hq.ne, ennreal.to_real_pos_iff, hpq, hp, hp', hq', hq], end protected lemma dichotomy (p : ℝ≥0∞) [fact (1 ≤ p)] : p = ∞ ∨ 1 ≤ p.to_real := begin have : p = ⊤ ∨ 0 < p.to_real ∧ 1 ≤ p.to_real, { simpa using ennreal.trichotomy₂ (fact.out _ : 1 ≤ p) }, exact this.imp_right (λ h, h.2) end /-- `ennreal.to_nnreal` as a `monoid_hom`. -/ def to_nnreal_hom : ℝ≥0∞ →* ℝ≥0 := { to_fun := ennreal.to_nnreal, map_one' := to_nnreal_coe, map_mul' := by rintro (_|x) (_|y); simp only [← coe_mul, none_eq_top, some_eq_coe, to_nnreal_top_mul, to_nnreal_mul_top, top_to_nnreal, mul_zero, zero_mul, to_nnreal_coe] } lemma to_nnreal_mul {a b : ℝ≥0∞}: (a * b).to_nnreal = a.to_nnreal * b.to_nnreal := to_nnreal_hom.map_mul a b lemma to_nnreal_pow (a : ℝ≥0∞) (n : ℕ) : (a ^ n).to_nnreal = a.to_nnreal ^ n := to_nnreal_hom.map_pow a n lemma to_nnreal_prod {ι : Type*} {s : finset ι} {f : ι → ℝ≥0∞} : (∏ i in s, f i).to_nnreal = ∏ i in s, (f i).to_nnreal := to_nnreal_hom.map_prod _ _ lemma to_nnreal_inv (a : ℝ≥0∞) : (a⁻¹).to_nnreal = (a.to_nnreal)⁻¹ := begin rcases eq_or_ne a ∞ with rfl|ha, { simp }, lift a to ℝ≥0 using ha, rcases eq_or_ne a 0 with rfl|ha, { simp }, rw [← coe_inv ha, to_nnreal_coe, to_nnreal_coe] end lemma to_nnreal_div (a b : ℝ≥0∞) : (a / b).to_nnreal = a.to_nnreal / b.to_nnreal := by rw [div_eq_mul_inv, to_nnreal_mul, to_nnreal_inv, div_eq_mul_inv] /-- `ennreal.to_real` as a `monoid_hom`. -/ def to_real_hom : ℝ≥0∞ →* ℝ := (nnreal.to_real_hom : ℝ≥0 →* ℝ).comp to_nnreal_hom lemma to_real_mul : (a * b).to_real = a.to_real * b.to_real := to_real_hom.map_mul a b lemma to_real_pow (a : ℝ≥0∞) (n : ℕ) : (a ^ n).to_real = a.to_real ^ n := to_real_hom.map_pow a n lemma to_real_prod {ι : Type*} {s : finset ι} {f : ι → ℝ≥0∞} : (∏ i in s, f i).to_real = ∏ i in s, (f i).to_real := to_real_hom.map_prod _ _ lemma to_real_inv (a : ℝ≥0∞) : (a⁻¹).to_real = (a.to_real)⁻¹ := by { simp_rw ennreal.to_real, norm_cast, exact to_nnreal_inv a, } lemma to_real_div (a b : ℝ≥0∞) : (a / b).to_real = a.to_real / b.to_real := by rw [div_eq_mul_inv, to_real_mul, to_real_inv, div_eq_mul_inv] lemma of_real_prod_of_nonneg {s : finset α} {f : α → ℝ} (hf : ∀ i, i ∈ s → 0 ≤ f i) : ennreal.of_real (∏ i in s, f i) = ∏ i in s, ennreal.of_real (f i) := begin simp_rw [ennreal.of_real, ←coe_finset_prod, coe_eq_coe], exact real.to_nnreal_prod_of_nonneg hf, end @[simp] lemma to_nnreal_bit0 {x : ℝ≥0∞} : (bit0 x).to_nnreal = bit0 (x.to_nnreal) := begin by_cases hx_top : x = ∞, { simp [hx_top, bit0_eq_top_iff.mpr rfl], }, exact to_nnreal_add hx_top hx_top, end @[simp] lemma to_nnreal_bit1 {x : ℝ≥0∞} (hx_top : x ≠ ∞) : (bit1 x).to_nnreal = bit1 (x.to_nnreal) := by simp [bit1, bit1, to_nnreal_add (by rwa [ne.def, bit0_eq_top_iff]) ennreal.one_ne_top] @[simp] lemma to_real_bit0 {x : ℝ≥0∞} : (bit0 x).to_real = bit0 (x.to_real) := by simp [ennreal.to_real] @[simp] lemma to_real_bit1 {x : ℝ≥0∞} (hx_top : x ≠ ∞) : (bit1 x).to_real = bit1 (x.to_real) := by simp [ennreal.to_real, hx_top] @[simp] lemma of_real_bit0 {r : ℝ} (hr : 0 ≤ r) : ennreal.of_real (bit0 r) = bit0 (ennreal.of_real r) := of_real_add hr hr @[simp] lemma of_real_bit1 {r : ℝ} (hr : 0 ≤ r) : ennreal.of_real (bit1 r) = bit1 (ennreal.of_real r) := (of_real_add (by simp [hr]) zero_le_one).trans (by simp [real.to_nnreal_one, bit1, hr]) end real section infi variables {ι : Sort*} {f g : ι → ℝ≥0∞} lemma infi_add : infi f + a = ⨅i, f i + a := le_antisymm (le_infi $ assume i, add_le_add (infi_le _ _) $ le_rfl) (tsub_le_iff_right.1 $ le_infi $ assume i, tsub_le_iff_right.2 $ infi_le _ _) lemma supr_sub : (⨆i, f i) - a = (⨆i, f i - a) := le_antisymm (tsub_le_iff_right.2 $ supr_le $ assume i, tsub_le_iff_right.1 $ le_supr _ i) (supr_le $ assume i, tsub_le_tsub (le_supr _ _) (le_refl a)) lemma sub_infi : a - (⨅i, f i) = (⨆i, a - f i) := begin refine (eq_of_forall_ge_iff $ λ c, _), rw [tsub_le_iff_right, add_comm, infi_add], simp [tsub_le_iff_right, sub_eq_add_neg, add_comm], end lemma Inf_add {s : set ℝ≥0∞} : Inf s + a = ⨅b∈s, b + a := by simp [Inf_eq_infi, infi_add] lemma add_infi {a : ℝ≥0∞} : a + infi f = ⨅b, a + f b := by rw [add_comm, infi_add]; simp [add_comm] lemma infi_add_infi (h : ∀i j, ∃k, f k + g k ≤ f i + g j) : infi f + infi g = (⨅a, f a + g a) := suffices (⨅a, f a + g a) ≤ infi f + infi g, from le_antisymm (le_infi $ assume a, add_le_add (infi_le _ _) (infi_le _ _)) this, calc (⨅a, f a + g a) ≤ (⨅ a a', f a + g a') : le_infi $ assume a, le_infi $ assume a', let ⟨k, h⟩ := h a a' in infi_le_of_le k h ... = infi f + infi g : by simp [add_infi, infi_add] lemma infi_sum {f : ι → α → ℝ≥0∞} {s : finset α} [nonempty ι] (h : ∀(t : finset α) (i j : ι), ∃k, ∀a∈t, f k a ≤ f i a ∧ f k a ≤ f j a) : (⨅i, ∑ a in s, f i a) = ∑ a in s, ⨅i, f i a := finset.induction_on s (by simp) $ assume a s ha ih, have ∀ (i j : ι), ∃ (k : ι), f k a + ∑ b in s, f k b ≤ f i a + ∑ b in s, f j b, from assume i j, let ⟨k, hk⟩ := h (insert a s) i j in ⟨k, add_le_add (hk a (finset.mem_insert_self _ _)).left $ finset.sum_le_sum $ assume a ha, (hk _ $ finset.mem_insert_of_mem ha).right⟩, by simp [ha, ih.symm, infi_add_infi this] /-- If `x ≠ 0` and `x ≠ ∞`, then right multiplication by `x` maps infimum to infimum. See also `ennreal.infi_mul` that assumes `[nonempty ι]` but does not require `x ≠ 0`. -/ lemma infi_mul_of_ne {ι} {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h0 : x ≠ 0) (h : x ≠ ∞) : infi f * x = ⨅ i, f i * x := le_antisymm mul_right_mono.map_infi_le ((div_le_iff_le_mul (or.inl h0) $ or.inl h).mp $ le_infi $ λ i, (div_le_iff_le_mul (or.inl h0) $ or.inl h).mpr $ infi_le _ _) /-- If `x ≠ ∞`, then right multiplication by `x` maps infimum over a nonempty type to infimum. See also `ennreal.infi_mul_of_ne` that assumes `x ≠ 0` but does not require `[nonempty ι]`. -/ lemma infi_mul {ι} [nonempty ι] {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h : x ≠ ∞) : infi f * x = ⨅ i, f i * x := begin by_cases h0 : x = 0, { simp only [h0, mul_zero, infi_const] }, { exact infi_mul_of_ne h0 h } end /-- If `x ≠ ∞`, then left multiplication by `x` maps infimum over a nonempty type to infimum. See also `ennreal.mul_infi_of_ne` that assumes `x ≠ 0` but does not require `[nonempty ι]`. -/ lemma mul_infi {ι} [nonempty ι] {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h : x ≠ ∞) : x * infi f = ⨅ i, x * f i := by simpa only [mul_comm] using infi_mul h /-- If `x ≠ 0` and `x ≠ ∞`, then left multiplication by `x` maps infimum to infimum. See also `ennreal.mul_infi` that assumes `[nonempty ι]` but does not require `x ≠ 0`. -/ lemma mul_infi_of_ne {ι} {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h0 : x ≠ 0) (h : x ≠ ∞) : x * infi f = ⨅ i, x * f i := by simpa only [mul_comm] using infi_mul_of_ne h0 h /-! `supr_mul`, `mul_supr` and variants are in `topology.instances.ennreal`. -/ end infi section supr @[simp] lemma supr_eq_zero {ι : Sort*} {f : ι → ℝ≥0∞} : (⨆ i, f i) = 0 ↔ ∀ i, f i = 0 := supr_eq_bot @[simp] lemma supr_zero_eq_zero {ι : Sort*} : (⨆ i : ι, (0 : ℝ≥0∞)) = 0 := by simp lemma sup_eq_zero {a b : ℝ≥0∞} : a ⊔ b = 0 ↔ a = 0 ∧ b = 0 := sup_eq_bot_iff lemma supr_coe_nat : (⨆n:ℕ, (n : ℝ≥0∞)) = ∞ := (supr_eq_top _).2 $ assume b hb, ennreal.exists_nat_gt (lt_top_iff_ne_top.1 hb) end supr end ennreal
e58edee57e542719c3d631c5ece1c39fd63364c3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/conj.lean
e708cbaf67d6f96c3a63291bd472c70121781656
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
7,153
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.endomorphism import Mathlib.algebra.group_power.default import Mathlib.PostPort universes u v v₁ u₁ namespace Mathlib /-! # Conjugate morphisms by isomorphisms An isomorphism `α : X ≅ Y` defines - a monoid isomorphism `conj : End X ≃* End Y` by `α.conj f = α.inv ≫ f ≫ α.hom`; - a group isomorphism `conj_Aut : Aut X ≃* Aut Y` by `α.conj_Aut f = α.symm ≪≫ f ≪≫ α`. For completeness, we also define `hom_congr : (X ≅ X₁) → (Y ≅ Y₁) → (X ⟶ Y) ≃ (X₁ ⟶ Y₁)`, cf. `equiv.arrow_congr`. -/ namespace category_theory namespace iso /-- If `X` is isomorphic to `X₁` and `Y` is isomorphic to `Y₁`, then there is a natural bijection between `X ⟶ Y` and `X₁ ⟶ Y₁`. See also `equiv.arrow_congr`. -/ def hom_congr {C : Type u} [category C] {X : C} {Y : C} {X₁ : C} {Y₁ : C} (α : X ≅ X₁) (β : Y ≅ Y₁) : (X ⟶ Y) ≃ (X₁ ⟶ Y₁) := equiv.mk (fun (f : X ⟶ Y) => inv α ≫ f ≫ hom β) (fun (f : X₁ ⟶ Y₁) => hom α ≫ f ≫ inv β) sorry sorry @[simp] theorem hom_congr_apply {C : Type u} [category C] {X : C} {Y : C} {X₁ : C} {Y₁ : C} (α : X ≅ X₁) (β : Y ≅ Y₁) (f : X ⟶ Y) : coe_fn (hom_congr α β) f = inv α ≫ f ≫ hom β := rfl theorem hom_congr_comp {C : Type u} [category C] {X : C} {Y : C} {Z : C} {X₁ : C} {Y₁ : C} {Z₁ : C} (α : X ≅ X₁) (β : Y ≅ Y₁) (γ : Z ≅ Z₁) (f : X ⟶ Y) (g : Y ⟶ Z) : coe_fn (hom_congr α γ) (f ≫ g) = coe_fn (hom_congr α β) f ≫ coe_fn (hom_congr β γ) g := sorry @[simp] theorem hom_congr_refl {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) : coe_fn (hom_congr (refl X) (refl Y)) f = f := sorry @[simp] theorem hom_congr_trans {C : Type u} [category C] {X₁ : C} {Y₁ : C} {X₂ : C} {Y₂ : C} {X₃ : C} {Y₃ : C} (α₁ : X₁ ≅ X₂) (β₁ : Y₁ ≅ Y₂) (α₂ : X₂ ≅ X₃) (β₂ : Y₂ ≅ Y₃) (f : X₁ ⟶ Y₁) : coe_fn (hom_congr (α₁ ≪≫ α₂) (β₁ ≪≫ β₂)) f = coe_fn (equiv.trans (hom_congr α₁ β₁) (hom_congr α₂ β₂)) f := sorry @[simp] theorem hom_congr_symm {C : Type u} [category C] {X₁ : C} {Y₁ : C} {X₂ : C} {Y₂ : C} (α : X₁ ≅ X₂) (β : Y₁ ≅ Y₂) : equiv.symm (hom_congr α β) = hom_congr (symm α) (symm β) := rfl /-- An isomorphism between two objects defines a monoid isomorphism between their monoid of endomorphisms. -/ def conj {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) : End X ≃* End Y := mul_equiv.mk (equiv.to_fun (hom_congr α α)) (equiv.inv_fun (hom_congr α α)) sorry sorry sorry theorem conj_apply {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : End X) : coe_fn (conj α) f = inv α ≫ f ≫ hom α := rfl @[simp] theorem conj_comp {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : End X) (g : End X) : coe_fn (conj α) (f ≫ g) = coe_fn (conj α) f ≫ coe_fn (conj α) g := mul_equiv.map_mul (conj α) g f @[simp] theorem conj_id {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) : coe_fn (conj α) 𝟙 = 𝟙 := mul_equiv.map_one (conj α) @[simp] theorem refl_conj {C : Type u} [category C] {X : C} (f : End X) : coe_fn (conj (refl X)) f = f := sorry @[simp] theorem trans_conj {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) {Z : C} (β : Y ≅ Z) (f : End X) : coe_fn (conj (α ≪≫ β)) f = coe_fn (conj β) (coe_fn (conj α) f) := hom_congr_trans α α β β f @[simp] theorem symm_self_conj {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : End X) : coe_fn (conj (symm α)) (coe_fn (conj α) f) = f := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (conj (symm α)) (coe_fn (conj α) f) = f)) (Eq.symm (trans_conj α (symm α) f)))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (conj (α ≪≫ symm α)) f = f)) (self_symm_id α))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (conj (refl X)) f = f)) (refl_conj f))) (Eq.refl f))) @[simp] theorem self_symm_conj {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : End Y) : coe_fn (conj α) (coe_fn (conj (symm α)) f) = f := symm_self_conj (symm α) f @[simp] theorem conj_pow {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : End X) (n : ℕ) : coe_fn (conj α) (f ^ n) = coe_fn (conj α) f ^ n := monoid_hom.map_pow (mul_equiv.to_monoid_hom (conj α)) f n /-- `conj` defines a group isomorphisms between groups of automorphisms -/ def conj_Aut {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) : Aut X ≃* Aut Y := mul_equiv.trans (mul_equiv.symm (Aut.units_End_equiv_Aut X)) (mul_equiv.trans (units.map_equiv (conj α)) (Aut.units_End_equiv_Aut Y)) theorem conj_Aut_apply {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : Aut X) : coe_fn (conj_Aut α) f = symm α ≪≫ f ≪≫ α := sorry @[simp] theorem conj_Aut_hom {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : Aut X) : hom (coe_fn (conj_Aut α) f) = coe_fn (conj α) (hom f) := rfl @[simp] theorem trans_conj_Aut {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) {Z : C} (β : Y ≅ Z) (f : Aut X) : coe_fn (conj_Aut (α ≪≫ β)) f = coe_fn (conj_Aut β) (coe_fn (conj_Aut α) f) := sorry @[simp] theorem conj_Aut_mul {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : Aut X) (g : Aut X) : coe_fn (conj_Aut α) (f * g) = coe_fn (conj_Aut α) f * coe_fn (conj_Aut α) g := mul_equiv.map_mul (conj_Aut α) f g @[simp] theorem conj_Aut_trans {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : Aut X) (g : Aut X) : coe_fn (conj_Aut α) (f ≪≫ g) = coe_fn (conj_Aut α) f ≪≫ coe_fn (conj_Aut α) g := conj_Aut_mul α g f @[simp] theorem conj_Aut_pow {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : Aut X) (n : ℕ) : coe_fn (conj_Aut α) (f ^ n) = coe_fn (conj_Aut α) f ^ n := monoid_hom.map_pow (mul_equiv.to_monoid_hom (conj_Aut α)) f n @[simp] theorem conj_Aut_gpow {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : Aut X) (n : ℤ) : coe_fn (conj_Aut α) (f ^ n) = coe_fn (conj_Aut α) f ^ n := monoid_hom.map_gpow (mul_equiv.to_monoid_hom (conj_Aut α)) f n end iso namespace functor theorem map_hom_congr {C : Type u} [category C] {D : Type u₁} [category D] (F : C ⥤ D) {X : C} {Y : C} {X₁ : C} {Y₁ : C} (α : X ≅ X₁) (β : Y ≅ Y₁) (f : X ⟶ Y) : map F (coe_fn (iso.hom_congr α β) f) = coe_fn (iso.hom_congr (map_iso F α) (map_iso F β)) (map F f) := sorry theorem map_conj {C : Type u} [category C] {D : Type u₁} [category D] (F : C ⥤ D) {X : C} {Y : C} (α : X ≅ Y) (f : End X) : map F (coe_fn (iso.conj α) f) = coe_fn (iso.conj (map_iso F α)) (map F f) := map_hom_congr F α α f theorem map_conj_Aut {C : Type u} [category C] {D : Type u₁} [category D] (F : C ⥤ D) {X : C} {Y : C} (α : X ≅ Y) (f : Aut X) : map_iso F (coe_fn (iso.conj_Aut α) f) = coe_fn (iso.conj_Aut (map_iso F α)) (map_iso F f) := sorry
c06687fba9914f38611ab665bda67ac63aaf7fd2
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/matrix/basic.lean
eec3b8ff4664fea7498e751b004b2e6b2ac2d18f
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
28,197
lean
/- Copyright (c) 2018 Ellen Arlt. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin -/ import algebra.big_operators.pi import algebra.module.pi import algebra.big_operators.ring /-! # Matrices -/ universes u v w open_locale big_operators @[nolint unused_arguments] def matrix (m n : Type u) [fintype m] [fintype n] (α : Type v) : Type (max u v) := m → n → α variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o] variables {α : Type v} namespace matrix section ext variables {M N : matrix m n α} theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N := ⟨λ h, funext $ λ i, funext $ h i, λ h, by simp [h]⟩ @[ext] theorem ext : (∀ i j, M i j = N i j) → M = N := ext_iff.mp end ext /-- Apply a function to each matrix entry. -/ def map (M : matrix m n α) {β : Type w} (f : α → β) : matrix m n β := λ i j, f (M i j) @[simp] lemma map_apply {M : matrix m n α} {β : Type w} {f : α → β} {i : m} {j : n} : M.map f i j = f (M i j) := rfl def transpose (M : matrix m n α) : matrix n m α | x y := M y x localized "postfix `ᵀ`:1500 := matrix.transpose" in matrix def col (w : m → α) : matrix m punit α | x y := w x def row (v : n → α) : matrix punit n α | x y := v y instance [inhabited α] : inhabited (matrix m n α) := pi.inhabited _ instance [has_add α] : has_add (matrix m n α) := pi.has_add instance [add_semigroup α] : add_semigroup (matrix m n α) := pi.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (matrix m n α) := pi.add_comm_semigroup instance [has_zero α] : has_zero (matrix m n α) := pi.has_zero instance [add_monoid α] : add_monoid (matrix m n α) := pi.add_monoid instance [add_comm_monoid α] : add_comm_monoid (matrix m n α) := pi.add_comm_monoid instance [has_neg α] : has_neg (matrix m n α) := pi.has_neg instance [add_group α] : add_group (matrix m n α) := pi.add_group instance [add_comm_group α] : add_comm_group (matrix m n α) := pi.add_comm_group @[simp] theorem zero_val [has_zero α] (i j) : (0 : matrix m n α) i j = 0 := rfl @[simp] theorem neg_val [has_neg α] (M : matrix m n α) (i j) : (- M) i j = - M i j := rfl @[simp] theorem add_val [has_add α] (M N : matrix m n α) (i j) : (M + N) i j = M i j + N i j := rfl @[simp] lemma map_zero [has_zero α] {β : Type w} [has_zero β] {f : α → β} (h : f 0 = 0) : (0 : matrix m n α).map f = 0 := by { ext, simp [h], } lemma map_add [add_monoid α] {β : Type w} [add_monoid β] (f : α →+ β) (M N : matrix m n α) : (M + N).map f = M.map f + N.map f := by { ext, simp, } end matrix /-- The `add_monoid_hom` between spaces of matrices induced by an `add_monoid_hom` between their coefficients. -/ def add_monoid_hom.map_matrix [add_monoid α] {β : Type w} [add_monoid β] (f : α →+ β) : matrix m n α →+ matrix m n β := { to_fun := λ M, M.map f, map_zero' := by simp, map_add' := matrix.map_add f, } @[simp] lemma add_monoid_hom.map_matrix_apply [add_monoid α] {β : Type w} [add_monoid β] (f : α →+ β) (M : matrix m n α) : f.map_matrix M = M.map f := rfl open_locale matrix namespace matrix section diagonal variables [decidable_eq n] /-- `diagonal d` is the square matrix such that `(diagonal d) i i = d i` and `(diagonal d) i j = 0` if `i ≠ j`. -/ def diagonal [has_zero α] (d : n → α) : matrix n n α := λ i j, if i = j then d i else 0 @[simp] theorem diagonal_val_eq [has_zero α] {d : n → α} (i : n) : (diagonal d) i i = d i := by simp [diagonal] @[simp] theorem diagonal_val_ne [has_zero α] {d : n → α} {i j : n} (h : i ≠ j) : (diagonal d) i j = 0 := by simp [diagonal, h] theorem diagonal_val_ne' [has_zero α] {d : n → α} {i j : n} (h : j ≠ i) : (diagonal d) i j = 0 := diagonal_val_ne h.symm @[simp] theorem diagonal_zero [has_zero α] : (diagonal (λ _, 0) : matrix n n α) = 0 := by simp [diagonal]; refl @[simp] lemma diagonal_transpose [has_zero α] (v : n → α) : (diagonal v)ᵀ = diagonal v := begin ext i j, by_cases h : i = j, { simp [h, transpose] }, { simp [h, transpose, diagonal_val_ne' h] } end @[simp] theorem diagonal_add [add_monoid α] (d₁ d₂ : n → α) : diagonal d₁ + diagonal d₂ = diagonal (λ i, d₁ i + d₂ i) := by ext i j; by_cases h : i = j; simp [h] @[simp] lemma diagonal_map {β : Type w} [has_zero α] [has_zero β] {f : α → β} (h : f 0 = 0) {d : n → α} : (diagonal d).map f = diagonal (λ m, f (d m)) := by { ext, simp only [diagonal, map_apply], split_ifs; simp [h], } section one variables [has_zero α] [has_one α] instance : has_one (matrix n n α) := ⟨diagonal (λ _, 1)⟩ @[simp] theorem diagonal_one : (diagonal (λ _, 1) : matrix n n α) = 1 := rfl theorem one_val {i j} : (1 : matrix n n α) i j = if i = j then 1 else 0 := rfl @[simp] theorem one_val_eq (i) : (1 : matrix n n α) i i = 1 := diagonal_val_eq i @[simp] theorem one_val_ne {i j} : i ≠ j → (1 : matrix n n α) i j = 0 := diagonal_val_ne theorem one_val_ne' {i j} : j ≠ i → (1 : matrix n n α) i j = 0 := diagonal_val_ne' @[simp] lemma one_map {β : Type w} [has_zero β] [has_one β] {f : α → β} (h₀ : f 0 = 0) (h₁ : f 1 = 1) : (1 : matrix n n α).map f = (1 : matrix n n β) := by { ext, simp only [one_val, map_apply], split_ifs; simp [h₀, h₁], } end one section numeral @[simp] lemma bit0_val [has_add α] (M : matrix m m α) (i : m) (j : m) : (bit0 M) i j = bit0 (M i j) := rfl variables [add_monoid α] [has_one α] lemma bit1_val (M : matrix n n α) (i : n) (j : n) : (bit1 M) i j = if i = j then bit1 (M i j) else bit0 (M i j) := by dsimp [bit1]; by_cases h : i = j; simp [h] @[simp] lemma bit1_val_eq (M : matrix n n α) (i : n) : (bit1 M) i i = bit1 (M i i) := by simp [bit1_val] @[simp] lemma bit1_val_ne (M : matrix n n α) {i j : n} (h : i ≠ j) : (bit1 M) i j = bit0 (M i j) := by simp [bit1_val, h] end numeral end diagonal section dot_product /-- `dot_product v w` is the sum of the entrywise products `v i * w i` -/ def dot_product [has_mul α] [add_comm_monoid α] (v w : m → α) : α := ∑ i, v i * w i lemma dot_product_assoc [semiring α] (u : m → α) (v : m → n → α) (w : n → α) : dot_product (λ j, dot_product u (λ i, v i j)) w = dot_product u (λ i, dot_product (v i) w) := by simpa [dot_product, finset.mul_sum, finset.sum_mul, mul_assoc] using finset.sum_comm lemma dot_product_comm [comm_semiring α] (v w : m → α) : dot_product v w = dot_product w v := by simp_rw [dot_product, mul_comm] @[simp] lemma dot_product_punit [add_comm_monoid α] [has_mul α] (v w : punit → α) : dot_product v w = v ⟨⟩ * w ⟨⟩ := by simp [dot_product] @[simp] lemma dot_product_zero [semiring α] (v : m → α) : dot_product v 0 = 0 := by simp [dot_product] @[simp] lemma dot_product_zero' [semiring α] (v : m → α) : dot_product v (λ _, 0) = 0 := dot_product_zero v @[simp] lemma zero_dot_product [semiring α] (v : m → α) : dot_product 0 v = 0 := by simp [dot_product] @[simp] lemma zero_dot_product' [semiring α] (v : m → α) : dot_product (λ _, (0 : α)) v = 0 := zero_dot_product v @[simp] lemma add_dot_product [semiring α] (u v w : m → α) : dot_product (u + v) w = dot_product u w + dot_product v w := by simp [dot_product, add_mul, finset.sum_add_distrib] @[simp] lemma dot_product_add [semiring α] (u v w : m → α) : dot_product u (v + w) = dot_product u v + dot_product u w := by simp [dot_product, mul_add, finset.sum_add_distrib] @[simp] lemma diagonal_dot_product [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product (diagonal v i) w = v i * w i := have ∀ j ≠ i, diagonal v i j * w j = 0 := λ j hij, by simp [diagonal_val_ne' hij], by convert finset.sum_eq_single i (λ j _, this j) _; simp @[simp] lemma dot_product_diagonal [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product v (diagonal w i) = v i * w i := have ∀ j ≠ i, v j * diagonal w i j = 0 := λ j hij, by simp [diagonal_val_ne' hij], by convert finset.sum_eq_single i (λ j _, this j) _; simp @[simp] lemma dot_product_diagonal' [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product v (λ j, diagonal w j i) = v i * w i := have ∀ j ≠ i, v j * diagonal w j i = 0 := λ j hij, by simp [diagonal_val_ne hij], by convert finset.sum_eq_single i (λ j _, this j) _; simp @[simp] lemma neg_dot_product [ring α] (v w : m → α) : dot_product (-v) w = - dot_product v w := by simp [dot_product] @[simp] lemma dot_product_neg [ring α] (v w : m → α) : dot_product v (-w) = - dot_product v w := by simp [dot_product] @[simp] lemma smul_dot_product [semiring α] (x : α) (v w : m → α) : dot_product (x • v) w = x * dot_product v w := by simp [dot_product, finset.mul_sum, mul_assoc] @[simp] lemma dot_product_smul [comm_semiring α] (x : α) (v w : m → α) : dot_product v (x • w) = x * dot_product v w := by simp [dot_product, finset.mul_sum, mul_assoc, mul_comm, mul_left_comm] end dot_product protected def mul [has_mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) : matrix l n α := λ i k, dot_product (λ j, M i j) (λ j, N j k) localized "infixl ` ⬝ `:75 := matrix.mul" in matrix theorem mul_val [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} : (M ⬝ N) i k = ∑ j, M i j * N j k := rfl instance [has_mul α] [add_comm_monoid α] : has_mul (matrix n n α) := ⟨matrix.mul⟩ @[simp] theorem mul_eq_mul [has_mul α] [add_comm_monoid α] (M N : matrix n n α) : M * N = M ⬝ N := rfl theorem mul_val' [has_mul α] [add_comm_monoid α] {M N : matrix n n α} {i k} : (M ⬝ N) i k = dot_product (λ j, M i j) (λ j, N j k) := rfl section semigroup variables [semiring α] protected theorem mul_assoc (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) : (L ⬝ M) ⬝ N = L ⬝ (M ⬝ N) := by { ext, apply dot_product_assoc } instance : semigroup (matrix n n α) := { mul_assoc := matrix.mul_assoc, ..matrix.has_mul } end semigroup @[simp] theorem diagonal_neg [decidable_eq n] [add_group α] (d : n → α) : -diagonal d = diagonal (λ i, -d i) := by ext i j; by_cases i = j; simp [h] section semiring variables [semiring α] @[simp] protected theorem mul_zero (M : matrix m n α) : M ⬝ (0 : matrix n o α) = 0 := by { ext i j, apply dot_product_zero } @[simp] protected theorem zero_mul (M : matrix m n α) : (0 : matrix l m α) ⬝ M = 0 := by { ext i j, apply zero_dot_product } protected theorem mul_add (L : matrix m n α) (M N : matrix n o α) : L ⬝ (M + N) = L ⬝ M + L ⬝ N := by { ext i j, apply dot_product_add } protected theorem add_mul (L M : matrix l m α) (N : matrix m n α) : (L + M) ⬝ N = L ⬝ N + M ⬝ N := by { ext i j, apply add_dot_product } @[simp] theorem diagonal_mul [decidable_eq m] (d : m → α) (M : matrix m n α) (i j) : (diagonal d).mul M i j = d i * M i j := diagonal_dot_product _ _ _ @[simp] theorem mul_diagonal [decidable_eq n] (d : n → α) (M : matrix m n α) (i j) : (M ⬝ diagonal d) i j = M i j * d j := by { rw ← diagonal_transpose, apply dot_product_diagonal } @[simp] protected theorem one_mul [decidable_eq m] (M : matrix m n α) : (1 : matrix m m α) ⬝ M = M := by ext i j; rw [← diagonal_one, diagonal_mul, one_mul] @[simp] protected theorem mul_one [decidable_eq n] (M : matrix m n α) : M ⬝ (1 : matrix n n α) = M := by ext i j; rw [← diagonal_one, mul_diagonal, mul_one] instance [decidable_eq n] : monoid (matrix n n α) := { one_mul := matrix.one_mul, mul_one := matrix.mul_one, ..matrix.has_one, ..matrix.semigroup } instance [decidable_eq n] : semiring (matrix n n α) := { mul_zero := matrix.mul_zero, zero_mul := matrix.zero_mul, left_distrib := matrix.mul_add, right_distrib := matrix.add_mul, ..matrix.add_comm_monoid, ..matrix.monoid } @[simp] theorem diagonal_mul_diagonal [decidable_eq n] (d₁ d₂ : n → α) : (diagonal d₁) ⬝ (diagonal d₂) = diagonal (λ i, d₁ i * d₂ i) := by ext i j; by_cases i = j; simp [h] theorem diagonal_mul_diagonal' [decidable_eq n] (d₁ d₂ : n → α) : diagonal d₁ * diagonal d₂ = diagonal (λ i, d₁ i * d₂ i) := diagonal_mul_diagonal _ _ lemma map_mul {L : matrix m n α} {M : matrix n o α} {β : Type w} [semiring β] {f : α →+* β} : (L ⬝ M).map f = L.map f ⬝ M.map f := by { ext, simp [mul_val, ring_hom.map_sum], } lemma is_add_monoid_hom_mul_left (M : matrix l m α) : is_add_monoid_hom (λ x : matrix m n α, M ⬝ x) := { to_is_add_hom := ⟨matrix.mul_add _⟩, map_zero := matrix.mul_zero _ } lemma is_add_monoid_hom_mul_right (M : matrix m n α) : is_add_monoid_hom (λ x : matrix l m α, x ⬝ M) := { to_is_add_hom := ⟨λ _ _, matrix.add_mul _ _ _⟩, map_zero := matrix.zero_mul _ } protected lemma sum_mul {β : Type*} (s : finset β) (f : β → matrix l m α) (M : matrix m n α) : (∑ a in s, f a) ⬝ M = ∑ a in s, f a ⬝ M := (@finset.sum_hom _ _ _ _ _ s f (λ x, x ⬝ M) /- This line does not type-check without `id` and `: _`. Lean did not recognize that two different `add_monoid` instances were def-eq -/ (id (@is_add_monoid_hom_mul_right l _ _ _ _ _ _ _ M) : _)).symm protected lemma mul_sum {β : Type*} (s : finset β) (f : β → matrix m n α) (M : matrix l m α) : M ⬝ ∑ a in s, f a = ∑ a in s, M ⬝ f a := (@finset.sum_hom _ _ _ _ _ s f (λ x, M ⬝ x) /- This line does not type-check without `id` and `: _`. Lean did not recognize that two different `add_monoid` instances were def-eq -/ (id (@is_add_monoid_hom_mul_left _ _ n _ _ _ _ _ M) : _)).symm @[simp] lemma row_mul_col_val (v w : m → α) (i j) : (row v ⬝ col w) i j = dot_product v w := rfl end semiring end matrix /-- The `ring_hom` between spaces of square matrices induced by a `ring_hom` between their coefficients. -/ def ring_hom.map_matrix [decidable_eq m] [semiring α] {β : Type w} [semiring β] (f : α →+* β) : matrix m m α →+* matrix m m β := { to_fun := λ M, M.map f, map_one' := by simp, map_mul' := λ L M, matrix.map_mul, ..(f.to_add_monoid_hom).map_matrix } @[simp] lemma ring_hom.map_matrix_apply [decidable_eq m] [semiring α] {β : Type w} [semiring β] (f : α →+* β) (M : matrix m m α) : f.map_matrix M = M.map f := rfl open_locale matrix namespace matrix section ring variables [ring α] @[simp] theorem neg_mul (M : matrix m n α) (N : matrix n o α) : (-M) ⬝ N = -(M ⬝ N) := by { ext, apply neg_dot_product } @[simp] theorem mul_neg (M : matrix m n α) (N : matrix n o α) : M ⬝ (-N) = -(M ⬝ N) := by { ext, apply dot_product_neg } end ring instance [decidable_eq n] [ring α] : ring (matrix n n α) := { ..matrix.semiring, ..matrix.add_comm_group } instance [semiring α] : has_scalar α (matrix m n α) := pi.has_scalar instance {β : Type w} [semiring α] [add_comm_monoid β] [semimodule α β] : semimodule α (matrix m n β) := pi.semimodule _ _ _ @[simp] lemma smul_val [semiring α] (a : α) (A : matrix m n α) (i : m) (j : n) : (a • A) i j = a * A i j := rfl section semiring variables [semiring α] lemma smul_eq_diagonal_mul [decidable_eq m] (M : matrix m n α) (a : α) : a • M = diagonal (λ _, a) ⬝ M := by { ext, simp } @[simp] lemma smul_mul (M : matrix m n α) (a : α) (N : matrix n l α) : (a • M) ⬝ N = a • M ⬝ N := by { ext, apply smul_dot_product } @[simp] lemma mul_mul_left (M : matrix m n α) (N : matrix n o α) (a : α) : (λ i j, a * M i j) ⬝ N = a • (M ⬝ N) := begin simp only [←smul_val], simp, end /-- The ring homomorphism `α →+* matrix n n α` sending `a` to the diagonal matrix with `a` on the diagonal. -/ def scalar (n : Type u) [fintype n] [decidable_eq n] : α →+* matrix n n α := { to_fun := λ a, a • 1, map_zero' := by simp, map_add' := by { intros, ext, simp [add_mul], }, map_one' := by simp, map_mul' := by { intros, ext, simp [mul_assoc], }, } section scalar variable [decidable_eq n] @[simp] lemma coe_scalar : (scalar n : α → matrix n n α) = λ a, a • 1 := rfl lemma scalar_apply_eq (a : α) (i : n) : scalar n a i i = a := by simp only [coe_scalar, mul_one, one_val_eq, smul_val] lemma scalar_apply_ne (a : α) (i j : n) (h : i ≠ j) : scalar n a i j = 0 := by simp only [h, coe_scalar, one_val_ne, ne.def, not_false_iff, smul_val, mul_zero] end scalar end semiring section comm_semiring variables [comm_semiring α] lemma smul_eq_mul_diagonal [decidable_eq n] (M : matrix m n α) (a : α) : a • M = M ⬝ diagonal (λ _, a) := by { ext, simp [mul_comm] } @[simp] lemma mul_smul (M : matrix m n α) (a : α) (N : matrix n l α) : M ⬝ (a • N) = a • M ⬝ N := by { ext, apply dot_product_smul } @[simp] lemma mul_mul_right (M : matrix m n α) (N : matrix n o α) (a : α) : M ⬝ (λ i j, a * N i j) = a • (M ⬝ N) := begin simp only [←smul_val], simp, end end comm_semiring section semiring variables [semiring α] def vec_mul_vec (w : m → α) (v : n → α) : matrix m n α | x y := w x * v y def mul_vec (M : matrix m n α) (v : n → α) : m → α | i := dot_product (λ j, M i j) v def vec_mul (v : m → α) (M : matrix m n α) : n → α | j := dot_product v (λ i, M i j) instance mul_vec.is_add_monoid_hom_left (v : n → α) : is_add_monoid_hom (λM:matrix m n α, mul_vec M v) := { map_zero := by ext; simp [mul_vec]; refl, map_add := begin intros x y, ext m, apply add_dot_product end } lemma mul_vec_diagonal [decidable_eq m] (v w : m → α) (x : m) : mul_vec (diagonal v) w x = v x * w x := diagonal_dot_product v w x lemma vec_mul_diagonal [decidable_eq m] (v w : m → α) (x : m) : vec_mul v (diagonal w) x = v x * w x := dot_product_diagonal' v w x @[simp] lemma mul_vec_one [decidable_eq m] (v : m → α) : mul_vec 1 v = v := by { ext, rw [←diagonal_one, mul_vec_diagonal, one_mul] } @[simp] lemma vec_mul_one [decidable_eq m] (v : m → α) : vec_mul v 1 = v := by { ext, rw [←diagonal_one, vec_mul_diagonal, mul_one] } @[simp] lemma mul_vec_zero (A : matrix m n α) : mul_vec A 0 = 0 := by { ext, simp [mul_vec] } @[simp] lemma vec_mul_zero (A : matrix m n α) : vec_mul 0 A = 0 := by { ext, simp [vec_mul] } @[simp] lemma vec_mul_vec_mul (v : m → α) (M : matrix m n α) (N : matrix n o α) : vec_mul (vec_mul v M) N = vec_mul v (M ⬝ N) := by { ext, apply dot_product_assoc } @[simp] lemma mul_vec_mul_vec (v : o → α) (M : matrix m n α) (N : matrix n o α) : mul_vec M (mul_vec N v) = mul_vec (M ⬝ N) v := by { ext, symmetry, apply dot_product_assoc } lemma vec_mul_vec_eq (w : m → α) (v : n → α) : vec_mul_vec w v = (col w) ⬝ (row v) := by { ext i j, simp [vec_mul_vec, mul_val], refl } variables [decidable_eq m] [decidable_eq n] /-- `std_basis_matrix i j a` is the matrix with `a` in the `i`-th row, `j`-th column, and zeroes elsewhere. -/ def std_basis_matrix (i : m) (j : n) (a : α) : matrix m n α := (λ i' j', if i' = i ∧ j' = j then a else 0) @[simp] lemma smul_std_basis_matrix (i : m) (j : n) (a b : α) : b • std_basis_matrix i j a = std_basis_matrix i j (b • a) := by { unfold std_basis_matrix, ext, dsimp, simp } @[simp] lemma std_basis_matrix_zero (i : m) (j : n) : std_basis_matrix i j (0 : α) = 0 := by { unfold std_basis_matrix, ext, simp } lemma std_basis_matrix_add (i : m) (j : n) (a b : α) : std_basis_matrix i j (a + b) = std_basis_matrix i j a + std_basis_matrix i j b := begin unfold std_basis_matrix, ext, split_ifs with h; simp [h], end lemma matrix_eq_sum_std_basis (x : matrix n m α) : x = ∑ (i : n) (j : m), std_basis_matrix i j (x i j) := begin ext, iterate 2 {rw finset.sum_apply}, rw ← finset.sum_subset, swap 4, exact {i}, { norm_num [std_basis_matrix] }, { simp }, intros, norm_num at a, norm_num, convert finset.sum_const_zero, ext, norm_num [std_basis_matrix], rw if_neg, tauto!, end -- TODO: tie this up with the `basis` machinery of linear algebra -- this is not completely trivial because we are indexing by two types, instead of one -- TODO: add `std_basis_vec` lemma std_basis_eq_basis_mul_basis (i : m) (j : n) : std_basis_matrix i j 1 = vec_mul_vec (λ i', ite (i = i') 1 0) (λ j', ite (j = j') 1 0) := begin ext, norm_num [std_basis_matrix, vec_mul_vec], split_ifs; tauto, end @[elab_as_eliminator] protected lemma induction_on' {X : Type*} [semiring X] {M : matrix n n X → Prop} (m : matrix n n X) (h_zero : M 0) (h_add : ∀p q, M p → M q → M (p + q)) (h_std_basis : ∀ i j x, M (std_basis_matrix i j x)) : M m := begin rw [matrix_eq_sum_std_basis m, ← finset.sum_product'], apply finset.sum_induction _ _ h_add h_zero, { intros, apply h_std_basis, } end @[elab_as_eliminator] protected lemma induction_on [nonempty n] {X : Type*} [semiring X] {M : matrix n n X → Prop} (m : matrix n n X) (h_add : ∀p q, M p → M q → M (p + q)) (h_std_basis : ∀ i j x, M (std_basis_matrix i j x)) : M m := matrix.induction_on' m begin have i : n := classical.choice (by assumption), simpa using h_std_basis i i 0, end h_add h_std_basis end semiring section ring variables [ring α] lemma neg_vec_mul (v : m → α) (A : matrix m n α) : vec_mul (-v) A = - vec_mul v A := by { ext, apply neg_dot_product } lemma vec_mul_neg (v : m → α) (A : matrix m n α) : vec_mul v (-A) = - vec_mul v A := by { ext, apply dot_product_neg } lemma neg_mul_vec (v : n → α) (A : matrix m n α) : mul_vec (-A) v = - mul_vec A v := by { ext, apply neg_dot_product } lemma mul_vec_neg (v : n → α) (A : matrix m n α) : mul_vec A (-v) = - mul_vec A v := by { ext, apply dot_product_neg } end ring section transpose open_locale matrix /-- Tell `simp` what the entries are in a transposed matrix. Compare with `mul_val`, `diagonal_val_eq`, etc. -/ @[simp] lemma transpose_val (M : matrix m n α) (i j) : M.transpose j i = M i j := rfl @[simp] lemma transpose_transpose (M : matrix m n α) : Mᵀᵀ = M := by ext; refl @[simp] lemma transpose_zero [has_zero α] : (0 : matrix m n α)ᵀ = 0 := by ext i j; refl @[simp] lemma transpose_one [decidable_eq n] [has_zero α] [has_one α] : (1 : matrix n n α)ᵀ = 1 := begin ext i j, unfold has_one.one transpose, by_cases i = j, { simp only [h, diagonal_val_eq] }, { simp only [diagonal_val_ne h, diagonal_val_ne (λ p, h (symm p))] } end @[simp] lemma transpose_add [has_add α] (M : matrix m n α) (N : matrix m n α) : (M + N)ᵀ = Mᵀ + Nᵀ := by { ext i j, simp } @[simp] lemma transpose_sub [add_group α] (M : matrix m n α) (N : matrix m n α) : (M - N)ᵀ = Mᵀ - Nᵀ := by { ext i j, simp } @[simp] lemma transpose_mul [comm_semiring α] (M : matrix m n α) (N : matrix n l α) : (M ⬝ N)ᵀ = Nᵀ ⬝ Mᵀ := begin ext i j, apply dot_product_comm end @[simp] lemma transpose_smul [semiring α] (c : α) (M : matrix m n α) : (c • M)ᵀ = c • Mᵀ := by { ext i j, refl } @[simp] lemma transpose_neg [has_neg α] (M : matrix m n α) : (- M)ᵀ = - Mᵀ := by ext i j; refl lemma transpose_map {β : Type w} {f : α → β} {M : matrix m n α} : Mᵀ.map f = (M.map f)ᵀ := by { ext, refl } end transpose def minor (A : matrix m n α) (row : l → m) (col : o → n) : matrix l o α := λ i j, A (row i) (col j) @[reducible] def sub_left {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin l) α := minor A id (fin.cast_add r) @[reducible] def sub_right {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin r) α := minor A id (fin.nat_add l) @[reducible] def sub_up {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin u) (fin n) α := minor A (fin.cast_add d) id @[reducible] def sub_down {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin d) (fin n) α := minor A (fin.nat_add u) id @[reducible] def sub_up_right {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin r) α := sub_up (sub_right A) @[reducible] def sub_down_right {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin r) α := sub_down (sub_right A) @[reducible] def sub_up_left {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin (l)) α := sub_up (sub_left A) @[reducible] def sub_down_left {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin (l)) α := sub_down (sub_left A) section row_col /-! ### `row_col` section Simplification lemmas for `matrix.row` and `matrix.col`. -/ open_locale matrix @[simp] lemma col_add [semiring α] (v w : m → α) : col (v + w) = col v + col w := by { ext, refl } @[simp] lemma col_smul [semiring α] (x : α) (v : m → α) : col (x • v) = x • col v := by { ext, refl } @[simp] lemma row_add [semiring α] (v w : m → α) : row (v + w) = row v + row w := by { ext, refl } @[simp] lemma row_smul [semiring α] (x : α) (v : m → α) : row (x • v) = x • row v := by { ext, refl } @[simp] lemma col_val (v : m → α) (i j) : matrix.col v i j = v i := rfl @[simp] lemma row_val (v : m → α) (i j) : matrix.row v i j = v j := rfl @[simp] lemma transpose_col (v : m → α) : (matrix.col v).transpose = matrix.row v := by {ext, refl} @[simp] lemma transpose_row (v : m → α) : (matrix.row v).transpose = matrix.col v := by {ext, refl} lemma row_vec_mul [semiring α] (M : matrix m n α) (v : m → α) : matrix.row (matrix.vec_mul v M) = matrix.row v ⬝ M := by {ext, refl} lemma col_vec_mul [semiring α] (M : matrix m n α) (v : m → α) : matrix.col (matrix.vec_mul v M) = (matrix.row v ⬝ M)ᵀ := by {ext, refl} lemma col_mul_vec [semiring α] (M : matrix m n α) (v : n → α) : matrix.col (matrix.mul_vec M v) = M ⬝ matrix.col v := by {ext, refl} lemma row_mul_vec [semiring α] (M : matrix m n α) (v : n → α) : matrix.row (matrix.mul_vec M v) = (M ⬝ matrix.col v)ᵀ := by {ext, refl} end row_col section update /-- Update, i.e. replace the `i`th row of matrix `A` with the values in `b`. -/ def update_row [decidable_eq n] (M : matrix n m α) (i : n) (b : m → α) : matrix n m α := function.update M i b /-- Update, i.e. replace the `i`th column of matrix `A` with the values in `b`. -/ def update_column [decidable_eq m] (M : matrix n m α) (j : m) (b : n → α) : matrix n m α := λ i, function.update (M i) j (b i) variables {M : matrix n m α} {i : n} {j : m} {b : m → α} {c : n → α} @[simp] lemma update_row_self [decidable_eq n] : update_row M i b i = b := function.update_same i b M @[simp] lemma update_column_self [decidable_eq m] : update_column M j c i j = c i := function.update_same j (c i) (M i) @[simp] lemma update_row_ne [decidable_eq n] {i' : n} (i_ne : i' ≠ i) : update_row M i b i' = M i' := function.update_noteq i_ne b M @[simp] lemma update_column_ne [decidable_eq m] {j' : m} (j_ne : j' ≠ j) : update_column M j c i j' = M i j' := function.update_noteq j_ne (c i) (M i) lemma update_row_val [decidable_eq n] {i' : n} : update_row M i b i' j = if i' = i then b j else M i' j := begin by_cases i' = i, { rw [h, update_row_self, if_pos rfl] }, { rwa [update_row_ne h, if_neg h] } end lemma update_column_val [decidable_eq m] {j' : m} : update_column M j c i j' = if j' = j then c i else M i j' := begin by_cases j' = j, { rw [h, update_column_self, if_pos rfl] }, { rwa [update_column_ne h, if_neg h] } end lemma update_row_transpose [decidable_eq m] : update_row Mᵀ j c = (update_column M j c)ᵀ := begin ext i' j, rw [transpose_val, update_row_val, update_column_val], refl end lemma update_column_transpose [decidable_eq n] : update_column Mᵀ i b = (update_row M i b)ᵀ := begin ext i' j, rw [transpose_val, update_row_val, update_column_val], refl end end update end matrix namespace ring_hom variables {β : Type*} [semiring α] [semiring β] lemma map_matrix_mul (M : matrix m n α) (N : matrix n o α) (i : m) (j : o) (f : α →+* β) : f (matrix.mul M N i j) = matrix.mul (λ i j, f (M i j)) (λ i j, f (N i j)) i j := by simp [matrix.mul_val, ring_hom.map_sum] end ring_hom
eef0f2611c77e7193a7ed01cf49ba918a665577e
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/topology/algebra/group.lean
5934c1069656c67904c4551df8d2d321c4188c30
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,716
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 order.filter.pointwise import group_theory.quotient_group import topology.algebra.monoid import topology.homeomorph /-! # Theory of topological groups This file defines the following typeclasses: * `topological_group`, `topological_add_group`: multiplicative and additive topological groups, i.e., groups with continuous `(*)` and `(⁻¹)` / `(+)` and `(-)`; * `has_continuous_sub G` means that `G` has a continuous subtraction operation. There is an instance deducing `has_continuous_sub` from `topological_group` but we use a separate typeclass because, e.g., `ℕ` and `ℝ≥0` have continuous subtraction but are not additive groups. We also define `homeomorph` versions of several `equiv`s: `homeomorph.mul_left`, `homeomorph.mul_right`, `homeomorph.inv`, and prove a few facts about neighbourhood filters in groups. ## Tags topological space, group, topological group -/ open classical set filter topological_space function open_locale classical topological_space filter universes u v w x variables {α : Type u} {β : Type v} {G : Type w} {H : Type x} section continuous_mul_group /-! ### Groups with continuous multiplication In this section we prove a few statements about groups with continuous `(*)`. -/ variables [topological_space G] [group G] [has_continuous_mul G] /-- Multiplication from the left in a topological group as a homeomorphism. -/ @[to_additive "Addition from the left in a topological additive group as a homeomorphism."] protected def homeomorph.mul_left (a : G) : G ≃ₜ G := { continuous_to_fun := continuous_const.mul continuous_id, continuous_inv_fun := continuous_const.mul continuous_id, .. equiv.mul_left a } @[simp, to_additive] lemma homeomorph.coe_mul_left (a : G) : ⇑(homeomorph.mul_left a) = (*) a := rfl @[to_additive] lemma homeomorph.mul_left_symm (a : G) : (homeomorph.mul_left a).symm = homeomorph.mul_left a⁻¹ := by { ext, refl } @[to_additive] lemma is_open_map_mul_left (a : G) : is_open_map (λ x, a * x) := (homeomorph.mul_left a).is_open_map @[to_additive] lemma is_closed_map_mul_left (a : G) : is_closed_map (λ x, a * x) := (homeomorph.mul_left a).is_closed_map /-- Multiplication from the right in a topological group as a homeomorphism. -/ @[to_additive "Addition from the right in a topological additive group as a homeomorphism."] protected def homeomorph.mul_right (a : G) : G ≃ₜ G := { continuous_to_fun := continuous_id.mul continuous_const, continuous_inv_fun := continuous_id.mul continuous_const, .. equiv.mul_right a } @[to_additive] lemma is_open_map_mul_right (a : G) : is_open_map (λ x, x * a) := (homeomorph.mul_right a).is_open_map @[to_additive] lemma is_closed_map_mul_right (a : G) : is_closed_map (λ x, x * a) := (homeomorph.mul_right a).is_closed_map @[to_additive] lemma is_open_map_div_right (a : G) : is_open_map (λ x, x / a) := by simpa only [div_eq_mul_inv] using is_open_map_mul_right (a⁻¹) @[to_additive] lemma is_closed_map_div_right (a : G) : is_closed_map (λ x, x / a) := by simpa only [div_eq_mul_inv] using is_closed_map_mul_right (a⁻¹) @[to_additive] lemma discrete_topology_of_open_singleton_one (h : is_open ({1} : set G)) : discrete_topology G := begin rw ← singletons_open_iff_discrete, intro g, suffices : {g} = (λ (x : G), g⁻¹ * x) ⁻¹' {1}, { rw this, exact (continuous_mul_left (g⁻¹)).is_open_preimage _ h, }, simp only [mul_one, set.preimage_mul_left_singleton, eq_self_iff_true, inv_inv, set.singleton_eq_singleton_iff], end end continuous_mul_group section topological_group /-! ### Topological groups A topological group is a group in which the multiplication and inversion operations are continuous. Topological additive groups are defined in the same way. Equivalently, we can require that the division operation `λ x y, x * y⁻¹` (resp., subtraction) is continuous. -/ /-- A topological (additive) group is a group in which the addition and negation operations are continuous. -/ class topological_add_group (G : Type u) [topological_space G] [add_group G] extends has_continuous_add G : Prop := (continuous_neg : continuous (λa:G, -a)) /-- A topological group is a group in which the multiplication and inversion operations are continuous. -/ @[to_additive] class topological_group (G : Type*) [topological_space G] [group G] extends has_continuous_mul G : Prop := (continuous_inv : continuous (has_inv.inv : G → G)) variables [topological_space G] [group G] [topological_group G] export topological_group (continuous_inv) export topological_add_group (continuous_neg) @[to_additive] lemma continuous_on_inv {s : set G} : continuous_on has_inv.inv s := continuous_inv.continuous_on @[to_additive] lemma continuous_within_at_inv {s : set G} {x : G} : continuous_within_at has_inv.inv s x := continuous_inv.continuous_within_at @[to_additive] lemma continuous_at_inv {x : G} : continuous_at has_inv.inv x := continuous_inv.continuous_at @[to_additive] lemma tendsto_inv (a : G) : tendsto has_inv.inv (𝓝 a) (𝓝 (a⁻¹)) := continuous_at_inv /-- If a function converges to a value in a multiplicative topological group, then its inverse converges to the inverse of this value. For the version in normed fields assuming additionally that the limit is nonzero, use `tendsto.inv'`. -/ @[to_additive] lemma filter.tendsto.inv {f : α → G} {l : filter α} {y : G} (h : tendsto f l (𝓝 y)) : tendsto (λ x, (f x)⁻¹) l (𝓝 y⁻¹) := (continuous_inv.tendsto y).comp h variables [topological_space α] {f : α → G} {s : set α} {x : α} @[continuity, to_additive] lemma continuous.inv (hf : continuous f) : continuous (λx, (f x)⁻¹) := continuous_inv.comp hf attribute [continuity] continuous.neg -- TODO @[to_additive] lemma continuous_on.inv (hf : continuous_on f s) : continuous_on (λx, (f x)⁻¹) s := continuous_inv.comp_continuous_on hf @[to_additive] lemma continuous_within_at.inv (hf : continuous_within_at f s x) : continuous_within_at (λ x, (f x)⁻¹) s x := hf.inv @[instance, to_additive] instance [topological_space H] [group H] [topological_group H] : topological_group (G × H) := { continuous_inv := continuous_inv.prod_map continuous_inv } @[to_additive] instance pi.topological_group {C : β → Type*} [∀ b, topological_space (C b)] [∀ b, group (C b)] [∀ b, topological_group (C b)] : topological_group (Π b, C b) := { continuous_inv := continuous_pi (λ i, (continuous_apply i).inv) } variable (G) /-- Inversion in a topological group as a homeomorphism. -/ @[to_additive "Negation in a topological group as a homeomorphism."] protected def homeomorph.inv : G ≃ₜ G := { continuous_to_fun := continuous_inv, continuous_inv_fun := continuous_inv, .. equiv.inv G } @[to_additive] lemma nhds_one_symm : comap has_inv.inv (𝓝 (1 : G)) = 𝓝 (1 : G) := ((homeomorph.inv G).comap_nhds_eq _).trans (congr_arg nhds one_inv) /-- The map `(x, y) ↦ (x, xy)` as a homeomorphism. This is a shear mapping. -/ @[to_additive "The map `(x, y) ↦ (x, x + y)` as a homeomorphism. This is a shear mapping."] protected def homeomorph.shear_mul_right : G × G ≃ₜ G × G := { continuous_to_fun := continuous_fst.prod_mk continuous_mul, continuous_inv_fun := continuous_fst.prod_mk $ continuous_fst.inv.mul continuous_snd, .. equiv.prod_shear (equiv.refl _) equiv.mul_left } @[simp, to_additive] lemma homeomorph.shear_mul_right_coe : ⇑(homeomorph.shear_mul_right G) = λ z : G × G, (z.1, z.1 * z.2) := rfl @[simp, to_additive] lemma homeomorph.shear_mul_right_symm_coe : ⇑(homeomorph.shear_mul_right G).symm = λ z : G × G, (z.1, z.1⁻¹ * z.2) := rfl variable {G} @[to_additive] lemma inv_closure (s : set G) : (closure s)⁻¹ = closure s⁻¹ := (homeomorph.inv G).preimage_closure s /-- The (topological-space) closure of a subgroup of a space `M` with `has_continuous_mul` is itself a subgroup. -/ @[to_additive "The (topological-space) closure of an additive subgroup of a space `M` with `has_continuous_add` is itself an additive subgroup."] def subgroup.topological_closure (s : subgroup G) : subgroup G := { carrier := closure (s : set G), inv_mem' := λ g m, by simpa [←mem_inv, inv_closure] using m, ..s.to_submonoid.topological_closure } @[to_additive] instance subgroup.topological_closure_topological_group (s : subgroup G) : topological_group (s.topological_closure) := { continuous_inv := begin apply continuous_induced_rng, change continuous (λ p : s.topological_closure, (p : G)⁻¹), continuity, end ..s.to_submonoid.topological_closure_has_continuous_mul} lemma subgroup.subgroup_topological_closure (s : subgroup G) : s ≤ s.topological_closure := subset_closure lemma subgroup.is_closed_topological_closure (s : subgroup G) : is_closed (s.topological_closure : set G) := by convert is_closed_closure lemma subgroup.topological_closure_minimal (s : subgroup G) {t : subgroup G} (h : s ≤ t) (ht : is_closed (t : set G)) : s.topological_closure ≤ t := closure_minimal h ht @[to_additive exists_nhds_half_neg] lemma exists_nhds_split_inv {s : set G} (hs : s ∈ 𝓝 (1 : G)) : ∃ V ∈ 𝓝 (1 : G), ∀ (v ∈ V) (w ∈ V), v / w ∈ s := have ((λp : G × G, p.1 * p.2⁻¹) ⁻¹' s) ∈ 𝓝 ((1, 1) : G × G), from continuous_at_fst.mul continuous_at_snd.inv (by simpa), by simpa only [div_eq_mul_inv, nhds_prod_eq, mem_prod_self_iff, prod_subset_iff, mem_preimage] using this @[to_additive] lemma nhds_translation_mul_inv (x : G) : comap (λ y : G, y * x⁻¹) (𝓝 1) = 𝓝 x := ((homeomorph.mul_right x⁻¹).comap_nhds_eq 1).trans $ show 𝓝 (1 * x⁻¹⁻¹) = 𝓝 x, by simp @[simp, to_additive] lemma map_mul_left_nhds (x y : G) : map ((*) x) (𝓝 y) = 𝓝 (x * y) := (homeomorph.mul_left x).map_nhds_eq y @[to_additive] lemma map_mul_left_nhds_one (x : G) : map ((*) x) (𝓝 1) = 𝓝 x := by simp @[to_additive] lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G} (tg : @topological_group G t _) (tg' : @topological_group G t' _) (h : @nhds G t 1 = @nhds G t' 1) : t = t' := eq_of_nhds_eq_nhds $ λ x, by rw [← @nhds_translation_mul_inv G t _ _ x , ← @nhds_translation_mul_inv G t' _ _ x , ← h] @[to_additive] lemma topological_group.of_nhds_aux {G : Type*} [group G] [topological_space G] (hinv : tendsto (λ (x : G), x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ (x₀ : G), 𝓝 x₀ = map (λ (x : G), x₀ * x) (𝓝 1)) (hconj : ∀ (x₀ : G), map (λ (x : G), x₀ * x * x₀⁻¹) (𝓝 1) ≤ 𝓝 1) : continuous (λ x : G, x⁻¹) := begin rw continuous_iff_continuous_at, rintros x₀, have key : (λ x, (x₀*x)⁻¹) = (λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹) ∘ (λ x, x⁻¹), by {ext ; simp[mul_assoc] }, calc map (λ x, x⁻¹) (𝓝 x₀) = map (λ x, x⁻¹) (map (λ x, x₀*x) $ 𝓝 1) : by rw hleft ... = map (λ x, (x₀*x)⁻¹) (𝓝 1) : by rw filter.map_map ... = map (((λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹)) ∘ (λ x, x⁻¹)) (𝓝 1) : by rw key ... = map ((λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹)) _ : by rw ← filter.map_map ... ≤ map ((λ x, x₀⁻¹ * x) ∘ λ x, x₀ * x * x₀⁻¹) (𝓝 1) : map_mono hinv ... = map (λ x, x₀⁻¹ * x) (map (λ x, x₀ * x * x₀⁻¹) (𝓝 1)) : filter.map_map ... ≤ map (λ x, x₀⁻¹ * x) (𝓝 1) : map_mono (hconj x₀) ... = 𝓝 x₀⁻¹ : (hleft _).symm end @[to_additive] lemma topological_group.of_nhds_one' {G : Type*} [group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hright : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x*x₀) (𝓝 1)) : topological_group G := begin refine { continuous_mul := (has_continuous_mul.of_nhds_one hmul hleft hright).continuous_mul, continuous_inv := topological_group.of_nhds_aux hinv hleft _ }, intros x₀, suffices : map (λ (x : G), x₀ * x * x₀⁻¹) (𝓝 1) = 𝓝 1, by simp [this, le_refl], rw [show (λ x, x₀ * x * x₀⁻¹) = (λ x, x₀ * x) ∘ λ x, x*x₀⁻¹, by {ext, simp [mul_assoc] }, ← filter.map_map, ← hright, hleft x₀⁻¹, filter.map_map], convert map_id, ext, simp end @[to_additive] lemma topological_group.of_nhds_one {G : Type u} [group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hconj : ∀ x₀ : G, tendsto (λ x, x₀*x*x₀⁻¹) (𝓝 1) (𝓝 1)) : topological_group G := { continuous_mul := begin rw continuous_iff_continuous_at, rintros ⟨x₀, y₀⟩, have key : (λ (p : G × G), x₀ * p.1 * (y₀ * p.2)) = ((λ x, x₀*y₀*x) ∘ (uncurry (*)) ∘ (prod.map (λ x, y₀⁻¹*x*y₀) id)), by { ext, simp [uncurry, prod.map, mul_assoc] }, specialize hconj y₀⁻¹, rw inv_inv at hconj, calc map (λ (p : G × G), p.1 * p.2) (𝓝 (x₀, y₀)) = map (λ (p : G × G), p.1 * p.2) ((𝓝 x₀) ×ᶠ 𝓝 y₀) : by rw nhds_prod_eq ... = map (λ (p : G × G), x₀ * p.1 * (y₀ * p.2)) ((𝓝 1) ×ᶠ (𝓝 1)) : by rw [hleft x₀, hleft y₀, prod_map_map_eq, filter.map_map] ... = map (((λ x, x₀*y₀*x) ∘ (uncurry (*))) ∘ (prod.map (λ x, y₀⁻¹*x*y₀) id))((𝓝 1) ×ᶠ (𝓝 1)) : by rw key ... = map ((λ x, x₀*y₀*x) ∘ (uncurry (*))) ((map (λ x, y₀⁻¹*x*y₀) $ 𝓝 1) ×ᶠ (𝓝 1)) : by rw [← filter.map_map, ← prod_map_map_eq', map_id] ... ≤ map ((λ x, x₀*y₀*x) ∘ (uncurry (*))) ((𝓝 1) ×ᶠ (𝓝 1)) : map_mono (filter.prod_mono hconj $ le_refl _) ... = map (λ x, x₀*y₀*x) (map (uncurry (*)) ((𝓝 1) ×ᶠ (𝓝 1))) : by rw filter.map_map ... ≤ map (λ x, x₀*y₀*x) (𝓝 1) : map_mono hmul ... = 𝓝 (x₀*y₀) : (hleft _).symm end, continuous_inv := topological_group.of_nhds_aux hinv hleft hconj} @[to_additive] lemma topological_group.of_comm_of_nhds_one {G : Type*} [comm_group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) : topological_group G := topological_group.of_nhds_one hmul hinv hleft (by simpa using tendsto_id) end topological_group section quotient_topological_group variables [topological_space G] [group G] [topological_group G] (N : subgroup G) (n : N.normal) @[to_additive] instance {G : Type*} [group G] [topological_space G] (N : subgroup G) : topological_space (quotient_group.quotient N) := quotient.topological_space open quotient_group @[to_additive] lemma quotient_group.is_open_map_coe : is_open_map (coe : G → quotient N) := begin intros s s_op, change is_open ((coe : G → quotient N) ⁻¹' (coe '' s)), rw quotient_group.preimage_image_coe N s, exact is_open_Union (λ n, is_open_map_mul_right n s s_op) end @[to_additive] instance topological_group_quotient [N.normal] : topological_group (quotient N) := { continuous_mul := begin have cont : continuous ((coe : G → quotient N) ∘ (λ (p : G × G), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, have quot : quotient_map (λ p : G × G, ((p.1:quotient N), (p.2:quotient N))), { apply is_open_map.to_quotient_map, { exact (quotient_group.is_open_map_coe N).prod (quotient_group.is_open_map_coe N) }, { exact continuous_quot_mk.prod_map continuous_quot_mk }, { exact (surjective_quot_mk _).prod_map (surjective_quot_mk _) } }, exact (quotient_map.continuous_iff quot).2 cont, end, continuous_inv := begin have : continuous ((coe : G → quotient N) ∘ (λ (a : G), a⁻¹)) := continuous_quot_mk.comp continuous_inv, convert continuous_quotient_lift _ this, end } attribute [instance] topological_add_group_quotient end quotient_topological_group /-- A typeclass saying that `λ p : G × G, p.1 - p.2` is a continuous function. This property automatically holds for topological additive groups but it also holds, e.g., for `ℝ≥0`. -/ class has_continuous_sub (G : Type*) [topological_space G] [has_sub G] : Prop := (continuous_sub : continuous (λ p : G × G, p.1 - p.2)) @[priority 100] -- see Note [lower instance priority] instance topological_add_group.to_has_continuous_sub [topological_space G] [add_group G] [topological_add_group G] : has_continuous_sub G := ⟨by { simp only [sub_eq_add_neg], exact continuous_fst.add continuous_snd.neg }⟩ export has_continuous_sub (continuous_sub) section has_continuous_sub variables [topological_space G] [has_sub G] [has_continuous_sub G] lemma filter.tendsto.sub {f g : α → G} {l : filter α} {a b : G} (hf : tendsto f l (𝓝 a)) (hg : tendsto g l (𝓝 b)) : tendsto (λx, f x - g x) l (𝓝 (a - b)) := (continuous_sub.tendsto (a, b)).comp (hf.prod_mk_nhds hg) variables [topological_space α] {f g : α → G} {s : set α} {x : α} @[continuity] lemma continuous.sub (hf : continuous f) (hg : continuous g) : continuous (λ x, f x - g x) := continuous_sub.comp (hf.prod_mk hg : _) lemma continuous_within_at.sub (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λ x, f x - g x) s x := hf.sub hg lemma continuous_on.sub (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x - g x) s := λ x hx, (hf x hx).sub (hg x hx) end has_continuous_sub lemma nhds_translation [topological_space G] [add_group G] [topological_add_group G] (x : G) : comap (λy:G, y - x) (𝓝 0) = 𝓝 x := by simpa only [sub_eq_add_neg] using nhds_translation_add_neg x /-- additive group with a neighbourhood around 0. Only used to construct a topology and uniform space. This is currently only available for commutative groups, but it can be extended to non-commutative groups too. -/ class add_group_with_zero_nhd (G : Type u) extends add_comm_group G := (Z [] : filter G) (zero_Z : pure 0 ≤ Z) (sub_Z : tendsto (λp:G×G, p.1 - p.2) (Z ×ᶠ Z) Z) namespace add_group_with_zero_nhd variables (G) [add_group_with_zero_nhd G] local notation `Z` := add_group_with_zero_nhd.Z @[priority 100] -- see Note [lower instance priority] instance : topological_space G := topological_space.mk_of_nhds $ λa, map (λx, x + a) (Z G) variables {G} lemma neg_Z : tendsto (λa:G, - a) (Z G) (Z G) := have tendsto (λa, (0:G)) (Z G) (Z G), by refine le_trans (assume h, _) zero_Z; simp [univ_mem_sets'] {contextual := tt}, have tendsto (λa:G, 0 - a) (Z G) (Z G), from sub_Z.comp (tendsto.prod_mk this tendsto_id), by simpa lemma add_Z : tendsto (λp:G×G, p.1 + p.2) (Z G ×ᶠ Z G) (Z G) := suffices tendsto (λp:G×G, p.1 - -p.2) (Z G ×ᶠ Z G) (Z G), by simpa [sub_eq_add_neg], sub_Z.comp (tendsto.prod_mk tendsto_fst (neg_Z.comp tendsto_snd)) lemma exists_Z_half {s : set G} (hs : s ∈ Z G) : ∃ V ∈ Z G, ∀ (v ∈ V) (w ∈ V), v + w ∈ s := begin have : ((λa:G×G, a.1 + a.2) ⁻¹' s) ∈ Z G ×ᶠ Z G := add_Z (by simpa using hs), rcases mem_prod_self_iff.1 this with ⟨V, H, H'⟩, exact ⟨V, H, prod_subset_iff.1 H'⟩ end lemma nhds_eq (a : G) : 𝓝 a = map (λx, x + a) (Z G) := topological_space.nhds_mk_of_nhds _ _ (assume a, calc pure a = map (λx, x + a) (pure 0) : by simp ... ≤ _ : map_mono zero_Z) (assume b s hs, let ⟨t, ht, eqt⟩ := exists_Z_half hs in have t0 : (0:G) ∈ t, by simpa using zero_Z ht, begin refine ⟨(λx:G, x + b) '' t, image_mem_map ht, _, _⟩, { refine set.image_subset_iff.2 (assume b hbt, _), simpa using eqt 0 t0 b hbt }, { rintros _ ⟨c, hb, rfl⟩, refine (Z G).sets_of_superset ht (assume x hxt, _), simpa [add_assoc] using eqt _ hxt _ hb } end) lemma nhds_zero_eq_Z : 𝓝 0 = Z G := by simp [nhds_eq]; exact filter.map_id @[priority 100] -- see Note [lower instance priority] instance : has_continuous_add G := ⟨ continuous_iff_continuous_at.2 $ assume ⟨a, b⟩, begin rw [continuous_at, nhds_prod_eq, nhds_eq, nhds_eq, nhds_eq, filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λx:G, (a + b) + x) ∘ (λp:G×G,p.1 + p.2)) (Z G ×ᶠ Z G) (map (λx:G, (a + b) + x) (Z G)), { simpa [(∘), add_comm, add_left_comm] }, exact tendsto_map.comp add_Z end ⟩ @[priority 100] -- see Note [lower instance priority] instance : topological_add_group G := ⟨continuous_iff_continuous_at.2 $ assume a, begin rw [continuous_at, nhds_eq, nhds_eq, tendsto_map'_iff], suffices : tendsto ((λx:G, x - a) ∘ (λx:G, -x)) (Z G) (map (λx:G, x - a) (Z G)), { simpa [(∘), add_comm, sub_eq_add_neg] using this }, exact tendsto_map.comp neg_Z end⟩ end add_group_with_zero_nhd section filter_mul section variables [topological_space G] [group G] [topological_group G] @[to_additive] lemma is_open.mul_left {s t : set G} : is_open t → is_open (s * t) := λ ht, begin have : ∀a, is_open ((λ (x : G), a * x) '' t) := assume a, is_open_map_mul_left a t ht, rw ← Union_mul_left_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end @[to_additive] lemma is_open.mul_right {s t : set G} : is_open s → is_open (s * t) := λ hs, begin have : ∀a, is_open ((λ (x : G), x * a) '' s), assume a, apply is_open_map_mul_right, exact hs, rw ← Union_mul_right_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end variables (G) lemma topological_group.t1_space (h : @is_closed G _ {1}) : t1_space G := ⟨assume x, by { convert is_closed_map_mul_right x _ h, simp }⟩ lemma topological_group.regular_space [t1_space G] : regular_space G := ⟨assume s a hs ha, let f := λ p : G × G, p.1 * (p.2)⁻¹ in have hf : continuous f := continuous_fst.mul continuous_snd.inv, -- a ∈ -s implies f (a, 1) ∈ -s, and so (a, 1) ∈ f⁻¹' (-s); -- and so can find t₁ t₂ open such that a ∈ t₁ × t₂ ⊆ f⁻¹' (-s) let ⟨t₁, t₂, ht₁, ht₂, a_mem_t₁, one_mem_t₂, t_subset⟩ := is_open_prod_iff.1 ((is_open_compl_iff.2 hs).preimage hf) a (1:G) (by simpa [f]) in begin use [s * t₂, ht₂.mul_left, λ x hx, ⟨x, 1, hx, one_mem_t₂, mul_one _⟩], rw [nhds_within, inf_principal_eq_bot, mem_nhds_sets_iff], refine ⟨t₁, _, ht₁, a_mem_t₁⟩, rintros x hx ⟨y, z, hy, hz, yz⟩, have : x * z⁻¹ ∈ sᶜ := (prod_subset_iff.1 t_subset) x hx z hz, have : x * z⁻¹ ∈ s, rw ← yz, simpa, contradiction end⟩ local attribute [instance] topological_group.regular_space lemma topological_group.t2_space [t1_space G] : t2_space G := regular_space.t2_space G end section /-! Some results about an open set containing the product of two sets in a topological group. -/ variables [topological_space G] [group G] [topological_group G] /-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1` such that `KV ⊆ U`. -/ @[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `0` such that `K + V ⊆ U`."] lemma compact_open_separated_mul {K U : set G} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V : set G, is_open V ∧ (1 : G) ∈ V ∧ K * V ⊆ U := begin let W : G → set G := λ x, (λ y, x * y) ⁻¹' U, have h1W : ∀ x, is_open (W x) := λ x, hU.preimage (continuous_mul_left x), have h2W : ∀ x ∈ K, (1 : G) ∈ W x := λ x hx, by simp only [mem_preimage, mul_one, hKU hx], choose V hV using λ x : K, exists_open_nhds_one_mul_subset (mem_nhds_sets (h1W x) (h2W x.1 x.2)), let X : K → set G := λ x, (λ y, (x : G)⁻¹ * y) ⁻¹' (V x), obtain ⟨t, ht⟩ : ∃ t : finset ↥K, K ⊆ ⋃ i ∈ t, X i, { refine hK.elim_finite_subcover X (λ x, (hV x).1.preimage (continuous_mul_left x⁻¹)) _, intros x hx, rw [mem_Union], use ⟨x, hx⟩, rw [mem_preimage], convert (hV _).2.1, simp only [mul_left_inv, subtype.coe_mk] }, refine ⟨⋂ x ∈ t, V x, is_open_bInter (finite_mem_finset _) (λ x hx, (hV x).1), _, _⟩, { simp only [mem_Inter], intros x hx, exact (hV x).2.1 }, rintro _ ⟨x, y, hx, hy, rfl⟩, simp only [mem_Inter] at hy, have := ht hx, simp only [mem_Union, mem_preimage] at this, rcases this with ⟨z, h1z, h2z⟩, have : (z : G)⁻¹ * x * y ∈ W z := (hV z).2.2 (mul_mem_mul h2z (hy z h1z)), rw [mem_preimage] at this, convert this using 1, simp only [mul_assoc, mul_inv_cancel_left] end /-- A compact set is covered by finitely many left multiplicative translates of a set with non-empty interior. -/ @[to_additive "A compact set is covered by finitely many left additive translates of a set with non-empty interior."] lemma compact_covered_by_mul_left_translates {K V : set G} (hK : is_compact K) (hV : (interior V).nonempty) : ∃ t : finset G, K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V := begin obtain ⟨t, ht⟩ : ∃ t : finset G, K ⊆ ⋃ x ∈ t, interior (((*) x) ⁻¹' V), { refine hK.elim_finite_subcover (λ x, interior $ ((*) x) ⁻¹' V) (λ x, is_open_interior) _, cases hV with g₀ hg₀, refine λ g hg, mem_Union.2 ⟨g₀ * g⁻¹, _⟩, refine preimage_interior_subset_interior_preimage (continuous_const.mul continuous_id) _, rwa [mem_preimage, inv_mul_cancel_right] }, exact ⟨t, subset.trans ht $ bUnion_subset_bUnion_right $ λ g hg, interior_subset⟩ end /-- Every locally compact separable topological group is σ-compact. Note: this is not true if we drop the topological group hypothesis. -/ @[priority 100] instance separable_locally_compact_group.sigma_compact_space [separable_space G] [locally_compact_space G] : sigma_compact_space G := begin obtain ⟨L, hLc, hL1⟩ := exists_compact_mem_nhds (1 : G), refine ⟨⟨λ n, (λ x, x * dense_seq G n) ⁻¹' L, _, _⟩⟩, { intro n, exact (homeomorph.mul_right _).compact_preimage.mpr hLc }, { refine Union_eq_univ_iff.2 (λ x, _), obtain ⟨_, ⟨n, rfl⟩, hn⟩ : (range (dense_seq G) ∩ (λ y, x * y) ⁻¹' L).nonempty, { rw [← (homeomorph.mul_left x).apply_symm_apply 1] at hL1, exact (dense_range_dense_seq G).inter_nhds_nonempty ((homeomorph.mul_left x).continuous.continuous_at $ hL1) }, exact ⟨n, hn⟩ } end end section variables [topological_space G] [comm_group G] [topological_group G] @[to_additive] lemma nhds_mul (x y : G) : 𝓝 (x * y) = 𝓝 x * 𝓝 y := filter_eq $ set.ext $ assume s, begin rw [← nhds_translation_mul_inv x, ← nhds_translation_mul_inv y, ← nhds_translation_mul_inv (x*y)], split, { rintros ⟨t, ht, ts⟩, rcases exists_nhds_one_split ht with ⟨V, V1, h⟩, refine ⟨(λa, a * x⁻¹) ⁻¹' V, (λa, a * y⁻¹) ⁻¹' V, ⟨V, V1, subset.refl _⟩, ⟨V, V1, subset.refl _⟩, _⟩, rintros a ⟨v, w, v_mem, w_mem, rfl⟩, apply ts, simpa [mul_comm, mul_assoc, mul_left_comm] using h (v * x⁻¹) v_mem (w * y⁻¹) w_mem }, { rintros ⟨a, c, ⟨b, hb, ba⟩, ⟨d, hd, dc⟩, ac⟩, refine ⟨b ∩ d, inter_mem_sets hb hd, assume v, _⟩, simp only [preimage_subset_iff, mul_inv_rev, mem_preimage] at *, rintros ⟨vb, vd⟩, refine ac ⟨v * y⁻¹, y, _, _, _⟩, { rw ← mul_assoc _ _ _ at vb, exact ba _ vb }, { apply dc y, rw mul_right_inv, exact mem_of_nhds hd }, { simp only [inv_mul_cancel_right] } } end @[to_additive] lemma nhds_is_mul_hom : is_mul_hom (λx:G, 𝓝 x) := ⟨λ_ _, nhds_mul _ _⟩ end end filter_mul instance additive.topological_add_group {G} [h : topological_space G] [group G] [topological_group G] : @topological_add_group (additive G) h _ := { continuous_neg := @continuous_inv G _ _ _ } instance multiplicative.topological_group {G} [h : topological_space G] [add_group G] [topological_add_group G] : @topological_group (multiplicative G) h _ := { continuous_inv := @continuous_neg G _ _ _ } namespace units variables [monoid α] [topological_space α] [has_continuous_mul α] instance : topological_group (units α) := { continuous_inv := continuous_induced_rng ((continuous_unop.comp (continuous_snd.comp (@continuous_embed_product α _ _))).prod_mk (continuous_op.comp continuous_coe)) } end units
b6cd9379ca6413395c2cc2818bdc98d2ba94cdd7
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/generalizeTelescope.lean
8949d90c4e786ef024fc6360a729c2b4d0373e96
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,393
lean
import Lean open Lean open Lean.Meta inductive Vec (α : Type) : Nat → Type | nil : Vec 0 | cons {n} : α → Vec n → Vec (n+1) set_option trace.Meta.debug true def nat := mkConst `Nat def succ := mkConst `Nat.succ def tst1 : MetaM Unit := withLocalDeclD `n nat $ fun n => do let n1 := mkApp succ n; let vecN1 := mkApp2 (mkConst `Vec) nat n1; withLocalDeclD `xs vecN1 $ fun xs => do generalizeTelescope #[n1, xs] `aux $ fun ys => do t ← mkLambdaFVars ys ys.back; trace! `Meta.debug t; pure () #eval tst1 set_option pp.all true def tst2 : MetaM Unit := withLocalDeclD `n nat $ fun n => do let n1 := mkApp succ n; let vecN1 := mkApp2 (mkConst `Vec) nat n1; withLocalDeclD `xs vecN1 $ fun xs => do e ← mkEqRefl xs; generalizeTelescope #[n1, xs, e] `aux $ fun ys => do t ← mkLambdaFVars ys ys.back; trace! `Meta.debug t; pure () #eval tst2 def failIfSuccess (x : MetaM Unit) : MetaM Unit := whenM (catch (x *> pure true) (fun _ => pure false)) $ throwError "unexpected success" def tst3 : MetaM Unit := withLocalDeclD `n nat $ fun n => do let n1 := mkApp succ n; let vecN1 := mkApp2 (mkConst `Vec) nat n1; withLocalDeclD `xs vecN1 $ fun xs => do e ← mkEqRefl xs; failIfSuccess $ do { generalizeTelescope #[n1, e] `aux $ fun ys => do t ← mkLambdaFVars ys ys.back; trace! `Meta.debug t; pure () }; trace! `Meta.debug "failed as expected" #eval tst3