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
fcdf5220913edd68883b2d037ba4e7ed05d2cec9
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/zipper.lean
0f26a406d2a5af8aa88312397e918c618e927e18
[ "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,402
lean
structure ListZipper (α : Type) := (xs : List α) (bs : List α) -- set_option trace.compiler.ir.rc true variable {α : Type} namespace ListZipper def goForward : ListZipper α → ListZipper α | ⟨[], bs⟩ => ⟨[], bs⟩ | ⟨x::xs, bs⟩ => ⟨xs, x::bs⟩ def goBackward : ListZipper α → ListZipper α | ⟨xs, []⟩ => ⟨xs, []⟩ | ⟨xs, b::bs⟩ => ⟨b::xs, bs⟩ def insert : ListZipper α → α → ListZipper α | ⟨xs, bs⟩, x => ⟨xs, x::bs⟩ def erase : ListZipper α → ListZipper α | ⟨[], bs⟩ => ⟨[], bs⟩ | ⟨x::xs, bs⟩ => ⟨xs, bs⟩ def curr [Inhabited α] : ListZipper α → α | ⟨[], bs⟩ => default | ⟨x::xs, bs⟩ => x def currOpt : ListZipper α → Option α | ⟨[], bs⟩ => none | ⟨x::xs, bs⟩ => some x def toList : ListZipper α → List α | ⟨xs, bs⟩ => bs.reverse ++ xs def atEnd (z : ListZipper α) : Bool := z.xs.isEmpty end ListZipper def List.toListZipper (xs : List α) : ListZipper α := ⟨xs, []⟩ partial def testAux : ListZipper Nat → ListZipper Nat | z => if z.atEnd then z else if z.curr % 2 == 0 then testAux (z.goForward.insert 0) else if z.curr > 20 then testAux z.erase else testAux z.goForward -- testAux z.goForward def test (xs : List Nat) : List Nat := (testAux xs.toListZipper).toList #eval (IO.println (test [10, 11, 13, 20, 22, 40, 41, 11]) : IO Unit)
5ac22c31c73dac0ffff081151b913520b7368fa8
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/limits/over.lean
16be8d564aece38333fd4f315b717d1c8c28eec8
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
5,528
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Reid Barton, Bhavik Mehta -/ import category_theory.over import category_theory.adjunction.opposites import category_theory.limits.preserves.basic import category_theory.limits.shapes.pullbacks import category_theory.limits.creates import category_theory.limits.comma /-! # Limits and colimits in the over and under categories Show that the forgetful functor `forget X : over X ⥤ C` creates colimits, and hence `over X` has any colimits that `C` has (as well as the dual that `forget X : under X ⟶ C` creates limits). Note that the folder `category_theory.limits.shapes.constructions.over` further shows that `forget X : over X ⥤ C` creates connected limits (so `over X` has connected limits), and that `over X` has `J`-indexed products if `C` has `J`-indexed wide pullbacks. TODO: If `C` has binary products, then `forget X : over X ⥤ C` has a right adjoint. -/ noncomputable theory universes v u -- morphism levels before object levels. See note [category_theory universes]. open category_theory category_theory.limits variables {J : Type v} [small_category J] variables {C : Type u} [category.{v} C] variable {X : C} namespace category_theory.over instance has_colimit_of_has_colimit_comp_forget (F : J ⥤ over X) [i : has_colimit (F ⋙ forget X)] : has_colimit F := @@costructured_arrow.has_colimit _ _ _ _ i _ instance [has_colimits_of_shape J C] : has_colimits_of_shape J (over X) := {} instance [has_colimits C] : has_colimits (over X) := ⟨infer_instance⟩ instance creates_colimits : creates_colimits (forget X) := costructured_arrow.creates_colimits -- We can automatically infer that the forgetful functor preserves and reflects colimits. example [has_colimits C] : preserves_colimits (forget X) := infer_instance example : reflects_colimits (forget X) := infer_instance lemma epi_left_of_epi [has_pushouts C] {f g : over X} (h : f ⟶ g) [epi h] : epi h.left := costructured_arrow.epi_left_of_epi _ lemma epi_iff_epi_left [has_pushouts C] {f g : over X} (h : f ⟶ g) : epi h ↔ epi h.left := costructured_arrow.epi_iff_epi_left _ section variables [has_pullbacks C] open tactic /-- When `C` has pullbacks, a morphism `f : X ⟶ Y` induces a functor `over Y ⥤ over X`, by pulling back a morphism along `f`. -/ @[simps] def pullback {X Y : C} (f : X ⟶ Y) : over Y ⥤ over X := { obj := λ g, over.mk (pullback.snd : pullback g.hom f ⟶ X), map := λ g h k, over.hom_mk (pullback.lift (pullback.fst ≫ k.left) pullback.snd (by simp [pullback.condition])) (by tidy) } /-- `over.map f` is left adjoint to `over.pullback f`. -/ def map_pullback_adj {A B : C} (f : A ⟶ B) : over.map f ⊣ pullback f := adjunction.mk_of_hom_equiv { hom_equiv := λ g h, { to_fun := λ X, over.hom_mk (pullback.lift X.left g.hom (over.w X)) (pullback.lift_snd _ _ _), inv_fun := λ Y, begin refine over.hom_mk _ _, refine Y.left ≫ pullback.fst, dsimp, rw [← over.w Y, category.assoc, pullback.condition, category.assoc], refl, end, left_inv := λ X, by { ext, dsimp, simp, }, right_inv := λ Y, begin ext, dsimp, simp only [pullback.lift_fst], dsimp, rw [pullback.lift_snd, ← over.w Y], refl, end } } /-- pullback (𝟙 A) : over A ⥤ over A is the identity functor. -/ def pullback_id {A : C} : pullback (𝟙 A) ≅ 𝟭 _ := adjunction.right_adjoint_uniq (map_pullback_adj _) (adjunction.id.of_nat_iso_left over.map_id.symm) /-- pullback commutes with composition (up to natural isomorphism). -/ def pullback_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) : pullback (f ≫ g) ≅ pullback g ⋙ pullback f := adjunction.right_adjoint_uniq (map_pullback_adj _) (((map_pullback_adj _).comp (map_pullback_adj _)).of_nat_iso_left (over.map_comp _ _).symm) instance pullback_is_right_adjoint {A B : C} (f : A ⟶ B) : is_right_adjoint (pullback f) := ⟨_, map_pullback_adj f⟩ end end category_theory.over namespace category_theory.under instance has_limit_of_has_limit_comp_forget (F : J ⥤ under X) [i : has_limit (F ⋙ forget X)] : has_limit F := @@structured_arrow.has_limit _ _ _ _ i _ instance [has_limits_of_shape J C] : has_limits_of_shape J (under X) := {} instance [has_limits C] : has_limits (under X) := ⟨infer_instance⟩ lemma mono_right_of_mono [has_pullbacks C] {f g : under X} (h : f ⟶ g) [mono h] : mono h.right := structured_arrow.mono_right_of_mono _ lemma mono_iff_mono_right [has_pullbacks C] {f g : under X} (h : f ⟶ g) : mono h ↔ mono h.right := structured_arrow.mono_iff_mono_right _ instance creates_limits : creates_limits (forget X) := structured_arrow.creates_limits -- We can automatically infer that the forgetful functor preserves and reflects limits. example [has_limits C] : preserves_limits (forget X) := infer_instance example : reflects_limits (forget X) := infer_instance section variables [has_pushouts C] /-- When `C` has pushouts, a morphism `f : X ⟶ Y` induces a functor `under X ⥤ under Y`, by pushing a morphism forward along `f`. -/ @[simps] def pushout {X Y : C} (f : X ⟶ Y) : under X ⥤ under Y := { obj := λ g, under.mk (pushout.inr : Y ⟶ pushout g.hom f), map := λ g h k, under.hom_mk (pushout.desc (k.right ≫ pushout.inl) pushout.inr (by { simp [←pushout.condition], })) (by tidy) } end end category_theory.under
a9816b841a742852790544ec1e23bec0bda6a5de
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/ring_theory/fractional_ideal.lean
133fb6afb9cd2e2b20cc9342c3700bed1a222d06
[ "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
24,229
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import ring_theory.localization import ring_theory.principal_ideal_domain /-! # Fractional ideals This file defines fractional ideals of an integral domain and proves basic facts about them. ## Main definitions Let `S` be a submonoid of an integral domain `R`, `P` the localization of `R` at `S`, and `f` the natural ring hom from `R` to `P`. * `is_fractional` defines which `R`-submodules of `P` are fractional ideals * `fractional_ideal f` is the type of fractional ideals in `P` * `has_coe (ideal R) (fractional_ideal f)` instance * `comm_semiring (fractional_ideal f)` instance: the typical ideal operations generalized to fractional ideals * `lattice (fractional_ideal f)` instance * `map` is the pushforward of a fractional ideal along an algebra morphism Let `K` be the localization of `R` at `R \ {0}` and `g` the natural ring hom from `R` to `K`. * `has_div (fractional_ideal g)` instance: the ideal quotient `I / J` (typically written $I : J$, but a `:` operator cannot be defined) ## Main statements * `mul_left_mono` and `mul_right_mono` state that ideal multiplication is monotone * `right_inverse_eq` states that `1 / I` is the inverse of `I` if one exists ## Implementation notes Fractional ideals are considered equal when they contain the same elements, independent of the denominator `a : R` such that `a I ⊆ R`. Thus, we define `fractional_ideal` to be the subtype of the predicate `is_fractional`, instead of having `fractional_ideal` be a structure of which `a` is a field. Most definitions in this file specialize operations from submodules to fractional ideals, proving that the result of this operation is fractional if the input is fractional. Exceptions to this rule are defining `(+) := (⊔)` and `⊥ := 0`, in order to re-use their respective proof terms. We can still use `simp` to show `I.1 + J.1 = (I + J).1` and `⊥.1 = 0.1`. In `ring_theory.localization`, we define a copy of the localization map `f`'s codomain `P` (`f.codomain`) so that the `R`-algebra instance on `P` can 'know' the map needed to induce the `R`-algebra structure. We don't assume that the localization is a field until we need it to define ideal quotients. When this assumption is needed, we replace `S` with `non_zero_divisors R`, making the localization a field. ## References * https://en.wikipedia.org/wiki/Fractional_ideal ## Tags fractional ideal, fractional ideals, invertible ideal -/ open localization_map namespace ring section defs variables {R : Type*} [integral_domain R] {S : submonoid R} {P : Type*} [comm_ring P] (f : localization_map S P) /-- A submodule `I` is a fractional ideal if `a I ⊆ R` for some `a ≠ 0`. -/ def is_fractional (I : submodule R f.codomain) := ∃ a ∈ S, ∀ b ∈ I, f.is_integer (f.to_map a * b) /-- The fractional ideals of a domain `R` are ideals of `R` divided by some `a ∈ R`. More precisely, let `P` be a localization of `R` at some submonoid `S`, then a fractional ideal `I ⊆ P` is an `R`-submodule of `P`, such that there is a nonzero `a : R` with `a I ⊆ R`. -/ def fractional_ideal := {I : submodule R f.codomain // is_fractional f I} end defs namespace fractional_ideal open set open submodule variables {R : Type*} [integral_domain R] {S : submonoid R} {P : Type*} [comm_ring P] {f : localization_map S P} instance : has_coe (fractional_ideal f) (submodule R f.codomain) := ⟨λ I, I.val⟩ @[simp] lemma val_eq_coe (I : fractional_ideal f) : I.val = I := rfl instance : has_mem P (fractional_ideal f) := ⟨λ x I, x ∈ (I : submodule R f.codomain)⟩ /-- Fractional ideals are equal if their submodules are equal. Combined with `submodule.ext` this gives that fractional ideals are equal if they have the same elements. -/ @[ext] lemma ext {I J : fractional_ideal f} : (I : submodule R f.codomain) = J → I = J := subtype.ext_iff_val.mpr lemma fractional_of_subset_one (I : submodule R f.codomain) (h : I ≤ (submodule.span R {1})) : is_fractional f I := begin use [1, S.one_mem], intros b hb, rw [f.to_map.map_one, one_mul], rw ←submodule.one_eq_span at h, obtain ⟨b', b'_mem, b'_eq_b⟩ := h hb, rw (show b = f.to_map b', from b'_eq_b.symm), exact set.mem_range_self b', end instance coe_to_fractional_ideal : has_coe (ideal R) (fractional_ideal f) := ⟨ λ I, ⟨↑I, fractional_of_subset_one _ $ λ x ⟨y, hy, h⟩, submodule.mem_span_singleton.2 ⟨y, by rw ←h; exact mul_one _⟩⟩ ⟩ @[simp] lemma coe_coe_ideal (I : ideal R) : ((I : fractional_ideal f) : submodule R f.codomain) = I := rfl @[simp] lemma mem_coe {x : f.codomain} {I : ideal R} : x ∈ (I : fractional_ideal f) ↔ ∃ (x' ∈ I), f.to_map x' = x := ⟨ λ ⟨x', hx', hx⟩, ⟨x', hx', hx⟩, λ ⟨x', hx', hx⟩, ⟨x', hx', hx⟩ ⟩ instance : has_zero (fractional_ideal f) := ⟨(0 : ideal R)⟩ @[simp] lemma mem_zero_iff {x : P} : x ∈ (0 : fractional_ideal f) ↔ x = 0 := ⟨ (λ ⟨x', x'_mem_zero, x'_eq_x⟩, have x'_eq_zero : x' = 0 := x'_mem_zero, by simp [x'_eq_x.symm, x'_eq_zero]), (λ hx, ⟨0, rfl, by simp [hx]⟩) ⟩ @[simp] lemma coe_zero : ↑(0 : fractional_ideal f) = (⊥ : submodule R f.codomain) := submodule.ext $ λ _, mem_zero_iff lemma coe_ne_bot_iff_nonzero {I : fractional_ideal f} : ↑I ≠ (⊥ : submodule R f.codomain) ↔ I ≠ 0 := ⟨ λ h h', h (by simp [h']), λ h h', h (ext (by simp [h'])) ⟩ instance : inhabited (fractional_ideal f) := ⟨0⟩ instance : has_one (fractional_ideal f) := ⟨(1 : ideal R)⟩ lemma mem_one_iff {x : P} : x ∈ (1 : fractional_ideal f) ↔ ∃ x' : R, f.to_map x' = x := iff.intro (λ ⟨x', _, h⟩, ⟨x', h⟩) (λ ⟨x', h⟩, ⟨x', ⟨x', set.mem_univ _, rfl⟩, h⟩) lemma coe_mem_one (x : R) : f.to_map x ∈ (1 : fractional_ideal f) := mem_one_iff.mpr ⟨x, rfl⟩ lemma one_mem_one : (1 : P) ∈ (1 : fractional_ideal f) := mem_one_iff.mpr ⟨1, f.to_map.map_one⟩ @[simp] lemma coe_one : ↑(1 : fractional_ideal f) = ((1 : ideal R) : submodule R f.codomain) := rfl section lattice /-! ### `lattice` section Defines the order on fractional ideals as inclusion of their underlying sets, and ports the lattice structure on submodules to fractional ideals. -/ instance : partial_order (fractional_ideal f) := { le := λ I J, I.1 ≤ J.1, le_refl := λ I, le_refl I.1, le_antisymm := λ ⟨I, hI⟩ ⟨J, hJ⟩ hIJ hJI, by { congr, exact le_antisymm hIJ hJI }, le_trans := λ _ _ _ hIJ hJK, le_trans hIJ hJK } lemma le_iff {I J : fractional_ideal f} : I ≤ J ↔ (∀ x ∈ I, x ∈ J) := iff.refl _ lemma zero_le (I : fractional_ideal f) : 0 ≤ I := begin intros x hx, convert submodule.zero_mem _, simpa using hx end instance order_bot : order_bot (fractional_ideal f) := { bot := 0, bot_le := zero_le, ..fractional_ideal.partial_order } @[simp] lemma bot_eq_zero : (⊥ : fractional_ideal f) = 0 := rfl lemma eq_zero_iff {I : fractional_ideal f} : I = 0 ↔ (∀ x ∈ I, x = (0 : P)) := ⟨ (λ h x hx, by simpa [h, mem_zero_iff] using hx), (λ h, le_bot_iff.mp (λ x hx, mem_zero_iff.mpr (h x hx))) ⟩ lemma fractional_sup (I J : fractional_ideal f) : is_fractional f (I.1 ⊔ J.1) := begin rcases I.2 with ⟨aI, haI, hI⟩, rcases J.2 with ⟨aJ, haJ, hJ⟩, use aI * aJ, use S.mul_mem haI haJ, intros b hb, rcases mem_sup.mp hb with ⟨bI, hbI, bJ, hbJ, hbIJ⟩, rw [←hbIJ, mul_add], apply is_integer_add, { rw [mul_comm aI, f.to_map.map_mul, mul_assoc], apply is_integer_smul (hI bI hbI), }, { rw [f.to_map.map_mul, mul_assoc], apply is_integer_smul (hJ bJ hbJ) } end lemma fractional_inf (I J : fractional_ideal f) : is_fractional f (I.1 ⊓ J.1) := begin rcases I.2 with ⟨aI, haI, hI⟩, use aI, use haI, intros b hb, rcases mem_inf.mp hb with ⟨hbI, hbJ⟩, exact (hI b hbI) end instance lattice : lattice (fractional_ideal f) := { inf := λ I J, ⟨I.1 ⊓ J.1, fractional_inf I J⟩, sup := λ I J, ⟨I.1 ⊔ J.1, fractional_sup I J⟩, inf_le_left := λ I J, show I.1 ⊓ J.1 ≤ I.1, from inf_le_left, inf_le_right := λ I J, show I.1 ⊓ J.1 ≤ J.1, from inf_le_right, le_inf := λ I J K hIJ hIK, show I.1 ≤ (J.1 ⊓ K.1), from le_inf hIJ hIK, le_sup_left := λ I J, show I.1 ≤ I.1 ⊔ J.1, from le_sup_left, le_sup_right := λ I J, show J.1 ≤ I.1 ⊔ J.1, from le_sup_right, sup_le := λ I J K hIK hJK, show (I.1 ⊔ J.1) ≤ K.1, from sup_le hIK hJK, ..fractional_ideal.partial_order } instance : semilattice_sup_bot (fractional_ideal f) := { ..fractional_ideal.order_bot, ..fractional_ideal.lattice } end lattice section semiring instance : has_add (fractional_ideal f) := ⟨(⊔)⟩ @[simp] lemma sup_eq_add (I J : fractional_ideal f) : I ⊔ J = I + J := rfl @[simp] lemma coe_add (I J : fractional_ideal f) : (↑(I + J) : submodule R f.codomain) = I + J := rfl lemma fractional_mul (I J : fractional_ideal f) : is_fractional f (I.1 * J.1) := begin rcases I with ⟨I, aI, haI, hI⟩, rcases J with ⟨I, aJ, haJ, hJ⟩, use aI * aJ, use S.mul_mem haI haJ, intros b hb, apply submodule.mul_induction_on hb, { intros m hm n hn, obtain ⟨n', hn'⟩ := hJ n hn, rw [f.to_map.map_mul, mul_comm m, ←mul_assoc, mul_assoc _ _ n], erw ←hn', rw mul_assoc, apply hI, exact submodule.smul_mem _ _ hm }, { rw [mul_zero], exact ⟨0, f.to_map.map_zero⟩ }, { intros x y hx hy, rw [mul_add], apply is_integer_add hx hy }, { intros r x hx, show f.is_integer (_ * (f.to_map r * x)), rw [←mul_assoc, ←f.to_map.map_mul, mul_comm _ r, f.to_map.map_mul, mul_assoc], apply is_integer_smul hx }, end instance : has_mul (fractional_ideal f) := ⟨λ I J, ⟨I.1 * J.1, fractional_mul I J⟩⟩ @[simp] lemma coe_mul (I J : fractional_ideal f) : (↑(I * J) : submodule R f.codomain) = I * J := rfl lemma mul_left_mono (I : fractional_ideal f) : monotone ((*) I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul hx (h hy)) lemma mul_right_mono (I : fractional_ideal f) : monotone (λ J, J * I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul (h hx) hy) instance add_comm_monoid : add_comm_monoid (fractional_ideal f) := { add_assoc := λ I J K, sup_assoc, add_comm := λ I J, sup_comm, add_zero := λ I, sup_bot_eq, zero_add := λ I, bot_sup_eq, ..fractional_ideal.has_zero, ..fractional_ideal.has_add } instance comm_monoid : comm_monoid (fractional_ideal f) := { mul_assoc := λ I J K, ext (submodule.mul_assoc _ _ _), mul_comm := λ I J, ext (submodule.mul_comm _ _), mul_one := λ I, begin ext, split; intro h, { apply mul_le.mpr _ h, rintros x hx y ⟨y', y'_mem_R, y'_eq_y⟩, rw [←y'_eq_y, mul_comm], exact submodule.smul_mem _ _ hx }, { have : x * 1 ∈ (I * 1) := mul_mem_mul h one_mem_one, rwa [mul_one] at this } end, one_mul := λ I, begin ext, split; intro h, { apply mul_le.mpr _ h, rintros x ⟨x', x'_mem_R, x'_eq_x⟩ y hy, rw ←x'_eq_x, exact submodule.smul_mem _ _ hy }, { have : 1 * x ∈ (1 * I) := mul_mem_mul one_mem_one h, rwa [one_mul] at this } end, ..fractional_ideal.has_mul, ..fractional_ideal.has_one } instance comm_semiring : comm_semiring (fractional_ideal f) := { mul_zero := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, by simp [mem_zero_iff.mp hy]) rfl (λ x y hx hy, by simp [hx, hy]) (λ r x hx, by simp [hx])), zero_mul := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, by simp [mem_zero_iff.mp hx]) rfl (λ x y hx hy, by simp [hx, hy]) (λ r x hx, by simp [hx])), left_distrib := λ I J K, ext (mul_add _ _ _), right_distrib := λ I J K, ext (add_mul _ _ _), ..fractional_ideal.add_comm_monoid, ..fractional_ideal.comm_monoid } variables {P' : Type*} [comm_ring P'] {f' : localization_map S P'} variables {P'' : Type*} [comm_ring P''] {f'' : localization_map S P''} lemma fractional_map (g : f.codomain →ₐ[R] f'.codomain) (I : fractional_ideal f) : is_fractional f' (submodule.map g.to_linear_map I.1) := begin rcases I with ⟨I, a, a_nonzero, hI⟩, use [a, a_nonzero], intros b hb, obtain ⟨b', b'_mem, hb'⟩ := submodule.mem_map.mp hb, obtain ⟨x, hx⟩ := hI b' b'_mem, use x, erw [←g.commutes, hx, g.map_smul, hb'], refl end /-- `I.map g` is the pushforward of the fractional ideal `I` along the algebra morphism `g` -/ def map (g : f.codomain →ₐ[R] f'.codomain) : fractional_ideal f → fractional_ideal f' := λ I, ⟨submodule.map g.to_linear_map I.1, fractional_map g I⟩ @[simp] lemma coe_map (g : f.codomain →ₐ[R] f'.codomain) (I : fractional_ideal f) : ↑(map g I) = submodule.map g.to_linear_map I := rfl @[simp] lemma map_id (I : fractional_ideal f) : I.map (alg_hom.id _ _) = I := ext (submodule.map_id I.1) @[simp] lemma map_comp (g : f.codomain →ₐ[R] f'.codomain) (g' : f'.codomain →ₐ[R] f''.codomain) (I : fractional_ideal f) : I.map (g'.comp g) = (I.map g).map g' := ext (submodule.map_comp g.to_linear_map g'.to_linear_map I.1) @[simp] lemma map_add (I J : fractional_ideal f) (g : f.codomain →ₐ[R] f'.codomain) : (I + J).map g = I.map g + J.map g := ext (submodule.map_sup _ _ _) @[simp] lemma map_mul (I J : fractional_ideal f) (g : f.codomain →ₐ[R] f'.codomain) : (I * J).map g = I.map g * J.map g := ext (submodule.map_mul _ _ _) /-- If `g` is an equivalence, `map g` is an isomorphism -/ def map_equiv (g : f.codomain ≃ₐ[R] f'.codomain) : fractional_ideal f ≃+* fractional_ideal f' := { to_fun := map g, inv_fun := map g.symm, map_add' := λ I J, map_add I J _, map_mul' := λ I J, map_mul I J _, left_inv := λ I, by { rw [←map_comp, alg_equiv.symm_comp, map_id] }, right_inv := λ I, by { rw [←map_comp, alg_equiv.comp_symm, map_id] } } @[simp] lemma map_equiv_apply (g : f.codomain ≃ₐ[R] f'.codomain) (I : fractional_ideal f) : map_equiv g I = map ↑g I := rfl @[simp] lemma map_equiv_refl : map_equiv alg_equiv.refl = ring_equiv.refl (fractional_ideal f) := ring_equiv.ext (λ x, by simp) /-- `canonical_equiv f f'` is the canonical equivalence between the fractional ideals in `f.codomain` and in `f'.codomain` -/ noncomputable def canonical_equiv (f f' : localization_map S P) : fractional_ideal f ≃+* fractional_ideal f' := map_equiv { commutes' := λ r, ring_equiv_of_ring_equiv_eq _ _ _, ..ring_equiv_of_ring_equiv f f' (ring_equiv.refl R) (by rw [ring_equiv.to_monoid_hom_refl, submonoid.map_id]) } end semiring section quotient /-! ### `quotient` section This section defines the ideal quotient of fractional ideals. In this section we need that each non-zero `y : R` has an inverse in the localization, i.e. that the localization is a field. We satisfy this assumption by taking `S = non_zero_divisors R`, `R`'s localization at which is a field because `R` is a domain. -/ open_locale classical variables {K : Type*} [field K] {g : fraction_map R K} instance : nontrivial (fractional_ideal g) := ⟨⟨0, 1, λ h, have this : (1 : K) ∈ (0 : fractional_ideal g) := by rw ←g.to_map.map_one; convert coe_mem_one _, one_ne_zero (mem_zero_iff.mp this) ⟩⟩ lemma fractional_div_of_nonzero {I J : fractional_ideal g} (h : J ≠ 0) : is_fractional g (I.1 / J.1) := begin rcases I with ⟨I, aI, haI, hI⟩, rcases J with ⟨J, aJ, haJ, hJ⟩, obtain ⟨y, mem_J, not_mem_zero⟩ := exists_of_lt (bot_lt_iff_ne_bot.mpr h), obtain ⟨y', hy'⟩ := hJ y mem_J, use (aI * y'), split, { apply (non_zero_divisors R).mul_mem haI (mem_non_zero_divisors_iff_ne_zero.mpr _), intro y'_eq_zero, have : g.to_map aJ * y = 0 := by rw [←hy', y'_eq_zero, g.to_map.map_zero], obtain aJ_zero | y_zero := mul_eq_zero.mp this, { have : aJ = 0 := g.to_map.injective_iff.1 g.injective _ aJ_zero, have : aJ ≠ 0 := mem_non_zero_divisors_iff_ne_zero.mp haJ, contradiction }, { exact not_mem_zero (mem_zero_iff.mpr y_zero) } }, intros b hb, rw [g.to_map.map_mul, mul_assoc, mul_comm _ b, hy'], exact hI _ (hb _ (submodule.smul_mem _ aJ mem_J)), end noncomputable instance fractional_ideal_has_div : has_div (fractional_ideal g) := ⟨ λ I J, if h : J = 0 then 0 else ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ ⟩ noncomputable instance : has_inv (fractional_ideal g) := ⟨λ I, 1 / I⟩ lemma div_nonzero {I J : fractional_ideal g} (h : J ≠ 0) : (I / J) = ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ := dif_neg h lemma inv_nonzero {I : fractional_ideal g} (h : I ≠ 0) : I⁻¹ = ⟨(1 : fractional_ideal g) / I, fractional_div_of_nonzero h⟩ := div_nonzero h lemma coe_inv_of_nonzero {I : fractional_ideal g} (h : I ≠ 0) : (↑(I⁻¹) : submodule R g.codomain) = (1 : ideal R) / I := by { rw inv_nonzero h, refl } @[simp] lemma div_one {I : fractional_ideal g} : I / 1 = I := begin rw [div_nonzero (@one_ne_zero (fractional_ideal g) _ _)], ext, split; intro h, { convert mem_div_iff_forall_mul_mem.mp h 1 (g.to_map.map_one ▸ coe_mem_one 1), simp }, { apply mem_div_iff_forall_mul_mem.mpr, rintros y ⟨y', _, y_eq_y'⟩, rw [mul_comm], convert submodule.smul_mem _ y' h, rw ←y_eq_y', refl } end lemma ne_zero_of_mul_eq_one (I J : fractional_ideal g) (h : I * J = 1) : I ≠ 0 := λ hI, @zero_ne_one (fractional_ideal g) _ _ (by { convert h, simp [hI], }) /-- `I⁻¹` is the inverse of `I` if `I` has an inverse. -/ theorem right_inverse_eq (I J : fractional_ideal g) (h : I * J = 1) : J = I⁻¹ := begin have hI : I ≠ 0 := ne_zero_of_mul_eq_one I J h, suffices h' : I * (1 / I) = 1, { exact (congr_arg units.inv $ @units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) }, rw [div_nonzero hI], apply le_antisymm, { apply submodule.mul_le.mpr _, intros x hx y hy, rw [mul_comm], exact mem_div_iff_forall_mul_mem.mp hy x hx }, rw [←h], apply mul_left_mono I, apply submodule.le_div_iff.mpr _, intros y hy x hx, rw [mul_comm], exact mul_mem_mul hx hy end theorem mul_inv_cancel_iff {I : fractional_ideal g} : I * I⁻¹ = 1 ↔ ∃ J, I * J = 1 := ⟨λ h, ⟨I⁻¹, h⟩, λ ⟨J, hJ⟩, by rwa [←right_inverse_eq I J hJ]⟩ end quotient section principal_ideal_ring variables {K : Type*} [field K] {g : fraction_map R K} open_locale classical open submodule submodule.is_principal lemma span_fractional_iff {s : set f.codomain} : is_fractional f (span R s) ↔ ∃ a ∈ S, ∀ (b : P), b ∈ s → f.is_integer (f.to_map a * b) := ⟨ λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, h b (subset_span hb)⟩, λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, span_induction hb h (is_integer_smul ⟨0, f.to_map.map_zero⟩) (λ x y hx hy, by { rw mul_add, exact is_integer_add hx hy }) (λ s x hx, by { rw algebra.mul_smul_comm, exact is_integer_smul hx }) ⟩ ⟩ lemma span_singleton_fractional (x : f.codomain) : is_fractional f (span R {x}) := let ⟨a, ha⟩ := f.exists_integer_multiple x in span_fractional_iff.mpr ⟨ a.1, a.2, λ x hx, (mem_singleton_iff.mp hx).symm ▸ ha⟩ /-- `span_singleton x` is the fractional ideal generated by `x` if `0 ∉ S` -/ def span_singleton (x : f.codomain) : fractional_ideal f := ⟨span R {x}, span_singleton_fractional x⟩ @[simp] lemma coe_span_singleton (x : f.codomain) : (span_singleton x : submodule R f.codomain) = span R {x} := rfl lemma eq_span_singleton_of_principal (I : fractional_ideal f) [is_principal I.1] : I = span_singleton (generator I.1) := ext (span_singleton_generator I.1).symm lemma is_principal_iff (I : fractional_ideal f) : is_principal I.1 ↔ ∃ x, I = span_singleton x := ⟨ λ h, ⟨@generator _ _ _ _ _ I.1 h, @eq_span_singleton_of_principal _ _ _ _ _ _ I h⟩, λ ⟨x, hx⟩, { principal := ⟨x, trans (congr_arg _ hx) (coe_span_singleton x)⟩ } ⟩ @[simp] lemma span_singleton_zero : span_singleton (0 : f.codomain) = 0 := by { ext, simp [submodule.mem_span_singleton, eq_comm, -singleton_zero] } lemma span_singleton_eq_zero_iff {y : f.codomain} : span_singleton y = 0 ↔ y = 0 := ⟨ λ h, span_eq_bot.mp (by simpa using congr_arg subtype.val h : span R {y} = ⊥) y (mem_singleton y), λ h, by simp [h] ⟩ @[simp] lemma span_singleton_one : span_singleton (1 : f.codomain) = 1 := begin ext, refine mem_span_singleton.trans ((exists_congr _).trans mem_one_iff.symm), intro x', refine eq.congr (mul_one _) rfl, end @[simp] lemma span_singleton_mul_span_singleton (x y : f.codomain) : span_singleton x * span_singleton y = span_singleton (x * y) := begin ext, simp_rw [coe_mul, coe_span_singleton, span_mul_span, singleton.is_mul_hom.map_mul] end @[simp] lemma coe_ideal_span_singleton (x : R) : (↑(span R {x} : ideal R) : fractional_ideal f) = span_singleton (f.to_map x) := begin ext y, refine mem_coe.trans (iff.trans _ mem_span_singleton.symm), split, { rintros ⟨y', hy', rfl⟩, obtain ⟨x', rfl⟩ := mem_span_singleton.mp hy', use x', rw [smul_eq_mul, f.to_map.map_mul], refl }, { rintros ⟨y', rfl⟩, exact ⟨y' * x, mem_span_singleton.mpr ⟨y', rfl⟩, f.to_map.map_mul _ _⟩ } end lemma mem_singleton_mul {x y : f.codomain} {I : fractional_ideal f} : y ∈ span_singleton x * I ↔ ∃ y' ∈ I, y = x * y' := begin split, { intro h, apply submodule.mul_induction_on h, { intros x' hx' y' hy', obtain ⟨a, ha⟩ := mem_span_singleton.mp hx', use [a • y', I.1.smul_mem a hy'], rw [←ha, algebra.mul_smul_comm, algebra.smul_mul_assoc] }, { exact ⟨0, I.1.zero_mem, (mul_zero x).symm⟩ }, { rintros _ _ ⟨y, hy, rfl⟩ ⟨y', hy', rfl⟩, exact ⟨y + y', I.1.add_mem hy hy', (mul_add _ _ _).symm⟩ }, { rintros r _ ⟨y', hy', rfl⟩, exact ⟨r • y', I.1.smul_mem r hy', (algebra.mul_smul_comm _ _ _).symm ⟩ } }, { rintros ⟨y', hy', rfl⟩, exact mul_mem_mul (mem_span_singleton.mpr ⟨1, one_smul _ _⟩) hy' } end lemma mul_generator_self_inv (I : fractional_ideal g) [submodule.is_principal I.1] (h : I ≠ 0) : I * span_singleton (generator I.1)⁻¹ = 1 := begin -- Rewrite only the `I` that appears alone. conv_lhs { congr, rw eq_span_singleton_of_principal I }, rw [span_singleton_mul_span_singleton, mul_inv_cancel, span_singleton_one], intro generator_I_eq_zero, apply h, rw [eq_span_singleton_of_principal I, generator_I_eq_zero, span_singleton_zero] end lemma exists_eq_span_singleton_mul (I : fractional_ideal g) : ∃ (a : K) (aI : ideal R), I = span_singleton a * aI := begin obtain ⟨a_inv, nonzero, ha⟩ := I.2, have nonzero := mem_non_zero_divisors_iff_ne_zero.mp nonzero, have map_a_nonzero := mt g.to_map_eq_zero_iff.mpr nonzero, use (g.to_map a_inv)⁻¹, use (span_singleton (g.to_map a_inv) * I).1.comap g.lin_coe, ext, refine iff.trans _ mem_singleton_mul.symm, split, { intro hx, obtain ⟨x', hx'⟩ := ha x hx, refine ⟨g.to_map x', mem_coe.mpr ⟨x', (mem_singleton_mul.mpr ⟨x, hx, hx'⟩), rfl⟩, _⟩, erw [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul] }, { rintros ⟨y, hy, rfl⟩, obtain ⟨x', hx', rfl⟩ := mem_coe.mp hy, obtain ⟨y', hy', hx'⟩ := mem_singleton_mul.mp hx', rw lin_coe_apply at hx', erw [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul], exact hy' } end instance is_principal {R} [integral_domain R] [is_principal_ideal_ring R] {f : fraction_map R K} (I : fractional_ideal f) : (I : submodule R f.codomain).is_principal := ⟨ begin obtain ⟨a, aI, ha⟩ := exists_eq_span_singleton_mul I, have := a * f.to_map (generator aI), use a * f.to_map (generator aI), suffices : I = span_singleton (a * f.to_map (generator aI)), { exact congr_arg subtype.val this }, conv_lhs { rw [ha, ←span_singleton_generator aI] }, rw [coe_ideal_span_singleton (generator aI), span_singleton_mul_span_singleton] end ⟩ end principal_ideal_ring end fractional_ideal end ring
049ba2170b20e516783655cb416a04a9d7c16ada
35677d2df3f081738fa6b08138e03ee36bc33cad
/test/delta_instance.lean
1a455ab7a7760fe67c1d70d95a7f3256ae9c357a
[ "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
555
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import data.set @[derive has_coe_to_sort] def X : Type := set ℕ @[derive ring] def T := ℤ class binclass (T1 T2 : Type) instance : binclass ℤ ℤ := ⟨⟩ @[derive [ring, binclass ℤ]] def U := ℤ @[derive λ α, binclass α ℤ] def V := ℤ @[derive ring] def id_ring (α) [ring α] : Type := α @[derive decidable_eq] def S := ℕ @[derive decidable_eq] inductive P | a | b | c
745a726527113d99bae6436a377013f126695589
9dc8cecdf3c4634764a18254e94d43da07142918
/src/measure_theory/measure/content.lean
db25dc4c278bd9db144867c730f43719ffc69262
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
17,079
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import measure_theory.measure.measure_space import measure_theory.measure.regular import topology.sets.compacts /-! # Contents In this file we work with *contents*. A content `λ` is a function from a certain class of subsets (such as the compact subsets) to `ℝ≥0` that is * additive: If `K₁` and `K₂` are disjoint sets in the domain of `λ`, then `λ(K₁ ∪ K₂) = λ(K₁) + λ(K₂)`; * subadditive: If `K₁` and `K₂` are in the domain of `λ`, then `λ(K₁ ∪ K₂) ≤ λ(K₁) + λ(K₂)`; * monotone: If `K₁ ⊆ K₂` are in the domain of `λ`, then `λ(K₁) ≤ λ(K₂)`. We show that: * Given a content `λ` on compact sets, let us define a function `λ*` on open sets, by letting `λ* U` be the supremum of `λ K` for `K` included in `U`. This is a countably subadditive map that vanishes at `∅`. In Halmos (1950) this is called the *inner content* `λ*` of `λ`, and formalized as `inner_content`. * Given an inner content, we define an outer measure `μ*`, by letting `μ* E` be the infimum of `λ* U` over the open sets `U` containing `E`. This is indeed an outer measure. It is formalized as `outer_measure`. * Restricting this outer measure to Borel sets gives a regular measure `μ`. We define bundled contents as `content`. In this file we only work on contents on compact sets, and inner contents on open sets, and both contents and inner contents map into the extended nonnegative reals. However, in other applications other choices can be made, and it is not a priori clear what the best interface should be. ## Main definitions For `μ : content G`, we define * `μ.inner_content` : the inner content associated to `μ`. * `μ.outer_measure` : the outer measure associated to `μ`. * `μ.measure` : the Borel measure associated to `μ`. We prove that, on a locally compact space, the measure `μ.measure` is regular. ## References * Paul Halmos (1950), Measure Theory, §53 * <https://en.wikipedia.org/wiki/Content_(measure_theory)> -/ universes u v w noncomputable theory open set topological_space open_locale nnreal ennreal measure_theory namespace measure_theory variables {G : Type w} [topological_space G] /-- A content is an additive function on compact sets taking values in `ℝ≥0`. It is a device from which one can define a measure. -/ structure content (G : Type w) [topological_space G] := (to_fun : compacts G → ℝ≥0) (mono' : ∀ (K₁ K₂ : compacts G), (K₁ : set G) ⊆ K₂ → to_fun K₁ ≤ to_fun K₂) (sup_disjoint' : ∀ (K₁ K₂ : compacts G), disjoint (K₁ : set G) K₂ → to_fun (K₁ ⊔ K₂) = to_fun K₁ + to_fun K₂) (sup_le' : ∀ (K₁ K₂ : compacts G), to_fun (K₁ ⊔ K₂) ≤ to_fun K₁ + to_fun K₂) instance : inhabited (content G) := ⟨{ to_fun := λ K, 0, mono' := by simp, sup_disjoint' := by simp, sup_le' := by simp }⟩ /-- Although the `to_fun` field of a content takes values in `ℝ≥0`, we register a coercion to functions taking values in `ℝ≥0∞` as most constructions below rely on taking suprs and infs, which is more convenient in a complete lattice, and aim at constructing a measure. -/ instance : has_coe_to_fun (content G) (λ _, compacts G → ℝ≥0∞) := ⟨λ μ s, μ.to_fun s⟩ namespace content variable (μ : content G) lemma apply_eq_coe_to_fun (K : compacts G) : μ K = μ.to_fun K := rfl lemma mono (K₁ K₂ : compacts G) (h : (K₁ : set G) ⊆ K₂) : μ K₁ ≤ μ K₂ := by simp [apply_eq_coe_to_fun, μ.mono' _ _ h] lemma sup_disjoint (K₁ K₂ : compacts G) (h : disjoint (K₁ : set G) K₂) : μ (K₁ ⊔ K₂) = μ K₁ + μ K₂ := by simp [apply_eq_coe_to_fun, μ.sup_disjoint' _ _ h] lemma sup_le (K₁ K₂ : compacts G) : μ (K₁ ⊔ K₂) ≤ μ K₁ + μ K₂ := by { simp only [apply_eq_coe_to_fun], norm_cast, exact μ.sup_le' _ _ } lemma lt_top (K : compacts G) : μ K < ∞ := ennreal.coe_lt_top lemma empty : μ ⊥ = 0 := begin have := μ.sup_disjoint' ⊥ ⊥, simpa [apply_eq_coe_to_fun] using this, end /-- Constructing the inner content of a content. From a content defined on the compact sets, we obtain a function defined on all open sets, by taking the supremum of the content of all compact subsets. -/ def inner_content (U : opens G) : ℝ≥0∞ := ⨆ (K : compacts G) (h : (K : set G) ⊆ U), μ K lemma le_inner_content (K : compacts G) (U : opens G) (h2 : (K : set G) ⊆ U) : μ K ≤ μ.inner_content U := le_supr_of_le K $ le_supr _ h2 lemma inner_content_le (U : opens G) (K : compacts G) (h2 : (U : set G) ⊆ K) : μ.inner_content U ≤ μ K := supr₂_le $ λ K' hK', μ.mono _ _ (subset.trans hK' h2) lemma inner_content_of_is_compact {K : set G} (h1K : is_compact K) (h2K : is_open K) : μ.inner_content ⟨K, h2K⟩ = μ ⟨K, h1K⟩ := le_antisymm (supr₂_le $ λ K' hK', μ.mono _ ⟨K, h1K⟩ hK') (μ.le_inner_content _ _ subset.rfl) lemma inner_content_empty : μ.inner_content ∅ = 0 := begin refine le_antisymm _ (zero_le _), rw ←μ.empty, refine supr₂_le (λ K hK, _), have : K = ⊥, { ext1, rw [subset_empty_iff.mp hK, compacts.coe_bot] }, rw this, refl' end /-- This is "unbundled", because that it required for the API of `induced_outer_measure`. -/ lemma inner_content_mono ⦃U V : set G⦄ (hU : is_open U) (hV : is_open V) (h2 : U ⊆ V) : μ.inner_content ⟨U, hU⟩ ≤ μ.inner_content ⟨V, hV⟩ := bsupr_mono $ λ K hK, hK.trans h2 lemma inner_content_exists_compact {U : opens G} (hU : μ.inner_content U ≠ ∞) {ε : ℝ≥0} (hε : ε ≠ 0) : ∃ K : compacts G, (K : set G) ⊆ U ∧ μ.inner_content U ≤ μ K + ε := begin have h'ε := ennreal.coe_ne_zero.2 hε, cases le_or_lt (μ.inner_content U) ε, { exact ⟨⊥, empty_subset _, le_add_left h⟩ }, have := ennreal.sub_lt_self hU h.ne_bot h'ε, conv at this {to_rhs, rw inner_content }, simp only [lt_supr_iff] at this, rcases this with ⟨U, h1U, h2U⟩, refine ⟨U, h1U, _⟩, rw [← tsub_le_iff_right], exact le_of_lt h2U end /-- The inner content of a supremum of opens is at most the sum of the individual inner contents. -/ lemma inner_content_Sup_nat [t2_space G] (U : ℕ → opens G) : μ.inner_content (⨆ (i : ℕ), U i) ≤ ∑' (i : ℕ), μ.inner_content (U i) := begin have h3 : ∀ (t : finset ℕ) (K : ℕ → compacts G), μ (t.sup K) ≤ t.sum (λ i, μ (K i)), { intros t K, refine finset.induction_on t _ _, { simp only [μ.empty, nonpos_iff_eq_zero, finset.sum_empty, finset.sup_empty], }, { intros n s hn ih, rw [finset.sup_insert, finset.sum_insert hn], exact le_trans (μ.sup_le _ _) (add_le_add_left ih _) }}, refine supr₂_le (λ K hK, _), obtain ⟨t, ht⟩ := K.compact.elim_finite_subcover _ (λ i, (U i).prop) _, swap, { convert hK, rw [opens.supr_def, subtype.coe_mk] }, rcases K.compact.finite_compact_cover t (coe ∘ U) (λ i _, (U _).prop) (by simp only [ht]) with ⟨K', h1K', h2K', h3K'⟩, let L : ℕ → compacts G := λ n, ⟨K' n, h1K' n⟩, convert le_trans (h3 t L) _, { ext1, rw [compacts.coe_finset_sup, finset.sup_eq_supr], exact h3K' }, refine le_trans (finset.sum_le_sum _) (ennreal.sum_le_tsum t), intros i hi, refine le_trans _ (le_supr _ (L i)), refine le_trans _ (le_supr _ (h2K' i)), refl' end /-- The inner content of a union of sets is at most the sum of the individual inner contents. This is the "unbundled" version of `inner_content_Sup_nat`. It required for the API of `induced_outer_measure`. -/ lemma inner_content_Union_nat [t2_space G] ⦃U : ℕ → set G⦄ (hU : ∀ (i : ℕ), is_open (U i)) : μ.inner_content ⟨⋃ (i : ℕ), U i, is_open_Union hU⟩ ≤ ∑' (i : ℕ), μ.inner_content ⟨U i, hU i⟩ := by { have := μ.inner_content_Sup_nat (λ i, ⟨U i, hU i⟩), rwa [opens.supr_def] at this } lemma inner_content_comap (f : G ≃ₜ G) (h : ∀ ⦃K : compacts G⦄, μ (K.map f f.continuous) = μ K) (U : opens G) : μ.inner_content (opens.comap f.to_continuous_map U) = μ.inner_content U := begin refine (compacts.equiv f).surjective.supr_congr _ (λ K, supr_congr_Prop image_subset_iff _), intro hK, simp only [equiv.coe_fn_mk, subtype.mk_eq_mk, ennreal.coe_eq_coe, compacts.equiv], apply h, end @[to_additive] lemma is_mul_left_invariant_inner_content [group G] [topological_group G] (h : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (g : G) (U : opens G) : μ.inner_content (opens.comap (homeomorph.mul_left g).to_continuous_map U) = μ.inner_content U := by convert μ.inner_content_comap (homeomorph.mul_left g) (λ K, h g) U @[to_additive] lemma inner_content_pos_of_is_mul_left_invariant [t2_space G] [group G] [topological_group G] (h3 : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (K : compacts G) (hK : μ K ≠ 0) (U : opens G) (hU : (U : set G).nonempty) : 0 < μ.inner_content U := begin have : (interior (U : set G)).nonempty, rwa [U.prop.interior_eq], rcases compact_covered_by_mul_left_translates K.2 this with ⟨s, hs⟩, suffices : μ K ≤ s.card * μ.inner_content U, { exact (ennreal.mul_pos_iff.mp $ hK.bot_lt.trans_le this).2 }, have : (K : set G) ⊆ ↑⨆ (g ∈ s), opens.comap (homeomorph.mul_left g).to_continuous_map U, { simpa only [opens.supr_def, opens.coe_comap, subtype.coe_mk] }, refine (μ.le_inner_content _ _ this).trans _, refine (rel_supr_sum (μ.inner_content) (μ.inner_content_empty) (≤) (μ.inner_content_Sup_nat) _ _).trans _, simp only [μ.is_mul_left_invariant_inner_content h3, finset.sum_const, nsmul_eq_mul, le_refl] end lemma inner_content_mono' ⦃U V : set G⦄ (hU : is_open U) (hV : is_open V) (h2 : U ⊆ V) : μ.inner_content ⟨U, hU⟩ ≤ μ.inner_content ⟨V, hV⟩ := bsupr_mono $ λ K hK, hK.trans h2 /-- Extending a content on compact sets to an outer measure on all sets. -/ protected def outer_measure : outer_measure G := induced_outer_measure (λ U hU, μ.inner_content ⟨U, hU⟩) is_open_empty μ.inner_content_empty variables [t2_space G] lemma outer_measure_opens (U : opens G) : μ.outer_measure U = μ.inner_content U := induced_outer_measure_eq' (λ _, is_open_Union) μ.inner_content_Union_nat μ.inner_content_mono U.2 lemma outer_measure_of_is_open (U : set G) (hU : is_open U) : μ.outer_measure U = μ.inner_content ⟨U, hU⟩ := μ.outer_measure_opens ⟨U, hU⟩ lemma outer_measure_le (U : opens G) (K : compacts G) (hUK : (U : set G) ⊆ K) : μ.outer_measure U ≤ μ K := (μ.outer_measure_opens U).le.trans $ μ.inner_content_le U K hUK lemma le_outer_measure_compacts (K : compacts G) : μ K ≤ μ.outer_measure K := begin rw [content.outer_measure, induced_outer_measure_eq_infi], { exact le_infi (λ U, le_infi $ λ hU, le_infi $ μ.le_inner_content K ⟨U, hU⟩) }, { exact μ.inner_content_Union_nat }, { exact μ.inner_content_mono } end lemma outer_measure_eq_infi (A : set G) : μ.outer_measure A = ⨅ (U : set G) (hU : is_open U) (h : A ⊆ U), μ.inner_content ⟨U, hU⟩ := induced_outer_measure_eq_infi _ μ.inner_content_Union_nat μ.inner_content_mono A lemma outer_measure_interior_compacts (K : compacts G) : μ.outer_measure (interior K) ≤ μ K := (μ.outer_measure_opens $ opens.interior K).le.trans $ μ.inner_content_le _ _ interior_subset lemma outer_measure_exists_compact {U : opens G} (hU : μ.outer_measure U ≠ ∞) {ε : ℝ≥0} (hε : ε ≠ 0) : ∃ K : compacts G, (K : set G) ⊆ U ∧ μ.outer_measure U ≤ μ.outer_measure K + ε := begin rw [μ.outer_measure_opens] at hU ⊢, rcases μ.inner_content_exists_compact hU hε with ⟨K, h1K, h2K⟩, exact ⟨K, h1K, le_trans h2K $ add_le_add_right (μ.le_outer_measure_compacts K) _⟩, end lemma outer_measure_exists_open {A : set G} (hA : μ.outer_measure A ≠ ∞) {ε : ℝ≥0} (hε : ε ≠ 0) : ∃ U : opens G, A ⊆ U ∧ μ.outer_measure U ≤ μ.outer_measure A + ε := begin rcases induced_outer_measure_exists_set _ _ μ.inner_content_mono hA (ennreal.coe_ne_zero.2 hε) with ⟨U, hU, h2U, h3U⟩, exact ⟨⟨U, hU⟩, h2U, h3U⟩, swap, exact μ.inner_content_Union_nat end lemma outer_measure_preimage (f : G ≃ₜ G) (h : ∀ ⦃K : compacts G⦄, μ (K.map f f.continuous) = μ K) (A : set G) : μ.outer_measure (f ⁻¹' A) = μ.outer_measure A := begin refine induced_outer_measure_preimage _ μ.inner_content_Union_nat μ.inner_content_mono _ (λ s, f.is_open_preimage) _, intros s hs, convert μ.inner_content_comap f h ⟨s, hs⟩ end lemma outer_measure_lt_top_of_is_compact [locally_compact_space G] {K : set G} (hK : is_compact K) : μ.outer_measure K < ∞ := begin rcases exists_compact_superset hK with ⟨F, h1F, h2F⟩, calc μ.outer_measure K ≤ μ.outer_measure (interior F) : outer_measure.mono' _ h2F ... ≤ μ ⟨F, h1F⟩ : by apply μ.outer_measure_le ⟨interior F, is_open_interior⟩ ⟨F, h1F⟩ interior_subset ... < ⊤ : μ.lt_top _ end @[to_additive] lemma is_mul_left_invariant_outer_measure [group G] [topological_group G] (h : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (g : G) (A : set G) : μ.outer_measure ((λ h, g * h) ⁻¹' A) = μ.outer_measure A := by convert μ.outer_measure_preimage (homeomorph.mul_left g) (λ K, h g) A lemma outer_measure_caratheodory (A : set G) : measurable_set[μ.outer_measure.caratheodory] A ↔ ∀ (U : opens G), μ.outer_measure (U ∩ A) + μ.outer_measure (U \ A) ≤ μ.outer_measure U := begin dsimp [opens], rw subtype.forall, apply induced_outer_measure_caratheodory, apply inner_content_Union_nat, apply inner_content_mono' end @[to_additive] lemma outer_measure_pos_of_is_mul_left_invariant [group G] [topological_group G] (h3 : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (K : compacts G) (hK : μ K ≠ 0) {U : set G} (h1U : is_open U) (h2U : U.nonempty) : 0 < μ.outer_measure U := by { convert μ.inner_content_pos_of_is_mul_left_invariant h3 K hK ⟨U, h1U⟩ h2U, exact μ.outer_measure_opens ⟨U, h1U⟩ } variables [S : measurable_space G] [borel_space G] include S /-- For the outer measure coming from a content, all Borel sets are measurable. -/ lemma borel_le_caratheodory : S ≤ μ.outer_measure.caratheodory := begin rw [@borel_space.measurable_eq G _ _], refine measurable_space.generate_from_le _, intros U hU, rw μ.outer_measure_caratheodory, intro U', rw μ.outer_measure_of_is_open ((U' : set G) ∩ U) (is_open.inter U'.prop hU), simp only [inner_content, supr_subtype'], rw [opens.coe_mk], haveI : nonempty {L : compacts G // (L : set G) ⊆ U' ∩ U} := ⟨⟨⊥, empty_subset _⟩⟩, rw [ennreal.supr_add], refine supr_le _, rintro ⟨L, hL⟩, simp only [subset_inter_iff] at hL, have : ↑U' \ U ⊆ U' \ L := diff_subset_diff_right hL.2, refine le_trans (add_le_add_left (μ.outer_measure.mono' this) _) _, rw μ.outer_measure_of_is_open (↑U' \ L) (is_open.sdiff U'.2 L.2.is_closed), simp only [inner_content, supr_subtype'], rw [opens.coe_mk], haveI : nonempty {M : compacts G // (M : set G) ⊆ ↑U' \ L} := ⟨⟨⊥, empty_subset _⟩⟩, rw [ennreal.add_supr], refine supr_le _, rintro ⟨M, hM⟩, simp only [subset_diff] at hM, have : (↑(L ⊔ M) : set G) ⊆ U', { simp only [union_subset_iff, compacts.coe_sup, hM, hL, and_self] }, rw μ.outer_measure_of_is_open ↑U' U'.2, refine le_trans (ge_of_eq _) (μ.le_inner_content _ _ this), exact μ.sup_disjoint _ _ hM.2.symm, end /-- The measure induced by the outer measure coming from a content, on the Borel sigma-algebra. -/ protected def measure : measure G := μ.outer_measure.to_measure μ.borel_le_caratheodory lemma measure_apply {s : set G} (hs : measurable_set s) : μ.measure s = μ.outer_measure s := to_measure_apply _ _ hs /-- In a locally compact space, any measure constructed from a content is regular. -/ instance regular [locally_compact_space G] : μ.measure.regular := begin haveI : μ.measure.outer_regular, { refine ⟨λ A hA r (hr : _ < _), _⟩, rw [μ.measure_apply hA, outer_measure_eq_infi] at hr, simp only [infi_lt_iff] at hr, rcases hr with ⟨U, hUo, hAU, hr⟩, rw [← μ.outer_measure_of_is_open U hUo, ← μ.measure_apply hUo.measurable_set] at hr, exact ⟨U, hAU, hUo, hr⟩ }, haveI : is_finite_measure_on_compacts μ.measure, { refine ⟨λ K hK, _⟩, rw [measure_apply _ hK.measurable_set], exact μ.outer_measure_lt_top_of_is_compact hK }, refine ⟨λ U hU r hr, _⟩, rw [measure_apply _ hU.measurable_set, μ.outer_measure_of_is_open U hU] at hr, simp only [inner_content, lt_supr_iff] at hr, rcases hr with ⟨K, hKU, hr⟩, refine ⟨K, hKU, K.2, hr.trans_le _⟩, exact (μ.le_outer_measure_compacts K).trans (le_to_measure_apply _ _ _) end end content end measure_theory
93961fc389a41c10fc7a35877f8a3f197e2a30b1
367134ba5a65885e863bdc4507601606690974c1
/test/abel.lean
b771aed7048b9aa0659c8fb9ee99578e7b870cdc
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
250
lean
import tactic.abel variables {α : Type*} {a b : α} example [add_comm_monoid α] : a + (b + a) = a + a + b := by abel example [add_comm_group α] : (a + b) - ((b + a) + a) = -a := by abel example [add_comm_group α] (x : α) : x - 0 = x := by abel
ec0704eb699e27a13fb1c558a63f4eb2a8ef68b2
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/src/Lean/Util/Trace.lean
fcd756d4edcd1f8e888f863ac6e95e1f41b7f8c1
[ "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
4,294
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Leonardo de Moura -/ import Lean.Message import Lean.MonadEnv universe u namespace Lean open Std (PersistentArray) structure TraceState := (enabled : Bool := true) (traces : PersistentArray MessageData := {}) namespace TraceState instance : Inhabited TraceState := ⟨{}⟩ private def toFormat (traces : PersistentArray MessageData) (sep : Format) : Format := traces.size.fold (fun i r => let curr := format $ traces.get! i; if i > 0 then r ++ sep ++ curr else r ++ curr) Format.nil instance : HasFormat TraceState := ⟨fun s => toFormat s.traces Format.line⟩ instance : HasToString TraceState := ⟨toString ∘ fmt⟩ end TraceState class MonadTrace (m : Type → Type) := (modifyTraceState : (TraceState → TraceState) → m Unit) (getTraceState : m TraceState) export MonadTrace (getTraceState modifyTraceState) instance monadTraceTrans (m n) [MonadTrace m] [MonadLift m n] : MonadTrace n := { modifyTraceState := fun f => liftM (modifyTraceState f : m _), getTraceState := liftM (getTraceState : m _) } variables {α : Type} {m : Type → Type} [Monad m] [MonadTrace m] def printTraces {m} [Monad m] [MonadTrace m] [MonadIO m] : m Unit := do traceState ← getTraceState; traceState.traces.forM $ fun m => liftIO $ IO.println $ format m def resetTraceState {m} [MonadTrace m] : m Unit := modifyTraceState (fun _ => {}) private def checkTraceOptionAux (opts : Options) : Name → Bool | n@(Name.str p _ _) => opts.getBool n || (!opts.contains n && checkTraceOptionAux p) | _ => false def checkTraceOption (opts : Options) (cls : Name) : Bool := if opts.isEmpty then false else checkTraceOptionAux opts (`trace ++ cls) private def checkTraceOptionM [MonadOptions m] (cls : Name) : m Bool := do opts ← getOptions; pure $ checkTraceOption opts cls @[inline] def isTracingEnabledFor [MonadOptions m] (cls : Name) : m Bool := do s ← getTraceState; if !s.enabled then pure false else checkTraceOptionM cls @[inline] def enableTracing (b : Bool) : m Bool := do s ← getTraceState; let oldEnabled := s.enabled; modifyTraceState $ fun s => { s with enabled := b }; pure oldEnabled @[inline] def getTraces : m (PersistentArray MessageData) := do s ← getTraceState; pure s.traces @[inline] def modifyTraces (f : PersistentArray MessageData → PersistentArray MessageData) : m Unit := modifyTraceState $ fun s => { s with traces := f s.traces } @[inline] def setTrace (f : PersistentArray MessageData → PersistentArray MessageData) : m Unit := modifyTraceState $ fun s => { s with traces := f s.traces } @[inline] def setTraceState (s : TraceState) : m Unit := modifyTraceState $ fun _ => s private def addNode (oldTraces : PersistentArray MessageData) (cls : Name) : m Unit := modifyTraces $ fun traces => let d := MessageData.tagged cls (MessageData.node traces.toArray); oldTraces.push d private def getResetTraces : m (PersistentArray MessageData) := do oldTraces ← getTraces; modifyTraces $ fun _ => {}; pure oldTraces section variables [AddMessageDataContext m] [MonadOptions m] def addTrace (cls : Name) (msg : MessageData) : m Unit := do msg ← addMessageDataContext msg; modifyTraces $ fun traces => traces.push (MessageData.tagged cls msg) @[inline] def trace (cls : Name) (msg : Unit → MessageData) : m Unit := whenM (isTracingEnabledFor cls) (addTrace cls (msg ())) @[inline] def traceM (cls : Name) (mkMsg : m MessageData) : m Unit := whenM (isTracingEnabledFor cls) (do msg ← mkMsg; addTrace cls msg) @[inline] def traceCtx [MonadFinally m] (cls : Name) (ctx : m α) : m α := do b ← isTracingEnabledFor cls; if !b then do old ← enableTracing false; finally ctx (enableTracing old) else do oldCurrTraces ← getResetTraces; finally ctx (addNode oldCurrTraces cls) -- TODO: delete after fix old frontend def MonadTracer.trace (cls : Name) (msg : Unit → MessageData) : m Unit := trace cls msg end def registerTraceClass (traceClassName : Name) : IO Unit := registerOption (`trace ++ traceClassName) { group := "trace", defValue := false, descr := "enable/disable tracing for the given module and submodules" } end Lean
a00055ea90a273a7b7931283bd4e2eefe6d6dbde
1a9d3677cccdaaccacb163507570e75d34043a38
/src/week_6/Part_A_tendsto.lean
13f4859cd8ea20fd70c392af9ef91070757ab143
[ "Apache-2.0" ]
permissive
alreadydone/formalising-mathematics
687d386a72065795e784e270f5c05ea3948b67dd
65869362cd7a2ac74dd1a97c7f9471835726570b
refs/heads/master
1,680,260,936,332
1,616,563,371,000
1,616,563,371,000
348,780,769
0
0
null
null
null
null
UTF-8
Lean
false
false
12,593
lean
import order.filter.basic /- # tendsto Here's an overview of the main definition we're learning today. If `X` and `Y` are types, `φ : X → Y` is a function, and `F : filter X` and `G : filter Y` are filters, then `filter.tendsto φ F G` is a true-false statement, which is pronounced something like "`F` tends to `G` along `φ`". Of course we will `open filter` in this file, so you can just write `tendsto φ F G`, or if you like the dot notation you can even write `F.tendsto φ G`. ## Geometric meaning of `tendsto`. Let's start by thinking about the easy case where `F` and `G` are actually subsets of `X` and `Y` (that is, principal filters, associated to sets which we will also call `F` and `G`). In this case, `tendsto φ F G` simply means "`φ` restricts to a function from `F` to `G`", or in other words `∀ x ∈ F, φ(x) ∈ G`. There are two other ways of writing this predicate. The first involves pushing a set forward along a map. If `F` is a subset of `X` then let `φ(F)` denote the image of `F` under `φ`, that is, the subset `{y : Y | ∃ x : X, φ x = y}` of `Y`. Then `tendsto φ F G` simply means `φ(F) ⊆ G`. The second involves pulling a set back along a map. If `G` is a subset of `Y` then let `φ⁻¹(G)` denote the preimage of `G` under `φ`, that is, the subset `{x : X | φ x ∈ G}` of `Y`. Then `tendsto φ F G` simply means `F ⊆ φ⁻¹(G)`. This is how it all works in the case of sets. What we need to do today is to figure out how to push forward and pull back filters along a map `φ`. Once we have done this, then we can prove `φ(F) ≤ G ↔ F ≤ φ⁻¹(G)` and use either one of these as our definition of `tendsto φ F G` -- it doesn't matter which. ## Digression : adjoint functors. The discussion below is not needed to be able to do this week's problems, but it might provide some helpful background for some. Also note that anyone who still doens't like the word "type" can literally just change it for the word "set" (and change "term of type" to "element of set"), which is how arguments of the below kind would appear in the traditional mathematical literature. Partially ordered types, such as the type of subsets of a fixed type `X` or the type of filters on `X`, are actually very simple examples of categories. In general if `P` is a partially ordered type and `x,y` are terms of type `P` then the idea is that we can define `Hom(x,y)` to have exactly one element if `x ≤ y` is true, and no elements at all if `x ≤ y` is false. The structure/axioms for a category are that `Hom(x,x)` is supposed to have an identity element, which follows from reflexivity of `≤`, and that one can compose morphisms, which follows from transitivity of `≤`. Antisymmetry states that if two objects are isomorphic (i.e., in this case, if `Hom(x,y)` and `Hom(y,x)` are both nonempty), then they are equal. If `φ : X → Y` is a map of types, then pushing forward subsets and pulling back subsets are both functors from `set X` to `set Y`, because `S ⊆ T → φ(S) ⊆ φ(T)` and `U ⊆ V → φ⁻¹(U) ⊆ φ⁻¹(V)`. The statement that `φ(S) ≤ U ↔ S ≤ φ⁻¹(U)` is simply the statement that these functors are adjoint to each other. Today we will define pushforward and pullback of filters, and show that they are also a pair of adjoint functors, but we will not use this language. In fact there is a special language for adjoint functors in this simple situation: we will say that pushforward and pullback form a Galois connection. -/ /- ## Warm-up: pushing forward and pulling back subsets. Say `X` and `Y` are types, and `f : X → Y`. -/ variables (X Y : Type) (f : X → Y) /- ### images In Lean, the image `f(S)` of a subset `S : set X` cannot be denoted `f S`, because `f` expects an _element_ of `X` as an input, not a subset of `X`, so we need new notation. Notation : `f '' S` is the image of `S` under `f`. Let's check this. -/ example (S : set X) : f '' S = {y : Y | ∃ x : X, x ∈ S ∧ f x = y} := begin -- true by definition refl end /- ### preimages In Lean, the preimage `f⁻¹(T)` of a subset `T : set Y` cannot be denoted `f⁻¹ T` because `⁻¹` is the inverse notation in group theory, so if anything would be a function from `Y` to `X`, not a function on subsets of `Y`. Notation : `f ⁻¹' T` is the preimage of `T` under `f`. Let's check this. Pro shortcut: `\-'` for `⁻¹'` -/ example (T : set Y) : f ⁻¹' T = {x : X | f x ∈ T} := begin -- true by definition refl end /- I claim that the following conditions on `S : set X` and `T : set Y` are equivalent: 1) `f '' S ⊆ T` 2) `S ⊆ f⁻¹' T` Indeed, they both say that `f` restricts to a function from `S` to `T`. Let's check this. You might find `mem_preimage : a ∈ f ⁻¹' s ↔ f a ∈ s` and -/ open set example (S : set X) (T : set Y) : f '' S ⊆ T ↔ S ⊆ f⁻¹' T := begin split, intros h x hx, exact h ⟨x,hx,rfl⟩, rintros h _ ⟨x,hx,rfl⟩, exact h hx end /- ## Pushing forward filters. Pushing forward is easy, so let's do that first. It's called `filter.map` in Lean. We define the pushforward filter `map f F` on `Y` to be the obvious thing: a subset of `Y` is in the filter iff `f⁻¹(Y)` is in `F`. Let's check this is a filter. Reminder of some helpful lemmas: In `set`: `mem_set_of_eq : a ∈ {x : α | p x} = p a` -- definitional In `filter`: `univ_mem_sets : univ ∈ F` `mem_sets_of_superset : S ∈ F → S ⊆ T → T ∈ F` `inter_mem_sets : S ∈ F → T ∈ F → S ∩ T ∈ F` -/ open filter -- this is called `F.map f` or `filter.map f F` -- or just `map f F` if `filter` is open. example (F : filter X) : filter Y := { sets := {T : set Y | f ⁻¹' T ∈ F }, univ_sets := begin exact univ_mem_sets end, sets_of_superset := begin intros S T hS hc, exact mem_sets_of_superset hS (preimage_mono hc) end, inter_sets := begin intros _ _, dsimp, rw ← preimage_inter, exact inter_mem_sets end, } -- this is `filter.mem_map` and it's true by definition. -- It's useful in the form `rw mem_map` if you want to figure out -- what's going on in a proof, but often you'll find you can -- delete it at the end. example (F : filter X) (T : set Y) : T ∈ F.map f ↔ f ⁻¹' T ∈ F := begin -- true by definition refl end -- Let's check that `map` satisfies some basic functorialities. -- Recall that if your goal is to check two filters are -- equal then you can use the `ext` tactic, e.g. with `ext S`. -- pushing along the identity map id : X → X doesn't change the filter. -- this is `filter.map_id` but see if you can prove it yourself. example (F : filter X) : F.map id = F := begin ext, refl end -- pushing along g ∘ f is the same as pushing along f and then g -- for some reason this isn't in mathlib, instead they have `map_map` which -- has the equality the other way. variables (Z : Type) (g : Y → Z) -- this isn't in mathlib, but `filter.map_map` is the equality the other -- way around. See if you can prove it yourself. example (F : filter X) : F.map (g ∘ f) = (F.map f).map g := begin refl end open_locale filter -- for 𝓟 notation -- pushing the principal filter `𝓟 S` along `f` gives `𝓟 (f '' S)` -- this is `filter.map_principal` but see if you can prove it yourself. example (S : set X) : (𝓟 S).map f = 𝓟 (f '' S) := begin ext, exact iff.symm image_subset_iff end /- ## tendsto The definition: if `f : X → Y` and `F : filter X` and `G : filter Y` then `tendsto f F G : Prop := map f F ≤ G`. It's pronounced something like "`F` tends to `G` along `f`". This is a *definition* (it has type `Prop`), not the proof of a theorem. It is a true-false statement attached to `f`, `F` and `G`, it's a bit like saying "f is continuous at x" or something like that, it might be true and it might be false. The mental model you might want to have of the definition is that `tendsto f F G` means that the function `f` restricts to a function from the generalized set `F` to the generalized set `G`. -/ -- this is `filter.tendsto_def` example (F : filter X) (G : filter Y) : tendsto f F G ↔ ∀ T : set Y, T ∈ G → f ⁻¹' T ∈ F := begin -- true by definition refl end -- Let's make a basic API for `tendsto` -- this is `tendsto_id` but see if you can prove it yourself. example (F : filter X) : tendsto id F F := begin exact λ_, id end -- this is `tendsto.comp` but see if you can prove it yourself example (F : filter X) (G : filter Y) (H : filter Z) (f : X → Y) (g : Y → Z) (hf : tendsto f F G) (hg : tendsto g G H) : tendsto (g ∘ f) F H := begin intros S hS, exact hf (hg hS) end -- I would recommend looking at the model answer to this one if -- you get stuck. lemma tendsto_comp_map (g : Y → Z) (F : filter X) (G : filter Z) : tendsto (g ∘ f) F G ↔ tendsto g (F.map f) G := begin refl -- so simple! end /- ## Pulling back filters We don't use this in the next part. Say `f : X → Y` and `G : filter Y`, and we want a filter on `X`. Let's make a naive definition. We want a collection of subsets of `X` corresponding to the filter obtained by pulling back `G` along `f`. When should `S : set X` be in this filter? Perhaps it is when `f '' S ∈ G`. However, there is no reason that the collectio n of `S` satisfying this property should be a filter on `X`. For example, there is no reason to espect that `f '' univ ∈ G` if `f` is not surjective. Our naive guess doesn't work. Here's a way of fixing this, by coming up with a less naive guess which is informed by our mental model. Remember that our model of a filter `G` is some kind of generalised notion of a set. If `T : set Y` then `T ∈ G` is supposed to mean that the "set" `G` is a subset of `T`. So this should imply that `f⁻¹(G) ⊆ f⁻¹(T)`. In particular, if `T ∈ G` and `f⁻¹(T) ⊆ S` then this should mean `f⁻¹(G) ⊆ S` and hence `S ∈ f⁻¹(G)`. Let's try this condition (defining `S ∈ f⁻¹(G)` to mean `∃ T ∈ G, f⁻¹(T) ⊆ S`) and see if it works. Random useful lemmas (you might be getting to the point where you can guess the names of the lemmas): `subset_univ S : S ⊆ univ` `subset.trans : A ⊆ B → B ⊆ C → A ⊆ C` -/ -- this is called filter.comap example (G : filter Y) : filter X := { sets := {S : set X | ∃ T ∈ G, f ⁻¹' T ⊆ S}, univ_sets := begin exact ⟨univ, univ_mem_sets, by refl /-subset.refl _-/⟩ end, sets_of_superset := begin rintros S1 S2 ⟨T,hT,hS1⟩ hc, exact ⟨T, hT, subset.trans hS1 hc⟩ end, inter_sets := begin rintros S1 S2 ⟨T1,hT1,hS1⟩ ⟨T2,hT2,hS2⟩, use T1 ∩ T2, rw preimage_inter, exact ⟨inter_mem_sets hT1 hT2, inter_subset_inter hS1 hS2⟩ end } -- Let's call this mem_comap lemma mem_comap (f : X → Y) (G : filter Y) (S : set X) : S ∈ comap f G ↔ ∃ T ∈ G, f ⁻¹' T ⊆ S := begin -- true by definition refl end -- If you want to, you can check some preliminary properties of `comap`. -- this is comap_id example (G : filter Y) : comap id G = G := begin ext S, split, rintro ⟨T,hT,hS⟩, exact mem_sets_of_superset hT hS, intro h, exact ⟨S, h, by refl⟩ end -- this is comap_comap but the other way around lemma comap_comp (H : filter Z) : comap (g ∘ f) H = comap f (comap g H) := begin ext S, split, rintro ⟨T,hT,hS⟩, exact ⟨g⁻¹'T, ⟨T, hT, by refl⟩, hS⟩, rintro ⟨T,⟨R,hR,hT⟩,hS⟩, refine ⟨R, hR, subset.trans _ hS⟩, exact preimage_mono hT -- can't insert this directly into _ ! end -- this is comap_principal. Remember `mem_principal_sets`! It's true by definition... example (T : set Y) : comap f (𝓟 T) = 𝓟 (f ⁻¹' T) := begin ext S, split, rintro ⟨R,hR,hS⟩, apply subset.trans (preimage_mono hR) hS, intro h, exact ⟨T, λ_,id, h⟩ end -- This is the proof that `map f` and `comap f` are adjoint functors, -- or in other words form a Galois connection. It is the "generalised set" -- analogue of the assertion that if S is a subset of X and T is a subset of Y -- then f(S) ⊆ T ↔ S ⊆ f⁻¹(T), these both being ways to say that `f` restricts -- to a function from `S` to `T`. lemma filter.galois_connection (F : filter X) (G : filter Y) : map f F ≤ G ↔ F ≤ comap f G := begin split, rintros h S ⟨T,hT,hS⟩, exact mem_sets_of_superset (h hT) hS, intros h S hS, exact h ⟨S, hS, by refl⟩ end -- indeed, `map f` and `comap f` form a Galois connection. example : galois_connection (map f) (comap f) := filter.galois_connection X Y f
cba2569bd9869d50ce83f4c3cdd7157c6494ac60
ba4794a0deca1d2aaa68914cd285d77880907b5c
/src/game/world10/level8.lean
0cd84910449098ecc0ec313f4410a4c578109d0b
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
438
lean
import game.world10.level7 -- hide namespace mynat -- hide /- # Inequality world. ## Level 8: `succ_le_succ` Another straightforward one. -/ /- Lemma For all naturals $a$ and $b$, if $a\le b$, then $\operatorname{succ}(a)\le\operatorname{succ}(b)$. -/ lemma succ_le_succ (a b : mynat) (h : a ≤ b) : succ a ≤ succ b := begin [less_leaky] cases h with c hc, use c, rw hc, rw succ_add, refl, end end mynat -- hide
b49b417b3c151cbb9d04c5f985ca1b39da7f397f
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/polynomial/degree/trailing_degree.lean
3903abea51ee591f5f52fa69fba34e98ad636646
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
16,039
lean
/- Copyright (c) 2020 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import data.enat.basic import data.polynomial.degree.definitions /-! # Trailing degree of univariate polynomials ## Main definitions * `trailing_degree p`: the multiplicity of `X` in the polynomial `p` * `nat_trailing_degree`: a variant of `trailing_degree` that takes values in the natural numbers * `trailing_coeff`: the coefficient at index `nat_trailing_degree p` Converts most results about `degree`, `nat_degree` and `leading_coeff` to results about the bottom end of a polynomial -/ noncomputable theory open function polynomial finsupp finset open_locale big_operators classical polynomial namespace polynomial universes u v variables {R : Type u} {S : Type v} {a b : R} {n m : ℕ} section semiring variables [semiring R] {p q r : R[X]} /-- `trailing_degree p` is the multiplicity of `x` in the polynomial `p`, i.e. the smallest `X`-exponent in `p`. `trailing_degree p = some n` when `p ≠ 0` and `n` is the smallest power of `X` that appears in `p`, otherwise `trailing_degree 0 = ⊤`. -/ def trailing_degree (p : R[X]) : ℕ∞ := p.support.min lemma trailing_degree_lt_wf : well_founded (λp q : R[X], trailing_degree p < trailing_degree q) := inv_image.wf trailing_degree (with_top.well_founded_lt nat.lt_wf) /-- `nat_trailing_degree p` forces `trailing_degree p` to `ℕ`, by defining `nat_trailing_degree ⊤ = 0`. -/ def nat_trailing_degree (p : R[X]) : ℕ := (trailing_degree p).get_or_else 0 /-- `trailing_coeff p` gives the coefficient of the smallest power of `X` in `p`-/ def trailing_coeff (p : R[X]) : R := coeff p (nat_trailing_degree p) /-- a polynomial is `monic_at` if its trailing coefficient is 1 -/ def trailing_monic (p : R[X]) := trailing_coeff p = (1 : R) lemma trailing_monic.def : trailing_monic p ↔ trailing_coeff p = 1 := iff.rfl instance trailing_monic.decidable [decidable_eq R] : decidable (trailing_monic p) := by unfold trailing_monic; apply_instance @[simp] lemma trailing_monic.trailing_coeff {p : R[X]} (hp : p.trailing_monic) : trailing_coeff p = 1 := hp @[simp] lemma trailing_degree_zero : trailing_degree (0 : R[X]) = ⊤ := rfl @[simp] lemma trailing_coeff_zero : trailing_coeff (0 : R[X]) = 0 := rfl @[simp] lemma nat_trailing_degree_zero : nat_trailing_degree (0 : R[X]) = 0 := rfl lemma trailing_degree_eq_top : trailing_degree p = ⊤ ↔ p = 0 := ⟨λ h, support_eq_empty.1 (finset.min_eq_top.1 h), λ h, by simp [h]⟩ lemma trailing_degree_eq_nat_trailing_degree (hp : p ≠ 0) : trailing_degree p = (nat_trailing_degree p : ℕ∞) := let ⟨n, hn⟩ := not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt trailing_degree_eq_top.1 hp)) in have hn : trailing_degree p = n := not_not.1 hn, by rw [nat_trailing_degree, hn]; refl lemma trailing_degree_eq_iff_nat_trailing_degree_eq {p : R[X]} {n : ℕ} (hp : p ≠ 0) : p.trailing_degree = n ↔ p.nat_trailing_degree = n := by rw [trailing_degree_eq_nat_trailing_degree hp, with_top.coe_eq_coe] lemma trailing_degree_eq_iff_nat_trailing_degree_eq_of_pos {p : R[X]} {n : ℕ} (hn : 0 < n) : p.trailing_degree = n ↔ p.nat_trailing_degree = n := begin split, { intro H, rwa ← trailing_degree_eq_iff_nat_trailing_degree_eq, rintro rfl, rw trailing_degree_zero at H, exact option.no_confusion H }, { intro H, rwa trailing_degree_eq_iff_nat_trailing_degree_eq, rintro rfl, rw nat_trailing_degree_zero at H, rw H at hn, exact lt_irrefl _ hn } end lemma nat_trailing_degree_eq_of_trailing_degree_eq_some {p : R[X]} {n : ℕ} (h : trailing_degree p = n) : nat_trailing_degree p = n := have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h, option.some_inj.1 $ show (nat_trailing_degree p : ℕ∞) = n, by rwa [← trailing_degree_eq_nat_trailing_degree hp0] @[simp] lemma nat_trailing_degree_le_trailing_degree : ↑(nat_trailing_degree p) ≤ trailing_degree p := begin by_cases hp : p = 0, { rw [hp, trailing_degree_zero], exact le_top }, rw [trailing_degree_eq_nat_trailing_degree hp], exact le_rfl end lemma nat_trailing_degree_eq_of_trailing_degree_eq [semiring S] {q : S[X]} (h : trailing_degree p = trailing_degree q) : nat_trailing_degree p = nat_trailing_degree q := by unfold nat_trailing_degree; rw h lemma le_trailing_degree_of_ne_zero (h : coeff p n ≠ 0) : trailing_degree p ≤ n := show @has_le.le ℕ∞ _ p.support.min n, from min_le (mem_support_iff.2 h) lemma nat_trailing_degree_le_of_ne_zero (h : coeff p n ≠ 0) : nat_trailing_degree p ≤ n := begin rw [← with_top.coe_le_coe, ← trailing_degree_eq_nat_trailing_degree], { exact le_trailing_degree_of_ne_zero h, }, { assume h, subst h, exact h rfl } end lemma trailing_degree_le_trailing_degree (h : coeff q (nat_trailing_degree p) ≠ 0) : trailing_degree q ≤ trailing_degree p := begin by_cases hp : p = 0, { rw hp, exact le_top }, { rw trailing_degree_eq_nat_trailing_degree hp, exact le_trailing_degree_of_ne_zero h } end lemma trailing_degree_ne_of_nat_trailing_degree_ne {n : ℕ} : p.nat_trailing_degree ≠ n → trailing_degree p ≠ n := mt $ λ h, by rw [nat_trailing_degree, h, option.get_or_else_coe] theorem nat_trailing_degree_le_of_trailing_degree_le {n : ℕ} {hp : p ≠ 0} (H : (n : ℕ∞) ≤ trailing_degree p) : n ≤ nat_trailing_degree p := begin rw trailing_degree_eq_nat_trailing_degree hp at H, exact with_top.coe_le_coe.mp H, end lemma nat_trailing_degree_le_nat_trailing_degree {hq : q ≠ 0} (hpq : p.trailing_degree ≤ q.trailing_degree) : p.nat_trailing_degree ≤ q.nat_trailing_degree := begin by_cases hp : p = 0, { rw [hp, nat_trailing_degree_zero], exact zero_le _ }, rwa [trailing_degree_eq_nat_trailing_degree hp, trailing_degree_eq_nat_trailing_degree hq, with_top.coe_le_coe] at hpq end @[simp] lemma trailing_degree_monomial (ha : a ≠ 0) : trailing_degree (monomial n a) = n := by rw [trailing_degree, support_monomial n ha, min_singleton] lemma nat_trailing_degree_monomial (ha : a ≠ 0) : nat_trailing_degree (monomial n a) = n := by rw [nat_trailing_degree, trailing_degree_monomial ha]; refl lemma nat_trailing_degree_monomial_le : nat_trailing_degree (monomial n a) ≤ n := if ha : a = 0 then by simp [ha] else (nat_trailing_degree_monomial ha).le lemma le_trailing_degree_monomial : ↑n ≤ trailing_degree (monomial n a) := if ha : a = 0 then by simp [ha] else (trailing_degree_monomial ha).ge @[simp] lemma trailing_degree_C (ha : a ≠ 0) : trailing_degree (C a) = (0 : ℕ∞) := trailing_degree_monomial ha lemma le_trailing_degree_C : (0 : ℕ∞) ≤ trailing_degree (C a) := le_trailing_degree_monomial lemma trailing_degree_one_le : (0 : ℕ∞) ≤ trailing_degree (1 : R[X]) := by rw [← C_1]; exact le_trailing_degree_C @[simp] lemma nat_trailing_degree_C (a : R) : nat_trailing_degree (C a) = 0 := nonpos_iff_eq_zero.1 nat_trailing_degree_monomial_le @[simp] lemma nat_trailing_degree_one : nat_trailing_degree (1 : R[X]) = 0 := nat_trailing_degree_C 1 @[simp] lemma nat_trailing_degree_nat_cast (n : ℕ) : nat_trailing_degree (n : R[X]) = 0 := by simp only [←C_eq_nat_cast, nat_trailing_degree_C] @[simp] lemma trailing_degree_C_mul_X_pow (n : ℕ) (ha : a ≠ 0) : trailing_degree (C a * X ^ n) = n := by rw [C_mul_X_pow_eq_monomial, trailing_degree_monomial ha] lemma le_trailing_degree_C_mul_X_pow (n : ℕ) (a : R) : (n : ℕ∞) ≤ trailing_degree (C a * X ^ n) := by { rw C_mul_X_pow_eq_monomial, exact le_trailing_degree_monomial } lemma coeff_eq_zero_of_trailing_degree_lt (h : (n : ℕ∞) < trailing_degree p) : coeff p n = 0 := not_not.1 (mt le_trailing_degree_of_ne_zero (not_le_of_gt h)) lemma coeff_eq_zero_of_lt_nat_trailing_degree {p : R[X]} {n : ℕ} (h : n < p.nat_trailing_degree) : p.coeff n = 0 := begin apply coeff_eq_zero_of_trailing_degree_lt, by_cases hp : p = 0, { rw [hp, trailing_degree_zero], exact with_top.coe_lt_top n, }, { rwa [trailing_degree_eq_nat_trailing_degree hp, with_top.coe_lt_coe] }, end @[simp] lemma coeff_nat_trailing_degree_pred_eq_zero {p : R[X]} {hp : (0 : ℕ∞) < nat_trailing_degree p} : p.coeff (p.nat_trailing_degree - 1) = 0 := coeff_eq_zero_of_lt_nat_trailing_degree $ nat.sub_lt ((with_top.zero_lt_coe (nat_trailing_degree p)).mp hp) nat.one_pos theorem le_trailing_degree_X_pow (n : ℕ) : (n : ℕ∞) ≤ trailing_degree (X^n : R[X]) := by simpa only [C_1, one_mul] using le_trailing_degree_C_mul_X_pow n (1:R) theorem le_trailing_degree_X : (1 : ℕ∞) ≤ trailing_degree (X : R[X]) := le_trailing_degree_monomial lemma nat_trailing_degree_X_le : (X : R[X]).nat_trailing_degree ≤ 1 := nat_trailing_degree_monomial_le @[simp] lemma trailing_coeff_eq_zero : trailing_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1 (not_not.2 h) (mem_of_min (trailing_degree_eq_nat_trailing_degree hp)), λ h, h.symm ▸ leading_coeff_zero⟩ lemma trailing_coeff_nonzero_iff_nonzero : trailing_coeff p ≠ 0 ↔ p ≠ 0 := not_congr trailing_coeff_eq_zero lemma nat_trailing_degree_mem_support_of_nonzero : p ≠ 0 → nat_trailing_degree p ∈ p.support := (mem_support_iff.mpr ∘ trailing_coeff_nonzero_iff_nonzero.mpr) lemma nat_trailing_degree_le_of_mem_supp (a : ℕ) : a ∈ p.support → nat_trailing_degree p ≤ a:= nat_trailing_degree_le_of_ne_zero ∘ mem_support_iff.mp lemma nat_trailing_degree_eq_support_min' (h : p ≠ 0) : nat_trailing_degree p = p.support.min' (nonempty_support_iff.mpr h) := begin apply le_antisymm, { apply le_min', intros y hy, exact nat_trailing_degree_le_of_mem_supp y hy }, { apply finset.min'_le, exact mem_support_iff.mpr (trailing_coeff_nonzero_iff_nonzero.mpr h), }, end lemma le_nat_trailing_degree (hp : p ≠ 0) (hn : ∀ m < n, p.coeff m = 0) : n ≤ p.nat_trailing_degree := begin rw nat_trailing_degree_eq_support_min' hp, exact finset.le_min' _ _ _ (λ m hm, not_lt.1 $ λ hmn, mem_support_iff.1 hm $ hn _ hmn), end lemma nat_trailing_degree_le_nat_degree (p : R[X]) : p.nat_trailing_degree ≤ p.nat_degree := begin by_cases hp : p = 0, { rw [hp, nat_degree_zero, nat_trailing_degree_zero] }, { exact le_nat_degree_of_ne_zero (mt trailing_coeff_eq_zero.mp hp) }, end lemma nat_trailing_degree_mul_X_pow {p : R[X]} (hp : p ≠ 0) (n : ℕ) : (p * X ^ n).nat_trailing_degree = p.nat_trailing_degree + n := begin apply le_antisymm, { refine nat_trailing_degree_le_of_ne_zero (λ h, mt trailing_coeff_eq_zero.mp hp _), rwa [trailing_coeff, ←coeff_mul_X_pow] }, { rw [nat_trailing_degree_eq_support_min' (λ h, hp (mul_X_pow_eq_zero h)), finset.le_min'_iff], intros y hy, have key : n ≤ y, { rw [mem_support_iff, coeff_mul_X_pow'] at hy, exact by_contra (λ h, hy (if_neg h)) }, rw [mem_support_iff, coeff_mul_X_pow', if_pos key] at hy, exact (le_tsub_iff_right key).mp (nat_trailing_degree_le_of_ne_zero hy) }, end lemma le_trailing_degree_mul : p.trailing_degree + q.trailing_degree ≤ (p * q).trailing_degree := begin refine finset.le_min (λ n hn, _), rw [mem_support_iff, coeff_mul] at hn, obtain ⟨⟨i, j⟩, hij, hpq⟩ := exists_ne_zero_of_sum_ne_zero hn, refine (add_le_add (min_le (mem_support_iff.mpr (left_ne_zero_of_mul hpq))) (min_le (mem_support_iff.mpr (right_ne_zero_of_mul hpq)))).trans (le_of_eq _), rwa [← with_top.coe_add, with_top.coe_eq_coe, ←nat.mem_antidiagonal], end lemma le_nat_trailing_degree_mul (h : p * q ≠ 0) : p.nat_trailing_degree + q.nat_trailing_degree ≤ (p * q).nat_trailing_degree := begin have hp : p ≠ 0 := λ hp, h (by rw [hp, zero_mul]), have hq : q ≠ 0 := λ hq, h (by rw [hq, mul_zero]), rw [←with_top.coe_le_coe, with_top.coe_add, ←trailing_degree_eq_nat_trailing_degree hp, ←trailing_degree_eq_nat_trailing_degree hq, ←trailing_degree_eq_nat_trailing_degree h], exact le_trailing_degree_mul, end lemma coeff_mul_nat_trailing_degree_add_nat_trailing_degree : (p * q).coeff (p.nat_trailing_degree + q.nat_trailing_degree) = p.trailing_coeff * q.trailing_coeff := begin rw coeff_mul, refine finset.sum_eq_single (p.nat_trailing_degree, q.nat_trailing_degree) _ (λ h, (h (nat.mem_antidiagonal.mpr rfl)).elim), rintro ⟨i, j⟩ h₁ h₂, rw nat.mem_antidiagonal at h₁, by_cases hi : i < p.nat_trailing_degree, { rw [coeff_eq_zero_of_lt_nat_trailing_degree hi, zero_mul] }, by_cases hj : j < q.nat_trailing_degree, { rw [coeff_eq_zero_of_lt_nat_trailing_degree hj, mul_zero] }, rw not_lt at hi hj, refine (h₂ (prod.ext_iff.mpr _).symm).elim, exact (add_eq_add_iff_eq_and_eq hi hj).mp h₁.symm, end lemma trailing_degree_mul' (h : p.trailing_coeff * q.trailing_coeff ≠ 0) : (p * q).trailing_degree = p.trailing_degree + q.trailing_degree := begin have hp : p ≠ 0 := λ hp, h (by rw [hp, trailing_coeff_zero, zero_mul]), have hq : q ≠ 0 := λ hq, h (by rw [hq, trailing_coeff_zero, mul_zero]), refine le_antisymm _ le_trailing_degree_mul, rw [trailing_degree_eq_nat_trailing_degree hp, trailing_degree_eq_nat_trailing_degree hq, ← enat.coe_add], apply le_trailing_degree_of_ne_zero, rwa coeff_mul_nat_trailing_degree_add_nat_trailing_degree, end lemma nat_trailing_degree_mul' (h : p.trailing_coeff * q.trailing_coeff ≠ 0) : (p * q).nat_trailing_degree = p.nat_trailing_degree + q.nat_trailing_degree := begin have hp : p ≠ 0 := λ hp, h (by rw [hp, trailing_coeff_zero, zero_mul]), have hq : q ≠ 0 := λ hq, h (by rw [hq, trailing_coeff_zero, mul_zero]), apply nat_trailing_degree_eq_of_trailing_degree_eq_some, rw [trailing_degree_mul' h, with_top.coe_add, ←trailing_degree_eq_nat_trailing_degree hp, ←trailing_degree_eq_nat_trailing_degree hq], end lemma nat_trailing_degree_mul [no_zero_divisors R] (hp : p ≠ 0) (hq : q ≠ 0) : (p * q).nat_trailing_degree = p.nat_trailing_degree + q.nat_trailing_degree := nat_trailing_degree_mul' (mul_ne_zero (mt trailing_coeff_eq_zero.mp hp) (mt trailing_coeff_eq_zero.mp hq)) end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : R[X]} @[simp] lemma trailing_degree_one : trailing_degree (1 : R[X]) = (0 : ℕ∞) := trailing_degree_C one_ne_zero @[simp] lemma trailing_degree_X : trailing_degree (X : R[X]) = 1 := trailing_degree_monomial one_ne_zero @[simp] lemma nat_trailing_degree_X : (X : R[X]).nat_trailing_degree = 1 := nat_trailing_degree_monomial one_ne_zero end nonzero_semiring section ring variables [ring R] @[simp] lemma trailing_degree_neg (p : R[X]) : trailing_degree (-p) = trailing_degree p := by unfold trailing_degree; rw support_neg @[simp] lemma nat_trailing_degree_neg (p : R[X]) : nat_trailing_degree (-p) = nat_trailing_degree p := by simp [nat_trailing_degree] @[simp] lemma nat_trailing_degree_int_cast (n : ℤ) : nat_trailing_degree (n : R[X]) = 0 := by simp only [←C_eq_int_cast, nat_trailing_degree_C] end ring section semiring variables [semiring R] /-- The second-lowest coefficient, or 0 for constants -/ def next_coeff_up (p : R[X]) : R := if p.nat_trailing_degree = 0 then 0 else p.coeff (p.nat_trailing_degree + 1) @[simp] lemma next_coeff_up_C_eq_zero (c : R) : next_coeff_up (C c) = 0 := by { rw next_coeff_up, simp } lemma next_coeff_up_of_pos_nat_trailing_degree (p : R[X]) (hp : 0 < p.nat_trailing_degree) : next_coeff_up p = p.coeff (p.nat_trailing_degree + 1) := by { rw [next_coeff_up, if_neg], contrapose! hp, simpa } end semiring section semiring variables [semiring R] {p q : R[X]} {ι : Type*} lemma coeff_nat_trailing_degree_eq_zero_of_trailing_degree_lt (h : trailing_degree p < trailing_degree q) : coeff q (nat_trailing_degree p) = 0 := coeff_eq_zero_of_trailing_degree_lt $ nat_trailing_degree_le_trailing_degree.trans_lt h lemma ne_zero_of_trailing_degree_lt {n : ℕ∞} (h : trailing_degree p < n) : p ≠ 0 := λ h₀, h.not_le (by simp [h₀]) end semiring end polynomial
6de1ed321f760f2d7d44ee503b4c0803a86240cb
d642a6b1261b2cbe691e53561ac777b924751b63
/src/algebra/category/Group.lean
167f669627a5effa12dc62302e6b57073e971435
[ "Apache-2.0" ]
permissive
cipher1024/mathlib
fee56b9954e969721715e45fea8bcb95f9dc03fe
d077887141000fefa5a264e30fa57520e9f03522
refs/heads/master
1,651,806,490,504
1,573,508,694,000
1,573,508,694,000
107,216,176
0
0
Apache-2.0
1,647,363,136,000
1,508,213,014,000
Lean
UTF-8
Lean
false
false
2,339
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.punit_instances import algebra.category.Mon.basic /-! # Category instances for group, add_group, comm_group, and add_comm_group. We introduce the bundled categories: * `Group` * `AddGroup` * `CommGroup` * `AddCommGroup` along with the relevant forgetful functors between them, and to the bundled monoid categories. ## Implementation notes See the note [locally reducible category instances]. -/ universes u v open category_theory /-- The category of groups and group morphisms. -/ @[to_additive AddGroup] def Group : Type (u+1) := induced_category Mon (bundled.map group.to_monoid) namespace Group /-- Construct a bundled Group from the underlying type and typeclass. -/ @[to_additive] def of (X : Type u) [group X] : Group := bundled.of X local attribute [reducible] Group @[to_additive] instance : has_coe_to_sort Group := infer_instance @[to_additive add_group] instance (G : Group) : group G := G.str @[to_additive] instance : has_one Group := ⟨Group.of punit⟩ @[to_additive] instance : concrete_category Group := infer_instance @[to_additive has_forget_to_AddMon] instance has_forget_to_Mon : has_forget₂ Group Mon := infer_instance end Group /-- The category of commutative groups and group morphisms. -/ @[to_additive AddCommGroup] def CommGroup : Type (u+1) := induced_category Group (bundled.map comm_group.to_group) namespace CommGroup /-- Construct a bundled CommGroup from the underlying type and typeclass. -/ @[to_additive] def of (G : Type u) [comm_group G] : CommGroup := bundled.of G local attribute [reducible] CommGroup @[to_additive] instance : has_coe_to_sort CommGroup := infer_instance @[to_additive add_comm_group] instance (G : CommGroup) : comm_group G := G.str @[to_additive] instance : has_one CommGroup := ⟨CommGroup.of punit⟩ @[to_additive] instance : concrete_category CommGroup := infer_instance @[to_additive has_forget_to_AddGroup] instance has_forget_to_Group : has_forget₂ CommGroup Group := infer_instance @[to_additive has_forget_to_AddCommMon] instance has_forget_to_CommMon : has_forget₂ CommGroup CommMon := induced_category.has_forget₂ (λ G : CommGroup, CommMon.of G) end CommGroup
97b5bc18a390c977b956427ea97a8687eaa3c4cc
2385ce0e3b60d8dbea33dd439902a2070cca7a24
/tests/lean/run/coinductive.lean
57bbc8f99e3a353da662f27ddca7fe90d86ed8bb
[ "Apache-2.0" ]
permissive
TehMillhouse/lean
68d6fdd2fb11a6c65bc28dec308d70f04dad38b4
6bbf2fbd8912617e5a973575bab8c383c9c268a1
refs/heads/master
1,620,830,893,339
1,515,592,479,000
1,515,592,997,000
116,964,828
0
0
null
1,515,592,734,000
1,515,592,734,000
null
UTF-8
Lean
false
false
4,660
lean
/- test cases for coinductive predicates -/ universe u def stream (α : Type u) := nat → α constant stream.cons {α} : α → stream α → stream α constant stream.head {α} : stream α → α constant stream.tail {α} : stream α → stream α notation h :: t := stream.cons h t coinductive all_stream {α : Type u} (s : set α) : stream α → Prop | step {} : ∀{a : α} {ω : stream α}, a ∈ s → all_stream ω → all_stream (a :: ω) #print prefix all_stream #check (@all_stream : Π {α : Type u}, set α → stream α → Prop) #check (@all_stream.step : ∀ {α : Type u} {s : set α} {a : α} {ω : stream α}, a ∈ s → all_stream s ω → all_stream s (a :: ω)) #check (@all_stream.corec_functional : ∀ {α : Type u} (s : set α) (C : stream α → Prop), (∀ (a : stream α), C a → all_stream.functional s C a) → ∀ (a : stream α), C a → all_stream s a) coinductive all_stream' {α : Type u} (s : set α) : stream α → Prop | step {} : ∀{ω : stream α}, stream.head ω ∈ s → all_stream' (stream.tail ω) → all_stream' ω coinductive alt_stream : stream bool → Prop | tt_step : ∀{ω : stream bool}, alt_stream (ff :: ω) → alt_stream (tt :: ff :: ω) | ff_step : ∀{ω : stream bool}, alt_stream (tt :: ω) → alt_stream (ff :: tt :: ω) #print prefix alt_stream #check (@alt_stream : stream bool → Prop) #check (@alt_stream.tt_step : ∀ {ω : stream bool}, alt_stream (ff :: ω) → alt_stream (tt :: ff :: ω)) #check (@alt_stream.ff_step : ∀ {ω : stream bool}, alt_stream (tt :: ω) → alt_stream (ff :: tt :: ω)) #check (@alt_stream.corec_functional : ∀ (C : stream bool → Prop), (∀ (a : stream bool), C a → alt_stream.functional C a) → ∀ (a : stream bool), C a → alt_stream a) mutual coinductive tt_stream, ff_stream with tt_stream : stream bool → Prop | step {} : ∀{ω : stream bool}, ff_stream ω → tt_stream (stream.cons tt ω) with ff_stream : stream bool → Prop | step {} : ∀{ω : stream bool}, tt_stream ω → ff_stream (stream.cons ff ω) #print prefix tt_stream #print prefix ff_stream #check (@tt_stream : stream bool → Prop) #check (@tt_stream.corec_functional : ∀ (C_tt_stream C_ff_stream : stream bool → Prop), (∀ (a : stream bool), C_tt_stream a → tt_stream.functional C_tt_stream C_ff_stream a) → (∀ (a : stream bool), C_ff_stream a → ff_stream.functional C_tt_stream C_ff_stream a) → ∀ (a : stream bool), C_tt_stream a → tt_stream a) #check (@ff_stream : stream bool → Prop) #check (@ff_stream.corec_functional : ∀ (C_tt_stream C_ff_stream : stream bool → Prop), (∀ (a : stream bool), C_tt_stream a → tt_stream.functional C_tt_stream C_ff_stream a) → (∀ (a : stream bool), C_ff_stream a → ff_stream.functional C_tt_stream C_ff_stream a) → ∀ (a : stream bool), C_ff_stream a → ff_stream a) mutual coinductive tt_ff_stream, ff_tt_stream with tt_ff_stream : stream bool → Prop | step {} : ∀{ω : stream bool}, tt_ff_stream ω ∨ ff_tt_stream ω → tt_ff_stream (stream.cons tt ω) with ff_tt_stream : stream bool → Prop | step {} : ∀{ω : stream bool}, ff_tt_stream ω ∨ tt_ff_stream ω → ff_tt_stream (stream.cons ff ω) #print prefix tt_ff_stream inductive all_list {α : Type} (p : α → Prop) : list α → Prop | nil : all_list [] | cons : ∀a xs, p a → all_list xs → all_list (a :: xs) @[monotonicity] lemma monotonicity.all_list {α : Type} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : ∀xs, implies (all_list p xs) (all_list q xs) | ._ (all_list.nil ._) := all_list.nil _ | ._ (all_list.cons a xs ha hxs) := all_list.cons _ _ (h a ha) (monotonicity.all_list _ hxs) mutual coinductive walk_a, walk_b {α β : Type} (f : α → list β) (g : β → α) (p : α → Prop) (t : α → Prop) with walk_a : α → Prop | step : ∀a, all_list walk_b (f a) → p a → walk_a a | term : ∀a, t a → walk_a a with walk_b : β → Prop | step : ∀b, walk_a (g b) → walk_b b coinductive walk_list {α : Type} (f : α → list α) (p : α → Prop) : ℕ → α → Prop | step : ∀n a, all_list (walk_list n) (f a) → p a → walk_list (n + 1) a -- #check walk_a.corec_on example {f : ℕ → list ℕ} {a' : ℕ} {n : ℕ} {a : fin n}: walk_list f (λ a'', a'' = a') (n + 1) a' := begin coinduction walk_list.corec_on generalizing a n, show ∃ (n : ℕ), all_list (λ (a : ℕ), ∃ {n_1 : ℕ} {a_1 : fin n_1}, n_1 + 1 = n ∧ a' = a) (f a') ∧ a' = a' ∧ n + 1 = w + 1, sorry end coinductive foo : list ℕ → Prop | mk : ∀ xs, (∀ k l m, foo (k::l::m::xs)) → foo xs
167d9cab421df7f3cd1e192f28f2dcbc9c83b6e9
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/simple_module.lean
0130a60f002c5aefad99896a7f45eed344fcfb33
[ "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
7,285
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import linear_algebra.isomorphisms import order.jordan_holder /-! # Simple Modules ## Main Definitions * `is_simple_module` indicates that a module has no proper submodules (the only submodules are `⊥` and `⊤`). * `is_semisimple_module` indicates that every submodule has a complement, or equivalently, the module is a direct sum of simple modules. * A `division_ring` structure on the endomorphism ring of a simple module. ## Main Results * Schur's Lemma: `bijective_or_eq_zero` shows that a linear map between simple modules is either bijective or 0, leading to a `division_ring` structure on the endomorphism ring. ## TODO * Artin-Wedderburn Theory * Unify with the work on Schur's Lemma in a category theory context -/ variables (R : Type*) [ring R] (M : Type*) [add_comm_group M] [module R M] /-- A module is simple when it has only two submodules, `⊥` and `⊤`. -/ abbreviation is_simple_module := (is_simple_order (submodule R M)) /-- A module is semisimple when every submodule has a complement, or equivalently, the module is a direct sum of simple modules. -/ abbreviation is_semisimple_module := (complemented_lattice (submodule R M)) -- Making this an instance causes the linter to complain of "dangerous instances" theorem is_simple_module.nontrivial [is_simple_module R M] : nontrivial M := ⟨⟨0, begin have h : (⊥ : submodule R M) ≠ ⊤ := bot_ne_top, contrapose! h, ext, simp [submodule.mem_bot,submodule.mem_top, h x], end⟩⟩ variables {R} {M} {m : submodule R M} {N : Type*} [add_comm_group N] [module R N] lemma is_simple_module.congr (l : M ≃ₗ[R] N) [is_simple_module R N] : is_simple_module R M := (submodule.order_iso_map_comap l).is_simple_order theorem is_simple_module_iff_is_atom : is_simple_module R m ↔ is_atom m := begin rw ← set.is_simple_order_Iic_iff_is_atom, apply order_iso.is_simple_order_iff, exact submodule.map_subtype.rel_iso m, end theorem is_simple_module_iff_is_coatom : is_simple_module R (M ⧸ m) ↔ is_coatom m := begin rw ← set.is_simple_order_Ici_iff_is_coatom, apply order_iso.is_simple_order_iff, exact submodule.comap_mkq.rel_iso m, end theorem covby_iff_quot_is_simple {A B : submodule R M} (hAB : A ≤ B) : A ⋖ B ↔ is_simple_module R (B ⧸ submodule.comap B.subtype A) := begin set f : submodule R B ≃o set.Iic B := submodule.map_subtype.rel_iso B with hf, rw [covby_iff_coatom_Iic hAB, is_simple_module_iff_is_coatom, ←order_iso.is_coatom_iff f, hf], simp [-order_iso.is_coatom_iff, submodule.map_subtype.rel_iso, submodule.map_comap_subtype, inf_eq_right.2 hAB], end namespace is_simple_module variable [hm : is_simple_module R m] @[simp] lemma is_atom : is_atom m := is_simple_module_iff_is_atom.1 hm end is_simple_module theorem is_semisimple_of_Sup_simples_eq_top (h : Sup {m : submodule R M | is_simple_module R m} = ⊤) : is_semisimple_module R M := complemented_lattice_of_Sup_atoms_eq_top (by simp_rw [← h, is_simple_module_iff_is_atom]) namespace is_semisimple_module variable [is_semisimple_module R M] theorem Sup_simples_eq_top : Sup {m : submodule R M | is_simple_module R m} = ⊤ := begin simp_rw is_simple_module_iff_is_atom, exact Sup_atoms_eq_top, end instance is_semisimple_submodule {m : submodule R M} : is_semisimple_module R m := begin have f : submodule R m ≃o set.Iic m := submodule.map_subtype.rel_iso m, exact f.complemented_lattice_iff.2 is_modular_lattice.complemented_lattice_Iic, end end is_semisimple_module theorem is_semisimple_iff_top_eq_Sup_simples : Sup {m : submodule R M | is_simple_module R m} = ⊤ ↔ is_semisimple_module R M := ⟨is_semisimple_of_Sup_simples_eq_top, by { introI, exact is_semisimple_module.Sup_simples_eq_top }⟩ namespace linear_map theorem injective_or_eq_zero [is_simple_module R M] (f : M →ₗ[R] N) : function.injective f ∨ f = 0 := begin rw [← ker_eq_bot, ← ker_eq_top], apply eq_bot_or_eq_top, end theorem injective_of_ne_zero [is_simple_module R M] {f : M →ₗ[R] N} (h : f ≠ 0) : function.injective f := f.injective_or_eq_zero.resolve_right h theorem surjective_or_eq_zero [is_simple_module R N] (f : M →ₗ[R] N) : function.surjective f ∨ f = 0 := begin rw [← range_eq_top, ← range_eq_bot, or_comm], apply eq_bot_or_eq_top, end theorem surjective_of_ne_zero [is_simple_module R N] {f : M →ₗ[R] N} (h : f ≠ 0) : function.surjective f := f.surjective_or_eq_zero.resolve_right h /-- **Schur's Lemma** for linear maps between (possibly distinct) simple modules -/ theorem bijective_or_eq_zero [is_simple_module R M] [is_simple_module R N] (f : M →ₗ[R] N) : function.bijective f ∨ f = 0 := begin by_cases h : f = 0, { right, exact h }, exact or.intro_left _ ⟨injective_of_ne_zero h, surjective_of_ne_zero h⟩, end theorem bijective_of_ne_zero [is_simple_module R M] [is_simple_module R N] {f : M →ₗ[R] N} (h : f ≠ 0): function.bijective f := f.bijective_or_eq_zero.resolve_right h theorem is_coatom_ker_of_surjective [is_simple_module R N] {f : M →ₗ[R] N} (hf : function.surjective f) : is_coatom f.ker := begin rw ←is_simple_module_iff_is_coatom, exact is_simple_module.congr (f.quot_ker_equiv_of_surjective hf) end /-- Schur's Lemma makes the endomorphism ring of a simple module a division ring. -/ noncomputable instance _root_.module.End.division_ring [decidable_eq (module.End R M)] [is_simple_module R M] : division_ring (module.End R M) := { inv := λ f, if h : f = 0 then 0 else (linear_map.inverse f (equiv.of_bijective _ (bijective_of_ne_zero h)).inv_fun (equiv.of_bijective _ (bijective_of_ne_zero h)).left_inv (equiv.of_bijective _ (bijective_of_ne_zero h)).right_inv), exists_pair_ne := ⟨0, 1, begin haveI := is_simple_module.nontrivial R M, have h := exists_pair_ne M, contrapose! h, intros x y, simp_rw [ext_iff, one_apply, zero_apply] at h, rw [← h x, h y], end⟩, mul_inv_cancel := begin intros a a0, change (a * (dite _ _ _)) = 1, ext, rw [dif_neg a0, mul_eq_comp, one_apply, comp_apply], exact (equiv.of_bijective _ (bijective_of_ne_zero a0)).right_inv x, end, inv_zero := dif_pos rfl, .. (module.End.ring : ring (module.End R M))} end linear_map instance jordan_holder_module : jordan_holder_lattice (submodule R M) := { is_maximal := (⋖), lt_of_is_maximal := λ x y, covby.lt, sup_eq_of_is_maximal := λ x y z hxz hyz, wcovby.sup_eq hxz.wcovby hyz.wcovby, is_maximal_inf_left_of_is_maximal_sup := λ A B, inf_covby_of_covby_sup_of_covby_sup_left, iso := λ X Y, nonempty $ (X.2 ⧸ X.1.comap X.2.subtype) ≃ₗ[R] Y.2 ⧸ Y.1.comap Y.2.subtype, iso_symm := λ A B ⟨f⟩, ⟨f.symm⟩, iso_trans := λ A B C ⟨f⟩ ⟨g⟩, ⟨f.trans g⟩, second_iso := λ A B h, ⟨by { rw [sup_comm, inf_comm], exact (linear_map.quotient_inf_equiv_sup_quotient B A).symm }⟩}
93216c43ffe2cec963875a92785f2796dd5abb5a
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/simplifier17.lean
9b0b5128a7c5c4eed8430c09fc9d20c91d96c9c6
[ "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
416
lean
import algebra.ring open algebra universe l constants (A : Type.{l}) (s : comm_ring A) (x : A) attribute s [instance] set_option simplify.numerals true #simplify eq env 0 (1:A) #simplify eq env 0 (1:A) + 1 #simplify eq env 0 (1:A) + 1 + 1 #simplify eq env 0 (1:A) + 2 + 1 #simplify eq env 0 (1:A) + 2 * 7 + 1 #simplify eq env 0 (1:A) + 2 * 7 + 10 #simplify eq env 0 (10000000000000000000:A) + 10000000000000000000
1b6cfcd142a8330268996e83a26a42788b152147
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/semiconj_Sup.lean
9d2b2f621412db25443edb4bd18519d04beffc4c
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,131
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import logic.function.conjugate import order.bounds.order_iso import order.conditionally_complete_lattice.basic import order.rel_iso.group import order.ord_continuous import algebra.hom.equiv.units.basic /-! # Semiconjugate by `Sup` In this file we prove two facts about semiconjugate (families of) functions. First, if an order isomorphism `fa : α → α` is semiconjugate to an order embedding `fb : β → β` by `g : α → β`, then `fb` is semiconjugate to `fa` by `y ↦ Sup {x | g x ≤ y}`, see `semiconj.symm_adjoint`. Second, consider two actions `f₁ f₂ : G → α → α` of a group on a complete lattice by order isomorphisms. Then the map `x ↦ ⨆ g : G, (f₁ g)⁻¹ (f₂ g x)` semiconjugates each `f₁ g'` to `f₂ g'`, see `function.Sup_div_semiconj`. In the case of a conditionally complete lattice, a similar statement holds true under an additional assumption that each set `{(f₁ g)⁻¹ (f₂ g x) | g : G}` is bounded above, see `function.cSup_div_semiconj`. The lemmas come from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes], Proposition 2.1 and 5.4 respectively. In the paper they are formulated for homeomorphisms of the circle, so in order to apply results from this file one has to lift these homeomorphisms to the real line first. -/ variables {α β γ : Type*} open set /-- We say that `g : β → α` is an order right adjoint function for `f : α → β` if it sends each `y` to a least upper bound for `{x | f x ≤ y}`. If `α` is a partial order, and `f : α → β` has a right adjoint, then this right adjoint is unique. -/ def is_order_right_adjoint [preorder α] [preorder β] (f : α → β) (g : β → α) := ∀ y, is_lub {x | f x ≤ y} (g y) lemma is_order_right_adjoint_Sup [complete_lattice α] [preorder β] (f : α → β) : is_order_right_adjoint f (λ y, Sup {x | f x ≤ y}) := λ y, is_lub_Sup _ lemma is_order_right_adjoint_cSup [conditionally_complete_lattice α] [preorder β] (f : α → β) (hne : ∀ y, ∃ x, f x ≤ y) (hbdd : ∀ y, bdd_above {x | f x ≤ y}) : is_order_right_adjoint f (λ y, Sup {x | f x ≤ y}) := λ y, is_lub_cSup (hne y) (hbdd y) namespace is_order_right_adjoint protected lemma unique [partial_order α] [preorder β] {f : α → β} {g₁ g₂ : β → α} (h₁ : is_order_right_adjoint f g₁) (h₂ : is_order_right_adjoint f g₂) : g₁ = g₂ := funext $ λ y, (h₁ y).unique (h₂ y) lemma right_mono [preorder α] [preorder β] {f : α → β} {g : β → α} (h : is_order_right_adjoint f g) : monotone g := λ y₁ y₂ hy, (h y₁).mono (h y₂) $ λ x hx, le_trans hx hy lemma order_iso_comp [preorder α] [preorder β] [preorder γ] {f : α → β} {g : β → α} (h : is_order_right_adjoint f g) (e : β ≃o γ) : is_order_right_adjoint (e ∘ f) (g ∘ e.symm) := λ y, by simpa [e.le_symm_apply] using h (e.symm y) lemma comp_order_iso [preorder α] [preorder β] [preorder γ] {f : α → β} {g : β → α} (h : is_order_right_adjoint f g) (e : γ ≃o α) : is_order_right_adjoint (f ∘ e) (e.symm ∘ g) := begin intro y, change is_lub (e ⁻¹' {x | f x ≤ y}) (e.symm (g y)), rw [e.is_lub_preimage, e.apply_symm_apply], exact h y end end is_order_right_adjoint namespace function /-- If an order automorphism `fa` is semiconjugate to an order embedding `fb` by a function `g` and `g'` is an order right adjoint of `g` (i.e. `g' y = Sup {x | f x ≤ y}`), then `fb` is semiconjugate to `fa` by `g'`. This is a version of Proposition 2.1 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. -/ lemma semiconj.symm_adjoint [partial_order α] [preorder β] {fa : α ≃o α} {fb : β ↪o β} {g : α → β} (h : function.semiconj g fa fb) {g' : β → α} (hg' : is_order_right_adjoint g g') : function.semiconj g' fb fa := begin refine λ y, (hg' _).unique _, rw [← fa.surjective.image_preimage {x | g x ≤ fb y}, preimage_set_of_eq], simp only [h.eq, fb.le_iff_le, fa.left_ord_continuous (hg' _)] end variable {G : Type*} lemma semiconj_of_is_lub [partial_order α] [group G] (f₁ f₂ : G →* (α ≃o α)) {h : α → α} (H : ∀ x, is_lub (range (λ g', (f₁ g')⁻¹ (f₂ g' x))) (h x)) (g : G) : function.semiconj h (f₂ g) (f₁ g) := begin refine λ y, (H _).unique _, have := (f₁ g).left_ord_continuous (H y), rw [← range_comp, ← (equiv.mul_right g).surjective.range_comp _] at this, simpa [(∘)] using this end /-- Consider two actions `f₁ f₂ : G → α → α` of a group on a complete lattice by order isomorphisms. Then the map `x ↦ ⨆ g : G, (f₁ g)⁻¹ (f₂ g x)` semiconjugates each `f₁ g'` to `f₂ g'`. This is a version of Proposition 5.4 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. -/ lemma Sup_div_semiconj [complete_lattice α] [group G] (f₁ f₂ : G →* (α ≃o α)) (g : G) : function.semiconj (λ x, ⨆ g' : G, (f₁ g')⁻¹ (f₂ g' x)) (f₂ g) (f₁ g) := semiconj_of_is_lub f₁ f₂ (λ x, is_lub_supr) _ /-- Consider two actions `f₁ f₂ : G → α → α` of a group on a conditionally complete lattice by order isomorphisms. Suppose that each set $s(x)=\{f_1(g)^{-1} (f_2(g)(x)) | g \in G\}$ is bounded above. Then the map `x ↦ Sup s(x)` semiconjugates each `f₁ g'` to `f₂ g'`. This is a version of Proposition 5.4 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. -/ lemma cSup_div_semiconj [conditionally_complete_lattice α] [group G] (f₁ f₂ : G →* (α ≃o α)) (hbdd : ∀ x, bdd_above (range $ λ g, (f₁ g)⁻¹ (f₂ g x))) (g : G) : function.semiconj (λ x, ⨆ g' : G, (f₁ g')⁻¹ (f₂ g' x)) (f₂ g) (f₁ g) := semiconj_of_is_lub f₁ f₂ (λ x, is_lub_cSup (range_nonempty _) (hbdd x)) _ end function -- Guard against import creep assert_not_exists finset
db309317de9562f5b72aff4c34d2401d02ec7506
d1bbf1801b3dcb214451d48214589f511061da63
/src/topology/algebra/group.lean
ab652c8922c3a4c20c5afa406699fc85714cd322
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,533
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⁻¹) 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 } 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 @[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*} [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 _⟩], apply inf_principal_eq_bot, rw 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), cases hK.elim_finite_subcover X (λ x, (hV x).1.preimage (continuous_mul_left x⁻¹)) _ with t ht, swap, { 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 cases hV with g₀ hg₀, rcases is_compact.elim_finite_subcover hK (λ x : G, interior $ (λ h, x * h) ⁻¹' V) _ _ with ⟨t, ht⟩, { refine ⟨t, subset.trans ht _⟩, apply Union_subset_Union, intro g, apply Union_subset_Union, intro hg, apply interior_subset }, { intro g, apply is_open_interior }, { intros g hg, rw [mem_Union], use g₀ * g⁻¹, apply preimage_interior_subset_interior_preimage, exact continuous_const.mul continuous_id, rwa [mem_preimage, inv_mul_cancel_right] } 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, h1L, h2L, h3L⟩ := exists_compact_subset is_open_univ (mem_univ (1 : G)), refine ⟨⟨λ n, (λ x, x * dense_seq G n) ⁻¹' L, _, _⟩⟩, { intro n, exact (homeomorph.mul_right _).compact_preimage.mpr h1L }, { rw [eq_univ_iff_forall], intro x, obtain ⟨_, hn, ⟨n, rfl⟩⟩ : ((λ y, x * y) ⁻¹' L ∩ range (dense_seq G)).nonempty := (dense_iff_inter_open.mp (dense_range_dense_seq G) _ ((homeomorph.mul_left _).continuous.is_open_preimage _ is_open_interior) ⟨x⁻¹, by simp [homeomorph.mul_left, h2L]⟩).mono (inter_subset_inter_left _ $ preimage_mono $ interior_subset), exact mem_Union.mpr ⟨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 _ _ _ }
b6577cc6f667947de139aa90acc9fb6db59f2db2
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/linear_algebra/eigenspace.lean
37720c8465f6844dd6763dfeb2e7d6512781a2af
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,770
lean
/- Copyright (c) 2020 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import field_theory.is_alg_closed.basic import linear_algebra.finsupp import linear_algebra.matrix.to_lin import order.preorder_hom import linear_algebra.charpoly.basic /-! # Eigenvectors and eigenvalues This file defines eigenspaces, eigenvalues, and eigenvalues, as well as their generalized counterparts. We follow Axler's approach [axler2015] because it allows us to derive many properties without choosing a basis and without using matrices. An eigenspace of a linear map `f` for a scalar `μ` is the kernel of the map `(f - μ • id)`. The nonzero elements of an eigenspace are eigenvectors `x`. They have the property `f x = μ • x`. If there are eigenvectors for a scalar `μ`, the scalar `μ` is called an eigenvalue. There is no consensus in the literature whether `0` is an eigenvector. Our definition of `has_eigenvector` permits only nonzero vectors. For an eigenvector `x` that may also be `0`, we write `x ∈ f.eigenspace μ`. A generalized eigenspace of a linear map `f` for a natural number `k` and a scalar `μ` is the kernel of the map `(f - μ • id) ^ k`. The nonzero elements of a generalized eigenspace are generalized eigenvectors `x`. If there are generalized eigenvectors for a natural number `k` and a scalar `μ`, the scalar `μ` is called a generalized eigenvalue. ## References * [Sheldon Axler, *Linear Algebra Done Right*][axler2015] * https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors ## Tags eigenspace, eigenvector, eigenvalue, eigen -/ universes u v w namespace module namespace End open module principal_ideal_ring polynomial finite_dimensional variables {K R : Type v} {V M : Type w} [comm_ring R] [add_comm_group M] [module R M] [field K] [add_comm_group V] [module K V] /-- The submodule `eigenspace f μ` for a linear map `f` and a scalar `μ` consists of all vectors `x` such that `f x = μ • x`. (Def 5.36 of [axler2015])-/ def eigenspace (f : End R M) (μ : R) : submodule R M := (f - algebra_map R (End R M) μ).ker /-- A nonzero element of an eigenspace is an eigenvector. (Def 5.7 of [axler2015]) -/ def has_eigenvector (f : End R M) (μ : R) (x : M) : Prop := x ∈ eigenspace f μ ∧ x ≠ 0 /-- A scalar `μ` is an eigenvalue for a linear map `f` if there are nonzero vectors `x` such that `f x = μ • x`. (Def 5.5 of [axler2015]) -/ def has_eigenvalue (f : End R M) (a : R) : Prop := eigenspace f a ≠ ⊥ lemma has_eigenvalue_of_has_eigenvector {f : End R M} {μ : R} {x : M} (h : has_eigenvector f μ x) : has_eigenvalue f μ := begin rw [has_eigenvalue, submodule.ne_bot_iff], use x, exact h, end lemma mem_eigenspace_iff {f : End R M} {μ : R} {x : M} : x ∈ eigenspace f μ ↔ f x = μ • x := by rw [eigenspace, linear_map.mem_ker, linear_map.sub_apply, algebra_map_End_apply, sub_eq_zero] lemma eigenspace_div (f : End K V) (a b : K) (hb : b ≠ 0) : eigenspace f (a / b) = (b • f - algebra_map K (End K V) a).ker := calc eigenspace f (a / b) = eigenspace f (b⁻¹ * a) : by { rw [div_eq_mul_inv, mul_comm] } ... = (f - (b⁻¹ * a) • linear_map.id).ker : rfl ... = (f - b⁻¹ • a • linear_map.id).ker : by rw smul_smul ... = (f - b⁻¹ • algebra_map K (End K V) a).ker : rfl ... = (b • (f - b⁻¹ • algebra_map K (End K V) a)).ker : by rw linear_map.ker_smul _ b hb ... = (b • f - algebra_map K (End K V) a).ker : by rw [smul_sub, smul_inv_smul₀ hb] lemma eigenspace_aeval_polynomial_degree_1 (f : End K V) (q : polynomial K) (hq : degree q = 1) : eigenspace f (- q.coeff 0 / q.leading_coeff) = (aeval f q).ker := calc eigenspace f (- q.coeff 0 / q.leading_coeff) = (q.leading_coeff • f - algebra_map K (End K V) (- q.coeff 0)).ker : by { rw eigenspace_div, intro h, rw leading_coeff_eq_zero_iff_deg_eq_bot.1 h at hq, cases hq } ... = (aeval f (C q.leading_coeff * X + C (q.coeff 0))).ker : by { rw [C_mul', aeval_def], simp [algebra_map, algebra.to_ring_hom], } ... = (aeval f q).ker : by { congr, apply (eq_X_add_C_of_degree_eq_one hq).symm } lemma ker_aeval_ring_hom'_unit_polynomial (f : End K V) (c : units (polynomial K)) : (aeval f (c : polynomial K)).ker = ⊥ := begin rw polynomial.eq_C_of_degree_eq_zero (degree_coe_units c), simp only [aeval_def, eval₂_C], apply ker_algebra_map_End, apply coeff_coe_units_zero_ne_zero c end theorem aeval_apply_of_has_eigenvector {f : End K V} {p : polynomial K} {μ : K} {x : V} (h : f.has_eigenvector μ x) : aeval f p x = (p.eval μ) • x := begin apply p.induction_on, { intro a, simp [module.algebra_map_End_apply] }, { intros p q hp hq, simp [hp, hq, add_smul] }, { intros n a hna, rw [mul_comm, pow_succ, mul_assoc, alg_hom.map_mul, linear_map.mul_apply, mul_comm, hna], simp [algebra_map_End_apply, mem_eigenspace_iff.1 h.1, smul_smul, mul_comm] } end section minpoly theorem is_root_of_has_eigenvalue {f : End K V} {μ : K} (h : f.has_eigenvalue μ) : (minpoly K f).is_root μ := begin rcases (submodule.ne_bot_iff _).1 h with ⟨w, ⟨H, ne0⟩⟩, refine or.resolve_right (smul_eq_zero.1 _) ne0, simp [← aeval_apply_of_has_eigenvector ⟨H, ne0⟩, minpoly.aeval K f], end variables [finite_dimensional K V] (f : End K V) variables {f} {μ : K} theorem has_eigenvalue_of_is_root (h : (minpoly K f).is_root μ) : f.has_eigenvalue μ := begin cases dvd_iff_is_root.2 h with p hp, rw [has_eigenvalue, eigenspace], intro con, cases (linear_map.is_unit_iff _).2 con with u hu, have p_ne_0 : p ≠ 0, { intro con, apply minpoly.ne_zero f.is_integral, rw [hp, con, mul_zero] }, have h_deg := minpoly.degree_le_of_ne_zero K f p_ne_0 _, { rw [hp, degree_mul, degree_X_sub_C, polynomial.degree_eq_nat_degree p_ne_0] at h_deg, norm_cast at h_deg, linarith, }, { have h_aeval := minpoly.aeval K f, revert h_aeval, simp [hp, ← hu] }, end theorem has_eigenvalue_iff_is_root : f.has_eigenvalue μ ↔ (minpoly K f).is_root μ := ⟨is_root_of_has_eigenvalue, has_eigenvalue_of_is_root⟩ end minpoly /-- Every linear operator on a vector space over an algebraically closed field has an eigenvalue. -/ -- This is Lemma 5.21 of [axler2015], although we are no longer following that proof. lemma exists_eigenvalue [is_alg_closed K] [finite_dimensional K V] [nontrivial V] (f : End K V) : ∃ (c : K), f.has_eigenvalue c := begin obtain ⟨c, nu⟩ := exists_spectrum_of_is_alg_closed_of_finite_dimensional K f, use c, rw linear_map.is_unit_iff at nu, exact has_eigenvalue_of_has_eigenvector (exists_mem_ne_zero_of_ne_bot nu).some_spec, end /-- Eigenvectors corresponding to distinct eigenvalues of a linear operator are linearly independent. (Lemma 5.10 of [axler2015]) We use the eigenvalues as indexing set to ensure that there is only one eigenvector for each eigenvalue in the image of `xs`. -/ lemma eigenvectors_linear_independent (f : End K V) (μs : set K) (xs : μs → V) (h_eigenvec : ∀ μ : μs, f.has_eigenvector μ (xs μ)) : linear_independent K xs := begin classical, -- We need to show that if a linear combination `l` of the eigenvectors `xs` is `0`, then all -- its coefficients are zero. suffices : ∀ l, finsupp.total μs V K xs l = 0 → l = 0, { rw linear_independent_iff, apply this }, intros l hl, -- We apply induction on the finite set of eigenvalues whose eigenvectors have nonzero -- coefficients, i.e. on the support of `l`. induction h_l_support : l.support using finset.induction with μ₀ l_support' hμ₀ ih generalizing l, -- If the support is empty, all coefficients are zero and we are done. { exact finsupp.support_eq_empty.1 h_l_support }, -- Now assume that the support of `l` contains at least one eigenvalue `μ₀`. We define a new -- linear combination `l'` to apply the induction hypothesis on later. The linear combination `l'` -- is derived from `l` by multiplying the coefficient of the eigenvector with eigenvalue `μ` -- by `μ - μ₀`. -- To get started, we define `l'` as a function `l'_f : μs → K` with potentially infinite support. { let l'_f : μs → K := (λ μ : μs, (↑μ - ↑μ₀) * l μ), -- The support of `l'_f` is the support of `l` without `μ₀`. have h_l_support' : ∀ (μ : μs), μ ∈ l_support' ↔ l'_f μ ≠ 0 , { intro μ, suffices : μ ∈ l_support' → μ ≠ μ₀, { simp [l'_f, ← finsupp.not_mem_support_iff, h_l_support, sub_eq_zero, ←subtype.ext_iff], tauto }, rintro hμ rfl, contradiction }, -- Now we can define `l'_f` as an actual linear combination `l'` because we know that the -- support is finite. let l' : μs →₀ K := { to_fun := l'_f, support := l_support', mem_support_to_fun := h_l_support' }, -- The linear combination `l'` over `xs` adds up to `0`. have total_l' : finsupp.total μs V K xs l' = 0, { let g := f - algebra_map K (End K V) μ₀, have h_gμ₀: g (l μ₀ • xs μ₀) = 0, by rw [linear_map.map_smul, linear_map.sub_apply, mem_eigenspace_iff.1 (h_eigenvec _).1, algebra_map_End_apply, sub_self, smul_zero], have h_useless_filter : finset.filter (λ (a : μs), l'_f a ≠ 0) l_support' = l_support', { rw finset.filter_congr _, { apply finset.filter_true }, { apply_instance }, exact λ μ hμ, (iff_true _).mpr ((h_l_support' μ).1 hμ) }, have bodies_eq : ∀ (μ : μs), l'_f μ • xs μ = g (l μ • xs μ), { intro μ, dsimp only [g, l'_f], rw [linear_map.map_smul, linear_map.sub_apply, mem_eigenspace_iff.1 (h_eigenvec _).1, algebra_map_End_apply, ←sub_smul, smul_smul, mul_comm] }, rw [←linear_map.map_zero g, ←hl, finsupp.total_apply, finsupp.total_apply, finsupp.sum, finsupp.sum, linear_map.map_sum, h_l_support, finset.sum_insert hμ₀, h_gμ₀, zero_add], refine finset.sum_congr rfl (λ μ _, _), apply bodies_eq }, -- Therefore, by the induction hypothesis, all coefficients in `l'` are zero. have l'_eq_0 : l' = 0 := ih l' total_l' rfl, -- By the defintion of `l'`, this means that `(μ - μ₀) * l μ = 0` for all `μ`. have h_mul_eq_0 : ∀ μ : μs, (↑μ - ↑μ₀) * l μ = 0, { intro μ, calc (↑μ - ↑μ₀) * l μ = l' μ : rfl ... = 0 : by { rw [l'_eq_0], refl } }, -- Thus, the coefficients in `l` for all `μ ≠ μ₀` are `0`. have h_lμ_eq_0 : ∀ μ : μs, μ ≠ μ₀ → l μ = 0, { intros μ hμ, apply or_iff_not_imp_left.1 (mul_eq_zero.1 (h_mul_eq_0 μ)), rwa [sub_eq_zero, ←subtype.ext_iff] }, -- So if we sum over all these coefficients, we obtain `0`. have h_sum_l_support'_eq_0 : finset.sum l_support' (λ (μ : ↥μs), l μ • xs μ) = 0, { rw ←finset.sum_const_zero, apply finset.sum_congr rfl, intros μ hμ, rw h_lμ_eq_0, apply zero_smul, intro h, rw h at hμ, contradiction }, -- The only potentially nonzero coefficient in `l` is the one corresponding to `μ₀`. But since -- the overall sum is `0` by assumption, this coefficient must also be `0`. have : l μ₀ = 0, { rw [finsupp.total_apply, finsupp.sum, h_l_support, finset.sum_insert hμ₀, h_sum_l_support'_eq_0, add_zero] at hl, by_contra h, exact (h_eigenvec μ₀).2 ((smul_eq_zero.1 hl).resolve_left h) }, -- Thus, all coefficients in `l` are `0`. show l = 0, { ext μ, by_cases h_cases : μ = μ₀, { rw h_cases, assumption }, exact h_lμ_eq_0 μ h_cases } } end /-- The generalized eigenspace for a linear map `f`, a scalar `μ`, and an exponent `k ∈ ℕ` is the kernel of `(f - μ • id) ^ k`. (Def 8.10 of [axler2015]). Furthermore, a generalized eigenspace for some exponent `k` is contained in the generalized eigenspace for exponents larger than `k`. -/ def generalized_eigenspace (f : End R M) (μ : R) : ℕ →ₘ submodule R M := { to_fun := λ k, ((f - algebra_map R (End R M) μ) ^ k).ker, monotone' := λ k m hm, begin simp only [← pow_sub_mul_pow _ hm], exact linear_map.ker_le_ker_comp ((f - algebra_map R (End R M) μ) ^ k) ((f - algebra_map R (End R M) μ) ^ (m - k)), end } @[simp] lemma mem_generalized_eigenspace (f : End R M) (μ : R) (k : ℕ) (m : M) : m ∈ f.generalized_eigenspace μ k ↔ ((f - μ • 1)^k) m = 0 := iff.rfl /-- A nonzero element of a generalized eigenspace is a generalized eigenvector. (Def 8.9 of [axler2015])-/ def has_generalized_eigenvector (f : End R M) (μ : R) (k : ℕ) (x : M) : Prop := x ≠ 0 ∧ x ∈ generalized_eigenspace f μ k /-- A scalar `μ` is a generalized eigenvalue for a linear map `f` and an exponent `k ∈ ℕ` if there are generalized eigenvectors for `f`, `k`, and `μ`. -/ def has_generalized_eigenvalue (f : End R M) (μ : R) (k : ℕ) : Prop := generalized_eigenspace f μ k ≠ ⊥ /-- The generalized eigenrange for a linear map `f`, a scalar `μ`, and an exponent `k ∈ ℕ` is the range of `(f - μ • id) ^ k`. -/ def generalized_eigenrange (f : End R M) (μ : R) (k : ℕ) : submodule R M := ((f - algebra_map R (End R M) μ) ^ k).range /-- The exponent of a generalized eigenvalue is never 0. -/ lemma exp_ne_zero_of_has_generalized_eigenvalue {f : End R M} {μ : R} {k : ℕ} (h : f.has_generalized_eigenvalue μ k) : k ≠ 0 := begin rintro rfl, exact h linear_map.ker_id end /-- The union of the kernels of `(f - μ • id) ^ k` over all `k`. -/ def maximal_generalized_eigenspace (f : End R M) (μ : R) : submodule R M := ⨆ k, f.generalized_eigenspace μ k lemma generalized_eigenspace_le_maximal (f : End R M) (μ : R) (k : ℕ) : f.generalized_eigenspace μ k ≤ f.maximal_generalized_eigenspace μ := le_supr _ _ @[simp] lemma mem_maximal_generalized_eigenspace (f : End R M) (μ : R) (m : M) : m ∈ f.maximal_generalized_eigenspace μ ↔ ∃ (k : ℕ), ((f - μ • 1)^k) m = 0 := by simp only [maximal_generalized_eigenspace, ← mem_generalized_eigenspace, submodule.mem_supr_of_chain] /-- If there exists a natural number `k` such that the kernel of `(f - μ • id) ^ k` is the maximal generalized eigenspace, then this value is the least such `k`. If not, this value is not meaningful. -/ noncomputable def maximal_generalized_eigenspace_index (f : End R M) (μ : R) := monotonic_sequence_limit_index (f.generalized_eigenspace μ) /-- For an endomorphism of a Noetherian module, the maximal eigenspace is always of the form kernel `(f - μ • id) ^ k` for some `k`. -/ lemma maximal_generalized_eigenspace_eq [h : is_noetherian R M] (f : End R M) (μ : R) : maximal_generalized_eigenspace f μ = f.generalized_eigenspace μ (maximal_generalized_eigenspace_index f μ) := begin rw is_noetherian_iff_well_founded at h, exact (well_founded.supr_eq_monotonic_sequence_limit h (f.generalized_eigenspace μ) : _), end /-- A generalized eigenvalue for some exponent `k` is also a generalized eigenvalue for exponents larger than `k`. -/ lemma has_generalized_eigenvalue_of_has_generalized_eigenvalue_of_le {f : End R M} {μ : R} {k : ℕ} {m : ℕ} (hm : k ≤ m) (hk : f.has_generalized_eigenvalue μ k) : f.has_generalized_eigenvalue μ m := begin unfold has_generalized_eigenvalue at *, contrapose! hk, rw [←le_bot_iff, ←hk], exact (f.generalized_eigenspace μ).monotone hm, end /-- The eigenspace is a subspace of the generalized eigenspace. -/ lemma eigenspace_le_generalized_eigenspace {f : End R M} {μ : R} {k : ℕ} (hk : 0 < k) : f.eigenspace μ ≤ f.generalized_eigenspace μ k := (f.generalized_eigenspace μ).monotone (nat.succ_le_of_lt hk) /-- All eigenvalues are generalized eigenvalues. -/ lemma has_generalized_eigenvalue_of_has_eigenvalue {f : End R M} {μ : R} {k : ℕ} (hk : 0 < k) (hμ : f.has_eigenvalue μ) : f.has_generalized_eigenvalue μ k := begin apply has_generalized_eigenvalue_of_has_generalized_eigenvalue_of_le hk, rw [has_generalized_eigenvalue, generalized_eigenspace, preorder_hom.coe_fun_mk, pow_one], exact hμ, end /-- All generalized eigenvalues are eigenvalues. -/ lemma has_eigenvalue_of_has_generalized_eigenvalue {f : End R M} {μ : R} {k : ℕ} (hμ : f.has_generalized_eigenvalue μ k) : f.has_eigenvalue μ := begin intros contra, apply hμ, erw linear_map.ker_eq_bot at ⊢ contra, rw linear_map.coe_pow, exact function.injective.iterate contra k, end /-- Generalized eigenvalues are actually just eigenvalues. -/ @[simp] lemma has_generalized_eigenvalue_iff_has_eigenvalue {f : End R M} {μ : R} {k : ℕ} (hk : 0 < k) : f.has_generalized_eigenvalue μ k ↔ f.has_eigenvalue μ := ⟨has_eigenvalue_of_has_generalized_eigenvalue, has_generalized_eigenvalue_of_has_eigenvalue hk⟩ /-- Every generalized eigenvector is a generalized eigenvector for exponent `finrank K V`. (Lemma 8.11 of [axler2015]) -/ lemma generalized_eigenspace_le_generalized_eigenspace_finrank [finite_dimensional K V] (f : End K V) (μ : K) (k : ℕ) : f.generalized_eigenspace μ k ≤ f.generalized_eigenspace μ (finrank K V) := ker_pow_le_ker_pow_finrank _ _ /-- Generalized eigenspaces for exponents at least `finrank K V` are equal to each other. -/ lemma generalized_eigenspace_eq_generalized_eigenspace_finrank_of_le [finite_dimensional K V] (f : End K V) (μ : K) {k : ℕ} (hk : finrank K V ≤ k) : f.generalized_eigenspace μ k = f.generalized_eigenspace μ (finrank K V) := ker_pow_eq_ker_pow_finrank_of_le hk /-- If `f` maps a subspace `p` into itself, then the generalized eigenspace of the restriction of `f` to `p` is the part of the generalized eigenspace of `f` that lies in `p`. -/ lemma generalized_eigenspace_restrict (f : End R M) (p : submodule R M) (k : ℕ) (μ : R) (hfp : ∀ (x : M), x ∈ p → f x ∈ p) : generalized_eigenspace (linear_map.restrict f hfp) μ k = submodule.comap p.subtype (f.generalized_eigenspace μ k) := begin simp only [generalized_eigenspace, preorder_hom.coe_fun_mk, ← linear_map.ker_comp], induction k with k ih, { rw [pow_zero, pow_zero, linear_map.one_eq_id], apply (submodule.ker_subtype _).symm }, { erw [pow_succ', pow_succ', linear_map.ker_comp, linear_map.ker_comp, ih, ← linear_map.ker_comp, ← linear_map.ker_comp, linear_map.comp_assoc] }, end /-- Generalized eigenrange and generalized eigenspace for exponent `finrank K V` are disjoint. -/ lemma generalized_eigenvec_disjoint_range_ker [finite_dimensional K V] (f : End K V) (μ : K) : disjoint (f.generalized_eigenrange μ (finrank K V)) (f.generalized_eigenspace μ (finrank K V)) := begin have h := calc submodule.comap ((f - algebra_map _ _ μ) ^ finrank K V) (f.generalized_eigenspace μ (finrank K V)) = ((f - algebra_map _ _ μ) ^ finrank K V * (f - algebra_map K (End K V) μ) ^ finrank K V).ker : by { simpa only [generalized_eigenspace, preorder_hom.coe_fun_mk, ← linear_map.ker_comp] } ... = f.generalized_eigenspace μ (finrank K V + finrank K V) : by { rw ←pow_add, refl } ... = f.generalized_eigenspace μ (finrank K V) : by { rw generalized_eigenspace_eq_generalized_eigenspace_finrank_of_le, linarith }, rw [disjoint, generalized_eigenrange, linear_map.range_eq_map, submodule.map_inf_eq_map_inf_comap, top_inf_eq, h], apply submodule.map_comap_le end /-- The generalized eigenspace of an eigenvalue has positive dimension for positive exponents. -/ lemma pos_finrank_generalized_eigenspace_of_has_eigenvalue [finite_dimensional K V] {f : End K V} {k : ℕ} {μ : K} (hx : f.has_eigenvalue μ) (hk : 0 < k): 0 < finrank K (f.generalized_eigenspace μ k) := calc 0 = finrank K (⊥ : submodule K V) : by rw finrank_bot ... < finrank K (f.eigenspace μ) : submodule.finrank_lt_finrank_of_lt (bot_lt_iff_ne_bot.2 hx) ... ≤ finrank K (f.generalized_eigenspace μ k) : submodule.finrank_mono ((f.generalized_eigenspace μ).monotone (nat.succ_le_of_lt hk)) /-- A linear map maps a generalized eigenrange into itself. -/ lemma map_generalized_eigenrange_le {f : End K V} {μ : K} {n : ℕ} : submodule.map f (f.generalized_eigenrange μ n) ≤ f.generalized_eigenrange μ n := calc submodule.map f (f.generalized_eigenrange μ n) = (f * ((f - algebra_map _ _ μ) ^ n)).range : (linear_map.range_comp _ _).symm ... = (((f - algebra_map _ _ μ) ^ n) * f).range : by rw algebra.mul_sub_algebra_map_pow_commutes ... = submodule.map ((f - algebra_map _ _ μ) ^ n) f.range : linear_map.range_comp _ _ ... ≤ f.generalized_eigenrange μ n : linear_map.map_le_range /-- The generalized eigenvectors span the entire vector space (Lemma 8.21 of [axler2015]). -/ lemma supr_generalized_eigenspace_eq_top [is_alg_closed K] [finite_dimensional K V] (f : End K V) : (⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k) = ⊤ := begin tactic.unfreeze_local_instances, -- We prove the claim by strong induction on the dimension of the vector space. induction h_dim : finrank K V using nat.strong_induction_on with n ih generalizing V, cases n, -- If the vector space is 0-dimensional, the result is trivial. { rw ←top_le_iff, simp only [finrank_eq_zero.1 (eq.trans finrank_top h_dim), bot_le] }, -- Otherwise the vector space is nontrivial. { haveI : nontrivial V := finrank_pos_iff.1 (by { rw h_dim, apply nat.zero_lt_succ }), -- Hence, `f` has an eigenvalue `μ₀`. obtain ⟨μ₀, hμ₀⟩ : ∃ μ₀, f.has_eigenvalue μ₀ := exists_eigenvalue f, -- We define `ES` to be the generalized eigenspace let ES := f.generalized_eigenspace μ₀ (finrank K V), -- and `ER` to be the generalized eigenrange. let ER := f.generalized_eigenrange μ₀ (finrank K V), -- `f` maps `ER` into itself. have h_f_ER : ∀ (x : V), x ∈ ER → f x ∈ ER, from λ x hx, map_generalized_eigenrange_le (submodule.mem_map_of_mem hx), -- Therefore, we can define the restriction `f'` of `f` to `ER`. let f' : End K ER := f.restrict h_f_ER, -- The dimension of `ES` is positive have h_dim_ES_pos : 0 < finrank K ES, { dsimp only [ES], rw h_dim, apply pos_finrank_generalized_eigenspace_of_has_eigenvalue hμ₀ (nat.zero_lt_succ n) }, -- and the dimensions of `ES` and `ER` add up to `finrank K V`. have h_dim_add : finrank K ER + finrank K ES = finrank K V, { apply linear_map.finrank_range_add_finrank_ker }, -- Therefore the dimension `ER` mus be smaller than `finrank K V`. have h_dim_ER : finrank K ER < n.succ, by linarith, -- This allows us to apply the induction hypothesis on `ER`: have ih_ER : (⨆ (μ : K) (k : ℕ), f'.generalized_eigenspace μ k) = ⊤, from ih (finrank K ER) h_dim_ER f' rfl, -- The induction hypothesis gives us a statement about subspaces of `ER`. We can transfer this -- to a statement about subspaces of `V` via `submodule.subtype`: have ih_ER' : (⨆ (μ : K) (k : ℕ), (f'.generalized_eigenspace μ k).map ER.subtype) = ER, by simp only [(submodule.map_supr _ _).symm, ih_ER, submodule.map_subtype_top ER], -- Moreover, every generalized eigenspace of `f'` is contained in the corresponding generalized -- eigenspace of `f`. have hff' : ∀ μ k, (f'.generalized_eigenspace μ k).map ER.subtype ≤ f.generalized_eigenspace μ k, { intros, rw generalized_eigenspace_restrict, apply submodule.map_comap_le }, -- It follows that `ER` is contained in the span of all generalized eigenvectors. have hER : ER ≤ ⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k, { rw ← ih_ER', apply supr_le_supr _, exact λ μ, supr_le_supr (λ k, hff' μ k), }, -- `ES` is contained in this span by definition. have hES : ES ≤ ⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k, from le_trans (le_supr (λ k, f.generalized_eigenspace μ₀ k) (finrank K V)) (le_supr (λ (μ : K), ⨆ (k : ℕ), f.generalized_eigenspace μ k) μ₀), -- Moreover, we know that `ER` and `ES` are disjoint. have h_disjoint : disjoint ER ES, from generalized_eigenvec_disjoint_range_ker f μ₀, -- Since the dimensions of `ER` and `ES` add up to the dimension of `V`, it follows that the -- span of all generalized eigenvectors is all of `V`. show (⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k) = ⊤, { rw [←top_le_iff, ←submodule.eq_top_of_disjoint ER ES h_dim_add h_disjoint], apply sup_le hER hES } } end end End end module
bf653f73976a09488d5db9692ec6a225155a3db2
d29d82a0af640c937e499f6be79fc552eae0aa13
/src/ring_theory/noetherian.lean
0f460381273c9eaf762b353286402c2725727d11
[ "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
34,789
lean
/- Copyright (c) 2018 Mario Carneiro, Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import algebraic_geometry.prime_spectrum import data.multiset.finset_ops import linear_algebra.linear_independent import order.order_iso_nat import order.compactly_generated import ring_theory.ideal.operations import group_theory.finiteness /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodules M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. (Note that we do not assume yet that our rings are commutative, so perhaps this should be called "left Noetherian". To avoid cumbersome names once we specialize to the commutative case, we don't make this explicit in the declaration names.) ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] * [samuel] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set open_locale big_operators namespace submodule variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [module R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, finite S ∧ span R S = N := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ lemma fg_iff_add_submonoid_fg (P : submodule ℕ M) : P.fg ↔ P.to_add_submonoid.fg := ⟨λ ⟨S, hS⟩, ⟨S, by simpa [← span_nat_eq_add_submonoid_closure] using hS⟩, λ ⟨S, hS⟩, ⟨S, by simpa [← span_nat_eq_add_submonoid_closure] using hS⟩⟩ lemma fg_iff_add_subgroup_fg {G : Type*} [add_comm_group G] (P : submodule ℤ G) : P.fg ↔ P.to_add_subgroup.fg := ⟨λ ⟨S, hS⟩, ⟨S, by simpa [← span_int_eq_add_subgroup_closure] using hS⟩, λ ⟨S, hS⟩, ⟨S, by simpa [← span_int_eq_add_subgroup_closure] using hS⟩⟩ lemma fg_iff_exists_fin_generating_family {N : submodule R M} : N.fg ↔ ∃ (n : ℕ) (s : fin n → M), span R (range s) = N := begin rw fg_def, split, { rintros ⟨S, Sfin, hS⟩, obtain ⟨n, f, rfl⟩ := Sfin.fin_embedding, exact ⟨n, f, hS⟩, }, { rintros ⟨n, s, hs⟩, refine ⟨range s, finite_range s, hs⟩ }, end /-- **Nakayama's Lemma**. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, [Stacks 00DV](https://stacks.math.columbia.edu/tag/00VL) -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ring_hom.map_one] at hr1 hc1 ⊢, rw [ring_hom.map_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_span {s : set M} (hs : finite s) : fg (span R s) := ⟨hs.to_finset, by rw [hs.coe_to_finset]⟩ theorem fg_span_singleton (x : M) : fg (R ∙ x) := fg_span (finite_singleton x) theorem fg_sup {N₁ N₂ : submodule R M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {P : Type*} [add_comm_monoid P] [module R P] variables {f : M →ₗ[R] P} theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩ lemma fg_of_fg_map {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) {N : submodule R M} (hfn : (N.map f).fg) : N.fg := let ⟨t, ht⟩ := hfn in ⟨t.preimage f $ λ x _ y _ h, linear_map.ker_eq_bot.1 hf h, linear_map.map_injective hf $ by { rw [f.map_span, finset.coe_preimage, set.image_preimage_eq_inter_range, set.inter_eq_self_of_subset_left, ht], rw [← linear_map.range_coe, ← span_le, ht, ← map_top], exact map_mono le_top }⟩ lemma fg_top {R M : Type*} [ring R] [add_comm_group M] [module R M] (N : submodule R M) : (⊤ : submodule R N).fg ↔ N.fg := ⟨λ h, N.range_subtype ▸ map_top N.subtype ▸ fg_map h, λ h, fg_of_fg_map N.subtype N.ker_subtype $ by rwa [map_top, range_subtype]⟩ lemma fg_of_linear_equiv (e : M ≃ₗ[R] P) (h : (⊤ : submodule R P).fg) : (⊤ : submodule R M).fg := e.symm.range ▸ map_top (e.symm : P →ₗ[R] M) ▸ fg_map h theorem fg_prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨linear_map.inl R M P '' tb ∪ linear_map.inr R M P '' tc, (htb.1.image _).union (htc.1.image _), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_image_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_image_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end /-- The image of a finitely generated ideal is finitely generated. -/ lemma map_fg_of_fg {R S : Type*} [comm_ring R] [comm_ring S] (I : ideal R) (h : I.fg) (f : R →+* S) : (I.map f).fg := begin obtain ⟨X, hXfin, hXgen⟩ := fg_def.1 h, apply fg_def.2, refine ⟨set.image f X, finite.image ⇑f hXfin, _⟩, rw [ideal.map, ideal.span, ← hXgen], refine le_antisymm (submodule.span_mono (image_subset _ ideal.subset_span)) _, rw [submodule.span_le, image_subset_iff], intros i hi, refine submodule.span_induction hi (λ x hx, _) _ (λ x y hx hy, _) (λ r x hx, _), { simp only [set_like.mem_coe, mem_preimage], suffices : f x ∈ f '' X, { exact ideal.subset_span this }, exact mem_image_of_mem ⇑f hx }, { simp only [set_like.mem_coe, ring_hom.map_zero, mem_preimage, zero_mem] }, { simp only [set_like.mem_coe, mem_preimage] at hx hy, simp only [ring_hom.map_add, set_like.mem_coe, mem_preimage], exact submodule.add_mem _ hx hy }, { simp only [set_like.mem_coe, mem_preimage] at hx, simp only [algebra.id.smul_eq_mul, set_like.mem_coe, mem_preimage, ring_hom.map_mul], exact submodule.smul_mem _ _ hx } end /-- The kernel of the composition of two linear maps is finitely generated if both kernels are and the first morphism is surjective. -/ lemma fg_ker_comp {R M N P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] [add_comm_group P] [module R P] (f : M →ₗ[R] N) (g : N →ₗ[R] P) (hf1 : f.ker.fg) (hf2 : g.ker.fg) (hsur : function.surjective f) : (g.comp f).ker.fg := begin rw linear_map.ker_comp, apply fg_of_fg_map_of_fg_inf_ker f, { rwa [linear_map.map_comap_eq, linear_map.range_eq_top.2 hsur, top_inf_eq] }, { rwa [inf_of_le_right (show f.ker ≤ (comap f g.ker), from comap_mono (@bot_le _ _ g.ker))] } end lemma fg_restrict_scalars {R S M : Type*} [comm_ring R] [comm_ring S] [algebra R S] [add_comm_group M] [module S M] [module R M] [is_scalar_tower R S M] (N : submodule S M) (hfin : N.fg) (h : function.surjective (algebra_map R S)) : (submodule.restrict_scalars R N).fg := begin obtain ⟨X, rfl⟩ := hfin, use X, exact submodule.span_eq_restrict_scalars R S M X h end lemma fg_ker_ring_hom_comp {R S A : Type*} [comm_ring R] [comm_ring S] [comm_ring A] (f : R →+* S) (g : S →+* A) (hf : f.ker.fg) (hg : g.ker.fg) (hsur : function.surjective f) : (g.comp f).ker.fg := begin letI : algebra R S := ring_hom.to_algebra f, letI : algebra R A := ring_hom.to_algebra (g.comp f), letI : algebra S A := ring_hom.to_algebra g, letI : is_scalar_tower R S A := restrict_scalars.is_scalar_tower R S A, let f₁ := algebra.linear_map R S, let g₁ := (is_scalar_tower.to_alg_hom R S A).to_linear_map, exact fg_ker_comp f₁ g₁ hf (fg_restrict_scalars g.ker hg hsur) hsur end /-- Finitely generated submodules are precisely compact elements in the submodule lattice. -/ theorem fg_iff_compact (s : submodule R M) : s.fg ↔ complete_lattice.is_compact_element s := begin classical, -- Introduce shorthand for span of an element let sp : M → submodule R M := λ a, span R {a}, -- Trivial rewrite lemma; a small hack since simp (only) & rw can't accomplish this smoothly. have supr_rw : ∀ t : finset M, (⨆ x ∈ t, sp x) = (⨆ x ∈ (↑t : set M), sp x), from λ t, by refl, split, { rintro ⟨t, rfl⟩, rw [span_eq_supr_of_singleton_spans, ←supr_rw, ←(finset.sup_eq_supr t sp)], apply complete_lattice.finset_sup_compact_of_compact, exact λ n _, singleton_span_is_compact_element n, }, { intro h, -- s is the Sup of the spans of its elements. have sSup : s = Sup (sp '' ↑s), by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, eq_comm, span_eq], -- by h, s is then below (and equal to) the sup of the spans of finitely many elements. obtain ⟨u, ⟨huspan, husup⟩⟩ := h (sp '' ↑s) (le_of_eq sSup), have ssup : s = u.sup id, { suffices : u.sup id ≤ s, from le_antisymm husup this, rw [sSup, finset.sup_id_eq_Sup], exact Sup_le_Sup huspan, }, obtain ⟨t, ⟨hts, rfl⟩⟩ := finset.subset_image_iff.mp huspan, rw [finset.sup_finset_image, function.comp.left_id, finset.sup_eq_supr, supr_rw, ←span_eq_supr_of_singleton_spans, eq_comm] at ssup, exact ⟨t, ssup⟩, }, end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [semiring R] [add_comm_monoid M] [module R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ instance is_noetherian_submodule' [is_noetherian R M] (N : submodule R M) : is_noetherian R N := is_noetherian_submodule.2 $ λ _ _, is_noetherian.noetherian _ variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range lemma is_noetherian_of_injective [is_noetherian R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) : is_noetherian R M := is_noetherian_of_linear_equiv (linear_equiv.of_injective f hf).symm lemma fg_of_injective [is_noetherian R P] {N : submodule R M} (f : M →ₗ[R] P) (hf : f.ker = ⊥) : N.fg := @@is_noetherian.noetherian _ _ _ (is_noetherian_of_injective f hf) N instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, linear_map.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices on_finset : ∀ s : finset ι, is_noetherian R (Π i : s, M i), { let coe_e := equiv.subtype_univ_equiv finset.mem_univ, letI : is_noetherian R (Π i : finset.univ, M (coe_e i)) := on_finset finset.univ, exact is_noetherian_of_linear_equiv (linear_equiv.Pi_congr_left R M coe_e), }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ _ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), fconstructor, { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext ⟨i, his⟩, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext ⟨i, hi⟩, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], } } end end open is_noetherian submodule function section variables {R M : Type*} [ring R] [add_comm_group M] [module R M] theorem is_noetherian_iff_well_founded : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := begin rw (complete_lattice.well_founded_characterisations $ submodule R M).out 0 3, exact ⟨λ ⟨h⟩, λ k, (fg_iff_compact k).mp (h k), λ h, ⟨λ k, (fg_iff_compact k).mpr (h k)⟩⟩, end variables (R M) lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp variables {R M} lemma finite_of_linear_independent [nontrivial R] [is_noetherian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, rel_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M) ⟨_⟩), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff hs (this a) (this b), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- A module is Noetherian iff every nonempty set of submodules has a maximal submodule among them. -/ theorem set_has_maximal_iff_noetherian : (∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, M' ≤ I → I = M') ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.well_founded_iff_has_max'] /-- A module is Noetherian iff every increasing chain of submodules stabilizes. -/ theorem monotone_stabilizes_iff_noetherian : (∀ (f : ℕ →ₘ submodule R M), ∃ n, ∀ m, n ≤ m → f n = f m) ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.monotone_chain_condition] /-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/ lemma is_noetherian.induction [is_noetherian R M] {P : submodule R M → Prop} (hgt : ∀ I, (∀ J > I, P J) → P I) (I : submodule R M) : P I := well_founded.recursion (well_founded_submodule_gt R M) I hgt /-- For any endomorphism of a Noetherian module, there is some nontrivial iterate with disjoint kernel and range. -/ theorem is_noetherian.exists_endomorphism_iterate_ker_inf_range_eq_bot [I : is_noetherian R M] (f : M →ₗ[R] M) : ∃ n : ℕ, n ≠ 0 ∧ (f ^ n).ker ⊓ (f ^ n).range = ⊥ := begin obtain ⟨n, w⟩ := monotone_stabilizes_iff_noetherian.mpr I (f.iterate_ker.comp ⟨λ n, n+1, λ n m w, by linarith⟩), specialize w (2 * n + 1) (by linarith), dsimp at w, refine ⟨n+1, nat.succ_ne_zero _, _⟩, rw eq_bot_iff, rintros - ⟨h, ⟨y, rfl⟩⟩, rw [mem_bot, ←linear_map.mem_ker, w], erw linear_map.mem_ker at h ⊢, change ((f ^ (n + 1)) * (f ^ (n + 1))) y = 0 at h, rw ←pow_add at h, convert h using 3, linarith, end /-- Any surjective endomorphism of a Noetherian module is injective. -/ theorem is_noetherian.injective_of_surjective_endomorphism [is_noetherian R M] (f : M →ₗ[R] M) (s : surjective f) : injective f := begin obtain ⟨n, ne, w⟩ := is_noetherian.exists_endomorphism_iterate_ker_inf_range_eq_bot f, rw [linear_map.range_eq_top.mpr (linear_map.iterate_surjective s n), inf_top_eq, linear_map.ker_eq_bot] at w, exact linear_map.injective_of_iterate_injective ne w, end /-- Any surjective endomorphism of a Noetherian module is bijective. -/ theorem is_noetherian.bijective_of_surjective_endomorphism [is_noetherian R M] (f : M →ₗ[R] M) (s : surjective f) : bijective f := ⟨is_noetherian.injective_of_surjective_endomorphism f s, s⟩ /-- A sequence `f` of submodules of a noetherian module, with `f (n+1)` disjoint from the supremum of `f 0`, ..., `f n`, is eventually zero. -/ lemma is_noetherian.disjoint_partial_sups_eventually_bot [I : is_noetherian R M] (f : ℕ → submodule R M) (h : ∀ n, disjoint (partial_sups f n) (f (n+1))) : ∃ n : ℕ, ∀ m, n ≤ m → f m = ⊥ := begin -- A little off-by-one cleanup first: suffices t : ∃ n : ℕ, ∀ m, n ≤ m → f (m+1) = ⊥, { obtain ⟨n, w⟩ := t, use n+1, rintros (_|m) p, { cases p, }, { apply w, exact nat.succ_le_succ_iff.mp p }, }, obtain ⟨n, w⟩ := monotone_stabilizes_iff_noetherian.mpr I (partial_sups f), exact ⟨n, (λ m p, eq_bot_of_disjoint_absorbs (h m) ((eq.symm (w (m + 1) (le_add_right p))).trans (w m p)))⟩ end universe w variables {N : Type w} [add_comm_group N] [module R N] /-- If `M ⊕ N` embeds into `M`, for `M` noetherian over `R`, then `N` is trivial. -/ noncomputable def is_noetherian.equiv_punit_of_prod_injective [is_noetherian R M] (f : M × N →ₗ[R] M) (i : injective f) : N ≃ₗ[R] punit.{w+1} := begin apply nonempty.some, obtain ⟨n, w⟩ := is_noetherian.disjoint_partial_sups_eventually_bot (f.tailing i) (f.tailings_disjoint_tailing i), specialize w n (le_refl n), apply nonempty.intro, refine (f.tailing_linear_equiv i n).symm.trans _, rw w, exact submodule.bot_equiv_punit, end end /-- A ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ class is_noetherian_ring (R) [ring R] extends is_noetherian R R : Prop theorem is_noetherian_ring_iff {R} [ring R] : is_noetherian_ring R ↔ is_noetherian R R := ⟨λ h, h.1, @is_noetherian_ring.mk _ _⟩ @[priority 80] -- see Note [lower instance priority] instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one h01; haveI := fintype.of_subsingleton (0:R); exact is_noetherian_ring_iff.2 (ring.is_noetherian_of_fintype R R) theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.map_subtype.order_embedding N).dual h, end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.comap_mkq.order_embedding N).dual h, end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.module _ _ _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_image_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x, subtype.ext _⟩, change ∑ i in s.attach, l i • (i : M) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end lemma is_noetherian_of_fg_of_noetherian' {R M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] (h : (⊤ : submodule R M).fg) : is_noetherian R M := have is_noetherian R (⊤ : submodule R M), from is_noetherian_of_fg_of_noetherian _ h, by exactI is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin rw [is_noetherian_ring_iff, is_noetherian_iff_well_founded] at H ⊢, exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf).dual H, end section local attribute [instance] subset.comm_ring instance is_noetherian_ring_set_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring (set.range f) := is_noetherian_ring_of_surjective R (set.range f) (f.cod_restrict (set.range f) set.mem_range_self) set.surjective_onto_range end instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring f.range := is_noetherian_ring_of_surjective R f.range f.range_restrict f.range_restrict_surjective theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, hfm.mul hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule section primes variables {R : Type*} [comm_ring R] [is_noetherian_ring R] /--In a noetherian ring, every ideal contains a product of prime ideals ([samuel, § 3.3, Lemma 3])-/ lemma exists_prime_spectrum_prod_le (I : ideal R) : ∃ (Z : multiset (prime_spectrum R)), multiset.prod (Z.map (coe : subtype _ → ideal R)) ≤ I := begin refine is_noetherian.induction (λ (M : ideal R) hgt, _) I, by_cases h_prM : M.is_prime, { use {⟨M, h_prM⟩}, rw [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk], exact le_rfl }, by_cases htop : M = ⊤, { rw htop, exact ⟨0, le_top⟩ }, have lt_add : ∀ z ∉ M, M < M + span R {z}, { intros z hz, refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _), rw m_eq, exact mem_sup_right (mem_span_singleton_self z) }, obtain ⟨x, hx, y, hy, hxy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left htop, obtain ⟨Wx, h_Wx⟩ := hgt (M + span R {x}) (lt_add _ hx), obtain ⟨Wy, h_Wy⟩ := hgt (M + span R {y}) (lt_add _ hy), use Wx + Wy, rw [multiset.map_add, multiset.prod_add], apply le_trans (submodule.mul_le_mul h_Wx h_Wy), rw add_mul, apply sup_le (show M * (M + span R {y}) ≤ M, from ideal.mul_le_right), rw mul_add, apply sup_le (show span R {x} * M ≤ M, from ideal.mul_le_left), rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem], end variables {A : Type*} [integral_domain A] [is_noetherian_ring A] /--In a noetherian integral domain which is not a field, every non-zero ideal contains a non-zero product of prime ideals; in a field, the whole ring is a non-zero ideal containing only 0 as product or prime ideals ([samuel, § 3.3, Lemma 3]) -/ lemma exists_prime_spectrum_prod_le_and_ne_bot_of_domain (h_fA : ¬ is_field A) {I : ideal A} (h_nzI: I ≠ ⊥) : ∃ (Z : multiset (prime_spectrum A)), multiset.prod (Z.map (coe : subtype _ → ideal A)) ≤ I ∧ multiset.prod (Z.map (coe : subtype _ → ideal A)) ≠ ⊥ := begin revert h_nzI, refine is_noetherian.induction (λ (M : ideal A) hgt, _) I, intro h_nzM, have hA_nont : nontrivial A, apply is_integral_domain.to_nontrivial (integral_domain.to_is_integral_domain A), by_cases h_topM : M = ⊤, { rcases h_topM with rfl, obtain ⟨p_id, h_nzp, h_pp⟩ : ∃ (p : ideal A), p ≠ ⊥ ∧ p.is_prime, { apply ring.not_is_field_iff_exists_prime.mp h_fA }, use [({⟨p_id, h_pp⟩} : multiset (prime_spectrum A)), le_top], rwa [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk] }, by_cases h_prM : M.is_prime, { use ({⟨M, h_prM⟩} : multiset (prime_spectrum A)), rw [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk], exact ⟨le_rfl, h_nzM⟩ }, obtain ⟨x, hx, y, hy, h_xy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left h_topM, have lt_add : ∀ z ∉ M, M < M + span A {z}, { intros z hz, refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _), rw m_eq, exact mem_sup_right (mem_span_singleton_self z) }, obtain ⟨Wx, h_Wx_le, h_Wx_ne⟩ := hgt (M + span A {x}) (lt_add _ hx) (ne_bot_of_gt (lt_add _ hx)), obtain ⟨Wy, h_Wy_le, h_Wx_ne⟩ := hgt (M + span A {y}) (lt_add _ hy) (ne_bot_of_gt (lt_add _ hy)), use Wx + Wy, rw [multiset.map_add, multiset.prod_add], refine ⟨le_trans (submodule.mul_le_mul h_Wx_le h_Wy_le) _, mt ideal.mul_eq_bot.mp _⟩, { rw add_mul, apply sup_le (show M * (M + span A {y}) ≤ M, from ideal.mul_le_right), rw mul_add, apply sup_le (show span A {x} * M ≤ M, from ideal.mul_le_left), rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem] }, { rintro (hx | hy); contradiction }, end end primes
9bd9b5c4ad8df6d77ecd3b9af52049d41cec5c0e
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/expr_maps.lean
81d9dd90b2103eb8dde66a44b3d4cec6f99b804c
[ "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
2,934
lean
import Lean.Expr open Lean def exprType : Expr := mkSort levelOne def biDef := BinderInfo.default def exprNat := mkConst `Nat [] -- Type -> Type def TypeArrowType := mkForall `α biDef exprType exprType -- Type -> Type def TypeArrowType2 := mkForall `β biDef exprType exprType -- fun (x : Nat) => x def exprT1 := mkLambda `x biDef exprNat (mkBVar 0) -- fun (y : Nat) => x def exprT2 := mkLambda `y biDef exprNat (mkBVar 0) -- fun (x : Nat) => (f x) def exprT3 := mkLambda `x biDef exprNat (mkApp (mkConst `f []) (mkBVar 0)) -- fun (x : Nat) => (f x) def exprT4 := mkLambda `x BinderInfo.implicit exprNat (mkApp (mkConst `f []) (mkBVar 0)) def check (b : Bool) : IO Unit := «unless» b (throw $ IO.userError "failed") def tst1 : IO Unit := do IO.println TypeArrowType; IO.println exprT1; IO.println exprT2; IO.println exprT3; IO.println exprT4; check (TypeArrowType == TypeArrowType2); check (ExprStructEq.mk TypeArrowType != ExprStructEq.mk TypeArrowType2); check (!Expr.equal TypeArrowType TypeArrowType2); check (exprT1 == exprT2); check (ExprStructEq.mk exprT1 != ExprStructEq.mk exprT2); check (ExprStructEq.mk exprT1 == ExprStructEq.mk exprT1); check (exprT3 == exprT4); check (ExprStructEq.mk exprT3 != ExprStructEq.mk exprT4); pure () #eval tst1 def tst2 : IO Unit := do let m1 : ExprMap Nat := {}; let m1 := m1.insert exprT1 10; check (m1.find? exprT1 == some 10); check (m1.find? exprT2 == some 10); check (m1.find? exprT3 == none); let m1 := m1.insert exprT4 20; check (m1.find? exprT1 == some 10); check (m1.find? exprT3 == some 20); IO.println (m1.find? exprT1); pure () #eval tst2 def tst3 : IO Unit := do let m1 : ExprStructMap Nat := {}; let m1 := m1.insert exprT1 10; check (m1.find? exprT1 == some 10); check (m1.find? exprT2 == none); check (m1.find? exprT3 == none); let m1 := m1.insert exprT4 20; check (m1.find? exprT1 == some 10); check (m1.find? exprT4 == some 20); check (m1.find? exprT3 == none); IO.println (m1.find? exprT1); pure () #eval tst3 def tst4 : IO Unit := do let m1 : PersistentExprMap Nat := {}; let m1 := m1.insert exprT1 10; check (m1.find? exprT1 == some 10); check (m1.find? exprT2 == some 10); check (m1.find? exprT3 == none); let m1 := m1.insert exprT4 20; check (m1.find? exprT1 == some 10); check (m1.find? exprT3 == some 20); IO.println (m1.find? exprT1); pure () #eval tst4 def tst5 : IO Unit := do let m1 : PersistentExprStructMap Nat := {}; let m1 := m1.insert exprT1 10; check (m1.find? exprT1 == some 10); check (m1.find? exprT2 == none); check (m1.find? exprT3 == none); let m1 := m1.insert exprT4 20; check (m1.find? exprT1 == some 10); check (m1.find? exprT4 == some 20); check (m1.find? exprT3 == none); IO.println (m1.find? exprT1); pure () #eval tst5
f87bf10990b1aa74b2bfdab7712c17bc8f6b715f
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/src/Lean/Elab/Match.lean
bd4d44b85c0cb03b58e4c091480587ca3be42f67
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
37,558
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Match.MatchPatternAttr import Lean.Meta.Match.Match import Lean.Elab.SyntheticMVars import Lean.Elab.App import Lean.Parser.Term namespace Lean.Elab.Term open Meta open Lean.Parser.Term /- This modules assumes "match"-expressions use the following syntax. ```lean def matchDiscr := parser! optional (try (ident >> checkNoWsBefore "no space before ':'" >> ":")) >> termParser def «match» := parser!:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts ``` -/ structure MatchAltView where ref : Syntax patterns : Array Syntax rhs : Syntax deriving Inhabited private def expandSimpleMatch (stx discr lhsVar rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let newStx ← `(let $lhsVar := $discr; $rhs) withMacroExpansion stx newStx $ elabTerm newStx expectedType? private def expandSimpleMatchWithType (stx discr lhsVar type rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let newStx ← `(let $lhsVar : $type := $discr; $rhs) withMacroExpansion stx newStx $ elabTerm newStx expectedType? private def elabDiscrsWitMatchType (discrStxs : Array Syntax) (matchType : Expr) (expectedType : Expr) : TermElabM (Array Expr) := do let mut discrs := #[] let mut i := 0 let mut matchType := matchType for discrStx in discrStxs do i := i + 1 matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let discr ← fullApproxDefEq $ elabTermEnsuringType discrStx[1] d trace[Elab.match]! "discr #{i} {discr} : {d}" matchType ← b.instantiate1 discr discrs := discrs.push discr | _ => throwError! "invalid type provided to match-expression, function type with arity #{discrStxs.size} expected" pure discrs private def mkUserNameFor (e : Expr) : TermElabM Name := match e with | Expr.fvar fvarId _ => do pure (← getLocalDecl fvarId).userName | _ => mkFreshBinderName -- `expandNonAtomicDiscrs?` create auxiliary variables with base name `_discr` private def isAuxDiscrName (n : Name) : Bool := n.eraseMacroScopes == `_discr -- See expandNonAtomicDiscrs? private def elabAtomicDiscr (discr : Syntax) : TermElabM Expr := do let term := discr[1] match (← isLocalIdent? term) with | some e@(Expr.fvar fvarId _) => let localDecl ← getLocalDecl fvarId if !isAuxDiscrName localDecl.userName then pure e -- it is not an auxiliary local created by `expandNonAtomicDiscrs?` else pure localDecl.value | _ => throwErrorAt discr "unexpected discriminant" private def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptType : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr) : TermElabM (Array Expr × Expr × Array MatchAltView) := do let numDiscrs := discrStxs.size if matchOptType.isNone then let rec loop (i : Nat) (discrs : Array Expr) (matchType : Expr) (matchAltViews : Array MatchAltView) := do match i with | 0 => pure (discrs.reverse, matchType, matchAltViews) | i+1 => let discrStx := discrStxs[i] let discr ← elabAtomicDiscr discrStx let discr ← instantiateMVars discr let discrType ← inferType discr let discrType ← instantiateMVars discrType let matchTypeBody ← kabstract matchType discr let userName ← mkUserNameFor discr if discrStx[0].isNone then loop i (discrs.push discr) (Lean.mkForall userName BinderInfo.default discrType matchTypeBody) matchAltViews else let identStx := discrStx[0][0] withLocalDeclD userName discrType fun x => do let eqType ← mkEq discr x withLocalDeclD identStx.getId eqType fun h => do let matchTypeBody := matchTypeBody.instantiate1 x let matchType ← mkForallFVars #[x, h] matchTypeBody let refl ← mkEqRefl discr let discrs := (discrs.push refl).push discr let matchAltViews := matchAltViews.map fun altView => { altView with patterns := altView.patterns.insertAt (i+1) identStx } loop i discrs matchType matchAltViews loop discrStxs.size #[] expectedType matchAltViews else let matchTypeStx := matchOptType[0][1] let matchType ← elabType matchTypeStx let discrs ← elabDiscrsWitMatchType discrStxs matchType expectedType pure (discrs, matchType, matchAltViews) def expandMacrosInPatterns (matchAlts : Array MatchAltView) : MacroM (Array MatchAltView) := do matchAlts.mapM fun matchAlt => do let patterns ← matchAlt.patterns.mapM expandMacros pure { matchAlt with patterns := patterns } /- Given `stx` a match-expression, return its alternatives. -/ private def getMatchAlts : Syntax → Array MatchAltView | `(match $discrs,* $[: $ty?]? with $alts:matchAlt*) => alts.map fun alt => match alt with | `(matchAltExpr| | $patterns,* => $rhs) => { ref := alt, patterns := patterns, rhs := rhs } | _ => unreachable! | _ => unreachable! /-- Auxiliary annotation used to mark terms marked with the "inaccessible" annotation `.(t)` and `_` in patterns. -/ def mkInaccessible (e : Expr) : Expr := mkAnnotation `_inaccessible e def inaccessible? (e : Expr) : Option Expr := annotation? `_inaccessible e inductive PatternVar where | localVar (userName : Name) -- anonymous variables (`_`) are encoded using metavariables | anonymousVar (mvarId : MVarId) instance : ToString PatternVar := ⟨fun | PatternVar.localVar x => toString x | PatternVar.anonymousVar mvarId => s!"?m{mvarId}"⟩ builtin_initialize Parser.registerBuiltinNodeKind `MVarWithIdKind /-- Create an auxiliary Syntax node wrapping a fresh metavariable id. We use this kind of Syntax for representing `_` occurring in patterns. The metavariables are created before we elaborate the patterns into `Expr`s. -/ private def mkMVarSyntax : TermElabM Syntax := do let mvarId ← mkFreshId pure $ Syntax.node `MVarWithIdKind #[Syntax.node mvarId #[]] /-- Given a syntax node constructed using `mkMVarSyntax`, return its MVarId -/ private def getMVarSyntaxMVarId (stx : Syntax) : MVarId := stx[0].getKind /-- The elaboration function for `Syntax` created using `mkMVarSyntax`. It just converts the metavariable id wrapped by the Syntax into an `Expr`. -/ @[builtinTermElab MVarWithIdKind] def elabMVarWithIdKind : TermElab := fun stx expectedType? => pure $ mkInaccessible $ mkMVar (getMVarSyntaxMVarId stx) @[builtinTermElab inaccessible] def elabInaccessible : TermElab := fun stx expectedType? => do let e ← elabTerm stx[1] expectedType? pure $ mkInaccessible e /- Patterns define new local variables. This module collect them and preprocess `_` occurring in patterns. Recall that an `_` may represent anonymous variables or inaccessible terms that are implied by typing constraints. Thus, we represent them with fresh named holes `?x`. After we elaborate the pattern, if the metavariable remains unassigned, we transform it into a regular pattern variable. Otherwise, it becomes an inaccessible term. Macros occurring in patterns are expanded before the `collectPatternVars` method is executed. The following kinds of Syntax are handled by this module - Constructor applications - Applications of functions tagged with the `[matchPattern]` attribute - Identifiers - Anonymous constructors - Structure instances - Inaccessible terms - Named patterns - Tuple literals - Type ascriptions - Literals: num, string and char -/ namespace CollectPatternVars structure State where found : NameSet := {} vars : Array PatternVar := #[] abbrev M := StateRefT State TermElabM private def throwCtorExpected {α} : M α := throwError "invalid pattern, constructor or constant marked with '[matchPattern]' expected" private def getNumExplicitCtorParams (ctorVal : ConstructorVal) : TermElabM Nat := forallBoundedTelescope ctorVal.type ctorVal.nparams fun ps _ => do let mut result := 0 for p in ps do let localDecl ← getLocalDecl p.fvarId! if localDecl.binderInfo.isExplicit then result := result+1 pure result private def throwInvalidPattern {α} : M α := throwError "invalid pattern" namespace CtorApp /- An application in a pattern can be 1- A constructor application The elaborator assumes fields are accessible and inductive parameters are not accessible. 2- A regular application `(f ...)` where `f` is tagged with `[matchPattern]`. The elaborator assumes implicit arguments are not accessible and explicit ones are accessible. -/ structure Context where funId : Syntax ctorVal? : Option ConstructorVal -- It is `some`, if constructor application explicit : Bool ellipsis : Bool paramDecls : Array LocalDecl paramDeclIdx : Nat := 0 namedArgs : Array NamedArg args : List Arg newArgs : Array Syntax := #[] deriving Inhabited private def isDone (ctx : Context) : Bool := ctx.paramDeclIdx ≥ ctx.paramDecls.size private def finalize (ctx : Context) : M Syntax := do if ctx.namedArgs.isEmpty && ctx.args.isEmpty then let fStx ← `(@$(ctx.funId):ident) pure $ Syntax.mkApp fStx ctx.newArgs else throwError "too many arguments" private def isNextArgAccessible (ctx : Context) : Bool := let i := ctx.paramDeclIdx match ctx.ctorVal? with | some ctorVal => i ≥ ctorVal.nparams -- For constructor applications only fields are accessible | none => if h : i < ctx.paramDecls.size then -- For `[matchPattern]` applications, only explicit parameters are accessible. let d := ctx.paramDecls.get ⟨i, h⟩ d.binderInfo.isExplicit else false private def getNextParam (ctx : Context) : LocalDecl × Context := let i := ctx.paramDeclIdx let d := ctx.paramDecls[i] (d, { ctx with paramDeclIdx := ctx.paramDeclIdx + 1 }) private def pushNewArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) (arg : Arg) : M Context := match arg with | Arg.stx stx => do let stx ← if accessible then collect stx else pure stx pure { ctx with newArgs := ctx.newArgs.push stx } | _ => unreachable! private def processExplicitArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) : M Context := match ctx.args with | [] => if ctx.ellipsis then do let hole ← `(_) pushNewArg collect accessible ctx (Arg.stx hole) else throwError! "explicit parameter is missing, unused named arguments {ctx.namedArgs.map fun narg => narg.name}" | arg::args => do let ctx := { ctx with args := args } pushNewArg collect accessible ctx arg private def processImplicitArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) : M Context := if ctx.explicit then processExplicitArg collect accessible ctx else do let hole ← `(_) pushNewArg collect accessible ctx (Arg.stx hole) private partial def processCtorAppAux (collect : Syntax → M Syntax) (ctx : Context) : M Syntax := do if isDone ctx then finalize ctx else let accessible := isNextArgAccessible ctx let (d, ctx) := getNextParam ctx match ctx.namedArgs.findIdx? fun namedArg => namedArg.name == d.userName with | some idx => let arg := ctx.namedArgs[idx] let ctx := { ctx with namedArgs := ctx.namedArgs.eraseIdx idx } let ctx ← pushNewArg collect accessible ctx arg.val processCtorAppAux collect ctx | none => let ctx ← match d.binderInfo with | BinderInfo.implicit => processImplicitArg collect accessible ctx | BinderInfo.instImplicit => processImplicitArg collect accessible ctx | _ => processExplicitArg collect accessible ctx processCtorAppAux collect ctx def processCtorApp (collect : Syntax → M Syntax) (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) : M Syntax := do let args := args.toList let (fId, explicit) ← match f with | `($fId:ident) => pure (fId, false) | `(@$fId:ident) => pure (fId, true) | _ => throwError "identifier expected" let some (Expr.const fName _ _) ← resolveId? fId "pattern" | throwCtorExpected let fInfo ← getConstInfo fName forallTelescopeReducing fInfo.type fun xs _ => do let paramDecls ← xs.mapM (getFVarLocalDecl ·) match fInfo with | ConstantInfo.ctorInfo val => processCtorAppAux collect { funId := fId, explicit := explicit, ctorVal? := val, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } | _ => let env ← getEnv if hasMatchPatternAttribute env fName then processCtorAppAux collect { funId := fId, explicit := explicit, ctorVal? := none, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } else throwCtorExpected end CtorApp def processCtorApp (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do let (f, namedArgs, args, ellipsis) ← liftM $ expandApp stx true CtorApp.processCtorApp collect f namedArgs args ellipsis def processCtor (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do CtorApp.processCtorApp collect stx #[] #[] false private def processVar (idStx : Syntax) : M Syntax := do unless idStx.isIdent do throwErrorAt idStx "identifier expected" let id := idStx.getId unless id.eraseMacroScopes.isAtomic do throwError "invalid pattern variable, must be atomic" let s ← get if s.found.contains id then throwError! "invalid pattern, variable '{id}' occurred more than once" modify fun s => { s with vars := s.vars.push (PatternVar.localVar id), found := s.found.insert id } pure idStx /- Check whether `stx` is a pattern variable or constructor-like (i.e., constructor or constant tagged with `[matchPattern]` attribute) -/ private def processId (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do let env ← getEnv match (← resolveId? stx "pattern") with | none => processVar stx | some f => match f with | Expr.const fName _ _ => match env.find? fName with | some (ConstantInfo.ctorInfo _) => processCtor collect stx | some _ => if hasMatchPatternAttribute env fName then processCtor collect stx else processVar stx | none => throwCtorExpected | _ => processVar stx private def nameToPattern : Name → TermElabM Syntax | Name.anonymous => `(Name.anonymous) | Name.str p s _ => do let p ← nameToPattern p; `(Name.str $p $(quote s) _) | Name.num p n _ => do let p ← nameToPattern p; `(Name.num $p $(quote n) _) private def quotedNameToPattern (stx : Syntax) : TermElabM Syntax := match stx[0].isNameLit? with | some val => nameToPattern val | none => throwIllFormedSyntax partial def collect : Syntax → M Syntax | stx@(Syntax.node k args) => withRef stx $ withFreshMacroScope do if k == `Lean.Parser.Term.app then processCtorApp collect stx else if k == `Lean.Parser.Term.anonymousCtor then let elems ← args[1].getArgs.mapSepElemsM collect pure $ Syntax.node k (args.set! 1 $ mkNullNode elems) else if k == `Lean.Parser.Term.structInst then /- ``` parser! "{" >> optional (atomic (termParser >> " with ")) >> manyIndent (group (structInstField >> optional ", ")) >> optional ".." >> optional (" : " >> termParser) >> " }" ``` -/ let withMod := args[1] unless withMod.isNone do throwErrorAt withMod "invalid struct instance pattern, 'with' is not allowed in patterns" let fields ← args[2].getArgs.mapM fun p => do -- p is of the form (group (structInstField >> optional ", ")) let field := p[0] -- parser! structInstLVal >> " := " >> termParser let newVal ← collect field[2] let field := field.setArg 2 newVal pure <| field.setArg 0 field pure <| Syntax.node k (args.set! 2 <| mkNullNode fields) else if k == `Lean.Parser.Term.hole then let r ← mkMVarSyntax modify fun s => { s with vars := s.vars.push $ PatternVar.anonymousVar $ getMVarSyntaxMVarId r } pure r else if k == `Lean.Parser.Term.paren then let arg := args[1] if arg.isNone then pure stx -- `()` else let t := arg[0] let s := arg[1] if s.isNone || s[0].getKind == `Lean.Parser.Term.typeAscription then -- Ignore `s`, since it empty or it is a type ascription let t ← collect t let arg := arg.setArg 0 t pure $ Syntax.node k (args.set! 1 arg) else -- Tuple literal is a constructor let t ← collect t let arg := arg.setArg 0 t let tupleTail := s[0] let tupleTailElems := tupleTail[1].getArgs let tupleTailElems ← tupleTailElems.mapSepElemsM collect let tupleTail := tupleTail.setArg 1 $ mkNullNode tupleTailElems let s := s.setArg 0 tupleTail let arg := arg.setArg 1 s pure $ Syntax.node k (args.set! 1 arg) else if k == `Lean.Parser.Term.explicitUniv then processCtor collect stx[0] else if k == `Lean.Parser.Term.namedPattern then /- Recall that def namedPattern := check... >> tparser! "@" >> termParser -/ let id := stx[0] discard <| processVar id let pat := stx[2] let pat ← collect pat `(_root_.namedPattern $id $pat) else if k == `Lean.Parser.Term.inaccessible then pure stx else if k == strLitKind then pure stx else if k == numLitKind then pure stx else if k == scientificLitKind then pure stx else if k == charLitKind then pure stx else if k == `Lean.Parser.Term.quotedName then /- Quoted names have an elaboration function associated with them, and they will not be macro expanded. Note that macro expansion is not a good option since it produces a term using the smart constructors `Name.mkStr`, `Name.mkNum` instead of the constructors `Name.str` and `Name.num` -/ quotedNameToPattern stx else if k == choiceKind then throwError "invalid pattern, notation is ambiguous" else throwInvalidPattern | stx@(Syntax.ident _ _ _ _) => processId collect stx | stx => throwInvalidPattern def main (alt : MatchAltView) : M MatchAltView := do let patterns ← alt.patterns.mapM fun p => do trace[Elab.match]! "collecting variables at pattern: {p}" collect p pure { alt with patterns := patterns } end CollectPatternVars private def collectPatternVars (alt : MatchAltView) : TermElabM (Array PatternVar × MatchAltView) := do let (alt, s) ← (CollectPatternVars.main alt).run {} pure (s.vars, alt) /- Return the pattern variables in the given pattern. Remark: this method is not used here, but in other macros (e.g., at `Do.lean`). -/ def getPatternVars (patternStx : Syntax) : TermElabM (Array PatternVar) := do let patternStx ← liftMacroM $ expandMacros patternStx let (_, s) ← (CollectPatternVars.collect patternStx).run {} pure s.vars def getPatternsVars (patterns : Array Syntax) : TermElabM (Array PatternVar) := do let collect : CollectPatternVars.M Unit := do for pattern in patterns do discard <| CollectPatternVars.collect (← liftMacroM $ expandMacros pattern) let (_, s) ← collect.run {} pure s.vars /- We convert the collected `PatternVar`s intro `PatternVarDecl` -/ inductive PatternVarDecl where /- For `anonymousVar`, we create both a metavariable and a free variable. The free variable is used as an assignment for the metavariable when it is not assigned during pattern elaboration. -/ | anonymousVar (mvarId : MVarId) (fvarId : FVarId) | localVar (fvarId : FVarId) private partial def withPatternVars {α} (pVars : Array PatternVar) (k : Array PatternVarDecl → TermElabM α) : TermElabM α := let rec loop (i : Nat) (decls : Array PatternVarDecl) := do if h : i < pVars.size then match pVars.get ⟨i, h⟩ with | PatternVar.anonymousVar mvarId => let type ← mkFreshTypeMVar let userName ← mkFreshBinderName withLocalDecl userName BinderInfo.default type fun x => loop (i+1) (decls.push (PatternVarDecl.anonymousVar mvarId x.fvarId!)) | PatternVar.localVar userName => let type ← mkFreshTypeMVar withLocalDecl userName BinderInfo.default type fun x => loop (i+1) (decls.push (PatternVarDecl.localVar x.fvarId!)) else /- We must create the metavariables for `PatternVar.anonymousVar` AFTER we create the new local decls using `withLocalDecl`. Reason: their scope must include the new local decls since some of them are assigned by typing constraints. -/ decls.forM fun decl => match decl with | PatternVarDecl.anonymousVar mvarId fvarId => do let type ← inferType (mkFVar fvarId) discard <| mkFreshExprMVarWithId mvarId type | _ => pure () k decls loop 0 #[] private def elabPatterns (patternStxs : Array Syntax) (matchType : Expr) : TermElabM (Array Expr × Expr) := do let mut patterns := #[] let mut matchType := matchType for patternStx in patternStxs do matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let pattern ← elabTermEnsuringType patternStx d matchType := b.instantiate1 pattern patterns := patterns.push pattern | _ => throwError "unexpected match type" pure (patterns, matchType) def finalizePatternDecls (patternVarDecls : Array PatternVarDecl) : TermElabM (Array LocalDecl) := do let mut decls := #[] for pdecl in patternVarDecls do match pdecl with | PatternVarDecl.localVar fvarId => let decl ← getLocalDecl fvarId let decl ← instantiateLocalDeclMVars decl decls := decls.push decl | PatternVarDecl.anonymousVar mvarId fvarId => let e ← instantiateMVars (mkMVar mvarId); trace[Elab.match]! "finalizePatternDecls: mvarId: {mvarId} := {e}, fvar: {mkFVar fvarId}" match e with | Expr.mvar newMVarId _ => /- Metavariable was not assigned, or assigned to another metavariable. So, we assign to the auxiliary free variable we created at `withPatternVars` to `newMVarId`. -/ assignExprMVar newMVarId (mkFVar fvarId) trace[Elab.match]! "finalizePatternDecls: {mkMVar newMVarId} := {mkFVar fvarId}" let decl ← getLocalDecl fvarId let decl ← instantiateLocalDeclMVars decl decls := decls.push decl | _ => pure () pure decls open Meta.Match (Pattern Pattern.var Pattern.inaccessible Pattern.ctor Pattern.as Pattern.val Pattern.arrayLit AltLHS MatcherResult) namespace ToDepElimPattern structure State where found : NameSet := {} localDecls : Array LocalDecl newLocals : NameSet := {} abbrev M := StateRefT State TermElabM private def alreadyVisited (fvarId : FVarId) : M Bool := do let s ← get pure $ s.found.contains fvarId private def markAsVisited (fvarId : FVarId) : M Unit := modify fun s => { s with found := s.found.insert fvarId } private def throwInvalidPattern {α} (e : Expr) : M α := throwError! "invalid pattern {indentExpr e}" /- Create a new LocalDecl `x` for the metavariable `mvar`, and return `Pattern.var x` -/ private def mkLocalDeclFor (mvar : Expr) : M Pattern := do let mvarId := mvar.mvarId! let s ← get match (← getExprMVarAssignment? mvarId) with | some val => pure $ Pattern.inaccessible val | none => let fvarId ← mkFreshId let type ← inferType mvar /- HACK: `fvarId` is not in the scope of `mvarId` If this generates problems in the future, we should update the metavariable declarations. -/ assignExprMVar mvarId (mkFVar fvarId) let userName ← liftM $ mkFreshBinderName let newDecl := LocalDecl.cdecl arbitrary fvarId userName type BinderInfo.default; modify fun s => { s with newLocals := s.newLocals.insert fvarId, localDecls := match s.localDecls.findIdx? fun decl => mvar.occurs decl.type with | none => s.localDecls.push newDecl -- None of the existing declarations depend on `mvar` | some i => s.localDecls.insertAt i newDecl } pure $ Pattern.var fvarId partial def main (e : Expr) : M Pattern := do let isLocalDecl (fvarId : FVarId) : M Bool := do let s ← get pure $ s.localDecls.any fun d => d.fvarId == fvarId let mkPatternVar (fvarId : FVarId) (e : Expr) : M Pattern := do if (← alreadyVisited fvarId) then pure $ Pattern.inaccessible e else markAsVisited fvarId pure $ Pattern.var e.fvarId! let mkInaccessible (e : Expr) : M Pattern := do match e with | Expr.fvar fvarId _ => if (← isLocalDecl fvarId) then mkPatternVar fvarId e else pure $ Pattern.inaccessible e | _ => pure $ Pattern.inaccessible e match inaccessible? e with | some t => mkInaccessible t | none => match e.arrayLit? with | some (α, lits) => let ps ← lits.mapM main; pure $ Pattern.arrayLit α ps | none => if e.isAppOfArity `namedPattern 3 then let p ← main $ e.getArg! 2; match e.getArg! 1 with | Expr.fvar fvarId _ => pure $ Pattern.as fvarId p | _ => throwError "unexpected occurrence of auxiliary declaration 'namedPattern'" else if e.isNatLit || e.isStringLit || e.isCharLit then pure $ Pattern.val e else if e.isFVar then let fvarId := e.fvarId! unless(← isLocalDecl fvarId) do throwInvalidPattern e mkPatternVar fvarId e else if e.isMVar then mkLocalDeclFor e else let newE ← whnf e if newE != e then main newE else matchConstCtor e.getAppFn (fun _ => throwInvalidPattern e) fun v us => do let args := e.getAppArgs unless args.size == v.nparams + v.nfields do throwInvalidPattern e let params := args.extract 0 v.nparams let fields := args.extract v.nparams args.size let fields ← fields.mapM main pure $ Pattern.ctor v.name us params.toList fields.toList end ToDepElimPattern def withDepElimPatterns {α} (localDecls : Array LocalDecl) (ps : Array Expr) (k : Array LocalDecl → Array Pattern → TermElabM α) : TermElabM α := do let (patterns, s) ← (ps.mapM ToDepElimPattern.main).run { localDecls := localDecls } let localDecls ← s.localDecls.mapM fun d => instantiateLocalDeclMVars d /- toDepElimPatterns may have added new localDecls. Thus, we must update the local context before we execute `k` -/ let lctx ← getLCtx let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.erase d.fvarId) lctx let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.addDecl d) lctx withTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) $ k localDecls patterns private def withElaboratedLHS {α} (ref : Syntax) (patternVarDecls : Array PatternVarDecl) (patternStxs : Array Syntax) (matchType : Expr) (k : AltLHS → Expr → TermElabM α) : TermElabM α := do let (patterns, matchType) ← withSynthesize $ elabPatterns patternStxs matchType let localDecls ← finalizePatternDecls patternVarDecls let patterns ← patterns.mapM (instantiateMVars ·) withDepElimPatterns localDecls patterns fun localDecls patterns => k { ref := ref, fvarDecls := localDecls.toList, patterns := patterns.toList } matchType def elabMatchAltView (alt : MatchAltView) (matchType : Expr) : TermElabM (AltLHS × Expr) := withRef alt.ref do let (patternVars, alt) ← collectPatternVars alt trace[Elab.match]! "patternVars: {patternVars}" withPatternVars patternVars fun patternVarDecls => do withElaboratedLHS alt.ref patternVarDecls alt.patterns matchType fun altLHS matchType => do let rhs ← elabTermEnsuringType alt.rhs matchType let xs := altLHS.fvarDecls.toArray.map LocalDecl.toExpr let rhs ← if xs.isEmpty then pure $ mkSimpleThunk rhs else mkLambdaFVars xs rhs trace[Elab.match]! "rhs: {rhs}" pure (altLHS, rhs) def mkMatcher (elimName : Name) (matchType : Expr) (numDiscrs : Nat) (lhss : List AltLHS) : TermElabM MatcherResult := liftMetaM $ Meta.Match.mkMatcher elimName matchType numDiscrs lhss builtin_initialize registerOption `match.ignoreUnusedAlts { defValue := false, group := "", descr := "if true, do not generate error if an alternative is not used" } def ignoreUnusedAlts (opts : Options) : Bool := opts.get `match.ignoreUnusedAlts false def reportMatcherResultErrors (altLHSS : List AltLHS) (result : MatcherResult) : TermElabM Unit := do unless result.counterExamples.isEmpty do throwError! "missing cases:\n{Meta.Match.counterExamplesToMessageData result.counterExamples}" unless ignoreUnusedAlts (← getOptions) || result.unusedAltIdxs.isEmpty do let mut i := 0 for alt in altLHSS do if result.unusedAltIdxs.contains i then withRef alt.ref do logError "redundant alternative" i := i + 1 private def elabMatchAux (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptType : Syntax) (expectedType : Expr) : TermElabM Expr := do let (discrs, matchType, altViews) ← elabMatchTypeAndDiscrs discrStxs matchOptType altViews expectedType let matchAlts ← liftMacroM $ expandMacrosInPatterns altViews trace[Elab.match]! "matchType: {matchType}" let alts ← matchAlts.mapM $ fun alt => elabMatchAltView alt matchType /- We should not use `synthesizeSyntheticMVarsNoPostponing` here. Otherwise, we will not be able to elaborate examples such as: ``` def f (x : Nat) : Option Nat := none def g (xs : List (Nat × Nat)) : IO Unit := xs.forM fun x => match f x.fst with | _ => pure () ``` If `synthesizeSyntheticMVarsNoPostponing`, the example above fails at `x.fst` because the type of `x` is only available after we proces the last argument of `List.forM`. We apply pending default types to make sure we can process examples such as ``` let (a, b) := (0, 0) ``` -/ synthesizeSyntheticMVarsUsingDefault let rhss := alts.map Prod.snd let matchType ← instantiateMVars matchType let altLHSS ← alts.toList.mapM fun alt => do let altLHS ← Match.instantiateAltLHSMVars alt.1 withRef altLHS.ref do for d in altLHS.fvarDecls do if d.hasExprMVar then withExistingLocalDecls altLHS.fvarDecls do throwMVarError m!"invalid match-expression, type of pattern variable '{d.toExpr}' contains metavariables{indentExpr d.type}" for p in altLHS.patterns do if p.hasExprMVar then withExistingLocalDecls altLHS.fvarDecls do throwMVarError m!"invalid match-expression, pattern contains metavariables{indentExpr (← p.toExpr)}" pure altLHS let numDiscrs := discrs.size let matcherName ← mkAuxName `match let matcherResult ← mkMatcher matcherName matchType numDiscrs altLHSS let motive ← forallBoundedTelescope matchType numDiscrs fun xs matchType => mkLambdaFVars xs matchType reportMatcherResultErrors altLHSS matcherResult let r := mkApp matcherResult.matcher motive let r := mkAppN r discrs let r := mkAppN r rhss trace[Elab.match]! "result: {r}" pure r private def getDiscrs (matchStx : Syntax) : Array Syntax := matchStx[1].getSepArgs private def getMatchOptType (matchStx : Syntax) : Syntax := matchStx[2] private def expandNonAtomicDiscrs? (matchStx : Syntax) : TermElabM (Option Syntax) := let matchOptType := getMatchOptType matchStx; if matchOptType.isNone then do let discrs := getDiscrs matchStx; let allLocal ← discrs.allM fun discr => Option.isSome <$> isLocalIdent? discr[1] if allLocal then pure none else let rec loop (discrs : List Syntax) (discrsNew : Array Syntax) := do match discrs with | [] => let discrs := Syntax.mkSep discrsNew (mkAtomFrom matchStx ", "); pure (matchStx.setArg 1 discrs) | discr :: discrs => -- Recall that -- matchDiscr := parser! optional (ident >> ":") >> termParser let term := discr[1] match (← isLocalIdent? term) with | some _ => loop discrs (discrsNew.push discr) | none => withFreshMacroScope do let d ← `(_discr); unless isAuxDiscrName d.getId do -- Use assertion? throwError "unexpected internal auxiliary discriminant name" let discrNew := discr.setArg 1 d; let r ← loop discrs (discrsNew.push discrNew) `(let _discr := $term; $r) pure (some (← loop discrs.toList #[])) else -- We do not pull non atomic discriminants when match type is provided explicitly by the user pure none private def waitExpectedType (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | some expectedType => pure expectedType | none => mkFreshTypeMVar private def tryPostponeIfDiscrTypeIsMVar (matchStx : Syntax) : TermElabM Unit := do -- We don't wait for the discriminants types when match type is provided by user if getMatchOptType matchStx |>.isNone then let discrs := getDiscrs matchStx for discr in discrs do let term := discr[1] match (← isLocalIdent? term) with | none => throwErrorAt discr "unexpected discriminant" -- see `expandNonAtomicDiscrs? | some d => let dType ← inferType d trace[Elab.match]! "discr {d} : {dType}" tryPostponeIfMVar dType /- We (try to) elaborate a `match` only when the expected type is available. If the `matchType` has not been provided by the user, we also try to postpone elaboration if the type of a discriminant is not available. That is, it is of the form `(?m ...)`. We use `expandNonAtomicDiscrs?` to make sure all discriminants are local variables. This is a standard trick we use in the elaborator, and it is also used to elaborate structure instances. Suppose, we are trying to elaborate ``` match g x with | ... => ... ``` `expandNonAtomicDiscrs?` converts it intro ``` let _discr := g x match _discr with | ... => ... ``` Thus, at `tryPostponeIfDiscrTypeIsMVar` we only need to check whether the type of `_discr` is not of the form `(?m ...)`. Note that, the auxiliary variable `_discr` is expanded at `elabAtomicDiscr`. This elaboration technique is needed to elaborate terms such as: ```lean xs.filter fun (a, b) => a > b ``` which are syntax sugar for ```lean List.filter (fun p => match p with | (a, b) => a > b) xs ``` When we visit `match p with | (a, b) => a > b`, we don't know the type of `p` yet. -/ private def waitExpectedTypeAndDiscrs (matchStx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? tryPostponeIfDiscrTypeIsMVar matchStx match expectedType? with | some expectedType => pure expectedType | none => mkFreshTypeMVar /- ``` parser!:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts ``` Remark the `optIdent` must be `none` at `matchDiscr`. They are expanded by `expandMatchDiscr?`. -/ private def elabMatchCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let expectedType ← waitExpectedTypeAndDiscrs stx expectedType? let discrStxs := (getDiscrs stx).map fun d => d let altViews := getMatchAlts stx let matchOptType := getMatchOptType stx elabMatchAux discrStxs altViews matchOptType expectedType -- parser! "match " >> sepBy1 termParser ", " >> optType >> " with " >> matchAlts @[builtinTermElab «match»] def elabMatch : TermElab := fun stx expectedType? => match stx with | `(match $discr:term with | $y:ident => $rhs:term) => expandSimpleMatch stx discr y rhs expectedType? | `(match $discr:term : $type with | $y:ident => $rhs:term) => expandSimpleMatchWithType stx discr y type rhs expectedType? | _ => do match (← expandNonAtomicDiscrs? stx) with | some stxNew => withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? | none => let discrs := getDiscrs stx; let matchOptType := getMatchOptType stx; if !matchOptType.isNone && discrs.any fun d => !d[0].isNone then throwErrorAt matchOptType "match expected type should not be provided when discriminants with equality proofs are used" elabMatchCore stx expectedType? @[builtinInit] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.match; pure () -- parser!:leadPrec "nomatch " >> termParser @[builtinTermElab «nomatch»] def elabNoMatch : TermElab := fun stx expectedType? => match stx with | `(nomatch $discrExpr) => do let expectedType ← waitExpectedType expectedType? let discr := Syntax.node `Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr] elabMatchAux #[discr] #[] mkNullNode expectedType | _ => throwUnsupportedSyntax end Term end Elab end Lean
5913c6996f71c399115e4f4e28c930a743186697
2d34dfb0a1cc250584282618dc10ea03d3fa858e
/src/for_mathlib/normed_group.lean
99f18476e4603260227df4db8d042c3b20890afa
[]
no_license
zeta1999/lean-liquid
61e294ec5adae959d8ee1b65d015775484ff58c2
96bb0fa3afc3b451bcd1fb7d974348de2f290541
refs/heads/master
1,676,579,150,248
1,610,771,445,000
1,610,771,445,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,477
lean
import analysis.normed_space.basic import normed_group_hom noncomputable theory open_locale nnreal section variables {V : Type*} [normed_group V] lemma norm_nsmul_le (n : ℕ) (v : V) : ∥n •ℕ v∥ ≤ n * ∥v∥ := begin induction n with n ih, { simp only [norm_zero, nat.cast_zero, zero_mul, zero_nsmul] }, { simp only [nat.succ_eq_add_one, add_nsmul, nat.cast_add, nat.cast_one, one_nsmul, add_mul, one_mul], calc ∥n •ℕ v + v∥ ≤ ∥n •ℕ v∥ + ∥v∥ : norm_add_le _ _ ... ≤ n * ∥v∥ + ∥v∥ : add_le_add_right ih _ } end lemma norm_gsmul_le (n : ℤ) (v : V) : ∥n •ℤ v∥ ≤ (abs n) * ∥v∥ := begin induction n, { simpa only [int.cast_coe_nat, int.of_nat_eq_coe, gsmul_coe_nat, nat.abs_cast] using norm_nsmul_le n v }, { simpa only [gsmul_neg_succ_of_nat, abs_neg, norm_neg, int.cast_neg_succ_of_nat, ← nat.cast_add_one, nat.abs_cast] using norm_nsmul_le (n+1) v } end namespace normed_group @[simps] def nsmul (n : ℕ) : normed_group_hom V V := { to_fun := λ v, n •ℕ v, map_zero' := nsmul_zero _, map_add' := λ _ _, nsmul_add _ _ _, bound' := ⟨n, λ v, norm_nsmul_le _ _⟩ } lemma nsmul_bound_by (n : ℕ) : (nsmul n : normed_group_hom V V).bound_by n := λ v, by simpa only [nnreal.coe_nat_cast] using norm_nsmul_le n v @[simps] def gsmul (n : ℤ) : normed_group_hom V V := { to_fun := λ v, n •ℤ v, map_zero' := gsmul_zero _, map_add' := λ _ _, gsmul_add _ _ _, bound' := ⟨abs n, λ v, norm_gsmul_le _ _⟩ } lemma gsmul_bound_by (n : ℤ) : (gsmul n : normed_group_hom V V).bound_by (real.nnabs n) := norm_gsmul_le _ end normed_group namespace normed_group_hom open_locale big_operators nnreal def mk_to_pi' {ι : Type} [fintype ι] (W : ι → Type*) [Π i, normed_group (W i)] (f : Π i, normed_group_hom V (W i)) (C : ι → ℝ≥0) (hC : ∀ i, (f i).bound_by (C i)) : normed_group_hom V (Π i, W i) := mk' { to_fun := λ v i, f i v, map_zero' := by { simp only [map_zero], refl }, map_add' := by { intros, simp only [map_add], refl } } (finset.sup finset.univ C) begin intro v, rw pi_norm_le_iff (mul_nonneg (nnreal.coe_nonneg _) (norm_nonneg _)), intro i, calc ∥f i v∥ ≤ C i * ∥v∥ : (hC i) v ... ≤ _ * ∥v∥ : mul_le_mul _ le_rfl (norm_nonneg _) (nnreal.coe_nonneg _), rw nnreal.coe_le_coe, apply finset.le_sup (finset.mem_univ _) end lemma mk_to_pi'_bound_by {ι : Type} [fintype ι] (W : ι → Type*) [Π i, normed_group (W i)] (f : Π i, normed_group_hom V (W i)) (C : ι → ℝ≥0) (hC : ∀ i, (f i).bound_by (C i)) : (mk_to_pi' _ f C hC).bound_by (finset.sup finset.univ C) := mk'_bound_by _ _ _ def mk_to_pi {ι : Type} [fintype ι] (W : ι → Type*) [Π i, normed_group (W i)] (f : Π i, normed_group_hom V (W i)) : normed_group_hom V (Π i, W i) := mk_to_pi' _ f (λ i, classical.some (f i).bound) $ λ i, (classical.some_spec (f i).bound).2 def mk_from_pi' {ι : Type} [fintype ι] (V : ι → Type*) [Π i, normed_group (V i)] (W : Type*) [normed_group W] (f : Π i, normed_group_hom (V i) W) (C : ι → ℝ≥0) (hC : ∀ i, (f i).bound_by (C i)) : normed_group_hom (Π i, V i) W := mk' { to_fun := λ v, ∑ i, f i (v i), map_zero' := by { simp only [pi.zero_apply, map_zero, finset.sum_const_zero] }, map_add' := by { intros, simp only [pi.add_apply, map_add, finset.sum_add_distrib] } } (∑ i, C i) begin intro v, calc ∥∑ i, f i (v i)∥ ≤ ∑ i, ∥f i (v i)∥ : norm_sum_le _ _ ... ≤ ∑ i, C i * ∥v∥ : finset.sum_le_sum _ -- proven below ... = (∑ i, C i) * ∥v∥ : by rw finset.sum_mul ... = ↑(∑ i, C i) * ∥v∥ : by rw nnreal.coe_sum, rintro i -, calc ∥f i (v i)∥ ≤ C i * ∥v i∥ : (hC i) _ ... ≤ C i * ∥v∥ : mul_le_mul le_rfl (norm_le_pi_norm _ _) (norm_nonneg _) (C i).coe_nonneg end def mk_from_pi'_bound_by {ι : Type} [fintype ι] (V : ι → Type*) [Π i, normed_group (V i)] (W : Type*) [normed_group W] (f : Π i, normed_group_hom (V i) W) (C : ι → ℝ≥0) (hC : ∀ i, (f i).bound_by (C i)) : (mk_from_pi' _ _ f C hC).bound_by (∑ i, C i) := mk'_bound_by _ _ _ def mk_from_pi {ι : Type} [fintype ι] (V : ι → Type*) [Π i, normed_group (V i)] (W : Type*) [normed_group W] (f : Π i, normed_group_hom (V i) W) : normed_group_hom (Π i, V i) W := mk_from_pi' _ _ f (λ i, classical.some (f i).bound) $ λ i, (classical.some_spec (f i).bound).2 end normed_group_hom end
f0f90aba3b1b7ecf24978fd9da785fdd18cf3a9b
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/polynomial/field_division.lean
a4a35a4936ef3f308cb01f6a9fe72180761b3a6b
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,831
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import algebra.gcd_monoid.basic import data.polynomial.derivative import data.polynomial.ring_division import ring_theory.euclidean_domain /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ noncomputable theory open_locale classical big_operators namespace polynomial universes u v w y z variables {R : Type u} {S : Type v} {k : Type y} {A : Type z} {a b : R} {n : ℕ} section integral_domain variables [integral_domain R] [normalization_monoid R] instance : normalization_monoid (polynomial R) := { norm_unit := λ p, ⟨C ↑(norm_unit (p.leading_coeff)), C ↑(norm_unit (p.leading_coeff))⁻¹, by rw [← ring_hom.map_mul, units.mul_inv, C_1], by rw [← ring_hom.map_mul, units.inv_mul, C_1]⟩, norm_unit_zero := units.ext (by simp), norm_unit_mul := λ p q hp0 hq0, units.ext (begin dsimp, rw [ne.def, ← leading_coeff_eq_zero] at *, rw [leading_coeff_mul, norm_unit_mul hp0 hq0, units.coe_mul, C_mul], end), norm_unit_coe_units := λ u, units.ext begin rw [← mul_one u⁻¹, units.coe_mul, units.eq_inv_mul_iff_mul_eq], dsimp, rcases polynomial.is_unit_iff.1 ⟨u, rfl⟩ with ⟨_, ⟨w, rfl⟩, h2⟩, rw [← h2, leading_coeff_C, norm_unit_coe_units, ← C_mul, units.mul_inv, C_1], end } @[simp] lemma coe_norm_unit {p : polynomial R} : (norm_unit p : polynomial R) = C ↑(norm_unit p.leading_coeff) := by simp [norm_unit] lemma leading_coeff_normalize (p : polynomial R) : leading_coeff (normalize p) = normalize (leading_coeff p) := by simp end integral_domain section field variables [field R] {p q : polynomial R} lemma is_unit_iff_degree_eq_zero : is_unit p ↔ degree p = 0 := ⟨degree_eq_zero_of_is_unit, λ h, have degree p ≤ 0, by simp [*, le_refl], have hc : coeff p 0 ≠ 0, from λ hc, by rw [eq_C_of_degree_le_zero this, hc] at h; simpa using h, is_unit_iff_dvd_one.2 ⟨C (coeff p 0)⁻¹, begin conv in p { rw eq_C_of_degree_le_zero this }, rw [← C_mul, _root_.mul_inv_cancel hc, C_1] end⟩⟩ lemma degree_pos_of_ne_zero_of_nonunit (hp0 : p ≠ 0) (hp : ¬is_unit p) : 0 < degree p := lt_of_not_ge (λ h, begin rw [eq_C_of_degree_le_zero h] at hp0 hp, exact hp (is_unit.map (C.to_monoid_hom : R →* _) (is_unit.mk0 (coeff p 0) (mt C_inj.2 (by simpa using hp0)))), end) lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (p : polynomial R) (h : q ≠ 0) : degree (p * C (leading_coeff q)⁻¹) = degree p := have h₁ : (leading_coeff q)⁻¹ ≠ 0 := inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul, degree_C h₁, add_zero] theorem irreducible_of_monic {p : polynomial R} (hp1 : p.monic) (hp2 : p ≠ 1) : irreducible p ↔ (∀ f g : polynomial R, f.monic → g.monic → f * g = p → f = 1 ∨ g = 1) := ⟨λ hp3 f g hf hg hfg, or.cases_on (hp3.is_unit_or_is_unit hfg.symm) (assume huf : is_unit f, or.inl $ eq_one_of_is_unit_of_monic hf huf) (assume hug : is_unit g, or.inr $ eq_one_of_is_unit_of_monic hg hug), λ hp3, ⟨mt (eq_one_of_is_unit_of_monic hp1) hp2, λ f g hp, have hf : f ≠ 0, from λ hf, by { rw [hp, hf, zero_mul] at hp1, exact not_monic_zero hp1 }, have hg : g ≠ 0, from λ hg, by { rw [hp, hg, mul_zero] at hp1, exact not_monic_zero hp1 }, or.imp (λ hf, is_unit_of_mul_eq_one _ _ hf) (λ hg, is_unit_of_mul_eq_one _ _ hg) $ hp3 (f * C f.leading_coeff⁻¹) (g * C g.leading_coeff⁻¹) (monic_mul_leading_coeff_inv hf) (monic_mul_leading_coeff_inv hg) $ by rw [mul_assoc, mul_left_comm _ g, ← mul_assoc, ← C_mul, ← mul_inv', ← leading_coeff_mul, ← hp, monic.def.1 hp1, inv_one, C_1, mul_one]⟩⟩ /-- Division of polynomials. See polynomial.div_by_monic for more details.-/ def div (p q : polynomial R) := C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) /-- Remainder of polynomial division, see the lemma `quotient_mul_add_remainder_eq_aux`. See polynomial.mod_by_monic for more details. -/ def mod (p q : polynomial R) := p %ₘ (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial R) : q * div p q + mod p q = p := if h : q = 0 then by simp only [h, zero_mul, mod, mod_by_monic_zero, zero_add] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [div, mod, add_comm, mul_assoc] end private lemma remainder_lt_aux (p : polynomial R) (hq : q ≠ 0) : degree (mod p q) < degree q := by rw ← degree_mul_leading_coeff_inv q hq; exact degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq) (mul_ne_zero hq (mt leading_coeff_eq_zero.2 (by rw leading_coeff_C; exact inv_ne_zero (mt leading_coeff_eq_zero.1 hq)))) instance : has_div (polynomial R) := ⟨div⟩ instance : has_mod (polynomial R) := ⟨mod⟩ lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl lemma mod_by_monic_eq_mod (p : polynomial R) (hq : monic q) : p %ₘ q = p % q := show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp only [monic.def.1 hq, inv_one, mul_one, C_1] lemma div_by_monic_eq_div (p : polynomial R) (hq : monic q) : p /ₘ q = p / q := show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)), by simp only [monic.def.1 hq, inv_one, C_1, one_mul, mul_one] lemma mod_X_sub_C_eq_C_eval (p : polynomial R) (a : R) : p % (X - C a) = C (p.eval a) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _ lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root instance : euclidean_domain (polynomial R) := { quotient := (/), quotient_zero := by simp [div_def], remainder := (%), r := _, r_well_founded := degree_lt_wf, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, remainder_lt := λ p q hq, remainder_lt_aux _ hq, mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq), .. polynomial.comm_ring, .. polynomial.nontrivial } lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := ⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0, λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p := not_le_of_gt $ by rwa degree_mul_leading_coeff_inv q hq0, begin rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)], unfold div_mod_by_monic_aux, simp only [this, false_and, if_false] end⟩ lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := ⟨λ h, by have := euclidean_domain.div_add_mod p q; rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this, λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹), by rwa degree_mul_leading_coeff_inv q hq0, have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0, by rw [div_def, (div_by_monic_eq_zero_iff hm (ne_zero_of_monic hm)).2 hlt, mul_zero]⟩ lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := have degree (p % q) < degree (q * (p / q)) := calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0 ... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)), by conv_rhs { rw [← euclidean_domain.div_add_mod p q, degree_add_eq_left_of_degree_lt this, degree_mul] } lemma degree_div_le (p q : polynomial R) : degree (p / q) ≤ degree p := if hq : q = 0 then by simp [hq] else by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq]; exact degree_div_by_monic_le _ _ lemma degree_div_lt (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p := have hq0 : q ≠ 0, from λ hq0, by simpa [hq0] using hq, by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq0]; exact degree_div_by_monic_lt _ (monic_mul_leading_coeff_inv hq0) hp (by rw degree_mul_leading_coeff_inv _ hq0; exact hq) @[simp] lemma degree_map [field k] (p : polynomial R) (f : R →+* k) : degree (p.map f) = degree p := p.degree_map_eq_of_injective f.injective @[simp] lemma nat_degree_map [field k] (f : R →+* k) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map _ f) @[simp] lemma leading_coeff_map [field k] (f : R →+* k) : leading_coeff (p.map f) = f (leading_coeff p) := by simp only [← coeff_nat_degree, coeff_map f, nat_degree_map] theorem monic_map_iff [field k] {f : R →+* k} {p : polynomial R} : (p.map f).monic ↔ p.monic := by rw [monic, leading_coeff_map, ← f.map_one, function.injective.eq_iff f.injective, monic] theorem is_unit_map [field k] (f : R →+* k) : is_unit (p.map f) ↔ is_unit p := by simp_rw [is_unit_iff_degree_eq_zero, degree_map] lemma map_div [field k] (f : R →+* k) : (p / q).map f = p.map f / q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [div_def, div_def, map_mul, map_div_by_monic f (monic_mul_leading_coeff_inv hq0)]; simp [f.map_inv, coeff_map f] lemma map_mod [field k] (f : R →+* k) : (p % q).map f = p.map f % q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [mod_def, mod_def, leading_coeff_map f, ← f.map_inv, ← map_C f, ← map_mul f, map_mod_by_monic f (monic_mul_leading_coeff_inv hq0)] section open euclidean_domain theorem gcd_map [field k] (f : R →+* k) : gcd (p.map f) (q.map f) = (gcd p q).map f := gcd.induction p q (λ x, by simp_rw [map_zero, euclidean_domain.gcd_zero_left]) $ λ x y hx ih, by rw [gcd_val, ← map_mod, ih, ← gcd_val] end lemma eval₂_gcd_eq_zero [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hf : f.eval₂ ϕ α = 0) (hg : g.eval₂ ϕ α = 0) : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 := by rw [euclidean_domain.gcd_eq_gcd_ab f g, polynomial.eval₂_add, polynomial.eval₂_mul, polynomial.eval₂_mul, hf, hg, zero_mul, zero_mul, zero_add] lemma eval_gcd_eq_zero {f g : polynomial R} {α : R} (hf : f.eval α = 0) (hg : g.eval α = 0) : (euclidean_domain.gcd f g).eval α = 0 := eval₂_gcd_eq_zero hf hg lemma root_left_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : f.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_left f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_right_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : g.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_right f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_gcd_iff_root_left_right [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 ↔ (f.eval₂ ϕ α = 0) ∧ (g.eval₂ ϕ α = 0) := ⟨λ h, ⟨root_left_of_root_gcd h, root_right_of_root_gcd h⟩, λ h, eval₂_gcd_eq_zero h.1 h.2⟩ lemma is_root_gcd_iff_is_root_left_right {f g : polynomial R} {α : R} : (euclidean_domain.gcd f g).is_root α ↔ f.is_root α ∧ g.is_root α := root_gcd_iff_root_left_right theorem is_coprime_map [field k] (f : R →+* k) : is_coprime (p.map f) (q.map f) ↔ is_coprime p q := by rw [← gcd_is_unit_iff, ← gcd_is_unit_iff, gcd_map, is_unit_map] @[simp] lemma map_eq_zero [semiring S] [nontrivial S] (f : R →+* S) : p.map f = 0 ↔ p = 0 := by simp only [polynomial.ext_iff, f.map_eq_zero, coeff_map, coeff_zero] lemma map_ne_zero [semiring S] [nontrivial S] {f : R →+* S} (hp : p ≠ 0) : p.map f ≠ 0 := mt (map_eq_zero f).1 hp lemma mem_roots_map [field k] {f : R →+* k} {x : k} (hp : p ≠ 0) : x ∈ (p.map f).roots ↔ p.eval₂ f x = 0 := begin rw mem_roots (show p.map f ≠ 0, by exact map_ne_zero hp), dsimp only [is_root], rw polynomial.eval_map, end lemma mem_root_set [field k] [algebra R k] {x : k} (hp : p ≠ 0) : x ∈ p.root_set k ↔ aeval x p = 0 := iff.trans multiset.mem_to_finset (mem_roots_map hp) lemma root_set_C_mul_X_pow {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) {a : R} (ha : a ≠ 0) : (C a * X ^ n).root_set S = {0} := begin ext x, rw [set.mem_singleton_iff, mem_root_set, aeval_mul, aeval_C, aeval_X_pow, mul_eq_zero], { simp_rw [ring_hom.map_eq_zero, pow_eq_zero_iff (nat.pos_of_ne_zero hn), or_iff_right_iff_imp], exact λ ha', (ha ha').elim }, { exact mul_ne_zero (mt C_eq_zero.mp ha) (pow_ne_zero n X_ne_zero) }, end lemma root_set_monomial {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) {a : R} (ha : a ≠ 0) : (monomial n a).root_set S = {0} := by rw [←C_mul_X_pow_eq_monomial, root_set_C_mul_X_pow hn ha] lemma root_set_X_pow {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) : (X ^ n : polynomial R).root_set S = {0} := by { rw [←one_mul (X ^ n : polynomial R), ←C_1, root_set_C_mul_X_pow hn], exact one_ne_zero } lemma exists_root_of_degree_eq_one (h : degree p = 1) : ∃ x, is_root p x := ⟨-(p.coeff 0 / p.coeff 1), have p.coeff 1 ≠ 0, by rw ← nat_degree_eq_of_degree_eq_some h; exact mt leading_coeff_eq_zero.1 (λ h0, by simpa [h0] using h), by conv in p { rw [eq_X_add_C_of_degree_le_one (show degree p ≤ 1, by rw h; exact le_refl _)] }; simp [is_root, mul_div_cancel' _ this]⟩ lemma coeff_inv_units (u : units (polynomial R)) (n : ℕ) : ((↑u : polynomial R).coeff n)⁻¹ = ((↑u⁻¹ : polynomial R).coeff n) := begin rw [eq_C_of_degree_eq_zero (degree_coe_units u), eq_C_of_degree_eq_zero (degree_coe_units u⁻¹), coeff_C, coeff_C, inv_eq_one_div], split_ifs, { rw [div_eq_iff_mul_eq (coeff_coe_units_zero_ne_zero u), coeff_zero_eq_eval_zero, coeff_zero_eq_eval_zero, ← eval_mul, ← units.coe_mul, inv_mul_self]; simp }, { simp } end lemma monic_normalize (hp0 : p ≠ 0) : monic (normalize p) := begin rw [ne.def, ← leading_coeff_eq_zero, ← ne.def, ← is_unit_iff_ne_zero] at hp0, rw [monic, leading_coeff_normalize, normalize_eq_one], apply hp0, end lemma coe_norm_unit_of_ne_zero (hp : p ≠ 0) : (norm_unit p : polynomial R) = C p.leading_coeff⁻¹ := by simp [hp] lemma normalize_monic (h : monic p) : normalize p = p := by simp [h] theorem map_dvd_map' [field k] (f : R →+* k) {x y : polynomial R} : x.map f ∣ y.map f ↔ x ∣ y := if H : x = 0 then by rw [H, map_zero, zero_dvd_iff, zero_dvd_iff, map_eq_zero] else by rw [← normalize_dvd_iff, ← @normalize_dvd_iff (polynomial R), normalize_apply, normalize_apply, coe_norm_unit_of_ne_zero H, coe_norm_unit_of_ne_zero (mt (map_eq_zero f).1 H), leading_coeff_map, ← f.map_inv, ← map_C, ← map_mul, map_dvd_map _ f.injective (monic_mul_leading_coeff_inv H)] lemma degree_normalize : degree (normalize p) = degree p := by simp lemma prime_of_degree_eq_one (hp1 : degree p = 1) : prime p := have prime (normalize p), from monic.prime_of_degree_eq_one (hp1 ▸ degree_normalize) (monic_normalize (λ hp0, absurd hp1 (hp0.symm ▸ by simp; exact dec_trivial))), (normalize_associated _).prime this lemma irreducible_of_degree_eq_one (hp1 : degree p = 1) : irreducible p := (prime_of_degree_eq_one hp1).irreducible theorem not_irreducible_C (x : R) : ¬irreducible (C x) := if H : x = 0 then by { rw [H, C_0], exact not_irreducible_zero } else λ hx, irreducible.not_unit hx $ is_unit_C.2 $ is_unit_iff_ne_zero.2 H theorem degree_pos_of_irreducible (hp : irreducible p) : 0 < p.degree := lt_of_not_ge $ λ hp0, have _ := eq_C_of_degree_le_zero hp0, not_irreducible_C (p.coeff 0) $ this ▸ hp theorem pairwise_coprime_X_sub {α : Type u} [field α] {I : Type v} {s : I → α} (H : function.injective s) : pairwise (is_coprime on (λ i : I, polynomial.X - polynomial.C (s i))) := λ i j hij, have h : s j - s i ≠ 0, from sub_ne_zero_of_ne $ function.injective.ne H hij.symm, ⟨polynomial.C (s j - s i)⁻¹, -polynomial.C (s j - s i)⁻¹, by rw [neg_mul_eq_neg_mul_symm, ← sub_eq_add_neg, ← mul_sub, sub_sub_sub_cancel_left, ← polynomial.C_sub, ← polynomial.C_mul, inv_mul_cancel h, polynomial.C_1]⟩ /-- If `f` is a polynomial over a field, and `a : K` satisfies `f' a ≠ 0`, then `f / (X - a)` is coprime with `X - a`. Note that we do not assume `f a = 0`, because `f / (X - a) = (f - f a) / (X - a)`. -/ lemma is_coprime_of_is_root_of_eval_derivative_ne_zero {K : Type*} [field K] (f : polynomial K) (a : K) (hf' : f.derivative.eval a ≠ 0) : is_coprime (X - C a : polynomial K) (f /ₘ (X - C a)) := begin refine or.resolve_left (dvd_or_coprime (X - C a) (f /ₘ (X - C a)) (irreducible_of_degree_eq_one (polynomial.degree_X_sub_C a))) _, contrapose! hf' with h, have key : (X - C a) * (f /ₘ (X - C a)) = f - (f %ₘ (X - C a)), { rw [eq_sub_iff_add_eq, ← eq_sub_iff_add_eq', mod_by_monic_eq_sub_mul_div], exact monic_X_sub_C a }, replace key := congr_arg derivative key, simp only [derivative_X, derivative_mul, one_mul, sub_zero, derivative_sub, mod_by_monic_X_sub_C_eq_C_eval, derivative_C] at key, have : (X - C a) ∣ derivative f := key ▸ (dvd_add h (dvd_mul_right _ _)), rw [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval] at this, rw [← C_inj, this, C_0], end lemma prod_multiset_root_eq_finset_root {p : polynomial R} (hzero : p ≠ 0) : (multiset.map (λ (a : R), X - C a) p.roots).prod = ∏ a in (multiset.to_finset p.roots), (λ (a : R), (X - C a) ^ (root_multiplicity a p)) a := by simp only [count_roots hzero, finset.prod_multiset_map_count] /-- The product `∏ (X - a)` for `a` inside the multiset `p.roots` divides `p`. -/ lemma prod_multiset_X_sub_C_dvd (p : polynomial R) : (multiset.map (λ (a : R), X - C a) p.roots).prod ∣ p := begin by_cases hp0 : p = 0, { simp only [hp0, roots_zero, is_unit_one, multiset.prod_zero, multiset.map_zero, is_unit.dvd] }, rw prod_multiset_root_eq_finset_root hp0, have hcoprime : pairwise (is_coprime on λ (a : R), polynomial.X - C (id a)) := pairwise_coprime_X_sub function.injective_id, have H : pairwise (is_coprime on λ (a : R), (polynomial.X - C (id a)) ^ (root_multiplicity a p)), { intros a b hdiff, exact (hcoprime a b hdiff).pow }, apply finset.prod_dvd_of_coprime (pairwise.pairwise_on H (↑(multiset.to_finset p.roots) : set R)), intros a h, rw multiset.mem_to_finset at h, exact pow_root_multiplicity_dvd p a end lemma roots_C_mul (p : polynomial R) {a : R} (hzero : a ≠ 0) : (C a * p).roots = p.roots := begin by_cases hpzero : p = 0, { simp only [hpzero, mul_zero] }, rw multiset.ext, intro b, have prodzero : C a * p ≠ 0, { simp only [hpzero, or_false, ne.def, mul_eq_zero, C_eq_zero, hzero, not_false_iff] }, rw [count_roots hpzero, count_roots prodzero, root_multiplicity_mul prodzero], have mulzero : root_multiplicity b (C a) = 0, { simp only [hzero, root_multiplicity_eq_zero, eval_C, is_root.def, not_false_iff] }, simp only [mulzero, zero_add] end lemma roots_normalize : (normalize p).roots = p.roots := begin by_cases hzero : p = 0, { rw [hzero, normalize_zero], }, { have hcoeff : p.leading_coeff ≠ 0, { intro h, exact hzero (leading_coeff_eq_zero.1 h) }, rw [normalize_apply, mul_comm, coe_norm_unit_of_ne_zero hzero, roots_C_mul _ (inv_ne_zero hcoeff)], }, end end field end polynomial
e6bd4a680b3ced11e83ee181d10277bf171a2b41
41ebf3cb010344adfa84907b3304db00e02db0a6
/uexp/test/TDP_test.lean
6a00eff22570d2ce71a8a1f3a5b7d712a5a34179
[ "BSD-2-Clause" ]
permissive
ReinierKoops/Cosette
e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb
eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29
refs/heads/master
1,686,483,953,198
1,624,293,498,000
1,624,293,498,000
378,997,885
0
0
BSD-2-Clause
1,624,293,485,000
1,624,293,484,000
null
UTF-8
Lean
false
false
1,730
lean
import ..src.uexp.meta.TDP import ..src.uexp.meta.cosette_tactics open list example {p q r s} {f : Tuple p → Tuple q → Tuple r → Tuple s → usr} : (∑ (a : Tuple p) (b : Tuple q) (c : Tuple r) (d : Tuple s), f a b c d) = (∑ (c : Tuple r) (a : Tuple p) (d : Tuple s) (b : Tuple q), f a b c d) := begin TDP' tactic.ac_refl, end example {p} {R S: Tuple p → usr} : (∑ (a b: Tuple p), R a * S b * S b) = (∑ (a b: Tuple p), R b * S a * S a) := begin TDP' tactic.ac_refl, end example {p} {R: Tuple p → usr} {b t: Tuple p}: (∑ (a: Tuple p), (a ≃ t) * R a * R b) = R t * R b := begin normalize_sig_body_lhs, removal_step, ac_refl, end example {p q} {R S: Tuple p → usr} {t: Tuple p} : (∑ (a b: Tuple p) (c: Tuple q), (a ≃ b) * R a * R b) = (∑ (t: Tuple p) (c: Tuple q), R t * R t) := begin normalize_sig_body_lhs, removal_step, refl, end example {r p} {R: Tuple r → usr} : (∑ (a1 a2 a3: Tuple r) (b c: Tuple p), (a2 ≃ a1) * (a2 ≃ a3) * (c ≃ b) * (R a1)) = (∑ (a: Tuple r)(b: Tuple p), R a) := begin remove_dup_sigs_lhs, refl, end example {p} {R: Tuple p → usr} {b t: Tuple p}: R t * R b = (∑ (a: Tuple p), (a ≃ t) * R a * R b) := begin apply ueq_symm, remove_dup_sigs_lhs, ac_refl, end example {r p} {R: Tuple r → usr} {k: Tuple (r++r)}: (∑ (a1 a2 a3: Tuple r) (b c: Tuple p), (k ≃ (pair a3 a2)) * (c ≃ b) * (R a1)) = (∑ (a: Tuple r)(b: Tuple p), R a) := begin unfold pair, remove_dup_sigs_lhs, print_size, ac_refl end example {r} {R: Tuple r → usr}: (∑ (a1), (∑ (a2: Tuple r), (a2 ≃ a1) * R a2 ) * R a1) = (∑ (t: Tuple r), R t * R t) := begin --remove_dup_sigs_lhs, simp, TDP, end
dd936840c34d1eb9e977a129000dd0f9429c6cf6
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/star/basic.lean
c3550fa6430b9280efdb058cb293c48574bab77b
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
17,524
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.ring.aut import algebra.ring.comp_typeclasses import data.rat.cast import group_theory.group_action.opposite /-! # Star monoids, rings, and modules We introduce the basic algebraic notions of star monoids, star rings, and star modules. A star algebra is simply a star ring that is also a star module. These are implemented as "mixin" typeclasses, so to summon a star ring (for example) one needs to write `(R : Type) [ring R] [star_ring R]`. This avoids difficulties with diamond inheritance. We also define the class `star_ordered_ring R`, which says that the order on `R` respects the star operation, i.e. an element `r` is nonnegative iff there exists an `s` such that `r = star s * s`. For now we simply do not introduce notations, as different users are expected to feel strongly about the relative merits of `r^*`, `r†`, `rᘁ`, and so on. Our star rings are actually star semirings, but of course we can prove `star_neg : star (-r) = - star r` when the underlying semiring is a ring. ## TODO * In a Banach star algebra without a well-defined square root, the natural ordering is given by the positive cone which is the closure of the sums of elements `star r * r`. A weaker version of `star_ordered_ring` could be defined for this case. Note that the current definition has the advantage of not requiring a topology. -/ universes u v open mul_opposite /-- Notation typeclass (with no default notation!) for an algebraic structure with a star operation. -/ class has_star (R : Type u) := (star : R → R) variables {R : Type u} export has_star (star) /-- A star operation (e.g. complex conjugate). -/ add_decl_doc star /-- Typeclass for a star operation with is involutive. -/ class has_involutive_star (R : Type u) extends has_star R := (star_involutive : function.involutive star) export has_involutive_star (star_involutive) @[simp] lemma star_star [has_involutive_star R] (r : R) : star (star r) = r := star_involutive _ lemma star_injective [has_involutive_star R] : function.injective (star : R → R) := star_involutive.injective /-- `star` as an equivalence when it is involutive. -/ protected def equiv.star [has_involutive_star R] : equiv.perm R := star_involutive.to_perm _ lemma eq_star_of_eq_star [has_involutive_star R] {r s : R} (h : r = star s) : s = star r := by simp [h] lemma eq_star_iff_eq_star [has_involutive_star R] {r s : R} : r = star s ↔ s = star r := ⟨eq_star_of_eq_star, eq_star_of_eq_star⟩ lemma star_eq_iff_star_eq [has_involutive_star R] {r s : R} : star r = s ↔ star s = r := eq_comm.trans $ eq_star_iff_eq_star.trans eq_comm /-- Typeclass for a trivial star operation. This is mostly meant for `ℝ`. -/ class has_trivial_star (R : Type u) [has_star R] : Prop := (star_trivial : ∀ (r : R), star r = r) export has_trivial_star (star_trivial) attribute [simp] star_trivial /-- A `*`-semigroup is a semigroup `R` with an involutive operations `star` so `star (r * s) = star s * star r`. -/ class star_semigroup (R : Type u) [semigroup R] extends has_involutive_star R := (star_mul : ∀ r s : R, star (r * s) = star s * star r) export star_semigroup (star_mul) attribute [simp] star_mul /-- In a commutative ring, make `simp` prefer leaving the order unchanged. -/ @[simp] lemma star_mul' [comm_semigroup R] [star_semigroup R] (x y : R) : star (x * y) = star x * star y := (star_mul x y).trans (mul_comm _ _) /-- `star` as an `mul_equiv` from `R` to `Rᵐᵒᵖ` -/ @[simps apply] def star_mul_equiv [semigroup R] [star_semigroup R] : R ≃* Rᵐᵒᵖ := { to_fun := λ x, mul_opposite.op (star x), map_mul' := λ x y, (star_mul x y).symm ▸ (mul_opposite.op_mul _ _), ..(has_involutive_star.star_involutive.to_perm star).trans op_equiv} /-- `star` as a `mul_aut` for commutative `R`. -/ @[simps apply] def star_mul_aut [comm_semigroup R] [star_semigroup R] : mul_aut R := { to_fun := star, map_mul' := star_mul', ..(has_involutive_star.star_involutive.to_perm star) } variables (R) @[simp] lemma star_one [monoid R] [star_semigroup R] : star (1 : R) = 1 := op_injective $ (star_mul_equiv : R ≃* Rᵐᵒᵖ).map_one.trans (op_one _).symm variables {R} @[simp] lemma star_pow [monoid R] [star_semigroup R] (x : R) (n : ℕ) : star (x ^ n) = star x ^ n := op_injective $ ((star_mul_equiv : R ≃* Rᵐᵒᵖ).to_monoid_hom.map_pow x n).trans (op_pow (star x) n).symm @[simp] lemma star_inv [group R] [star_semigroup R] (x : R) : star (x⁻¹) = (star x)⁻¹ := op_injective $ ((star_mul_equiv : R ≃* Rᵐᵒᵖ).to_monoid_hom.map_inv x).trans (op_inv (star x)).symm @[simp] lemma star_zpow [group R] [star_semigroup R] (x : R) (z : ℤ) : star (x ^ z) = star x ^ z := op_injective $ ((star_mul_equiv : R ≃* Rᵐᵒᵖ).to_monoid_hom.map_zpow x z).trans (op_zpow (star x) z).symm /-- When multiplication is commutative, `star` preserves division. -/ @[simp] lemma star_div [comm_group R] [star_semigroup R] (x y : R) : star (x / y) = star x / star y := map_div (star_mul_aut : R ≃* R) _ _ section open_locale big_operators @[simp] lemma star_prod [comm_monoid R] [star_semigroup R] {α : Type*} (s : finset α) (f : α → R): star (∏ x in s, f x) = ∏ x in s, star (f x) := map_prod (star_mul_aut : R ≃* R) _ _ end /-- Any commutative monoid admits the trivial `*`-structure. See note [reducible non-instances]. -/ @[reducible] def star_semigroup_of_comm {R : Type*} [comm_monoid R] : star_semigroup R := { star := id, star_involutive := λ x, rfl, star_mul := mul_comm } section local attribute [instance] star_semigroup_of_comm /-- Note that since `star_semigroup_of_comm` is reducible, `simp` can already prove this. --/ lemma star_id_of_comm {R : Type*} [comm_semiring R] {x : R} : star x = x := rfl end /-- A `*`-additive monoid `R` is an additive monoid with an involutive `star` operation which preserves addition. -/ class star_add_monoid (R : Type u) [add_monoid R] extends has_involutive_star R := (star_add : ∀ r s : R, star (r + s) = star r + star s) export star_add_monoid (star_add) attribute [simp] star_add /-- `star` as an `add_equiv` -/ @[simps apply] def star_add_equiv [add_monoid R] [star_add_monoid R] : R ≃+ R := { to_fun := star, map_add' := star_add, ..(has_involutive_star.star_involutive.to_perm star)} variables (R) @[simp] lemma star_zero [add_monoid R] [star_add_monoid R] : star (0 : R) = 0 := (star_add_equiv : R ≃+ R).map_zero variables {R} @[simp] lemma star_eq_zero [add_monoid R] [star_add_monoid R] {x : R} : star x = 0 ↔ x = 0 := star_add_equiv.map_eq_zero_iff lemma star_ne_zero [add_monoid R] [star_add_monoid R] {x : R} : star x ≠ 0 ↔ x ≠ 0 := star_eq_zero.not @[simp] lemma star_neg [add_group R] [star_add_monoid R] (r : R) : star (-r) = - star r := (star_add_equiv : R ≃+ R).map_neg _ @[simp] lemma star_sub [add_group R] [star_add_monoid R] (r s : R) : star (r - s) = star r - star s := (star_add_equiv : R ≃+ R).map_sub _ _ @[simp] lemma star_nsmul [add_monoid R] [star_add_monoid R] (x : R) (n : ℕ) : star (n • x) = n • star x := (star_add_equiv : R ≃+ R).to_add_monoid_hom.map_nsmul _ _ @[simp] lemma star_zsmul [add_group R] [star_add_monoid R] (x : R) (n : ℤ) : star (n • x) = n • star x := (star_add_equiv : R ≃+ R).to_add_monoid_hom.map_zsmul _ _ section open_locale big_operators @[simp] lemma star_sum [add_comm_monoid R] [star_add_monoid R] {α : Type*} (s : finset α) (f : α → R): star (∑ x in s, f x) = ∑ x in s, star (f x) := (star_add_equiv : R ≃+ R).map_sum _ _ end /-- A `*`-ring `R` is a (semi)ring with an involutive `star` operation which is additive which makes `R` with its multiplicative structure into a `*`-semigroup (i.e. `star (r * s) = star s * star r`). -/ class star_ring (R : Type u) [non_unital_semiring R] extends star_semigroup R := (star_add : ∀ r s : R, star (r + s) = star r + star s) @[priority 100] instance star_ring.to_star_add_monoid [non_unital_semiring R] [star_ring R] : star_add_monoid R := { star_add := star_ring.star_add } /-- `star` as an `ring_equiv` from `R` to `Rᵐᵒᵖ` -/ @[simps apply] def star_ring_equiv [non_unital_semiring R] [star_ring R] : R ≃+* Rᵐᵒᵖ := { to_fun := λ x, mul_opposite.op (star x), ..star_add_equiv.trans (mul_opposite.op_add_equiv : R ≃+ Rᵐᵒᵖ), ..star_mul_equiv } @[simp, norm_cast] lemma star_nat_cast [semiring R] [star_ring R] (n : ℕ) : star (n : R) = n := (congr_arg unop (map_nat_cast (star_ring_equiv : R ≃+* Rᵐᵒᵖ) n)).trans (unop_nat_cast _) @[simp, norm_cast] lemma star_int_cast [ring R] [star_ring R] (z : ℤ) : star (z : R) = z := (congr_arg unop $ map_int_cast (star_ring_equiv : R ≃+* Rᵐᵒᵖ) z).trans (unop_int_cast _) @[simp, norm_cast] lemma star_rat_cast [division_ring R] [star_ring R] (r : ℚ) : star (r : R) = r := (congr_arg unop $ map_rat_cast (star_ring_equiv : R ≃+* Rᵐᵒᵖ) r).trans (unop_rat_cast _) /-- `star` as a ring automorphism, for commutative `R`. -/ @[simps apply] def star_ring_aut [comm_semiring R] [star_ring R] : ring_aut R := { to_fun := star, ..star_add_equiv, ..star_mul_aut } variables (R) /-- `star` as a ring endomorphism, for commutative `R`. This is used to denote complex conjugation, and is available under the notation `conj` in the locale `complex_conjugate`. Note that this is the preferred form (over `star_ring_aut`, available under the same hypotheses) because the notation `E →ₗ⋆[R] F` for an `R`-conjugate-linear map (short for `E →ₛₗ[star_ring_end R] F`) does not pretty-print if there is a coercion involved, as would be the case for `(↑star_ring_aut : R →* R)`. -/ def star_ring_end [comm_semiring R] [star_ring R] : R →+* R := @star_ring_aut R _ _ variables {R} localized "notation (name := star_ring_end) `conj` := star_ring_end hole!" in complex_conjugate /-- This is not a simp lemma, since we usually want simp to keep `star_ring_end` bundled. For example, for complex conjugation, we don't want simp to turn `conj x` into the bare function `star x` automatically since most lemmas are about `conj x`. -/ lemma star_ring_end_apply [comm_semiring R] [star_ring R] {x : R} : star_ring_end R x = star x := rfl @[simp] lemma star_ring_end_self_apply [comm_semiring R] [star_ring R] (x : R) : star_ring_end R (star_ring_end R x) = x := star_star x -- A more convenient name for complex conjugation alias star_ring_end_self_apply ← complex.conj_conj alias star_ring_end_self_apply ← is_R_or_C.conj_conj @[simp] lemma star_inv' [division_ring R] [star_ring R] (x : R) : star (x⁻¹) = (star x)⁻¹ := op_injective $ (map_inv₀ (star_ring_equiv : R ≃+* Rᵐᵒᵖ) x).trans (op_inv (star x)).symm @[simp] lemma star_zpow₀ [division_ring R] [star_ring R] (x : R) (z : ℤ) : star (x ^ z) = star x ^ z := op_injective $ (map_zpow₀ (star_ring_equiv : R ≃+* Rᵐᵒᵖ) x z).trans (op_zpow (star x) z).symm /-- When multiplication is commutative, `star` preserves division. -/ @[simp] lemma star_div' [field R] [star_ring R] (x y : R) : star (x / y) = star x / star y := map_div₀ (star_ring_end R) _ _ @[simp] lemma star_bit0 [add_monoid R] [star_add_monoid R] (r : R) : star (bit0 r) = bit0 (star r) := by simp [bit0] @[simp] lemma star_bit1 [semiring R] [star_ring R] (r : R) : star (bit1 r) = bit1 (star r) := by simp [bit1] /-- Any commutative semiring admits the trivial `*`-structure. See note [reducible non-instances]. -/ @[reducible] def star_ring_of_comm {R : Type*} [comm_semiring R] : star_ring R := { star := id, star_add := λ x y, rfl, ..star_semigroup_of_comm } /-- An ordered `*`-ring is a ring which is both an `ordered_add_comm_group` and a `*`-ring, and `0 ≤ r ↔ ∃ s, r = star s * s`. -/ class star_ordered_ring (R : Type u) [non_unital_semiring R] [partial_order R] extends star_ring R := (add_le_add_left : ∀ a b : R, a ≤ b → ∀ c : R, c + a ≤ c + b) (nonneg_iff : ∀ r : R, 0 ≤ r ↔ ∃ s, r = star s * s) namespace star_ordered_ring variables [ring R] [partial_order R] [star_ordered_ring R] @[priority 100] -- see note [lower instance priority] instance : ordered_add_comm_group R := { ..show ring R, by apply_instance, ..show partial_order R, by apply_instance, ..show star_ordered_ring R, by apply_instance } end star_ordered_ring lemma star_mul_self_nonneg [non_unital_semiring R] [partial_order R] [star_ordered_ring R] {r : R} : 0 ≤ star r * r := (star_ordered_ring.nonneg_iff _).mpr ⟨r, rfl⟩ lemma star_mul_self_nonneg' [non_unital_semiring R] [partial_order R] [star_ordered_ring R] {r : R} : 0 ≤ r * star r := by { nth_rewrite_rhs 0 [←star_star r], exact star_mul_self_nonneg } /-- A star module `A` over a star ring `R` is a module which is a star add monoid, and the two star structures are compatible in the sense `star (r • a) = star r • star a`. Note that it is up to the user of this typeclass to enforce `[semiring R] [star_ring R] [add_comm_monoid A] [star_add_monoid A] [module R A]`, and that the statement only requires `[has_star R] [has_star A] [has_smul R A]`. If used as `[comm_ring R] [star_ring R] [semiring A] [star_ring A] [algebra R A]`, this represents a star algebra. -/ class star_module (R : Type u) (A : Type v) [has_star R] [has_star A] [has_smul R A] : Prop := (star_smul : ∀ (r : R) (a : A), star (r • a) = star r • star a) export star_module (star_smul) attribute [simp] star_smul /-- A commutative star monoid is a star module over itself via `monoid.to_mul_action`. -/ instance star_semigroup.to_star_module [comm_monoid R] [star_semigroup R] : star_module R R := ⟨star_mul'⟩ namespace ring_hom_inv_pair /-- Instance needed to define star-linear maps over a commutative star ring (ex: conjugate-linear maps when R = ℂ). -/ instance [comm_semiring R] [star_ring R] : ring_hom_inv_pair (star_ring_end R) (star_ring_end R) := ⟨ring_hom.ext star_star, ring_hom.ext star_star⟩ end ring_hom_inv_pair section set_option old_structure_cmd true /-- `star_hom_class F R S` states that `F` is a type of `star`-preserving maps from `R` to `S`. -/ class star_hom_class (F : Type*) (R S : out_param Type*) [has_star R] [has_star S] extends fun_like F R (λ _, S) := (map_star : ∀ (f : F) (r : R), f (star r) = star (f r)) export star_hom_class (map_star) end /-! ### Instances -/ namespace units variables [monoid R] [star_semigroup R] instance : star_semigroup Rˣ := { star := λ u, { val := star u, inv := star ↑u⁻¹, val_inv := (star_mul _ _).symm.trans $ (congr_arg star u.inv_val).trans $ star_one _, inv_val := (star_mul _ _).symm.trans $ (congr_arg star u.val_inv).trans $ star_one _ }, star_involutive := λ u, units.ext (star_involutive _), star_mul := λ u v, units.ext (star_mul _ _) } @[simp] lemma coe_star (u : Rˣ) : ↑(star u) = (star ↑u : R) := rfl @[simp] lemma coe_star_inv (u : Rˣ) : ↑(star u)⁻¹ = (star ↑u⁻¹ : R) := rfl instance {A : Type*} [has_star A] [has_smul R A] [star_module R A] : star_module Rˣ A := ⟨λ u a, (star_smul ↑u a : _)⟩ end units lemma is_unit.star [monoid R] [star_semigroup R] {a : R} : is_unit a → is_unit (star a) | ⟨u, hu⟩ := ⟨star u, hu ▸ rfl⟩ @[simp] lemma is_unit_star [monoid R] [star_semigroup R] {a : R} : is_unit (star a) ↔ is_unit a := ⟨λ h, star_star a ▸ h.star, is_unit.star⟩ lemma ring.inverse_star [semiring R] [star_ring R] (a : R) : ring.inverse (star a) = star (ring.inverse a) := begin by_cases ha : is_unit a, { obtain ⟨u, rfl⟩ := ha, rw [ring.inverse_unit, ←units.coe_star, ring.inverse_unit, ←units.coe_star_inv], }, rw [ring.inverse_non_unit _ ha, ring.inverse_non_unit _ (mt is_unit_star.mp ha), star_zero], end instance invertible.star {R : Type*} [monoid R] [star_semigroup R] (r : R) [invertible r] : invertible (star r) := { inv_of := star (⅟r), inv_of_mul_self := by rw [←star_mul, mul_inv_of_self, star_one], mul_inv_of_self := by rw [←star_mul, inv_of_mul_self, star_one] } lemma star_inv_of {R : Type*} [monoid R] [star_semigroup R] (r : R) [invertible r] [invertible (star r)] : star (⅟r) = ⅟(star r) := by { letI := invertible.star r, convert (rfl : star (⅟r) = _) } namespace mul_opposite /-- The opposite type carries the same star operation. -/ instance [has_star R] : has_star (Rᵐᵒᵖ) := { star := λ r, op (star (r.unop)) } @[simp] lemma unop_star [has_star R] (r : Rᵐᵒᵖ) : unop (star r) = star (unop r) := rfl @[simp] lemma op_star [has_star R] (r : R) : op (star r) = star (op r) := rfl instance [has_involutive_star R] : has_involutive_star (Rᵐᵒᵖ) := { star_involutive := λ r, unop_injective (star_star r.unop) } instance [monoid R] [star_semigroup R] : star_semigroup (Rᵐᵒᵖ) := { star_mul := λ x y, unop_injective (star_mul y.unop x.unop) } instance [add_monoid R] [star_add_monoid R] : star_add_monoid (Rᵐᵒᵖ) := { star_add := λ x y, unop_injective (star_add x.unop y.unop) } instance [semiring R] [star_ring R] : star_ring (Rᵐᵒᵖ) := { .. mul_opposite.star_add_monoid } end mul_opposite /-- A commutative star monoid is a star module over its opposite via `monoid.to_opposite_mul_action`. -/ instance star_semigroup.to_opposite_star_module [comm_monoid R] [star_semigroup R] : star_module Rᵐᵒᵖ R := ⟨λ r s, star_mul' s r.unop⟩
9e77084bdf70a04af4fc4ab6df4a6c0eaf98bde6
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Meta/Tactic.lean
f8dc0255a5734220fd04c701acef345ff4bc6793
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
712
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Assumption import Lean.Meta.Tactic.Contradiction import Lean.Meta.Tactic.Apply import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Rewrite import Lean.Meta.Tactic.Generalize import Lean.Meta.Tactic.Replace import Lean.Meta.Tactic.Induction import Lean.Meta.Tactic.Cases import Lean.Meta.Tactic.ElimInfo import Lean.Meta.Tactic.Delta import Lean.Meta.Tactic.Constructor import Lean.Meta.Tactic.Simp import Lean.Meta.Tactic.AuxLemma
112e990bd4e7af7a3c1c33041089da3d36313b51
70f065bb7bcce71301a0b7f8542ed0157358a740
/lean/perm.lean
6d33b418a0d6bcf435285891f67fbc0906e00687
[ "Apache-2.0", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
lambdageek/coda
0ff93e32d477be834e997955f04787d116bc0b0e
6cca584fca7af1a3d20df2eacf26ee3e7e34d0c7
refs/heads/master
1,586,044,462,939
1,540,629,980,000
1,540,629,980,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,262
lean
open function open nat -- seeking some position i, currently at some position n. -- todo: convert a cursor to a Prop def cursor (n s i k: ℕ) := n + s * k = i ∧ s > 0 -- k = 0 → i = n def start(i: ℕ) : cursor 0 1 i i := begin -- apply (@cursor.mk 0 1 i i), apply and.intro, rw [zero_add, one_mul], from nat.zero_lt_one_add 0, end inductive action :Π (n s i k: ℕ), cursor n s i k → Type | stop: Π (n s i: ℕ) (c : cursor n s i 0), action n s i 0 c | left: Π (n s i k: ℕ) (c : cursor n s i k), (k - 1) % 2 = 0 → cursor (n + s) (s*2) i ((k-1)/2) → action n s i k c | right: Π (n s i k: ℕ) (c : cursor n s i k), (k - 1) % 2 = 1 → cursor (n + 2 * s) (s*2) i ((k-1)/2) → action n s i k c private def lt_not_gt (m n: ℕ) (mn : m < n): ¬ m ≥ n := ((@nat.lt_iff_le_not_le m n).1 mn).2 def step: Π(n s i k : ℕ) (c : cursor n s i k), action n s i k c := begin introv, cases h : c with pi ps, cases k with km1, refine (action.stop n s i _), -- k = 0, stop have ds : s * 2 > 0, by rw [← nat.zero_mul 2]; from mul_lt_mul_of_pos_right ps (nat.zero_lt_one_add 1), have range: km1%2 < 2 := @nat.mod_lt km1 2 (nat.zero_lt_one_add 1), have sp : succ km1 - 1 = km1 := by simp, by_cases h2 : km1 % 2 <= 0, begin -- (k-1) % 2 = 0, go left apply action.left n s i (succ km1), from nat.eq_zero_of_le_zero h2, -- apply @cursor.mk (n+s) (s*2) i (km1/2) refine (and.intro _ ds), begin -- proof rw [sp, ← pi, nat.mul_assoc _ 2,← nat.zero_add (2*_), ← eq_zero_of_le_zero h2, mod_add_div], refine (eq.symm _), rw [← one_add km1, left_distrib, mul_one, ← add_assoc], end end, begin -- (k-1) % 2 = 1, go right have r_equals_1 : km1%2 = 1, begin cases h2 : km1 % 2, let c := nat.le_of_eq h2, contradiction, -- not 0 cases n_1, refl, -- exactly 1 exfalso, refine (lt_not_gt (km1%2) 2 range _), erw [h2], from succ_le_succ (succ_le_succ (zero_le n_1)) -- not 2+ end, apply action.right n s i, from r_equals_1, -- apply @cursor.mk (n+2*s) (s*2) i (km1/2) refine and.intro _ ds, begin -- proof rw [sp, mul_assoc, mul_comm _ s, add_assoc, ← left_distrib], have p11 : 2 + 2 * (km1 / 2) = 1 + 1 + 2 * (km1 / 2), by refl, have p1r : 1 + 1 = 1 + km1%2, by rw [r_equals_1], rw [p11, p1r, add_assoc, mod_add_div, add_comm 1 km1], from pi, end end end inductive T: Π(n s : ℕ) (occ : Prop), Type | tip : Π(n s: ℕ), T n s false | bin : Π (n s j: ℕ) (x y : Prop), n ≠ j ∨ x ∨ y → T (n+s) (2*s) x → T (n+2*s) (2*s) y → T n s true structure tree := (occ : Prop) (content: T 0 1 occ) -- def well_founded.fix_F : Π {α : Sort u} {r : α → α → Prop} {C : α → Sort v}, -- (Π (x : α), (Π (y : α), r y x → C y) → C x) → Π (x : α), acc r x → C x -- nat.well_founded -- induction on k def set.rec: Π (n s i j k: ℕ) (c: cursor n s i k) (o: Prop) (t : T n s o), Σ p : Prop, T n s p := begin simp_intros n s i j k c o t, let act := step n s i k c, cases hact: act, have ni : n = i := c_1.1; rw [ni]; from or.inl ij, cases ht: t, by_cases ij: i = j, -- i = j, stop, tip from sigma.mk false (T.tip n s), -- i /= j, stop, tip apply sigma.mk true, apply (T.bin n s j false false), apply T.tip, apply T.tip, by_cases ij: i = j, -- i = j, stop, bin cases ha_1: a_1, cases ha_2: a_2, -- tip/tip -> tip apply sigma.mk false, apply T.tip, -- bin/tip -> bin repeat { apply sigma.mk true, apply T.bin _ _ j _ _ _ a_1 a_2, simp }, -- i /= j, stop, bin apply sigma.mk true, apply T.bin n s j end -- def set (i j: ℕ) (t0: tree): tree := -- #reduce step 0 11 (start 11) -- simple implicit-heap-like navigation namespace dir @[simp] def u (i:ℕ) := (i-1)/2 @[simp] def l (i:ℕ) := i*2+1 @[simp] def r (i:ℕ) := i*2+2 def ul : left_inverse u l := begin delta u l left_inverse at ⊢, simp_intros i, rw [add_comm, nat.add_sub_cancel, nat.mul_div_cancel i (nat.zero_lt_one_add 1)], end def ur : left_inverse u r := begin delta u r left_inverse at ⊢, simp_intros i, erw [add_comm, nat.add_sub_cancel (i*2+1) 1, add_comm, mul_comm, nat.add_mul_div_left 1 i (nat.zero_lt_one_add 1), zero_add], end end dir
2033d42312c1ac2f798c676bc0e455a68d6af1aa
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/adjoin/basic.lean
a543ce028e8281152189a4c9315ea29e5e5c3fa1
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
11,959
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.algebra.tower import linear_algebra.prod import linear_algebra.finsupp /-! # Adjoining elements to form subalgebras This file develops the basic theory of subalgebras of an R-algebra generated by a set of elements. A basic interface for `adjoin` is set up. ## Tags adjoin, algebra -/ universes u v w open_locale pointwise open submodule subsemiring variables {R : Type u} {A : Type v} {B : Type w} namespace algebra section semiring variables [comm_semiring R] [semiring A] [semiring B] variables [algebra R A] [algebra R B] {s t : set A} theorem subset_adjoin : s ⊆ adjoin R s := algebra.gc.le_u_l s theorem adjoin_le {S : subalgebra R A} (H : s ⊆ S) : adjoin R s ≤ S := algebra.gc.l_le H lemma adjoin_eq_Inf : adjoin R s = Inf {p | s ⊆ p} := le_antisymm (le_Inf (λ _ h, adjoin_le h)) (Inf_le subset_adjoin) theorem adjoin_le_iff {S : subalgebra R A} : adjoin R s ≤ S ↔ s ⊆ S:= algebra.gc _ _ theorem adjoin_mono (H : s ⊆ t) : adjoin R s ≤ adjoin R t := algebra.gc.monotone_l H theorem adjoin_eq_of_le (S : subalgebra R A) (h₁ : s ⊆ S) (h₂ : S ≤ adjoin R s) : adjoin R s = S := le_antisymm (adjoin_le h₁) h₂ theorem adjoin_eq (S : subalgebra R A) : adjoin R ↑S = S := adjoin_eq_of_le _ (set.subset.refl _) subset_adjoin lemma adjoin_Union {α : Type*} (s : α → set A) : adjoin R (set.Union s) = ⨆ (i : α), adjoin R (s i) := (@algebra.gc R A _ _ _).l_supr lemma adjoin_attach_bUnion [decidable_eq A] {α : Type*} {s : finset α} (f : s → finset A) : adjoin R (s.attach.bUnion f : set A) = ⨆ x, adjoin R (f x) := by simpa [adjoin_Union] @[elab_as_eliminator] theorem adjoin_induction {p : A → Prop} {x : A} (h : x ∈ adjoin R s) (Hs : ∀ x ∈ s, p x) (Halg : ∀ r, p (algebra_map R A r)) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := let S : subalgebra R A := { carrier := p, mul_mem' := Hmul, add_mem' := Hadd, algebra_map_mem' := Halg } in adjoin_le (show s ≤ S, from Hs) h /-- The difference with `algebra.adjoin_induction` is that this acts on the subtype. -/ lemma adjoin_induction' {p : adjoin R s → Prop} (Hs : ∀ x (h : x ∈ s), p ⟨x, subset_adjoin h⟩) (Halg : ∀ r, p (algebra_map R _ r)) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hmul : ∀ x y, p x → p y → p (x * y)) (x : adjoin R s) : p x := subtype.rec_on x $ λ x hx, begin refine exists.elim _ (λ (hx : x ∈ adjoin R s) (hc : p ⟨x, hx⟩), hc), exact adjoin_induction hx (λ x hx, ⟨subset_adjoin hx, Hs x hx⟩) (λ r, ⟨subalgebra.algebra_map_mem _ r, Halg r⟩) (λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy, ⟨subalgebra.add_mem _ hx' hy', Hadd _ _ hx hy⟩) (λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy, ⟨subalgebra.mul_mem _ hx' hy', Hmul _ _ hx hy⟩), end @[simp] lemma adjoin_adjoin_coe_preimage {s : set A} : adjoin R ((coe : adjoin R s → A) ⁻¹' s) = ⊤ := begin refine eq_top_iff.2 (λ x, adjoin_induction' (λ a ha, _) (λ r, _) (λ _ _, _) (λ _ _, _) x), { exact subset_adjoin ha }, { exact subalgebra.algebra_map_mem _ r }, { exact subalgebra.add_mem _ }, { exact subalgebra.mul_mem _ } end lemma adjoin_union (s t : set A) : adjoin R (s ∪ t) = adjoin R s ⊔ adjoin R t := (algebra.gc : galois_connection _ (coe : subalgebra R A → set A)).l_sup variables (R A) @[simp] theorem adjoin_empty : adjoin R (∅ : set A) = ⊥ := show adjoin R ⊥ = ⊥, by { apply galois_connection.l_bot, exact algebra.gc } @[simp] theorem adjoin_univ : adjoin R (set.univ : set A) = ⊤ := eq_top_iff.2 $ λ x, subset_adjoin $ set.mem_univ _ variables (R) {A} (s) theorem adjoin_eq_span : (adjoin R s).to_submodule = span R (submonoid.closure s) := begin apply le_antisymm, { intros r hr, rcases subsemiring.mem_closure_iff_exists_list.1 hr with ⟨L, HL, rfl⟩, clear hr, induction L with hd tl ih, { exact zero_mem _ }, rw list.forall_mem_cons at HL, rw [list.map_cons, list.sum_cons], refine submodule.add_mem _ _ (ih HL.2), replace HL := HL.1, clear ih tl, suffices : ∃ z r (hr : r ∈ submonoid.closure s), has_scalar.smul z r = list.prod hd, { rcases this with ⟨z, r, hr, hzr⟩, rw ← hzr, exact smul_mem _ _ (subset_span hr) }, induction hd with hd tl ih, { exact ⟨1, 1, (submonoid.closure s).one_mem', one_smul _ _⟩ }, rw list.forall_mem_cons at HL, rcases (ih HL.2) with ⟨z, r, hr, hzr⟩, rw [list.prod_cons, ← hzr], rcases HL.1 with ⟨hd, rfl⟩ | hs, { refine ⟨hd * z, r, hr, _⟩, rw [algebra.smul_def, algebra.smul_def, (algebra_map _ _).map_mul, _root_.mul_assoc] }, { exact ⟨z, hd * r, submonoid.mul_mem _ (submonoid.subset_closure hs) hr, (mul_smul_comm _ _ _).symm⟩ } }, refine span_le.2 _, change submonoid.closure s ≤ (adjoin R s).to_subsemiring.to_submonoid, exact submonoid.closure_le.2 subset_adjoin end lemma span_le_adjoin (s : set A) : span R s ≤ (adjoin R s).to_submodule := span_le.mpr subset_adjoin lemma adjoin_to_submodule_le {s : set A} {t : submodule R A} : (adjoin R s).to_submodule ≤ t ↔ ↑(submonoid.closure s) ⊆ (t : set A) := by rw [adjoin_eq_span, span_le] lemma adjoin_eq_span_of_subset {s : set A} (hs : ↑(submonoid.closure s) ⊆ (span R s : set A)) : (adjoin R s).to_submodule = span R s := le_antisymm ((adjoin_to_submodule_le R).mpr hs) (span_le_adjoin R s) lemma adjoin_image (f : A →ₐ[R] B) (s : set A) : adjoin R (f '' s) = (adjoin R s).map f := le_antisymm (adjoin_le $ set.image_subset _ subset_adjoin) $ subalgebra.map_le.2 $ adjoin_le $ set.image_subset_iff.1 subset_adjoin @[simp] lemma adjoin_insert_adjoin (x : A) : adjoin R (insert x ↑(adjoin R s)) = adjoin R (insert x s) := le_antisymm (adjoin_le (set.insert_subset.mpr ⟨subset_adjoin (set.mem_insert _ _), adjoin_mono (set.subset_insert _ _)⟩)) (algebra.adjoin_mono (set.insert_subset_insert algebra.subset_adjoin)) lemma adjoin_prod_le (s : set A) (t : set B) : adjoin R (s ×ˢ t) ≤ (adjoin R s).prod (adjoin R t) := adjoin_le $ set.prod_mono subset_adjoin subset_adjoin lemma mem_adjoin_of_map_mul {s} {x : A} {f : A →ₗ[R] B} (hf : ∀ a₁ a₂, f(a₁ * a₂) = f a₁ * f a₂) (h : x ∈ adjoin R s) : f x ∈ adjoin R (f '' (s ∪ {1})) := begin refine @adjoin_induction R A _ _ _ _ (λ a, f a ∈ adjoin R (f '' (s ∪ {1}))) x h (λ a ha, subset_adjoin ⟨a, ⟨set.subset_union_left _ _ ha, rfl⟩⟩) (λ r, _) (λ y z hy hz, by simpa [hy, hz] using subalgebra.add_mem _ hy hz) (λ y z hy hz, by simpa [hy, hz, hf y z] using subalgebra.mul_mem _ hy hz), have : f 1 ∈ adjoin R (f '' (s ∪ {1})) := subset_adjoin ⟨1, ⟨set.subset_union_right _ _ $ set.mem_singleton 1, rfl⟩⟩, replace this := subalgebra.smul_mem (adjoin R (f '' (s ∪ {1}))) this r, convert this, rw algebra_map_eq_smul_one, exact f.map_smul _ _ end lemma adjoin_inl_union_inr_eq_prod (s) (t) : adjoin R (linear_map.inl R A B '' (s ∪ {1}) ∪ linear_map.inr R A B '' (t ∪ {1})) = (adjoin R s).prod (adjoin R t) := begin apply le_antisymm, { simp only [adjoin_le_iff, set.insert_subset, subalgebra.zero_mem, subalgebra.one_mem, subset_adjoin, -- the rest comes from `squeeze_simp` set.union_subset_iff, linear_map.coe_inl, set.mk_preimage_prod_right, set.image_subset_iff, set_like.mem_coe, set.mk_preimage_prod_left, linear_map.coe_inr, and_self, set.union_singleton, subalgebra.coe_prod] }, { rintro ⟨a, b⟩ ⟨ha, hb⟩, let P := adjoin R (linear_map.inl R A B '' (s ∪ {1}) ∪ linear_map.inr R A B '' (t ∪ {1})), have Ha : (a, (0 : B)) ∈ adjoin R ((linear_map.inl R A B) '' (s ∪ {1})) := mem_adjoin_of_map_mul R (linear_map.inl_map_mul) ha, have Hb : ((0 : A), b) ∈ adjoin R ((linear_map.inr R A B) '' (t ∪ {1})) := mem_adjoin_of_map_mul R (linear_map.inr_map_mul) hb, replace Ha : (a, (0 : B)) ∈ P := adjoin_mono (set.subset_union_left _ _) Ha, replace Hb : ((0 : A), b) ∈ P := adjoin_mono (set.subset_union_right _ _) Hb, simpa using subalgebra.add_mem _ Ha Hb } end end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] variables [algebra R A] {s t : set A} variables (R s t) theorem adjoin_union_eq_adjoin_adjoin : adjoin R (s ∪ t) = (adjoin (adjoin R s) t).restrict_scalars R := le_antisymm (closure_mono $ set.union_subset (set.range_subset_iff.2 $ λ r, or.inl ⟨algebra_map R (adjoin R s) r, rfl⟩) (set.union_subset_union_left _ $ λ x hxs, ⟨⟨_, subset_adjoin hxs⟩, rfl⟩)) (closure_le.2 $ set.union_subset (set.range_subset_iff.2 $ λ x, adjoin_mono (set.subset_union_left _ _) x.2) (set.subset.trans (set.subset_union_right _ _) subset_adjoin)) lemma adjoin_singleton_one : adjoin R ({1} : set A) = ⊥ := eq_bot_iff.2 $ adjoin_le $ set.singleton_subset_iff.2 $ set_like.mem_coe.2 $ one_mem _ theorem adjoin_union_coe_submodule : (adjoin R (s ∪ t)).to_submodule = (adjoin R s).to_submodule * (adjoin R t).to_submodule := begin rw [adjoin_eq_span, adjoin_eq_span, adjoin_eq_span, span_mul_span], congr' 1 with z, simp [submonoid.closure_union, submonoid.mem_sup, set.mem_mul] end lemma pow_smul_mem_adjoin_smul (r : R) (s : set A) {x : A} (hx : x ∈ adjoin R s) : ∃ n₀ : ℕ, ∀ n ≥ n₀, r ^ n • x ∈ adjoin R (r • s) := begin change x ∈ (adjoin R s).to_submodule at hx, rw [adjoin_eq_span, finsupp.mem_span_iff_total] at hx, rcases hx with ⟨l, rfl : l.sum (λ (i : submonoid.closure s) (c : R), c • ↑i) = x⟩, choose n₁ n₂ using (λ x : submonoid.closure s, submonoid.pow_smul_mem_closure_smul r s x.prop), use l.support.sup n₁, intros n hn, rw finsupp.smul_sum, refine (adjoin R (r • s)).to_submodule.sum_mem _, intros a ha, have : n ≥ n₁ a := le_trans (finset.le_sup ha) hn, dsimp only, rw [← tsub_add_cancel_of_le this, pow_add, ← smul_smul, smul_smul _ (l a), mul_comm, ← smul_smul, adjoin_eq_span], refine submodule.smul_mem _ _ _, exact submodule.smul_mem _ _ (submodule.subset_span (n₂ a)) end end comm_semiring section ring variables [comm_ring R] [ring A] variables [algebra R A] {s t : set A} variables {R s t} theorem adjoin_int (s : set R) : adjoin ℤ s = subalgebra_of_subring (subring.closure s) := le_antisymm (adjoin_le subring.subset_closure) (subring.closure_le.2 subset_adjoin : subring.closure s ≤ (adjoin ℤ s).to_subring) theorem mem_adjoin_iff {s : set A} {x : A} : x ∈ adjoin R s ↔ x ∈ subring.closure (set.range (algebra_map R A) ∪ s) := ⟨λ hx, subsemiring.closure_induction hx subring.subset_closure (subring.zero_mem _) (subring.one_mem _) (λ _ _, subring.add_mem _) ( λ _ _, subring.mul_mem _), suffices subring.closure (set.range ⇑(algebra_map R A) ∪ s) ≤ (adjoin R s).to_subring, from @this x, subring.closure_le.2 subsemiring.subset_closure⟩ theorem adjoin_eq_ring_closure (s : set A) : (adjoin R s).to_subring = subring.closure (set.range (algebra_map R A) ∪ s) := subring.ext $ λ x, mem_adjoin_iff end ring end algebra open algebra subalgebra namespace alg_hom variables [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] lemma map_adjoin (φ : A →ₐ[R] B) (s : set A) : (adjoin R s).map φ = adjoin R (φ '' s) := (adjoin_image _ _ _).symm lemma adjoin_le_equalizer (φ₁ φ₂ : A →ₐ[R] B) {s : set A} (h : s.eq_on φ₁ φ₂) : adjoin R s ≤ φ₁.equalizer φ₂ := adjoin_le h lemma ext_of_adjoin_eq_top {s : set A} (h : adjoin R s = ⊤) ⦃φ₁ φ₂ : A →ₐ[R] B⦄ (hs : s.eq_on φ₁ φ₂) : φ₁ = φ₂ := ext $ λ x, adjoin_le_equalizer φ₁ φ₂ hs $ h.symm ▸ trivial end alg_hom
caabe8e43205094f79da999074a0a9725ba79f18
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/matrix/notation.lean
548ae547ac30b50a0b17c0863a9225da49f594e8
[ "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
17,908
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen Notation for vectors and matrices -/ import data.fintype.card import data.matrix.basic import tactic.fin_cases /-! # Matrix and vector notation This file defines notation for vectors and matrices. Given `a b c d : α`, the notation allows us to write `![a, b, c, d] : fin 4 → α`. Nesting vectors gives a matrix, so `![![a, b], ![c, d]] : matrix (fin 2) (fin 2) α`. This file includes `simp` lemmas for applying operations in `data.matrix.basic` to values built out of this notation. ## Main definitions * `vec_empty` is the empty vector (or `0` by `n` matrix) `![]` * `vec_cons` prepends an entry to a vector, so `![a, b]` is `vec_cons a (vec_cons b vec_empty)` ## Implementation notes The `simp` lemmas require that one of the arguments is of the form `vec_cons _ _`. This ensures `simp` works with entries only when (some) entries are already given. In other words, this notation will only appear in the output of `simp` if it already appears in the input. ## Notations The main new notation is `![a, b]`, which gets expanded to `vec_cons a (vec_cons b vec_empty)`. ## Examples Examples of usage can be found in the `test/matrix.lean` file. -/ namespace matrix universe u variables {α : Type u} open_locale matrix section matrix_notation /-- `![]` is the vector with no entries. -/ def vec_empty : fin 0 → α := fin_zero_elim /-- `vec_cons h t` prepends an entry `h` to a vector `t`. The inverse functions are `vec_head` and `vec_tail`. The notation `![a, b, ...]` expands to `vec_cons a (vec_cons b ...)`. -/ def vec_cons {n : ℕ} (h : α) (t : fin n → α) : fin n.succ → α := fin.cons h t notation `![` l:(foldr `, ` (h t, vec_cons h t) vec_empty `]`) := l /-- `vec_head v` gives the first entry of the vector `v` -/ def vec_head {n : ℕ} (v : fin n.succ → α) : α := v 0 /-- `vec_tail v` gives a vector consisting of all entries of `v` except the first -/ def vec_tail {n : ℕ} (v : fin n.succ → α) : fin n → α := v ∘ fin.succ end matrix_notation variables {m n o : ℕ} {m' n' o' : Type*} [fintype m'] [fintype n'] [fintype o'] lemma empty_eq (v : fin 0 → α) : v = ![] := by { ext i, fin_cases i } section val @[simp] lemma head_fin_const (a : α) : vec_head (λ (i : fin (n + 1)), a) = a := rfl @[simp] lemma cons_val_zero (x : α) (u : fin m → α) : vec_cons x u 0 = x := rfl lemma cons_val_zero' (h : 0 < m.succ) (x : α) (u : fin m → α) : vec_cons x u ⟨0, h⟩ = x := rfl @[simp] lemma cons_val_succ (x : α) (u : fin m → α) (i : fin m) : vec_cons x u i.succ = u i := by simp [vec_cons] @[simp] lemma cons_val_succ' {i : ℕ} (h : i.succ < m.succ) (x : α) (u : fin m → α) : vec_cons x u ⟨i.succ, h⟩ = u ⟨i, nat.lt_of_succ_lt_succ h⟩ := by simp only [vec_cons, fin.cons, fin.cases_succ'] @[simp] lemma head_cons (x : α) (u : fin m → α) : vec_head (vec_cons x u) = x := rfl @[simp] lemma tail_cons (x : α) (u : fin m → α) : vec_tail (vec_cons x u) = u := by { ext, simp [vec_tail] } @[simp] lemma empty_val' {n' : Type*} (j : n') : (λ i, (![] : fin 0 → n' → α) i j) = ![] := empty_eq _ @[simp] lemma cons_val' (v : n' → α) (B : matrix (fin m) n' α) (i j) : vec_cons v B i j = vec_cons (v j) (λ i, B i j) i := by { refine fin.cases _ _ i; simp } @[simp] lemma head_val' (B : matrix (fin m.succ) n' α) (j : n') : vec_head (λ i, B i j) = vec_head B j := rfl @[simp] lemma tail_val' (B : matrix (fin m.succ) n' α) (j : n') : vec_tail (λ i, B i j) = λ i, vec_tail B i j := by { ext, simp [vec_tail] } @[simp] lemma cons_head_tail (u : fin m.succ → α) : vec_cons (vec_head u) (vec_tail u) = u := fin.cons_self_tail _ @[simp] lemma range_cons (x : α) (u : fin n → α) : set.range (vec_cons x u) = {x} ∪ set.range u := set.ext $ λ y, by simp [fin.exists_fin_succ, eq_comm] @[simp] lemma range_empty (u : fin 0 → α) : set.range u = ∅ := set.range_eq_empty.2 $ λ ⟨k⟩, k.elim0 /-- `![a, b, ...] 1` is equal to `b`. The simplifier needs a special lemma for length `≥ 2`, in addition to `cons_val_succ`, because `1 : fin 1 = 0 : fin 1`. -/ @[simp] lemma cons_val_one (x : α) (u : fin m.succ → α) : vec_cons x u 1 = vec_head u := by { rw [← fin.succ_zero_eq_one, cons_val_succ], refl } @[simp] lemma cons_val_fin_one (x : α) (u : fin 0 → α) (i : fin 1) : vec_cons x u i = x := by { fin_cases i, refl } lemma cons_fin_one (x : α) (u : fin 0 → α) : vec_cons x u = (λ _, x) := funext (cons_val_fin_one x u) /-! ### Numeral (`bit0` and `bit1`) indices The following definitions and `simp` lemmas are to allow any numeral-indexed element of a vector given with matrix notation to be extracted by `simp` (even when the numeral is larger than the number of elements in the vector, which is taken modulo that number of elements by virtue of the semantics of `bit0` and `bit1` and of addition on `fin n`). -/ @[simp] lemma empty_append (v : fin n → α) : fin.append (zero_add _).symm ![] v = v := by { ext, simp [fin.append] } @[simp] lemma cons_append (ho : o + 1 = m + 1 + n) (x : α) (u : fin m → α) (v : fin n → α) : fin.append ho (vec_cons x u) v = vec_cons x (fin.append (by rwa [add_assoc, add_comm 1, ←add_assoc, add_right_cancel_iff] at ho) u v) := begin ext i, simp_rw [fin.append], split_ifs with h, { rcases i with ⟨⟨⟩ | i, hi⟩, { simp }, { simp only [nat.succ_eq_add_one, add_lt_add_iff_right, fin.coe_mk] at h, simp [h] } }, { rcases i with ⟨⟨⟩ | i, hi⟩, { simpa using h }, { rw [not_lt, fin.coe_mk, nat.succ_eq_add_one, add_le_add_iff_right] at h, simp [h] } } end /-- `vec_alt0 v` gives a vector with half the length of `v`, with only alternate elements (even-numbered). -/ def vec_alt0 (hm : m = n + n) (v : fin m → α) (k : fin n) : α := v ⟨(k : ℕ) + k, hm.symm ▸ add_lt_add k.property k.property⟩ /-- `vec_alt1 v` gives a vector with half the length of `v`, with only alternate elements (odd-numbered). -/ def vec_alt1 (hm : m = n + n) (v : fin m → α) (k : fin n) : α := v ⟨(k : ℕ) + k + 1, hm.symm ▸ nat.add_succ_lt_add k.property k.property⟩ lemma vec_alt0_append (v : fin n → α) : vec_alt0 rfl (fin.append rfl v v) = v ∘ bit0 := begin ext i, simp_rw [function.comp, bit0, vec_alt0, fin.append], split_ifs with h; congr, { rw fin.coe_mk at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk], exact (nat.mod_eq_of_lt h).symm }, { rw [fin.coe_mk, not_lt] at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk, nat.mod_eq_sub_mod h], refine (nat.mod_eq_of_lt _).symm, rw nat.sub_lt_left_iff_lt_add h, exact add_lt_add i.property i.property } end lemma vec_alt1_append (v : fin (n + 1) → α) : vec_alt1 rfl (fin.append rfl v v) = v ∘ bit1 := begin ext i, simp_rw [function.comp, vec_alt1, fin.append], cases n, { simp, congr }, { split_ifs with h; simp_rw [bit1, bit0]; congr, { simp only [fin.ext_iff, fin.coe_add, fin.coe_mk], rw fin.coe_mk at h, rw fin.coe_one, rw nat.mod_eq_of_lt (nat.lt_of_succ_lt h), rw nat.mod_eq_of_lt h }, { rw [fin.coe_mk, not_lt] at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk, nat.mod_add_mod, fin.coe_one, nat.mod_eq_sub_mod h], refine (nat.mod_eq_of_lt _).symm, rw nat.sub_lt_left_iff_lt_add h, exact nat.add_succ_lt_add i.property i.property } } end @[simp] lemma vec_head_vec_alt0 (hm : (m + 2) = (n + 1) + (n + 1)) (v : fin (m + 2) → α) : vec_head (vec_alt0 hm v) = v 0 := rfl @[simp] lemma vec_head_vec_alt1 (hm : (m + 2) = (n + 1) + (n + 1)) (v : fin (m + 2) → α) : vec_head (vec_alt1 hm v) = v 1 := by simp [vec_head, vec_alt1] @[simp] lemma cons_vec_bit0_eq_alt0 (x : α) (u : fin n → α) (i : fin (n + 1)) : vec_cons x u (bit0 i) = vec_alt0 rfl (fin.append rfl (vec_cons x u) (vec_cons x u)) i := by rw vec_alt0_append @[simp] lemma cons_vec_bit1_eq_alt1 (x : α) (u : fin n → α) (i : fin (n + 1)) : vec_cons x u (bit1 i) = vec_alt1 rfl (fin.append rfl (vec_cons x u) (vec_cons x u)) i := by rw vec_alt1_append @[simp] lemma cons_vec_alt0 (h : m + 1 + 1 = (n + 1) + (n + 1)) (x y : α) (u : fin m → α) : vec_alt0 h (vec_cons x (vec_cons y u)) = vec_cons x (vec_alt0 (by rwa [add_assoc n, add_comm 1, ←add_assoc, ←add_assoc, add_right_cancel_iff, add_right_cancel_iff] at h) u) := begin ext i, simp_rw [vec_alt0], rcases i with ⟨⟨⟩ | i, hi⟩, { refl }, { simp [vec_alt0, nat.succ_add] } end -- Although proved by simp, extracting element 8 of a five-element -- vector does not work by simp unless this lemma is present. @[simp] lemma empty_vec_alt0 (α) {h} : vec_alt0 h (![] : fin 0 → α) = ![] := by simp @[simp] lemma cons_vec_alt1 (h : m + 1 + 1 = (n + 1) + (n + 1)) (x y : α) (u : fin m → α) : vec_alt1 h (vec_cons x (vec_cons y u)) = vec_cons y (vec_alt1 (by rwa [add_assoc n, add_comm 1, ←add_assoc, ←add_assoc, add_right_cancel_iff, add_right_cancel_iff] at h) u) := begin ext i, simp_rw [vec_alt1], rcases i with ⟨⟨⟩ | i, hi⟩, { refl }, { simp [vec_alt1, nat.succ_add] } end -- Although proved by simp, extracting element 9 of a five-element -- vector does not work by simp unless this lemma is present. @[simp] lemma empty_vec_alt1 (α) {h} : vec_alt1 h (![] : fin 0 → α) = ![] := by simp end val section dot_product variables [add_comm_monoid α] [has_mul α] @[simp] lemma dot_product_empty (v w : fin 0 → α) : dot_product v w = 0 := finset.sum_empty @[simp] lemma cons_dot_product (x : α) (v : fin n → α) (w : fin n.succ → α) : dot_product (vec_cons x v) w = x * vec_head w + dot_product v (vec_tail w) := by simp [dot_product, fin.sum_univ_succ, vec_head, vec_tail] @[simp] lemma dot_product_cons (v : fin n.succ → α) (x : α) (w : fin n → α) : dot_product v (vec_cons x w) = vec_head v * x + dot_product (vec_tail v) w := by simp [dot_product, fin.sum_univ_succ, vec_head, vec_tail] end dot_product section col_row @[simp] lemma col_empty (v : fin 0 → α) : col v = vec_empty := empty_eq _ @[simp] lemma col_cons (x : α) (u : fin m → α) : col (vec_cons x u) = vec_cons (λ _, x) (col u) := by { ext i j, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma row_empty : row (vec_empty : fin 0 → α) = λ _, vec_empty := by { ext, refl } @[simp] lemma row_cons (x : α) (u : fin m → α) : row (vec_cons x u) = λ _, vec_cons x u := by { ext, refl } end col_row section transpose @[simp] lemma transpose_empty_rows (A : matrix m' (fin 0) α) : Aᵀ = ![] := empty_eq _ @[simp] lemma transpose_empty_cols : (![] : matrix (fin 0) m' α)ᵀ = λ i, ![] := funext (λ i, empty_eq _) @[simp] lemma cons_transpose (v : n' → α) (A : matrix (fin m) n' α) : (vec_cons v A)ᵀ = λ i, vec_cons (v i) (Aᵀ i) := by { ext i j, refine fin.cases _ _ j; simp } @[simp] lemma head_transpose (A : matrix m' (fin n.succ) α) : vec_head (Aᵀ) = vec_head ∘ A := rfl @[simp] lemma tail_transpose (A : matrix m' (fin n.succ) α) : vec_tail (Aᵀ) = (vec_tail ∘ A)ᵀ := by { ext i j, refl } end transpose section mul variables [semiring α] @[simp] lemma empty_mul (A : matrix (fin 0) n' α) (B : matrix n' o' α) : A ⬝ B = ![] := empty_eq _ @[simp] lemma empty_mul_empty (A : matrix m' (fin 0) α) (B : matrix (fin 0) o' α) : A ⬝ B = 0 := rfl @[simp] lemma mul_empty (A : matrix m' n' α) (B : matrix n' (fin 0) α) : A ⬝ B = λ _, ![] := funext (λ _, empty_eq _) lemma mul_val_succ (A : matrix (fin m.succ) n' α) (B : matrix n' o' α) (i : fin m) (j : o') : (A ⬝ B) i.succ j = (vec_tail A ⬝ B) i j := rfl @[simp] lemma cons_mul (v : n' → α) (A : matrix (fin m) n' α) (B : matrix n' o' α) : vec_cons v A ⬝ B = vec_cons (vec_mul v B) (A ⬝ B) := by { ext i j, refine fin.cases _ _ i, { refl }, simp [mul_val_succ] } end mul section vec_mul variables [semiring α] @[simp] lemma empty_vec_mul (v : fin 0 → α) (B : matrix (fin 0) o' α) : vec_mul v B = 0 := rfl @[simp] lemma vec_mul_empty (v : n' → α) (B : matrix n' (fin 0) α) : vec_mul v B = ![] := empty_eq _ @[simp] lemma cons_vec_mul (x : α) (v : fin n → α) (B : matrix (fin n.succ) o' α) : vec_mul (vec_cons x v) B = x • (vec_head B) + vec_mul v (vec_tail B) := by { ext i, simp [vec_mul] } @[simp] lemma vec_mul_cons (v : fin n.succ → α) (w : o' → α) (B : matrix (fin n) o' α) : vec_mul v (vec_cons w B) = vec_head v • w + vec_mul (vec_tail v) B := by { ext i, simp [vec_mul] } end vec_mul section mul_vec variables [semiring α] @[simp] lemma empty_mul_vec (A : matrix (fin 0) n' α) (v : n' → α) : mul_vec A v = ![] := empty_eq _ @[simp] lemma mul_vec_empty (A : matrix m' (fin 0) α) (v : fin 0 → α) : mul_vec A v = 0 := rfl @[simp] lemma cons_mul_vec (v : n' → α) (A : fin m → n' → α) (w : n' → α) : mul_vec (vec_cons v A) w = vec_cons (dot_product v w) (mul_vec A w) := by { ext i, refine fin.cases _ _ i; simp [mul_vec] } @[simp] lemma mul_vec_cons {α} [comm_semiring α] (A : m' → (fin n.succ) → α) (x : α) (v : fin n → α) : mul_vec A (vec_cons x v) = (x • vec_head ∘ A) + mul_vec (vec_tail ∘ A) v := by { ext i, simp [mul_vec, mul_comm] } end mul_vec section vec_mul_vec variables [semiring α] @[simp] lemma empty_vec_mul_vec (v : fin 0 → α) (w : n' → α) : vec_mul_vec v w = ![] := empty_eq _ @[simp] lemma vec_mul_vec_empty (v : m' → α) (w : fin 0 → α) : vec_mul_vec v w = λ _, ![] := funext (λ i, empty_eq _) @[simp] lemma cons_vec_mul_vec (x : α) (v : fin m → α) (w : n' → α) : vec_mul_vec (vec_cons x v) w = vec_cons (x • w) (vec_mul_vec v w) := by { ext i, refine fin.cases _ _ i; simp [vec_mul_vec] } @[simp] lemma vec_mul_vec_cons (v : m' → α) (x : α) (w : fin n → α) : vec_mul_vec v (vec_cons x w) = λ i, v i • vec_cons x w := by { ext i j, simp [vec_mul_vec]} end vec_mul_vec section smul variables [semiring α] @[simp] lemma smul_empty (x : α) (v : fin 0 → α) : x • v = ![] := empty_eq _ @[simp] lemma smul_mat_empty {m' : Type*} (x : α) (A : fin 0 → m' → α) : x • A = ![] := empty_eq _ @[simp] lemma smul_cons (x y : α) (v : fin n → α) : x • vec_cons y v = vec_cons (x * y) (x • v) := by { ext i, refine fin.cases _ _ i; simp } @[simp] lemma smul_mat_cons (x : α) (v : n' → α) (A : matrix (fin m) n' α) : x • vec_cons v A = vec_cons (x • v) (x • A) := by { ext i, refine fin.cases _ _ i; simp } end smul section add variables [has_add α] @[simp] lemma empty_add_empty (v w : fin 0 → α) : v + w = ![] := empty_eq _ @[simp] lemma cons_add (x : α) (v : fin n → α) (w : fin n.succ → α) : vec_cons x v + w = vec_cons (x + vec_head w) (v + vec_tail w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma add_cons (v : fin n.succ → α) (y : α) (w : fin n → α) : v + vec_cons y w = vec_cons (vec_head v + y) (vec_tail v + w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma head_add (a b : fin n.succ → α) : vec_head (a + b) = vec_head a + vec_head b := rfl @[simp] lemma tail_add (a b : fin n.succ → α) : vec_tail (a + b) = vec_tail a + vec_tail b := rfl end add section sub variables [has_sub α] @[simp] lemma empty_sub_empty (v w : fin 0 → α) : v - w = ![] := empty_eq _ @[simp] lemma cons_sub (x : α) (v : fin n → α) (w : fin n.succ → α) : vec_cons x v - w = vec_cons (x - vec_head w) (v - vec_tail w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma sub_cons (v : fin n.succ → α) (y : α) (w : fin n → α) : v - vec_cons y w = vec_cons (vec_head v - y) (vec_tail v - w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma head_sub (a b : fin n.succ → α) : vec_head (a - b) = vec_head a - vec_head b := rfl @[simp] lemma tail_sub (a b : fin n.succ → α) : vec_tail (a - b) = vec_tail a - vec_tail b := rfl end sub section zero variables [has_zero α] @[simp] lemma zero_empty : (0 : fin 0 → α) = ![] := empty_eq _ @[simp] lemma cons_zero_zero : vec_cons (0 : α) (0 : fin n → α) = 0 := by { ext i j, refine fin.cases _ _ i, { refl }, simp } @[simp] lemma head_zero : vec_head (0 : fin n.succ → α) = 0 := rfl @[simp] lemma tail_zero : vec_tail (0 : fin n.succ → α) = 0 := rfl @[simp] lemma cons_eq_zero_iff {v : fin n → α} {x : α} : vec_cons x v = 0 ↔ x = 0 ∧ v = 0 := ⟨ λ h, ⟨ congr_fun h 0, by { convert congr_arg vec_tail h, simp } ⟩, λ ⟨hx, hv⟩, by simp [hx, hv] ⟩ open_locale classical lemma cons_nonzero_iff {v : fin n → α} {x : α} : vec_cons x v ≠ 0 ↔ (x ≠ 0 ∨ v ≠ 0) := ⟨ λ h, not_and_distrib.mp (h ∘ cons_eq_zero_iff.mpr), λ h, mt cons_eq_zero_iff.mp (not_and_distrib.mpr h) ⟩ end zero section neg variables [has_neg α] @[simp] lemma neg_empty (v : fin 0 → α) : -v = ![] := empty_eq _ @[simp] lemma neg_cons (x : α) (v : fin n → α) : -(vec_cons x v) = vec_cons (-x) (-v) := by { ext i, refine fin.cases _ _ i; simp } @[simp] lemma head_neg (a : fin n.succ → α) : vec_head (-a) = -vec_head a := rfl @[simp] lemma tail_neg (a : fin n.succ → α) : vec_tail (-a) = -vec_tail a := rfl end neg section minor @[simp] lemma minor_empty (A : matrix m' n' α) (row : fin 0 → m') (col : o' → n') : minor A row col = ![] := empty_eq _ @[simp] lemma minor_cons_row (A : matrix m' n' α) (i : m') (row : fin m → m') (col : o' → n') : minor A (vec_cons i row) col = vec_cons (λ j, A i (col j)) (minor A row col) := by { ext i j, refine fin.cases _ _ i; simp [minor] } end minor end matrix
741ec9159a256da43e53aa49acced2bd85e9ccd7
0942a74cc0b397d09bcd1059762fa076b1a5d308
/src/trivial.lean
bf0a99d28b7c4685ec35b870c050f2b9bfc15f45
[ "Unlicense" ]
permissive
sguzman/lean-examples
81df2010e204be1a9fde6ae18295e299e69cebca
c7428b2982d0468d0adb4453766a27e1550a72e8
refs/heads/master
1,668,438,655,034
1,594,156,605,000
1,594,156,605,000
277,626,098
0
0
null
null
null
null
UTF-8
Lean
false
false
35
lean
example: 2+2=4 := begin trivial end
4bbad155ae869e9d4e70e541f323ea184f9178a1
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/group_theory/order_of_element.lean
d8f6132b6c236b5d118607b6b8a8be272edfe3e9
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
22,629
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.set.finite group_theory.coset data.nat.totient open function variables {α : Type*} {s : set α} {a a₁ a₂ b c: α} -- TODO this lemma isn't used anywhere in this file, and should be moved elsewhere. namespace finset open finset lemma mem_range_iff_mem_finset_range_of_mod_eq [decidable_eq α] {f : ℤ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) := suffices (∃i, f (i % n) = a) ↔ ∃i, i < n ∧ f ↑i = a, by simpa [h], have hn' : 0 < (n : ℤ), from int.coe_nat_lt.mpr hn, iff.intro (assume ⟨i, hi⟩, have 0 ≤ i % ↑n, from int.mod_nonneg _ (ne_of_gt hn'), ⟨int.to_nat (i % n), by rw [←int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos i hn', hi⟩⟩) (assume ⟨i, hi, ha⟩, ⟨i, by rw [int.mod_eq_of_lt (int.coe_zero_le _) (int.coe_nat_lt_coe_nat_of_lt hi), ha]⟩) end finset lemma conj_inj [group α] {x : α} : function.injective (λ (g : α), x * g * x⁻¹) := λ a b h, by simpa [mul_left_inj, mul_right_inj] using h lemma mem_normalizer_fintype [group α] {s : set α} [fintype s] {x : α} (h : ∀ n, n ∈ s → x * n * x⁻¹ ∈ s) : x ∈ is_subgroup.normalizer s := by haveI := classical.prop_decidable; haveI := set.fintype_image s (λ n, x * n * x⁻¹); exact λ n, ⟨h n, λ h₁, have heq : (λ n, x * n * x⁻¹) '' s = s := set.eq_of_subset_of_card_le (λ n ⟨y, hy⟩, hy.2 ▸ h y hy.1) (by rw set.card_image_of_injective s conj_inj), have x * n * x⁻¹ ∈ (λ n, x * n * x⁻¹) '' s := heq.symm ▸ h₁, let ⟨y, hy⟩ := this in conj_inj hy.2 ▸ hy.1⟩ section order_of variables [group α] [fintype α] [decidable_eq α] open quotient_group set instance quotient_group.fintype (s : set α) [is_subgroup s] [d : decidable_pred s] : fintype (quotient s) := @quotient.fintype _ _ (left_rel s) (λ _ _, d _) lemma card_eq_card_quotient_mul_card_subgroup (s : set α) [hs : is_subgroup s] [fintype s] [decidable_pred s] : fintype.card α = fintype.card (quotient s) * fintype.card s := by rw ← fintype.card_prod; exact fintype.card_congr (is_subgroup.group_equiv_quotient_times_subgroup hs) lemma card_subgroup_dvd_card (s : set α) [is_subgroup s] [fintype s] : fintype.card s ∣ fintype.card α := by haveI := classical.prop_decidable; simp [card_eq_card_quotient_mul_card_subgroup s] lemma card_quotient_dvd_card (s : set α) [is_subgroup s] [decidable_pred s] [fintype s] : fintype.card (quotient s) ∣ fintype.card α := by simp [card_eq_card_quotient_mul_card_subgroup s] @[simp] lemma card_trivial [fintype (is_subgroup.trivial α)] : fintype.card (is_subgroup.trivial α) = 1 := fintype.card_eq_one_iff.2 ⟨⟨(1 : α), by simp⟩, λ ⟨y, hy⟩, subtype.eq $ is_subgroup.mem_trivial.1 hy⟩ lemma exists_gpow_eq_one (a : α) : ∃i≠0, a ^ (i:ℤ) = 1 := have ¬ injective (λi:ℤ, a ^ i), from not_injective_infinite_fintype _, let ⟨i, j, a_eq, ne⟩ := show ∃(i j : ℤ), a ^ i = a ^ j ∧ i ≠ j, by rw [injective] at this; simpa [classical.not_forall] in have a ^ (i - j) = 1, by simp [sub_eq_add_neg, gpow_add, gpow_neg, a_eq], ⟨i - j, sub_ne_zero.mpr ne, this⟩ lemma exists_pow_eq_one (a : α) : ∃i > 0, a ^ i = 1 := let ⟨i, hi, eq⟩ := exists_gpow_eq_one a in begin cases i, { exact ⟨i, nat.pos_of_ne_zero (by simp [int.of_nat_eq_coe, *] at *), eq⟩ }, { exact ⟨i + 1, dec_trivial, inv_eq_one.1 eq⟩ } end /-- `order_of a` is the order of the element `a`, i.e. the `n ≥ 1`, s.t. `a ^ n = 1` -/ def order_of (a : α) : ℕ := nat.find (exists_pow_eq_one a) lemma pow_order_of_eq_one (a : α) : a ^ order_of a = 1 := let ⟨h₁, h₂⟩ := nat.find_spec (exists_pow_eq_one a) in h₂ lemma order_of_pos (a : α) : order_of a > 0 := let ⟨h₁, h₂⟩ := nat.find_spec (exists_pow_eq_one a) in h₁ private lemma pow_injective_aux {n m : ℕ} (a : α) (h : n ≤ m) (hn : n < order_of a) (hm : m < order_of a) (eq : a ^ n = a ^ m) : n = m := decidable.by_contradiction $ assume ne : n ≠ m, have h₁ : m - n > 0, from nat.pos_of_ne_zero (by simp [nat.sub_eq_iff_eq_add h, ne.symm]), have h₂ : a ^ (m - n) = 1, by simp [pow_sub _ h, eq], have le : order_of a ≤ m - n, from nat.find_min' (exists_pow_eq_one a) ⟨h₁, h₂⟩, have lt : m - n < order_of a, from (nat.sub_lt_left_iff_lt_add h).mpr $ nat.lt_add_left _ _ _ hm, lt_irrefl _ (lt_of_le_of_lt le lt) lemma pow_injective_of_lt_order_of {n m : ℕ} (a : α) (hn : n < order_of a) (hm : m < order_of a) (eq : a ^ n = a ^ m) : n = m := (le_total n m).elim (assume h, pow_injective_aux a h hn hm eq) (assume h, (pow_injective_aux a h hm hn eq.symm).symm) lemma order_of_le_card_univ : order_of a ≤ fintype.card α := finset.card_le_of_inj_on ((^) a) (assume n _, fintype.complete _) (assume i j, pow_injective_of_lt_order_of a) lemma pow_eq_mod_order_of {n : ℕ} : a ^ n = a ^ (n % order_of a) := calc a ^ n = a ^ (n % order_of a + order_of a * (n / order_of a)) : by rw [nat.mod_add_div] ... = a ^ (n % order_of a) : by simp [pow_add, pow_mul, pow_order_of_eq_one] lemma gpow_eq_mod_order_of {i : ℤ} : a ^ i = a ^ (i % order_of a) := calc a ^ i = a ^ (i % order_of a + order_of a * (i / order_of a)) : by rw [int.mod_add_div] ... = a ^ (i % order_of a) : by simp [gpow_add, gpow_mul, pow_order_of_eq_one] lemma mem_gpowers_iff_mem_range_order_of {a a' : α} : a' ∈ gpowers a ↔ a' ∈ (finset.range (order_of a)).image ((^) a : ℕ → α) := finset.mem_range_iff_mem_finset_range_of_mod_eq (order_of_pos a) (assume i, gpow_eq_mod_order_of.symm) instance decidable_gpowers : decidable_pred (gpowers a) := assume a', decidable_of_iff' (a' ∈ (finset.range (order_of a)).image ((^) a)) mem_gpowers_iff_mem_range_order_of lemma order_of_dvd_of_pow_eq_one {n : ℕ} (h : a ^ n = 1) : order_of a ∣ n := by_contradiction (λ h₁, nat.find_min _ (show n % order_of a < order_of a, from nat.mod_lt _ (order_of_pos _)) ⟨nat.pos_of_ne_zero (mt nat.dvd_of_mod_eq_zero h₁), by rwa ← pow_eq_mod_order_of⟩) lemma order_of_le_of_pow_eq_one {n : ℕ} (hn : 0 < n) (h : a ^ n = 1) : order_of a ≤ n := nat.find_min' (exists_pow_eq_one a) ⟨hn, h⟩ lemma sum_card_order_of_eq_card_pow_eq_one {n : ℕ} (hn : 0 < n) : ((finset.range n.succ).filter (∣ n)).sum (λ m, (finset.univ.filter (λ a : α, order_of a = m)).card) = (finset.univ.filter (λ a : α, a ^ n = 1)).card := calc ((finset.range n.succ).filter (∣ n)).sum (λ m, (finset.univ.filter (λ a : α, order_of a = m)).card) = _ : (finset.card_bind (by { intros, apply finset.disjoint_filter.2, cc })).symm ... = _ : congr_arg finset.card (finset.ext.2 (begin assume a, suffices : order_of a ≤ n ∧ order_of a ∣ n ↔ a ^ n = 1, { simpa [nat.lt_succ_iff], }, exact ⟨λ h, let ⟨m, hm⟩ := h.2 in by rw [hm, pow_mul, pow_order_of_eq_one, _root_.one_pow], λ h, ⟨order_of_le_of_pow_eq_one hn h, order_of_dvd_of_pow_eq_one h⟩⟩ end)) section local attribute [instance] set_fintype lemma order_eq_card_gpowers : order_of a = fintype.card (gpowers a) := begin refine (finset.card_eq_of_bijective _ _ _ _).symm, { exact λn hn, ⟨gpow a n, ⟨n, rfl⟩⟩ }, { exact assume ⟨_, i, rfl⟩ _, have pos: (0:int) < order_of a, from int.coe_nat_lt.mpr $ order_of_pos a, have 0 ≤ i % (order_of a), from int.mod_nonneg _ $ ne_of_gt pos, ⟨int.to_nat (i % order_of a), by rw [← int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos _ pos, subtype.eq gpow_eq_mod_order_of.symm⟩⟩ }, { intros, exact finset.mem_univ _ }, { exact assume i j hi hj eq, pow_injective_of_lt_order_of a hi hj $ by simpa using eq } end @[simp] lemma order_of_one : order_of (1 : α) = 1 := by rw [order_eq_card_gpowers, fintype.card_eq_one_iff]; exact ⟨⟨1, 0, rfl⟩, λ ⟨a, i, ha⟩, by simp [ha.symm]⟩ @[simp] lemma order_of_eq_one_iff : order_of a = 1 ↔ a = 1 := ⟨λ h, by conv { to_lhs, rw [← pow_one a, ← h, pow_order_of_eq_one] }, λ h, by simp [h]⟩ section classical open_locale classical open quotient_group /- TODO: use cardinal theory, introduce `card : set α → ℕ`, or setup decidability for cosets -/ lemma order_of_dvd_card_univ : order_of a ∣ fintype.card α := have ft_prod : fintype (quotient (gpowers a) × (gpowers a)), from fintype.of_equiv α (gpowers.is_subgroup a).group_equiv_quotient_times_subgroup, have ft_s : fintype (gpowers a), from @fintype.fintype_prod_right _ _ _ ft_prod _, have ft_cosets : fintype (quotient (gpowers a)), from @fintype.fintype_prod_left _ _ _ ft_prod ⟨⟨1, is_submonoid.one_mem (gpowers a)⟩⟩, have ft : fintype (quotient (gpowers a) × (gpowers a)), from @prod.fintype _ _ ft_cosets ft_s, have eq₁ : fintype.card α = @fintype.card _ ft_cosets * @fintype.card _ ft_s, from calc fintype.card α = @fintype.card _ ft_prod : @fintype.card_congr _ _ _ ft_prod (gpowers.is_subgroup a).group_equiv_quotient_times_subgroup ... = @fintype.card _ (@prod.fintype _ _ ft_cosets ft_s) : congr_arg (@fintype.card _) $ subsingleton.elim _ _ ... = @fintype.card _ ft_cosets * @fintype.card _ ft_s : @fintype.card_prod _ _ ft_cosets ft_s, have eq₂ : order_of a = @fintype.card _ ft_s, from calc order_of a = _ : order_eq_card_gpowers ... = _ : congr_arg (@fintype.card _) $ subsingleton.elim _ _, dvd.intro (@fintype.card (quotient (gpowers a)) ft_cosets) $ by rw [eq₁, eq₂, mul_comm] end classical @[simp] lemma pow_card_eq_one (a : α) : a ^ fintype.card α = 1 := let ⟨m, hm⟩ := @order_of_dvd_card_univ _ a _ _ _ in by simp [hm, pow_mul, pow_order_of_eq_one] lemma powers_eq_gpowers (a : α) : powers a = gpowers a := set.ext (λ x, ⟨λ ⟨n, hn⟩, ⟨n, by simp * at *⟩, λ ⟨i, hi⟩, ⟨(i % order_of a).nat_abs, by rwa [← gpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), ← gpow_eq_mod_order_of]⟩⟩) open nat lemma order_of_pow (a : α) (n : ℕ) : order_of (a ^ n) = order_of a / gcd (order_of a) n := dvd_antisymm (order_of_dvd_of_pow_eq_one (by rw [← pow_mul, ← nat.mul_div_assoc _ (gcd_dvd_left _ _), mul_comm, nat.mul_div_assoc _ (gcd_dvd_right _ _), pow_mul, pow_order_of_eq_one, _root_.one_pow])) (have gcd_pos : 0 < gcd (order_of a) n, from gcd_pos_of_pos_left n (order_of_pos a), have hdvd : order_of a ∣ n * order_of (a ^ n), from order_of_dvd_of_pow_eq_one (by rw [pow_mul, pow_order_of_eq_one]), coprime.dvd_of_dvd_mul_right (coprime_div_gcd_div_gcd gcd_pos) (dvd_of_mul_dvd_mul_right gcd_pos (by rwa [nat.div_mul_cancel (gcd_dvd_left _ _), mul_assoc, nat.div_mul_cancel (gcd_dvd_right _ _), mul_comm]))) lemma pow_gcd_card_eq_one_iff {n : ℕ} {a : α} : a ^ n = 1 ↔ a ^ (gcd n (fintype.card α)) = 1 := ⟨λ h, have hn : order_of a ∣ n, from dvd_of_mod_eq_zero $ by_contradiction (λ ha, by rw pow_eq_mod_order_of at h; exact (not_le_of_gt (nat.mod_lt n (order_of_pos a))) (order_of_le_of_pow_eq_one (nat.pos_of_ne_zero ha) h)), let ⟨m, hm⟩ := dvd_gcd hn order_of_dvd_card_univ in by rw [hm, pow_mul, pow_order_of_eq_one, _root_.one_pow], λ h, let ⟨m, hm⟩ := gcd_dvd_left n (fintype.card α) in by rw [hm, pow_mul, h, _root_.one_pow]⟩ end end order_of section cyclic local attribute [instance] set_fintype class is_cyclic (α : Type*) [group α] : Prop := (exists_generator : ∃ g : α, ∀ x, x ∈ gpowers g) def is_cyclic.comm_group [hg : group α] [is_cyclic α] : comm_group α := { mul_comm := λ x y, show x * y = y * x, from let ⟨g, hg⟩ := is_cyclic.exists_generator α in let ⟨n, hn⟩ := hg x in let ⟨m, hm⟩ := hg y in hm ▸ hn ▸ gpow_mul_comm _ _ _, ..hg } lemma is_cyclic_of_order_of_eq_card [group α] [fintype α] [decidable_eq α] (x : α) (hx : order_of x = fintype.card α) : is_cyclic α := ⟨⟨x, set.eq_univ_iff_forall.1 $ set.eq_of_subset_of_card_le (set.subset_univ _) (by rw [fintype.card_congr (equiv.set.univ α), ← hx, order_eq_card_gpowers])⟩⟩ lemma order_of_eq_card_of_forall_mem_gpowers [group α] [fintype α] [decidable_eq α] {g : α} (hx : ∀ x, x ∈ gpowers g) : order_of g = fintype.card α := by rw [← fintype.card_congr (equiv.set.univ α), order_eq_card_gpowers]; simp [hx]; congr instance [group α] : is_cyclic (is_subgroup.trivial α) := ⟨⟨(1 : is_subgroup.trivial α), λ x, ⟨0, subtype.eq $ eq.symm (is_subgroup.mem_trivial.1 x.2)⟩⟩⟩ instance is_subgroup.is_cyclic [group α] [is_cyclic α] (H : set α) [is_subgroup H] : is_cyclic H := by haveI := classical.prop_decidable; exact let ⟨g, hg⟩ := is_cyclic.exists_generator α in if hx : ∃ (x : α), x ∈ H ∧ x ≠ (1 : α) then let ⟨x, hx₁, hx₂⟩ := hx in let ⟨k, hk⟩ := hg x in have hex : ∃ n : ℕ, 0 < n ∧ g ^ n ∈ H, from ⟨k.nat_abs, nat.pos_of_ne_zero (λ h, hx₂ $ by rw [← hk, int.eq_zero_of_nat_abs_eq_zero h, gpow_zero]), match k, hk with | (k : ℕ), hk := by rw [int.nat_abs_of_nat, ← gpow_coe_nat, hk]; exact hx₁ | -[1+ k], hk := by rw [int.nat_abs_of_neg_succ_of_nat, ← is_subgroup.inv_mem_iff H]; simp * at * end⟩, ⟨⟨⟨g ^ nat.find hex, (nat.find_spec hex).2⟩, λ ⟨x, hx⟩, let ⟨k, hk⟩ := hg x in have hk₁ : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) ∈ gpowers (g ^ nat.find hex), from ⟨k / nat.find hex, eq.symm $ gpow_mul _ _ _⟩, have hk₂ : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) ∈ H, by rw gpow_mul; exact is_subgroup.gpow_mem (nat.find_spec hex).2, have hk₃ : g ^ (k % nat.find hex) ∈ H, from (is_subgroup.mul_mem_cancel_left H hk₂).1 $ by rw [← gpow_add, int.mod_add_div, hk]; exact hx, have hk₄ : k % nat.find hex = (k % nat.find hex).nat_abs, by rw int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (nat.find_spec hex).1)), have hk₅ : g ^ (k % nat.find hex ).nat_abs ∈ H, by rwa [← gpow_coe_nat, ← hk₄], have hk₆ : (k % (nat.find hex : ℤ)).nat_abs = 0, from by_contradiction (λ h, nat.find_min hex (int.coe_nat_lt.1 $ by rw [← hk₄]; exact int.mod_lt_of_pos _ (int.coe_nat_pos.2 (nat.find_spec hex).1)) ⟨nat.pos_of_ne_zero h, hk₅⟩), ⟨k / (nat.find hex : ℤ), subtype.coe_ext.2 begin suffices : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) = x, { simpa [gpow_mul] }, rw [int.mul_div_cancel' (int.dvd_of_mod_eq_zero (int.eq_zero_of_nat_abs_eq_zero hk₆)), hk] end⟩⟩⟩ else have H = is_subgroup.trivial α, from set.ext $ λ x, ⟨λ h, by simp at *; tauto, λ h, by rw [is_subgroup.mem_trivial.1 h]; exact is_submonoid.one_mem _⟩, by clear _let_match; subst this; apply_instance open finset nat lemma is_cyclic.card_pow_eq_one_le [group α] [fintype α] [decidable_eq α] [is_cyclic α] {n : ℕ} (hn0 : 0 < n) : (univ.filter (λ a : α, a ^ n = 1)).card ≤ n := let ⟨g, hg⟩ := is_cyclic.exists_generator α in calc (univ.filter (λ a : α, a ^ n = 1)).card ≤ (gpowers (g ^ (fintype.card α / (gcd n (fintype.card α))))).to_finset.card : card_le_of_subset (λ x hx, let ⟨m, hm⟩ := show x ∈ powers g, from (powers_eq_gpowers g).symm ▸ hg x in set.mem_to_finset.2 ⟨(m / (fintype.card α / (gcd n (fintype.card α))) : ℕ), have hgmn : g ^ (m * gcd n (fintype.card α)) = 1, by rw [pow_mul, hm, ← pow_gcd_card_eq_one_iff]; exact (mem_filter.1 hx).2, begin rw [gpow_coe_nat, ← pow_mul, nat.mul_div_cancel_left', hm], refine dvd_of_mul_dvd_mul_right (gcd_pos_of_pos_left (fintype.card α) hn0) _, conv {to_lhs, rw [nat.div_mul_cancel (gcd_dvd_right _ _), ← order_of_eq_card_of_forall_mem_gpowers hg]}, exact order_of_dvd_of_pow_eq_one hgmn end⟩) ... ≤ n : let ⟨m, hm⟩ := gcd_dvd_right n (fintype.card α) in have hm0 : 0 < m, from nat.pos_of_ne_zero (λ hm0, (by rw [hm0, mul_zero, fintype.card_eq_zero_iff] at hm; exact hm 1)), begin rw [← fintype.card_of_finset' _ (λ _, set.mem_to_finset), ← order_eq_card_gpowers, order_of_pow, order_of_eq_card_of_forall_mem_gpowers hg], rw [hm] {occs := occurrences.pos [2,3]}, rw [nat.mul_div_cancel_left _ (gcd_pos_of_pos_left _ hn0), gcd_mul_left_left, hm, nat.mul_div_cancel _ hm0], exact le_of_dvd hn0 (gcd_dvd_left _ _) end section totient variables [group α] [fintype α] [decidable_eq α] (hn : ∀ n : ℕ, 0 < n → (univ.filter (λ a : α, a ^ n = 1)).card ≤ n) include hn lemma card_pow_eq_one_eq_order_of_aux (a : α) : (finset.univ.filter (λ b : α, b ^ order_of a = 1)).card = order_of a := le_antisymm (hn _ (order_of_pos _)) (calc order_of a = @fintype.card (gpowers a) (id _) : order_eq_card_gpowers ... ≤ @fintype.card (↑(univ.filter (λ b : α, b ^ order_of a = 1)) : set α) (fintype.of_finset _ (λ _, iff.rfl)) : @fintype.card_le_of_injective (gpowers a) (↑(univ.filter (λ b : α, b ^ order_of a = 1)) : set α) (id _) (id _) (λ b, ⟨b.1, mem_filter.2 ⟨mem_univ _, let ⟨i, hi⟩ := b.2 in by rw [← hi, ← gpow_coe_nat, ← gpow_mul, mul_comm, gpow_mul, gpow_coe_nat, pow_order_of_eq_one, one_gpow]⟩⟩) (λ _ _ h, subtype.eq (subtype.mk.inj h)) ... = (univ.filter (λ b : α, b ^ order_of a = 1)).card : fintype.card_of_finset _ _) open_locale nat -- use φ for nat.totient private lemma card_order_of_eq_totient_aux₁ : ∀ {d : ℕ}, d ∣ fintype.card α → 0 < (univ.filter (λ a : α, order_of a = d)).card → (univ.filter (λ a : α, order_of a = d)).card = φ d | 0 := λ hd hd0, let ⟨a, ha⟩ := card_pos.1 hd0 in absurd (mem_filter.1 ha).2 $ ne_of_gt $ order_of_pos a | (d+1) := λ hd hd0, let ⟨a, ha⟩ := card_pos.1 hd0 in have ha : order_of a = d.succ, from (mem_filter.1 ha).2, have h : ((range d.succ).filter (∣ d.succ)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) = ((range d.succ).filter (∣ d.succ)).sum φ, from finset.sum_congr rfl (λ m hm, have hmd : m < d.succ, from mem_range.1 (mem_filter.1 hm).1, have hm : m ∣ d.succ, from (mem_filter.1 hm).2, card_order_of_eq_totient_aux₁ (dvd.trans hm hd) (finset.card_pos.2 ⟨a ^ (d.succ / m), mem_filter.2 ⟨mem_univ _, by rw [order_of_pow, ha, gcd_eq_right (div_dvd_of_dvd hm), nat.div_div_self hm (succ_pos _)]⟩⟩)), have hinsert : insert d.succ ((range d.succ).filter (∣ d.succ)) = (range d.succ.succ).filter (∣ d.succ), from (finset.ext.2 $ λ x, ⟨λ h, (mem_insert.1 h).elim (λ h, by simp [h, range_succ]) (by clear _let_match; simp [range_succ]; tauto), by clear _let_match; simp [range_succ] {contextual := tt}; tauto⟩), have hinsert₁ : d.succ ∉ (range d.succ).filter (∣ d.succ), by simp [mem_range, zero_le_one, le_succ], (add_right_inj (((range d.succ).filter (∣ d.succ)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card))).1 (calc _ = (insert d.succ (filter (∣ d.succ) (range d.succ))).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : eq.symm (finset.sum_insert (by simp [mem_range, zero_le_one, le_succ])) ... = ((range d.succ.succ).filter (∣ d.succ)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : sum_congr hinsert (λ _ _, rfl) ... = (univ.filter (λ a : α, a ^ d.succ = 1)).card : sum_card_order_of_eq_card_pow_eq_one (succ_pos d) ... = ((range d.succ.succ).filter (∣ d.succ)).sum φ : ha ▸ (card_pow_eq_one_eq_order_of_aux hn a).symm ▸ (sum_totient _).symm ... = _ : by rw [h, ← sum_insert hinsert₁]; exact finset.sum_congr hinsert.symm (λ _ _, rfl)) lemma card_order_of_eq_totient_aux₂ {d : ℕ} (hd : d ∣ fintype.card α) : (univ.filter (λ a : α, order_of a = d)).card = φ d := by_contradiction $ λ h, have h0 : (univ.filter (λ a : α , order_of a = d)).card = 0 := not_not.1 (mt nat.pos_iff_ne_zero.2 (mt (card_order_of_eq_totient_aux₁ hn hd) h)), let c := fintype.card α in have hc0 : 0 < c, from fintype.card_pos_iff.2 ⟨1⟩, lt_irrefl c $ calc c = (univ.filter (λ a : α, a ^ c = 1)).card : congr_arg card $ by simp [finset.ext, c] ... = ((range c.succ).filter (∣ c)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : (sum_card_order_of_eq_card_pow_eq_one hc0).symm ... = (((range c.succ).filter (∣ c)).erase d).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : eq.symm (sum_subset (erase_subset _ _) (λ m hm₁ hm₂, have m = d, by simp at *; cc, by simp [*, finset.ext] at *; exact h0)) ... ≤ (((range c.succ).filter (∣ c)).erase d).sum φ : sum_le_sum (λ m hm, have hmc : m ∣ c, by simp at hm; tauto, (imp_iff_not_or.1 (card_order_of_eq_totient_aux₁ hn hmc)).elim (λ h, by simp [nat.le_zero_iff.1 (le_of_not_gt h), nat.zero_le]) (by simp [le_refl] {contextual := tt})) ... < φ d + (((range c.succ).filter (∣ c)).erase d).sum φ : lt_add_of_pos_left _ (totient_pos (nat.pos_of_ne_zero (λ h, nat.pos_iff_ne_zero.1 hc0 (eq_zero_of_zero_dvd $ h ▸ hd)))) ... = (insert d (((range c.succ).filter (∣ c)).erase d)).sum φ : eq.symm (sum_insert (by simp)) ... = ((range c.succ).filter (∣ c)).sum φ : finset.sum_congr (finset.insert_erase (mem_filter.2 ⟨mem_range.2 (lt_succ_of_le (le_of_dvd hc0 hd)), hd⟩)) (λ _ _, rfl) ... = c : sum_totient _ lemma is_cyclic_of_card_pow_eq_one_le : is_cyclic α := have (univ.filter (λ a : α, order_of a = fintype.card α)).nonempty, from (card_pos.1 $ by rw [card_order_of_eq_totient_aux₂ hn (dvd_refl _)]; exact totient_pos (fintype.card_pos_iff.2 ⟨1⟩)), let ⟨x, hx⟩ := this in is_cyclic_of_order_of_eq_card x (finset.mem_filter.1 hx).2 end totient lemma is_cyclic.card_order_of_eq_totient [group α] [is_cyclic α] [fintype α] [decidable_eq α] {d : ℕ} (hd : d ∣ fintype.card α) : (univ.filter (λ a : α, order_of a = d)).card = totient d := card_order_of_eq_totient_aux₂ (λ n, is_cyclic.card_pow_eq_one_le) hd end cyclic
0ea72d677ebe024b0bcbea91a14519554a929f98
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/ring_theory/subring.lean
c8a4050c4d4fae0a33d9e85e721f3dfbf32c3a10
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
7,954
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import group_theory.subgroup import algebra.ring universes u v open group variables {R : Type u} [ring R] /-- `S` is a subring: a set containing 1 and closed under multiplication, addition and and additive inverse. -/ class is_subring (S : set R) extends is_add_subgroup S, is_submonoid S : Prop. instance subset.ring {S : set R} [is_subring S] : ring S := by subtype_instance instance subtype.ring {S : set R} [is_subring S] : ring (subtype S) := subset.ring namespace is_ring_hom instance {S : set R} [is_subring S] : is_ring_hom (@subtype.val R S) := by refine {..} ; intros ; refl instance is_subring_preimage {R : Type u} {S : Type v} [ring R] [ring S] (f : R → S) [is_ring_hom f] (s : set S) [is_subring s] : is_subring (f ⁻¹' s) := {} instance is_subring_image {R : Type u} {S : Type v} [ring R] [ring S] (f : R → S) [is_ring_hom f] (s : set R) [is_subring s] : is_subring (f '' s) := {} instance is_subring_set_range {R : Type u} {S : Type v} [ring R] [ring S] (f : R → S) [is_ring_hom f] : is_subring (set.range f) := {} end is_ring_hom instance subtype_val.is_ring_hom {s : set R} [is_subring s] : is_ring_hom (subtype.val : s → R) := { ..subtype_val.is_add_group_hom, ..subtype_val.is_monoid_hom } instance coe.is_ring_hom {s : set R} [is_subring s] : is_ring_hom (coe : s → R) := subtype_val.is_ring_hom instance subtype_mk.is_ring_hom {γ : Type*} [ring γ] {s : set R} [is_subring s] (f : γ → R) [is_ring_hom f] (h : ∀ x, f x ∈ s) : is_ring_hom (λ x, (⟨f x, h x⟩ : s)) := { ..subtype_mk.is_add_group_hom f h, ..subtype_mk.is_monoid_hom f h } instance set_inclusion.is_ring_hom {s t : set R} [is_subring s] [is_subring t] (h : s ⊆ t) : is_ring_hom (set.inclusion h) := subtype_mk.is_ring_hom _ _ variables {cR : Type u} [comm_ring cR] instance subset.comm_ring {S : set cR} [is_subring S] : comm_ring S := by subtype_instance instance subtype.comm_ring {S : set cR} [is_subring S] : comm_ring (subtype S) := subset.comm_ring instance subring.domain {D : Type*} [integral_domain D] (S : set D) [is_subring S] : integral_domain S := by subtype_instance instance is_subring.inter (S₁ S₂ : set R) [is_subring S₁] [is_subring S₂] : is_subring (S₁ ∩ S₂) := { } instance is_subring.Inter {ι : Sort*} (S : ι → set R) [h : ∀ y : ι, is_subring (S y)] : is_subring (set.Inter S) := { } lemma is_subring_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set R) [∀ i, is_subring (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subring (⋃i, s i) := { to_is_add_subgroup := is_add_subgroup_Union_of_directed s directed, to_is_submonoid := is_submonoid_Union_of_directed s directed } namespace ring def closure (s : set R) := add_group.closure (monoid.closure s) variable {s : set R} local attribute [reducible] closure theorem exists_list_of_mem_closure {a : R} (h : a ∈ closure s) : (∃ L : list (list R), (∀ l ∈ L, ∀ x ∈ l, x ∈ s ∨ x = (-1:R)) ∧ (L.map list.prod).sum = a) := add_group.in_closure.rec_on h (λ x hx, match x, monoid.exists_list_of_mem_closure hx with | _, ⟨L, h1, rfl⟩ := ⟨[L], list.forall_mem_singleton.2 (λ r hr, or.inl (h1 r hr)), zero_add _⟩ end) ⟨[], list.forall_mem_nil _, rfl⟩ (λ b _ ih, match b, ih with | _, ⟨L1, h1, rfl⟩ := ⟨L1.map (list.cons (-1)), λ L2 h2, match L2, list.mem_map.1 h2 with | _, ⟨L3, h3, rfl⟩ := list.forall_mem_cons.2 ⟨or.inr rfl, h1 L3 h3⟩ end, by simp only [list.map_map, (∘), list.prod_cons, neg_one_mul]; exact list.rec_on L1 neg_zero.symm (λ hd tl ih, by rw [list.map_cons, list.sum_cons, ih, list.map_cons, list.sum_cons, neg_add])⟩ end) (λ r1 r2 hr1 hr2 ih1 ih2, match r1, r2, ih1, ih2 with | _, _, ⟨L1, h1, rfl⟩, ⟨L2, h2, rfl⟩ := ⟨L1 ++ L2, list.forall_mem_append.2 ⟨h1, h2⟩, by rw [list.map_append, list.sum_append]⟩ end) @[elab_as_eliminator] protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s) (h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n)) (ha : ∀ {x y}, C x → C y → C (x + y)) : C x := begin have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1, rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx, induction L with hd tl ih, { exact h0 }, rw list.forall_mem_cons at HL, suffices : C (list.prod hd), { rw [list.map_cons, list.sum_cons], exact ha this (ih HL.2) }, replace HL := HL.1, clear ih tl, suffices : ∃ L : list R, (∀ x ∈ L, x ∈ s) ∧ (list.prod hd = list.prod L ∨ list.prod hd = -list.prod L), { rcases this with ⟨L, HL', HP | HP⟩, { rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 }, rw list.forall_mem_cons at HL', rw list.prod_cons, exact hs _ HL'.1 _ (ih HL'.2) }, rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 }, rw [list.prod_cons, neg_mul_eq_mul_neg], rw list.forall_mem_cons at HL', exact hs _ HL'.1 _ (ih HL'.2) }, induction hd with hd tl ih, { exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ }, rw list.forall_mem_cons at HL, rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $ by rw [list.prod_cons, list.prod_cons, HP]⟩ }, { exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ }, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $ by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ }, { exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ } end instance : is_subring (closure s) := { one_mem := add_group.mem_closure (is_submonoid.one_mem _), mul_mem := λ a b ha hb, add_group.in_closure.rec_on hb (λ b hb, add_group.in_closure.rec_on ha (λ a ha, add_group.subset_closure (is_submonoid.mul_mem ha hb)) ((zero_mul b).symm ▸ is_add_submonoid.zero_mem _) (λ a ha hab, (neg_mul_eq_neg_mul a b) ▸ is_add_subgroup.neg_mem hab) (λ a c ha hc hab hcb, (add_mul a c b).symm ▸ is_add_submonoid.add_mem hab hcb)) ((mul_zero a).symm ▸ is_add_submonoid.zero_mem _) (λ b hb hab, (neg_mul_eq_mul_neg a b) ▸ is_add_subgroup.neg_mem hab) (λ b c hb hc hab hac, (mul_add a b c).symm ▸ is_add_submonoid.add_mem hab hac), .. add_group.closure.is_add_subgroup _ } theorem mem_closure {a : R} : a ∈ s → a ∈ closure s := add_group.mem_closure ∘ @monoid.subset_closure _ _ _ _ theorem subset_closure : s ⊆ closure s := λ _, mem_closure theorem closure_subset {t : set R} [is_subring t] : s ⊆ t → closure s ⊆ t := add_group.closure_subset ∘ monoid.closure_subset theorem closure_subset_iff (s t : set R) [is_subring t] : closure s ⊆ t ↔ s ⊆ t := (add_group.closure_subset_iff _ t).trans ⟨set.subset.trans monoid.subset_closure, monoid.closure_subset⟩ theorem closure_mono {s t : set R} (H : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans H subset_closure lemma image_closure {S : Type*} [ring S] (f : R → S) [is_ring_hom f] (s : set R) : f '' closure s = closure (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { rw [is_monoid_hom.map_one f], apply is_submonoid.one_mem }, { rw [is_ring_hom.map_neg f, is_monoid_hom.map_one f], apply is_add_subgroup.neg_mem, apply is_submonoid.one_mem }, { rw [is_monoid_hom.map_mul f], apply is_submonoid.mul_mem; solve_by_elim [subset_closure, set.mem_image_of_mem] }, { rw [is_ring_hom.map_add f], apply is_add_submonoid.add_mem, assumption' }, end (closure_subset $ set.image_subset _ subset_closure) end ring
54faedec2906780bcf6d4f3e57be9f46f614385a
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Meta/Tactic/Assumption.lean
c38a503875f99a8c9a3cf6ab99ebe40550dd3f3b
[ "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
879
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.ExprDefEq import Lean.Meta.Tactic.Util namespace Lean.Meta def assumptionAux (mvarId : MVarId) : MetaM Bool := withMVarContext mvarId do checkNotAssigned mvarId `assumption let mvarType ← getMVarType mvarId let lctx ← getLCtx let h? ← lctx.findDeclRevM? fun decl => do if decl.isAuxDecl then pure none else if (← isDefEq mvarType decl.type) then pure (some decl.toExpr) else pure none match h? with | some h => do assignExprMVar mvarId h; pure true | none => pure false def assumption (mvarId : MVarId) : MetaM Unit := unless (← assumptionAux mvarId) do throwTacticEx `assumption mvarId "" end Lean.Meta
da0dfd75b619d15252c7fe7c5754f14b2d994491
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/category_theory/limits/shapes/regular_mono.lean
84ef5d5f4591358b548f97ef8b3f606cc84900a8
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
5,476
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 category_theory.limits.shapes.kernels import category_theory.limits.shapes.strong_epi /-! # Definitions and basic properties of regular and normal monomorphisms and epimorphisms. A regular monomorphism is a morphism that is the equalizer of some parallel pair. A normal monomorphism is a morphism that is the kernel of some other morphism. We give the constructions * `split_mono → regular_mono` * `normal_mono → regular_mono`, and * `regular_mono → mono` as well as the dual constructions for regular and normal epimorphisms. Additionally, we give the construction * `regular_epi ⟶ strong_epi`. -/ namespace category_theory open category_theory.limits universes v₁ u₁ variables {C : Type u₁} [category.{v₁} C] variables {X Y : C} /-- A regular monomorphism is a morphism which is the equalizer of some parallel pair. -/ class regular_mono (f : X ⟶ Y) := (Z : C) (left right : Y ⟶ Z) (w : f ≫ left = f ≫ right) (is_limit : is_limit (fork.of_ι f w)) attribute [reassoc] regular_mono.w /-- Every regular monomorphism is a monomorphism. -/ @[priority 100] instance regular_mono.mono (f : X ⟶ Y) [regular_mono f] : mono f := mono_of_is_limit_parallel_pair regular_mono.is_limit /-- Every split monomorphism is a regular monomorphism. -/ @[priority 100] instance regular_mono.of_split_mono (f : X ⟶ Y) [split_mono f] : regular_mono f := { Z := Y, left := 𝟙 Y, right := retraction f ≫ f, w := by tidy, is_limit := split_mono_equalizes f } /-- If `f` is a regular mono, then any map `k : W ⟶ Y` equalizing `regular_mono.left` and `regular_mono.right` induces a morphism `l : W ⟶ X` such that `l ≫ f = k`. -/ def regular_mono.lift' {W : C} (f : X ⟶ Y) [regular_mono f] (k : W ⟶ Y) (h : k ≫ (regular_mono.left : Y ⟶ @regular_mono.Z _ _ _ _ f _) = k ≫ regular_mono.right) : {l : W ⟶ X // l ≫ f = k} := fork.is_limit.lift' regular_mono.is_limit _ h section variables [has_zero_morphisms.{v₁} C] /-- A normal monomorphism is a morphism which is the kernel of some morphism. -/ class normal_mono (f : X ⟶ Y) := (Z : C) (g : Y ⟶ Z) (w : f ≫ g = 0) (is_limit : is_limit (kernel_fork.of_ι f w)) /-- Every normal monomorphism is a regular monomorphism. -/ @[priority 100] instance normal_mono.regular_mono (f : X ⟶ Y) [I : normal_mono f] : regular_mono f := { left := I.g, right := 0, w := (by simpa using I.w), ..I } /-- If `f` is a normal mono, then any map `k : W ⟶ Y` such that `k ≫ normal_mono.g = 0` induces a morphism `l : W ⟶ X` such that `l ≫ f = k`. -/ def normal_mono.lift' {W : C} (f : X ⟶ Y) [normal_mono f] (k : W ⟶ Y) (h : k ≫ normal_mono.g = 0) : {l : W ⟶ X // l ≫ f = k} := kernel_fork.is_limit.lift' normal_mono.is_limit _ h end /-- A regular epimorphism is a morphism which is the coequalizer of some parallel pair. -/ class regular_epi (f : X ⟶ Y) := (W : C) (left right : W ⟶ X) (w : left ≫ f = right ≫ f) (is_colimit : is_colimit (cofork.of_π f w)) attribute [reassoc] regular_epi.w /-- Every regular epimorphism is an epimorphism. -/ @[priority 100] instance regular_epi.epi (f : X ⟶ Y) [regular_epi f] : epi f := epi_of_is_colimit_parallel_pair regular_epi.is_colimit /-- Every split epimorphism is a regular epimorphism. -/ @[priority 100] instance regular_epi.of_split_epi (f : X ⟶ Y) [split_epi f] : regular_epi f := { W := X, left := 𝟙 X, right := f ≫ section_ f, w := by tidy, is_colimit := split_epi_coequalizes f } /-- If `f` is a regular epi, then every morphism `k : X ⟶ W` coequalizing `regular_epi.left` and `regular_epi.right` induces `l : Y ⟶ W` such that `f ≫ l = k`. -/ def regular_epi.desc' {W : C} (f : X ⟶ Y) [regular_epi f] (k : X ⟶ W) (h : (regular_epi.left : regular_epi.W f ⟶ X) ≫ k = regular_epi.right ≫ k) : {l : Y ⟶ W // f ≫ l = k} := cofork.is_colimit.desc' (regular_epi.is_colimit) _ h @[priority 100] instance strong_epi_of_regular_epi (f : X ⟶ Y) [regular_epi f] : strong_epi f := { epi := by apply_instance, has_lift := begin introsI, have : (regular_epi.left : regular_epi.W f ⟶ X) ≫ u = regular_epi.right ≫ u, { apply (cancel_mono z).1, simp only [category.assoc, h, regular_epi.w_assoc] }, obtain ⟨t, ht⟩ := regular_epi.desc' f u this, exact ⟨t, ht, (cancel_epi f).1 (by simp only [←category.assoc, ht, ←h, arrow.mk_hom, arrow.hom_mk'_right])⟩, end } section variables [has_zero_morphisms.{v₁} C] /-- A normal epimorphism is a morphism which is the cokernel of some morphism. -/ class normal_epi (f : X ⟶ Y) := (W : C) (g : W ⟶ X) (w : g ≫ f = 0) (is_colimit : is_colimit (cokernel_cofork.of_π f w)) /-- Every normal epimorphism is a regular epimorphism. -/ @[priority 100] instance normal_epi.regular_epi (f : X ⟶ Y) [I : normal_epi f] : regular_epi f := { left := I.g, right := 0, w := (by simpa using I.w), ..I } /-- If `f` is a normal epi, then every morphism `k : X ⟶ W` satisfying `normal_epi.g ≫ k = 0` induces `l : Y ⟶ W` such that `f ≫ l = k`. -/ def normal_epi.desc' {W : C} (f : X ⟶ Y) [normal_epi f] (k : X ⟶ W) (h : normal_epi.g ≫ k = 0) : {l : Y ⟶ W // f ≫ l = k} := cokernel_cofork.is_colimit.desc' (normal_epi.is_colimit) _ h end end category_theory
70e3f68ac6fb7f0e663573abe62bd8a29422ba17
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/syntaxInNamespacesAndPP.lean
effec3aa65e6f9c6ecfd1eb8d2a4670ba75d59db
[ "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
287
lean
namespace Foo syntax "foo" term : term macro_rules | `(foo $x) => x set_option trace.Elab true in #check foo true end Foo namespace Bla syntax (name := bla) "bla" term : term macro_rules | `(bla $x) => x set_option trace.Elab true in #check bla true #print Bla.bla end Bla
33697673117b0641edf746267fde55b8071dba0a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/jacobson_ideal.lean
8055f53a97848ac0f1f7675b7e2e32f3d361f1f6
[ "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
14,782
lean
/- Copyright (c) 2020 Devon Tuma. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Devon Tuma -/ import ring_theory.ideal.quotient import ring_theory.polynomial.basic /-! # Jacobson radical The Jacobson radical of a ring `R` is defined to be the intersection of all maximal ideals of `R`. This is similar to how the nilradical is equal to the intersection of all prime ideals of `R`. We can extend the idea of the nilradical to ideals of `R`, by letting the radical of an ideal `I` be the intersection of prime ideals containing `I`. Under this extension, the original nilradical is the radical of the zero ideal `⊥`. Here we define the Jacobson radical of an ideal `I` in a similar way, as the intersection of maximal ideals containing `I`. ## Main definitions Let `R` be a commutative ring, and `I` be an ideal of `R` * `jacobson I` is the jacobson radical, i.e. the infimum of all maximal ideals containing I. * `is_local I` is the proposition that the jacobson radical of `I` is itself a maximal ideal ## Main statements * `mem_jacobson_iff` gives a characterization of members of the jacobson of I * `is_local_of_is_maximal_radical`: if the radical of I is maximal then so is the jacobson radical ## Tags Jacobson, Jacobson radical, Local Ideal -/ universes u v namespace ideal variables {R : Type u} {S : Type v} open_locale polynomial section jacobson section ring variables [ring R] [ring S] {I : ideal R} /-- The Jacobson radical of `I` is the infimum of all maximal (left) ideals containing `I`. -/ def jacobson (I : ideal R) : ideal R := Inf {J : ideal R | I ≤ J ∧ is_maximal J} lemma le_jacobson : I ≤ jacobson I := λ x hx, mem_Inf.mpr (λ J hJ, hJ.left hx) @[simp] lemma jacobson_idem : jacobson (jacobson I) = jacobson I := le_antisymm (Inf_le_Inf (λ J hJ, ⟨Inf_le hJ, hJ.2⟩)) le_jacobson @[simp] lemma jacobson_top : jacobson (⊤ : ideal R) = ⊤ := eq_top_iff.2 le_jacobson @[simp] theorem jacobson_eq_top_iff : jacobson I = ⊤ ↔ I = ⊤ := ⟨λ H, classical.by_contradiction $ λ hi, let ⟨M, hm, him⟩ := exists_le_maximal I hi in lt_top_iff_ne_top.1 (lt_of_le_of_lt (show jacobson I ≤ M, from Inf_le ⟨him, hm⟩) $ lt_top_iff_ne_top.2 hm.ne_top) H, λ H, eq_top_iff.2 $ le_Inf $ λ J ⟨hij, hj⟩, H ▸ hij⟩ lemma jacobson_eq_bot : jacobson I = ⊥ → I = ⊥ := λ h, eq_bot_iff.mpr (h ▸ le_jacobson) lemma jacobson_eq_self_of_is_maximal [H : is_maximal I] : I.jacobson = I := le_antisymm (Inf_le ⟨le_of_eq rfl, H⟩) le_jacobson @[priority 100] instance jacobson.is_maximal [H : is_maximal I] : is_maximal (jacobson I) := ⟨⟨λ htop, H.1.1 (jacobson_eq_top_iff.1 htop), λ J hJ, H.1.2 _ (lt_of_le_of_lt le_jacobson hJ)⟩⟩ theorem mem_jacobson_iff {x : R} : x ∈ jacobson I ↔ ∀ y, ∃ z, z * y * x + z - 1 ∈ I := ⟨λ hx y, classical.by_cases (assume hxy : I ⊔ span {y * x + 1} = ⊤, let ⟨p, hpi, q, hq, hpq⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 hxy) in let ⟨r, hr⟩ := mem_span_singleton'.1 hq in ⟨r, by rw [mul_assoc, ←mul_add_one, hr, ← hpq, ← neg_sub, add_sub_cancel]; exact I.neg_mem hpi⟩) (assume hxy : I ⊔ span {y * x + 1} ≠ ⊤, let ⟨M, hm1, hm2⟩ := exists_le_maximal _ hxy in suffices x ∉ M, from (this $ mem_Inf.1 hx ⟨le_trans le_sup_left hm2, hm1⟩).elim, λ hxm, hm1.1.1 $ (eq_top_iff_one _).2 $ add_sub_cancel' (y * x) 1 ▸ M.sub_mem (le_sup_right.trans hm2 $ subset_span rfl) (M.mul_mem_left _ hxm)), λ hx, mem_Inf.2 $ λ M ⟨him, hm⟩, classical.by_contradiction $ λ hxm, let ⟨y, i, hi, df⟩ := hm.exists_inv hxm, ⟨z, hz⟩ := hx (-y) in hm.1.1 $ (eq_top_iff_one _).2 $ sub_sub_cancel (z * -y * x + z) 1 ▸ M.sub_mem (by { rw [mul_assoc, ←mul_add_one, neg_mul, ← (sub_eq_iff_eq_add.mpr df.symm), neg_sub, sub_add_cancel], exact M.mul_mem_left _ hi }) (him hz)⟩ lemma exists_mul_sub_mem_of_sub_one_mem_jacobson {I : ideal R} (r : R) (h : r - 1 ∈ jacobson I) : ∃ s, s * r - 1 ∈ I := begin cases mem_jacobson_iff.1 h 1 with s hs, use s, simpa [mul_sub] using hs end /-- An ideal equals its Jacobson radical iff it is the intersection of a set of maximal ideals. Allowing the set to include ⊤ is equivalent, and is included only to simplify some proofs. -/ theorem eq_jacobson_iff_Inf_maximal : I.jacobson = I ↔ ∃ M : set (ideal R), (∀ J ∈ M, is_maximal J ∨ J = ⊤) ∧ I = Inf M := begin use λ hI, ⟨{J : ideal R | I ≤ J ∧ J.is_maximal}, ⟨λ _ hJ, or.inl hJ.right, hI.symm⟩⟩, rintros ⟨M, hM, hInf⟩, refine le_antisymm (λ x hx, _) le_jacobson, rw [hInf, mem_Inf], intros I hI, cases hM I hI with is_max is_top, { exact (mem_Inf.1 hx) ⟨le_Inf_iff.1 (le_of_eq hInf) I hI, is_max⟩ }, { exact is_top.symm ▸ submodule.mem_top } end theorem eq_jacobson_iff_Inf_maximal' : I.jacobson = I ↔ ∃ M : set (ideal R), (∀ (J ∈ M) (K : ideal R), J < K → K = ⊤) ∧ I = Inf M := eq_jacobson_iff_Inf_maximal.trans ⟨λ h, let ⟨M, hM⟩ := h in ⟨M, ⟨λ J hJ K hK, or.rec_on (hM.1 J hJ) (λ h, h.1.2 K hK) (λ h, eq_top_iff.2 (le_of_lt (h ▸ hK))), hM.2⟩⟩, λ h, let ⟨M, hM⟩ := h in ⟨M, ⟨λ J hJ, or.rec_on (classical.em (J = ⊤)) (λ h, or.inr h) (λ h, or.inl ⟨⟨h, hM.1 J hJ⟩⟩), hM.2⟩⟩⟩ /-- An ideal `I` equals its Jacobson radical if and only if every element outside `I` also lies outside of a maximal ideal containing `I`. -/ lemma eq_jacobson_iff_not_mem : I.jacobson = I ↔ ∀ x ∉ I, ∃ M : ideal R, (I ≤ M ∧ M.is_maximal) ∧ x ∉ M := begin split, { intros h x hx, erw [← h, mem_Inf] at hx, push_neg at hx, exact hx }, { refine λ h, le_antisymm (λ x hx, _) le_jacobson, contrapose hx, erw mem_Inf, push_neg, exact h x hx } end theorem map_jacobson_of_surjective {f : R →+* S} (hf : function.surjective f) : ring_hom.ker f ≤ I → map f (I.jacobson) = (map f I).jacobson := begin intro h, unfold ideal.jacobson, have : ∀ J ∈ {J : ideal R | I ≤ J ∧ J.is_maximal}, f.ker ≤ J := λ J hJ, le_trans h hJ.left, refine trans (map_Inf hf this) (le_antisymm _ _), { refine Inf_le_Inf (λ J hJ, ⟨comap f J, ⟨⟨le_comap_of_map_le hJ.1, _⟩, map_comap_of_surjective f hf J⟩⟩), haveI : J.is_maximal := hJ.right, exact comap_is_maximal_of_surjective f hf }, { refine Inf_le_Inf_of_subset_insert_top (λ j hj, hj.rec_on (λ J hJ, _)), rw ← hJ.2, cases map_eq_top_or_is_maximal_of_surjective f hf hJ.left.right with htop hmax, { exact htop.symm ▸ set.mem_insert ⊤ _ }, { exact set.mem_insert_of_mem ⊤ ⟨map_mono hJ.1.1, hmax⟩ } }, end lemma map_jacobson_of_bijective {f : R →+* S} (hf : function.bijective f) : map f (I.jacobson) = (map f I).jacobson := map_jacobson_of_surjective hf.right (le_trans (le_of_eq (f.injective_iff_ker_eq_bot.1 hf.left)) bot_le) lemma comap_jacobson {f : R →+* S} {K : ideal S} : comap f (K.jacobson) = Inf (comap f '' {J : ideal S | K ≤ J ∧ J.is_maximal}) := trans (comap_Inf' f _) (Inf_eq_infi).symm theorem comap_jacobson_of_surjective {f : R →+* S} (hf : function.surjective f) {K : ideal S} : comap f (K.jacobson) = (comap f K).jacobson := begin unfold ideal.jacobson, refine le_antisymm _ _, { refine le_trans (comap_mono (le_of_eq (trans top_inf_eq.symm Inf_insert.symm))) _, rw [comap_Inf', Inf_eq_infi], refine infi_le_infi_of_subset (λ J hJ, _), have : comap f (map f J) = J := trans (comap_map_of_surjective f hf J) (le_antisymm (sup_le_iff.2 ⟨le_of_eq rfl, le_trans (comap_mono bot_le) hJ.left⟩) le_sup_left), cases map_eq_top_or_is_maximal_of_surjective _ hf hJ.right with htop hmax, { refine ⟨⊤, ⟨set.mem_insert ⊤ _, htop ▸ this⟩⟩ }, { refine ⟨map f J, ⟨set.mem_insert_of_mem _ ⟨le_map_of_comap_le_of_surjective f hf hJ.1, hmax⟩, this⟩⟩ } }, { rw comap_Inf, refine le_infi_iff.2 (λ J, (le_infi_iff.2 (λ hJ, _))), haveI : J.is_maximal := hJ.right, refine Inf_le ⟨comap_mono hJ.left, comap_is_maximal_of_surjective _ hf⟩ } end @[mono] lemma jacobson_mono {I J : ideal R} : I ≤ J → I.jacobson ≤ J.jacobson := begin intros h x hx, erw mem_Inf at ⊢ hx, exact λ K ⟨hK, hK_max⟩, hx ⟨trans h hK, hK_max⟩ end end ring section comm_ring variables [comm_ring R] [comm_ring S] {I : ideal R} lemma radical_le_jacobson : radical I ≤ jacobson I := le_Inf (λ J hJ, (radical_eq_Inf I).symm ▸ Inf_le ⟨hJ.left, is_maximal.is_prime hJ.right⟩) lemma is_radical_of_eq_jacobson (h : jacobson I = I) : I.is_radical := radical_le_jacobson.trans h.le lemma is_unit_of_sub_one_mem_jacobson_bot (r : R) (h : r - 1 ∈ jacobson (⊥ : ideal R)) : is_unit r := begin cases exists_mul_sub_mem_of_sub_one_mem_jacobson r h with s hs, rw [mem_bot, sub_eq_zero, mul_comm] at hs, exact is_unit_of_mul_eq_one _ _ hs end lemma mem_jacobson_bot {x : R} : x ∈ jacobson (⊥ : ideal R) ↔ ∀ y, is_unit (x * y + 1) := ⟨λ hx y, let ⟨z, hz⟩ := (mem_jacobson_iff.1 hx) y in is_unit_iff_exists_inv.2 ⟨z, by rwa [add_mul, one_mul, ← sub_eq_zero, mul_right_comm, mul_comm _ z, mul_right_comm]⟩, λ h, mem_jacobson_iff.mpr (λ y, (let ⟨b, hb⟩ := is_unit_iff_exists_inv.1 (h y) in ⟨b, (submodule.mem_bot R).2 (hb ▸ (by ring))⟩))⟩ /-- An ideal `I` of `R` is equal to its Jacobson radical if and only if the Jacobson radical of the quotient ring `R/I` is the zero ideal -/ theorem jacobson_eq_iff_jacobson_quotient_eq_bot : I.jacobson = I ↔ jacobson (⊥ : ideal (R ⧸ I)) = ⊥ := begin have hf : function.surjective (quotient.mk I) := submodule.quotient.mk_surjective I, split, { intro h, replace h := congr_arg (map (quotient.mk I)) h, rw map_jacobson_of_surjective hf (le_of_eq mk_ker) at h, simpa using h }, { intro h, replace h := congr_arg (comap (quotient.mk I)) h, rw [comap_jacobson_of_surjective hf, ← (quotient.mk I).ker_eq_comap_bot] at h, simpa using h } end /-- The standard radical and Jacobson radical of an ideal `I` of `R` are equal if and only if the nilradical and Jacobson radical of the quotient ring `R/I` coincide -/ theorem radical_eq_jacobson_iff_radical_quotient_eq_jacobson_bot : I.radical = I.jacobson ↔ radical (⊥ : ideal (R ⧸ I)) = jacobson ⊥ := begin have hf : function.surjective (quotient.mk I) := submodule.quotient.mk_surjective I, split, { intro h, have := congr_arg (map (quotient.mk I)) h, rw [map_radical_of_surjective hf (le_of_eq mk_ker), map_jacobson_of_surjective hf (le_of_eq mk_ker)] at this, simpa using this }, { intro h, have := congr_arg (comap (quotient.mk I)) h, rw [comap_radical, comap_jacobson_of_surjective hf, ← (quotient.mk I).ker_eq_comap_bot] at this, simpa using this } end lemma jacobson_radical_eq_jacobson : I.radical.jacobson = I.jacobson := le_antisymm (le_trans (le_of_eq (congr_arg jacobson (radical_eq_Inf I))) (Inf_le_Inf (λ J hJ, ⟨Inf_le ⟨hJ.1, hJ.2.is_prime⟩, hJ.2⟩))) (jacobson_mono le_radical) end comm_ring end jacobson section polynomial open polynomial variables [comm_ring R] lemma jacobson_bot_polynomial_le_Inf_map_maximal : jacobson (⊥ : ideal R[X]) ≤ Inf (map (C : R →+* R[X]) '' {J : ideal R | J.is_maximal}) := begin refine le_Inf (λ J, exists_imp_distrib.2 (λ j hj, _)), haveI : j.is_maximal := hj.1, refine trans (jacobson_mono bot_le) (le_of_eq _ : J.jacobson ≤ J), suffices : (⊥ : ideal (polynomial (R ⧸ j))).jacobson = ⊥, { rw [← hj.2, jacobson_eq_iff_jacobson_quotient_eq_bot], replace this := congr_arg (map (polynomial_quotient_equiv_quotient_polynomial j).to_ring_hom) this, rwa [map_jacobson_of_bijective _, map_bot] at this, exact (ring_equiv.bijective (polynomial_quotient_equiv_quotient_polynomial j)) }, refine eq_bot_iff.2 (λ f hf, _), simpa [(λ hX, by simpa using congr_arg (λ f, coeff f 1) hX : (X : (R ⧸ j)[X]) ≠ 0)] using eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit ((mem_jacobson_bot.1 hf) X)), end lemma jacobson_bot_polynomial_of_jacobson_bot (h : jacobson (⊥ : ideal R) = ⊥) : jacobson (⊥ : ideal R[X]) = ⊥ := begin refine eq_bot_iff.2 (le_trans jacobson_bot_polynomial_le_Inf_map_maximal _), refine (λ f hf, ((submodule.mem_bot _).2 (polynomial.ext (λ n, trans _ (coeff_zero n).symm)))), suffices : f.coeff n ∈ ideal.jacobson ⊥, by rwa [h, submodule.mem_bot] at this, exact mem_Inf.2 (λ j hj, (mem_map_C_iff.1 ((mem_Inf.1 hf) ⟨j, ⟨hj.2, rfl⟩⟩)) n), end end polynomial section is_local variables [comm_ring R] /-- An ideal `I` is local iff its Jacobson radical is maximal. -/ class is_local (I : ideal R) : Prop := (out : is_maximal (jacobson I)) theorem is_local_iff {I : ideal R} : is_local I ↔ is_maximal (jacobson I) := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem is_local_of_is_maximal_radical {I : ideal R} (hi : is_maximal (radical I)) : is_local I := ⟨have radical I = jacobson I, from le_antisymm (le_Inf $ λ M ⟨him, hm⟩, hm.is_prime.radical_le_iff.2 him) (Inf_le ⟨le_radical, hi⟩), show is_maximal (jacobson I), from this ▸ hi⟩ theorem is_local.le_jacobson {I J : ideal R} (hi : is_local I) (hij : I ≤ J) (hj : J ≠ ⊤) : J ≤ jacobson I := let ⟨M, hm, hjm⟩ := exists_le_maximal J hj in le_trans hjm $ le_of_eq $ eq.symm $ hi.1.eq_of_le hm.1.1 $ Inf_le ⟨le_trans hij hjm, hm⟩ theorem is_local.mem_jacobson_or_exists_inv {I : ideal R} (hi : is_local I) (x : R) : x ∈ jacobson I ∨ ∃ y, y * x - 1 ∈ I := classical.by_cases (assume h : I ⊔ span {x} = ⊤, let ⟨p, hpi, q, hq, hpq⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 h) in let ⟨r, hr⟩ := mem_span_singleton.1 hq in or.inr ⟨r, by rw [← hpq, mul_comm, ← hr, ← neg_sub, add_sub_cancel]; exact I.neg_mem hpi⟩) (assume h : I ⊔ span {x} ≠ ⊤, or.inl $ le_trans le_sup_right (hi.le_jacobson le_sup_left h) $ mem_span_singleton.2 $ dvd_refl x) end is_local theorem is_primary_of_is_maximal_radical [comm_ring R] {I : ideal R} (hi : is_maximal (radical I)) : is_primary I := have radical I = jacobson I, from le_antisymm (le_Inf $ λ M ⟨him, hm⟩, hm.is_prime.radical_le_iff.2 him) (Inf_le ⟨le_radical, hi⟩), ⟨ne_top_of_lt $ lt_of_le_of_lt le_radical (lt_top_iff_ne_top.2 hi.1.1), λ x y hxy, ((is_local_of_is_maximal_radical hi).mem_jacobson_or_exists_inv y).symm.imp (λ ⟨z, hz⟩, by rw [← mul_one x, ← sub_sub_cancel (z * y) 1, mul_sub, mul_left_comm]; exact I.sub_mem (I.mul_mem_left _ hxy) (I.mul_mem_left _ hz)) (this ▸ id)⟩ end ideal
2412ad724f71f3dcd4628cbb407944c3b93d9c94
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20161026_ICTAC_Tutorial/ex9.lean
f6e177b65e52857aa9f6192fdc373cc107722d5a
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
720
lean
check fun x : nat, x + 5 check λ x : nat, x + 5 constants A B : Type constants a1 a2 : A constants b1 b2 : B constant f : A → A constant g : A → B constant h : A → B → A constant p : A → A → bool check fun x : A, f x -- A → A check λ x : A, f x -- A → A check λ x : A, f (f x) -- A → A check λ x : A, h x b1 -- A → A check λ y : B, h a1 y -- B → A check λ x : A, p (f (f x)) (h (f a1) b2) -- A → bool check λ x : A, λ y : B, h (f x) y -- A → B → A check λ (x : A) (y : B), h (f x) y -- A → B → A check λ x y, h (f x) y -- A → B → A
bb1cfcf39530da80f017e69dc768ea38781f4636
8930e38ac0fae2e5e55c28d0577a8e44e2639a6d
/data/prod.lean
7b3e402d2f6fcac773be57c00149e5dd066895e0
[ "Apache-2.0" ]
permissive
SG4316/mathlib
3d64035d02a97f8556ad9ff249a81a0a51a3321a
a7846022507b531a8ab53b8af8a91953fceafd3a
refs/heads/master
1,584,869,960,527
1,530,718,645,000
1,530,724,110,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,160
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 Extends theory on products -/ universes u v variables {α : Type u} {β : Type v} @[simp] theorem prod.forall {p : α × β → Prop} : (∀ x, p x) ↔ (∀ a b, p (a, b)) := ⟨assume h a b, h (a, b), assume h ⟨a, b⟩, h a b⟩ @[simp] theorem prod.exists {p : α × β → Prop} : (∃ x, p x) ↔ (∃ a b, p (a, b)) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ namespace prod @[simp] theorem mk.inj_iff {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) = (a₂, b₂) ↔ (a₁ = a₂ ∧ b₁ = b₂) := ⟨prod.mk.inj, by cc⟩ lemma ext_iff {p q : α × β} : p = q ↔ p.1 = q.1 ∧ p.2 = q.2 := by rw [← @mk.eta _ _ p, ← @mk.eta _ _ q, mk.inj_iff] lemma ext {α β} {p q : α × β} : p.1 = q.1 → p.2 = q.2 → p = q := by rw [ext_iff] ; intros ; split ; assumption /-- Swap the factors of a product. `swap (a, b) = (b, a)` -/ def swap : α × β → β × α := λp, (p.2, p.1) @[simp] lemma swap_swap : ∀ x : α × β, swap (swap x) = x | ⟨a, b⟩ := rfl @[simp] lemma fst_swap {p : α × β} : (swap p).1 = p.2 := rfl @[simp] lemma snd_swap {p : α × β} : (swap p).2 = p.1 := rfl @[simp] lemma swap_prod_mk {a : α} {b : β} : swap (a, b) = (b, a) := rfl @[simp] lemma swap_swap_eq : swap ∘ swap = @id (α × β) := funext swap_swap @[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap := swap_swap @[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap := swap_swap lemma eq_iff_fst_eq_snd_eq : ∀{p q : α × β}, p = q ↔ (p.1 = q.1 ∧ p.2 = q.2) | ⟨p₁, p₂⟩ ⟨q₁, q₂⟩ := by simp theorem lex_def (r : α → α → Prop) (s : β → β → Prop) {p q : α × β} : prod.lex r s p q ↔ r p.1 q.1 ∨ p.1 = q.1 ∧ s p.2 q.2 := ⟨λ h, by cases h; simp *, λ h, match p, q, h with | (a, b), (c, d), or.inl h := lex.left _ _ _ h | (a, b), (c, d), or.inr ⟨e, h⟩ := by change a = c at e; subst e; exact lex.right _ _ h end⟩ end prod
51c4d5777bcb7fc680a177ae541e88914af1a2e1
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/algebra/pi_instances.lean
51ab01f57db6e19926bf7753ca3b10ed46af7ba2
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
19,382
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot Pi instances for algebraic structures. -/ import algebra.module import ring_theory.subring namespace pi universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) instance has_zero [∀ i, has_zero $ f i] : has_zero (Π i : I, f i) := ⟨λ i, 0⟩ @[simp] lemma zero_apply [∀ i, has_zero $ f i] : (0 : Π i, f i) i = 0 := rfl instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ i, 1⟩ @[simp] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl attribute [to_additive] pi.has_one attribute [to_additive] pi.one_apply instance has_add [∀ i, has_add $ f i] : has_add (Π i : I, f i) := ⟨λ x y, λ i, x i + y i⟩ @[simp] lemma add_apply [∀ i, has_add $ f i] : (x + y) i = x i + y i := rfl instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ x y, λ i, x i * y i⟩ @[simp] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl attribute [to_additive] pi.has_mul attribute [to_additive] pi.mul_apply instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ x, λ i, (x i)⁻¹⟩ @[simp] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl instance has_neg [∀ i, has_neg $ f i] : has_neg (Π i : I, f i) := ⟨λ x, λ i, -(x i)⟩ @[simp] lemma neg_apply [∀ i, has_neg $ f i] : (-x) i = -x i := rfl attribute [to_additive] pi.has_inv attribute [to_additive] pi.inv_apply instance has_scalar {α : Type*} [∀ i, has_scalar α $ f i] : has_scalar α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩ @[simp] lemma smul_apply {α : Type*} [∀ i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) := by pi_instance instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) := by pi_instance instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) := by pi_instance instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) := by pi_instance instance group [∀ i, group $ f i] : group (Π i : I, f i) := by pi_instance instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) := by pi_instance instance add_semigroup [∀ i, add_semigroup $ f i] : add_semigroup (Π i : I, f i) := by pi_instance instance add_comm_semigroup [∀ i, add_comm_semigroup $ f i] : add_comm_semigroup (Π i : I, f i) := by pi_instance instance add_monoid [∀ i, add_monoid $ f i] : add_monoid (Π i : I, f i) := by pi_instance instance add_comm_monoid [∀ i, add_comm_monoid $ f i] : add_comm_monoid (Π i : I, f i) := by pi_instance instance add_group [∀ i, add_group $ f i] : add_group (Π i : I, f i) := by pi_instance instance add_comm_group [∀ i, add_comm_group $ f i] : add_comm_group (Π i : I, f i) := by pi_instance instance semiring [∀ i, semiring $ f i] : semiring (Π i : I, f i) := by pi_instance instance ring [∀ i, ring $ f i] : ring (Π i : I, f i) := by pi_instance instance comm_ring [∀ i, comm_ring $ f i] : comm_ring (Π i : I, f i) := by pi_instance instance mul_action (α) {m : monoid α} [∀ i, mul_action α $ f i] : mul_action α (Π i : I, f i) := { smul := λ c f i, c • f i, mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _, one_smul := λ f, funext $ λ i, one_smul α _ } instance distrib_mul_action (α) {m : monoid α} [∀ i, add_monoid $ f i] [∀ i, distrib_mul_action α $ f i] : distrib_mul_action α (Π i : I, f i) := { smul_zero := λ c, funext $ λ i, smul_zero _, smul_add := λ c f g, funext $ λ i, smul_add _ _ _, ..pi.mul_action _ } variables (I f) instance semimodule (α) {r : semiring α} [∀ i, add_comm_monoid $ f i] [∀ i, semimodule α $ f i] : semimodule α (Π i : I, f i) := { add_smul := λ c f g, funext $ λ i, add_smul _ _ _, zero_smul := λ f, funext $ λ i, zero_smul α _, ..pi.distrib_mul_action _ } variables {I f} instance module (α) {r : ring α} [∀ i, add_comm_group $ f i] [∀ i, module α $ f i] : module α (Π i : I, f i) := {..pi.semimodule I f α} instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] : left_cancel_semigroup (Π i : I, f i) := by pi_instance instance add_left_cancel_semigroup [∀ i, add_left_cancel_semigroup $ f i] : add_left_cancel_semigroup (Π i : I, f i) := by pi_instance instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] : right_cancel_semigroup (Π i : I, f i) := by pi_instance instance add_right_cancel_semigroup [∀ i, add_right_cancel_semigroup $ f i] : add_right_cancel_semigroup (Π i : I, f i) := by pi_instance instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_add_comm_monoid $ f i] : ordered_cancel_add_comm_monoid (Π i : I, f i) := by pi_instance instance ordered_add_comm_group [∀ i, ordered_add_comm_group $ f i] : ordered_add_comm_group (Π i : I, f i) := { add_le_add_left := λ x y hxy c i, add_le_add_left (hxy i) _, ..pi.add_comm_group, ..pi.partial_order } attribute [to_additive add_semigroup] pi.semigroup attribute [to_additive add_comm_semigroup] pi.comm_semigroup attribute [to_additive add_monoid] pi.monoid attribute [to_additive add_comm_monoid] pi.comm_monoid attribute [to_additive add_group] pi.group attribute [to_additive add_comm_group] pi.comm_group attribute [to_additive add_left_cancel_semigroup] pi.left_cancel_semigroup attribute [to_additive add_right_cancel_semigroup] pi.right_cancel_semigroup @[simp] lemma sub_apply [∀ i, add_group $ f i] : (x - y) i = x i - y i := rfl @[to_additive] lemma list_prod_apply {α : Type*} {β : α → Type*} [∀a, monoid (β a)] (a : α) : ∀ (l : list (Πa, β a)), l.prod a = (l.map (λf:Πa, β a, f a)).prod | [] := rfl | (f :: l) := by simp [mul_apply f l.prod a, list_prod_apply l] @[to_additive] lemma multiset_prod_apply {α : Type*} {β : α → Type*} [∀a, comm_monoid (β a)] (a : α) (s : multiset (Πa, β a)) : s.prod a = (s.map (λf:Πa, β a, f a)).prod := quotient.induction_on s $ assume l, begin simp [list_prod_apply a l] end @[to_additive] lemma finset_prod_apply {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)] (a : α) (s : finset γ) (g : γ → Πa, β a) : s.prod g a = s.prod (λc, g c a) := show (s.val.map g).prod a = (s.val.map (λc, g c a)).prod, by rw [multiset_prod_apply, multiset.map_map] /-- A family of ring homomorphisms `f a : γ →+* β a` defines a ring homomorphism `pi.ring_hom f : γ →+* Π a, β a` given by `pi.ring_hom f x b = f b x`. -/ protected def ring_hom {α : Type u} {β : α → Type v} [R : Π a : α, semiring (β a)] {γ : Type w} [semiring γ] (f : Π a : α, γ →+* β a) : γ →+* Π a, β a := { to_fun := λ x b, f b x, map_add' := λ x y, funext $ λ z, (f z).map_add x y, map_mul' := λ x y, funext $ λ z, (f z).map_mul x y, map_one' := funext $ λ z, (f z).map_one, map_zero' := funext $ λ z, (f z).map_zero } instance is_ring_hom_pi {α : Type u} {β : α → Type v} [R : Π a : α, ring (β a)] {γ : Type w} [ring γ] (f : Π a : α, γ → β a) [Rh : Π a : α, is_ring_hom (f a)] : is_ring_hom (λ x b, f b x) := (show γ →+* Π a, β a, from pi.ring_hom (λ a, ring_hom.of (f a))).is_ring_hom -- Note that we only define `single` here for dependent functions with additive fibres. section variables [decidable_eq I] variables [Π i, has_zero (f i)] /-- The function supported at `i`, with value `x` there. -/ def single (i : I) (x : f i) : Π i, f i := λ i', if h : i' = i then (by { subst h, exact x }) else 0 @[simp] lemma single_eq_same (i : I) (x : f i) : single i x i = x := begin dsimp [single], split_ifs, { refl, }, { exfalso, exact h rfl, } end @[simp] lemma single_eq_of_ne {i i' : I} (h : i' ≠ i) (x : f i) : single i x i' = 0 := begin dsimp [single], split_ifs with h', { exfalso, exact h h', }, { refl, } end end end pi section universes u v variable {I : Type u} -- The indexing type variable (f : I → Type v) -- The family of types already equipped with instances variables [Π i, monoid (f i)] /-- Evaluation of functions into an indexed collection of monoids at a point is a monoid homomorphism. -/ @[to_additive "Evaluation of functions into an indexed collection of additive monoids at a point is an additive monoid homomorphism."] def monoid_hom.apply (i : I) : (Π i, f i) →* f i := { to_fun := λ g, g i, map_one' := rfl, map_mul' := λ x y, rfl, } @[simp, to_additive] lemma monoid_hom.apply_apply (i : I) (g : Π i, f i) : (monoid_hom.apply f i) g = g i := rfl end section universes u v variable {I : Type u} -- The indexing type variable (f : I → Type v) -- The family of types already equipped with instances variables [Π i, semiring (f i)] /-- Evaluation of functions into an indexed collection of monoids at a point is a monoid homomorphism. -/ def ring_hom.apply (i : I) : (Π i, f i) →+* f i := { ..(monoid_hom.apply f i), ..(add_monoid_hom.apply f i) } @[simp] lemma ring_hom.apply_apply (i : I) (g : Π i, f i) : (ring_hom.apply f i) g = g i := rfl end section variables {I : Type*} (Z : I → Type*) variables [Π i, comm_monoid (Z i)] @[simp, to_additive] lemma finset.prod_apply {γ : Type*} {s : finset γ} (h : γ → (Π i, Z i)) (i : I) : (s.prod h) i = s.prod (λ g, h g i) := begin classical, induction s using finset.induction_on with b s nmem ih, { simp only [finset.prod_empty], refl }, { simp only [nmem, finset.prod_insert, not_false_iff], rw pi.mul_apply (h b) _ i, rw ih, } end end section -- As we only defined `single` into `add_monoid`, we only prove the `finset.sum` version here. variables {I : Type*} [decidable_eq I] {Z : I → Type*} variables [Π i, add_comm_monoid (Z i)] lemma finset.univ_sum_single [fintype I] (f : Π i, Z i) : finset.univ.sum (λ i, pi.single i (f i)) = f := begin ext a, rw [finset.sum_apply, finset.sum_eq_single a], { simp, }, { intros b _ h, simp [h.symm], }, { intro h, exfalso, simpa using h, }, end end section open pi variables {I : Type*} [decidable_eq I] variable (f : I → Type*) section variables [Π i, add_monoid (f i)] /-- The additive monoid homomorphism including a single additive monoid into a dependent family of additive monoids, as functions supported at a point. -/ def add_monoid_hom.single (i : I) : f i →+ Π i, f i := { to_fun := λ x, single i x, map_zero' := begin ext i', by_cases h : i' = i, { subst h, simp only [single_eq_same], refl, }, { simp only [h, single_eq_of_ne, ne.def, not_false_iff], refl, }, end, map_add' := λ x y, begin ext i', by_cases h : i' = i, -- FIXME in the next two `simp only`s, -- it would be really nice to not have to provide the arguments to `add_apply`. { subst h, simp only [single_eq_same, add_apply (single i' x) (single i' y) i'], }, { simp only [h, add_zero, single_eq_of_ne, add_apply (single i x) (single i y) i', ne.def, not_false_iff], }, end, } @[simp] lemma add_monoid_hom.single_apply {i : I} (x : f i) : (add_monoid_hom.single f i) x = single i x := rfl end section variables {f} variables [Π i, add_comm_monoid (f i)] @[ext] lemma add_monoid_hom.functions_ext [fintype I] (G : Type*) [add_comm_monoid G] (g h : (Π i, f i) →+ G) (w : ∀ (i : I) (x : f i), g (single i x) = h (single i x)) : g = h := begin ext k, rw [←finset.univ_sum_single k, add_monoid_hom.map_sum, add_monoid_hom.map_sum], apply finset.sum_congr rfl, intros, apply w, end end section variables {f} variables [Π i, semiring (f i)] -- it is somewhat unfortunate that we can't easily use `add_monoid_hom.functions_ext` here @[ext] lemma ring_hom.functions_ext [fintype I] (G : Type*) [semiring G] (g h : (Π i, f i) →+* G) (w : ∀ (i : I) (x : f i), g (single i x) = h (single i x)) : g = h := begin ext k, rw [←finset.univ_sum_single k, ring_hom.map_sum, ring_hom.map_sum], apply finset.sum_congr rfl, intros, apply w, end end end namespace prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {p q : α × β} @[to_additive is_add_monoid_hom] lemma fst.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.fst : α × β → α) := { map_mul := λ _ _, rfl, map_one := rfl } @[to_additive is_add_monoid_hom] lemma snd.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.snd : α × β → β) := { map_mul := λ _ _, rfl, map_one := rfl } @[to_additive is_add_group_hom] lemma fst.is_group_hom [group α] [group β] : is_group_hom (prod.fst : α × β → α) := { map_mul := λ _ _, rfl } @[to_additive is_add_group_hom] lemma snd.is_group_hom [group α] [group β] : is_group_hom (prod.snd : α × β → β) := { map_mul := λ _ _, rfl } attribute [instance] fst.is_monoid_hom fst.is_add_monoid_hom snd.is_monoid_hom snd.is_add_monoid_hom fst.is_group_hom fst.is_add_group_hom snd.is_group_hom snd.is_add_group_hom @[to_additive] lemma fst_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} : (t.prod f).1 = t.prod (λc, (f c).1) := (monoid_hom.fst α β).map_prod f t @[to_additive] lemma snd_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} : (t.prod f).2 = t.prod (λc, (f c).2) := (monoid_hom.snd α β).map_prod f t instance [semiring α] [semiring β] : semiring (α × β) := { zero_mul := λ a, mk.inj_iff.mpr ⟨zero_mul _, zero_mul _⟩, mul_zero := λ a, mk.inj_iff.mpr ⟨mul_zero _, mul_zero _⟩, left_distrib := λ a b c, mk.inj_iff.mpr ⟨left_distrib _ _ _, left_distrib _ _ _⟩, right_distrib := λ a b c, mk.inj_iff.mpr ⟨right_distrib _ _ _, right_distrib _ _ _⟩, ..prod.add_comm_monoid, ..prod.monoid } instance [ring α] [ring β] : ring (α × β) := { ..prod.add_comm_group, ..prod.semiring } instance [comm_ring α] [comm_ring β] : comm_ring (α × β) := { ..prod.ring, ..prod.comm_monoid } instance [nonzero_comm_ring α] [comm_ring β] : nonzero_comm_ring (α × β) := { zero_ne_one := mt (congr_arg prod.fst) zero_ne_one, ..prod.comm_ring } instance fst.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.fst : α × β → α) := by refine_struct {..}; simp instance snd.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.snd : α × β → β) := by refine_struct {..}; simp instance fst.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.fst : α × β → α) := by refine_struct {..}; simp instance snd.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.snd : α × β → β) := by refine_struct {..}; simp /-- Left injection function for the inner product From a vector space (and also group and module) perspective the product is the same as the sum of two vector spaces. `inl` and `inr` provide the corresponding injection functions. -/ def inl [has_zero β] (a : α) : α × β := (a, 0) /-- Right injection function for the inner product -/ def inr [has_zero α] (b : β) : α × β := (0, b) lemma injective_inl [has_zero β] : function.injective (inl : α → α × β) := assume x y h, (prod.mk.inj_iff.mp h).1 lemma injective_inr [has_zero α] : function.injective (inr : β → α × β) := assume x y h, (prod.mk.inj_iff.mp h).2 @[simp] lemma inl_eq_inl [has_zero β] {a₁ a₂ : α} : (inl a₁ : α × β) = inl a₂ ↔ a₁ = a₂ := iff.intro (assume h, injective_inl h) (assume h, h ▸ rfl) @[simp] lemma inr_eq_inr [has_zero α] {b₁ b₂ : β} : (inr b₁ : α × β) = inr b₂ ↔ b₁ = b₂ := iff.intro (assume h, injective_inr h) (assume h, h ▸ rfl) @[simp] lemma inl_eq_inr [has_zero α] [has_zero β] {a : α} {b : β} : inl a = inr b ↔ a = 0 ∧ b = 0 := by constructor; simp [inl, inr] {contextual := tt} @[simp] lemma inr_eq_inl [has_zero α] [has_zero β] {a : α} {b : β} : inr b = inl a ↔ a = 0 ∧ b = 0 := by constructor; simp [inl, inr] {contextual := tt} @[simp] lemma fst_inl [has_zero β] (a : α) : (inl a : α × β).1 = a := rfl @[simp] lemma snd_inl [has_zero β] (a : α) : (inl a : α × β).2 = 0 := rfl @[simp] lemma fst_inr [has_zero α] (b : β) : (inr b : α × β).1 = 0 := rfl @[simp] lemma snd_inr [has_zero α] (b : β) : (inr b : α × β).2 = b := rfl instance [has_scalar α β] [has_scalar α γ] : has_scalar α (β × γ) := ⟨λa p, (a • p.1, a • p.2)⟩ @[simp] theorem smul_fst [has_scalar α β] [has_scalar α γ] (a : α) (x : β × γ) : (a • x).1 = a • x.1 := rfl @[simp] theorem smul_snd [has_scalar α β] [has_scalar α γ] (a : α) (x : β × γ) : (a • x).2 = a • x.2 := rfl @[simp] theorem smul_mk [has_scalar α β] [has_scalar α γ] (a : α) (b : β) (c : γ) : a • (b, c) = (a • b, a • c) := rfl instance {r : semiring α} [add_comm_monoid β] [add_comm_monoid γ] [semimodule α β] [semimodule α γ] : semimodule α (β × γ) := { smul_add := assume a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩, add_smul := assume a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩, mul_smul := assume a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩, one_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _ _, one_smul _ _⟩, zero_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _ _, zero_smul _ _⟩, smul_zero := assume a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩, .. prod.has_scalar } instance {r : ring α} [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] : module α (β × γ) := {} section substructures variables (s : set α) (t : set β) @[to_additive is_add_submonoid] instance [monoid α] [monoid β] [is_submonoid s] [is_submonoid t] : is_submonoid (s.prod t) := { one_mem := by rw set.mem_prod; split; apply is_submonoid.one_mem, mul_mem := by intros; rw set.mem_prod at *; split; apply is_submonoid.mul_mem; tauto } @[to_additive prod.is_add_subgroup.prod] instance is_subgroup.prod [group α] [group β] [is_subgroup s] [is_subgroup t] : is_subgroup (s.prod t) := { inv_mem := by intros; rw set.mem_prod at *; split; apply is_subgroup.inv_mem; tauto, .. prod.is_submonoid s t } instance is_subring.prod [ring α] [ring β] [is_subring s] [is_subring t] : is_subring (s.prod t) := { .. prod.is_submonoid s t, .. prod.is_add_subgroup.prod s t } end substructures end prod namespace finset @[to_additive prod_mk_sum] lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ) (f : γ → α) (g : γ → β) : (s.prod f, s.prod g) = s.prod (λ x, (f x, g x)) := by haveI := classical.dec_eq γ; exact finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt}) end finset
df832c819e88cfca10e731af73b03328bb199254
12b755d17b2fc1d2a08d39a11658674c4dc6c2c3
/Testforpush.lean
84b75b6e79918c0e5c96d7e4e68cc0f7508cc96f
[]
no_license
UVM-M52/lean-hdthomas
a0066caf3bddd8fc8075016257a63a4d80a8fb33
1d399a5bb22544831ff466b2fe4cec38832b8ba6
refs/heads/master
1,609,092,927,189
1,580,748,817,000
1,580,748,817,000
238,001,939
0
0
null
null
null
null
UTF-8
Lean
false
false
78
lean
theorem my_first_theorem (P : Prop) : P → P := begin intro, assumption, end
9e120eb8d41966988161c489ef06bdfa73e7a368
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/order/filter/cofinite.lean
1edda3b8f90e9615ab786c722b7495fa802bde35
[ "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
5,241
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov -/ import order.filter.at_top_bot /-! # The cofinite filter In this file we define `cofinite`: the filter of sets with finite complement and prove its basic properties. In particular, we prove that for `ℕ` it is equal to `at_top`. ## TODO Define filters for other cardinalities of the complement. -/ open set open_locale classical variables {α : Type*} namespace filter /-- The cofinite filter is the filter of subsets whose complements are finite. -/ def cofinite : filter α := { sets := {s | finite sᶜ}, univ_sets := by simp only [compl_univ, finite_empty, mem_set_of_eq], sets_of_superset := assume s t (hs : finite sᶜ) (st: s ⊆ t), hs.subset $ compl_subset_compl.2 st, inter_sets := assume s t (hs : finite sᶜ) (ht : finite (tᶜ)), by simp only [compl_inter, finite.union, ht, hs, mem_set_of_eq] } @[simp] lemma mem_cofinite {s : set α} : s ∈ (@cofinite α) ↔ finite sᶜ := iff.rfl @[simp] lemma eventually_cofinite {p : α → Prop} : (∀ᶠ x in cofinite, p x) ↔ finite {x | ¬p x} := iff.rfl instance cofinite_ne_bot [infinite α] : ne_bot (@cofinite α) := ⟨mt empty_in_sets_eq_bot.mpr $ by { simp only [mem_cofinite, compl_empty], exact infinite_univ }⟩ lemma frequently_cofinite_iff_infinite {p : α → Prop} : (∃ᶠ x in cofinite, p x) ↔ set.infinite {x | p x} := by simp only [filter.frequently, filter.eventually, mem_cofinite, compl_set_of, not_not, set.infinite] /-- The coproduct of the cofinite filters on two types is the cofinite filter on their product. -/ lemma coprod_cofinite {β : Type*} : (cofinite : filter α).coprod (cofinite : filter β) = cofinite := begin ext S, simp only [mem_coprod_iff, exists_prop, mem_comap_sets, mem_cofinite], split, { rintro ⟨⟨A, hAf, hAS⟩, B, hBf, hBS⟩, rw [← compl_subset_compl, ← preimage_compl] at hAS hBS, exact (hAf.prod hBf).subset (subset_inter hAS hBS) }, { intro hS, refine ⟨⟨(prod.fst '' Sᶜ)ᶜ, _, _⟩, ⟨(prod.snd '' Sᶜ)ᶜ, _, _⟩⟩, { simpa using hS.image prod.fst }, { simpa [compl_subset_comm] using subset_preimage_image prod.fst Sᶜ }, { simpa using hS.image prod.snd }, { simpa [compl_subset_comm] using subset_preimage_image prod.snd Sᶜ } }, end end filter open filter lemma set.finite.compl_mem_cofinite {s : set α} (hs : s.finite) : sᶜ ∈ (@cofinite α) := mem_cofinite.2 $ (compl_compl s).symm ▸ hs lemma set.finite.eventually_cofinite_nmem {s : set α} (hs : s.finite) : ∀ᶠ x in cofinite, x ∉ s := hs.compl_mem_cofinite lemma finset.eventually_cofinite_nmem (s : finset α) : ∀ᶠ x in cofinite, x ∉ s := s.finite_to_set.eventually_cofinite_nmem lemma set.infinite_iff_frequently_cofinite {s : set α} : set.infinite s ↔ (∃ᶠ x in cofinite, x ∈ s) := frequently_cofinite_iff_infinite.symm lemma filter.eventually_cofinite_ne (x : α) : ∀ᶠ a in cofinite, a ≠ x := (set.finite_singleton x).eventually_cofinite_nmem /-- For natural numbers the filters `cofinite` and `at_top` coincide. -/ lemma nat.cofinite_eq_at_top : @cofinite ℕ = at_top := begin ext s, simp only [mem_cofinite, mem_at_top_sets], split, { assume hs, use (hs.to_finset.sup id) + 1, assume b hb, by_contradiction hbs, have := hs.to_finset.subset_range_sup_succ (hs.mem_to_finset.2 hbs), exact not_lt_of_le hb (finset.mem_range.1 this) }, { rintros ⟨N, hN⟩, apply (finite_lt_nat N).subset, assume n hn, change n < N, exact lt_of_not_ge (λ hn', hn $ hN n hn') } end lemma nat.frequently_at_top_iff_infinite {p : ℕ → Prop} : (∃ᶠ n in at_top, p n) ↔ set.infinite {n | p n} := by simp only [← nat.cofinite_eq_at_top, frequently_cofinite_iff_infinite] lemma filter.tendsto.exists_forall_le {α β : Type*} [nonempty α] [linear_order β] {f : α → β} (hf : tendsto f cofinite at_top) : ∃ a₀, ∀ a, f a₀ ≤ f a := begin inhabit α, by_cases not_all_top : ∃ y, ∃ x, f y < x, { -- take the inverse image, `small_vals`, of some bounded nonempty set; it's finite so has a min haveI : nonempty β := ⟨f (default α)⟩, obtain ⟨y, x, hx⟩ := not_all_top, let small_vals : finset α := (filter.eventually_cofinite.mp ((at_top_basis.tendsto_right_iff).1 hf x trivial)).to_finset, have y_in : y ∈ small_vals := by simp [hx], obtain ⟨a₀, -, others_bigger⟩ := small_vals.exists_min_image f ⟨y, y_in⟩, use a₀, intros a, by_cases h : a ∈ small_vals, { exact others_bigger a h }, refine le_trans (others_bigger y y_in) (le_trans hx.le _), simpa using h }, { -- in this case, f is constant because all values are at top push_neg at not_all_top, use default α, intros a, exact not_all_top a (f $ default α) } end lemma filter.tendsto.exists_forall_ge {α β : Type*} [nonempty α] [linear_order β] {f : α → β} (hf : tendsto f cofinite at_bot) : ∃ a₀, ∀ a, f a ≤ f a₀ := @filter.tendsto.exists_forall_le _ (order_dual β) _ _ _ hf
549b4e5f7945ae62aeb5f99459ef3f6ef3268202
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Meta/ExprDefEq.lean
722717e0670eaba8e5f58632b983acdca62bc549
[ "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
41,883
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.ProjFns import Init.Lean.Meta.WHNF import Init.Lean.Meta.InferType import Init.Lean.Meta.FunInfo import Init.Lean.Meta.LevelDefEq import Init.Lean.Meta.Check import Init.Lean.Meta.Offset namespace Lean namespace Meta /-- Try to solve `a := (fun x => t) =?= b` by eta-expanding `b`. Remark: eta-reduction is not a good alternative even in a system without universe cumulativity like Lean. Example: ``` (fun x : A => f ?m) =?= f ``` The left-hand side of the constraint above it not eta-reduced because `?m` is a metavariable. -/ private def isDefEqEta (a b : Expr) : MetaM Bool := if a.isLambda && !b.isLambda then do bType ← inferType b; bType ← whnfD bType; match bType with | Expr.forallE n d _ c => let b' := Lean.mkLambda n c.binderInfo d (mkApp b (mkBVar 0)); commitWhen $ isExprDefEqAux a b' | _ => pure false else pure false /-- Support for `Lean.reduceBool` and `Lean.reduceNat` -/ def isDefEqNative (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM $ isExprDefEqAux s t; s? ← reduceNative? s; t? ← reduceNative? t; match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for reducing Nat basic operations. -/ def isDefEqNat (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM $ isExprDefEqAux s t; if s.hasFVar || s.hasMVar || t.hasFVar || t.hasMVar then pure LBool.undef else do s? ← reduceNat? s; t? ← reduceNat? t; match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for constraints of the form `("..." =?= String.mk cs)` -/ def isDefEqStringLit (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM $ isExprDefEqAux s t; if s.isStringLit && t.isAppOf `String.mk then isDefEq (WHNF.toCtorIfLit s) t else if s.isAppOf `String.mk && t.isStringLit then isDefEq s (WHNF.toCtorIfLit t) else pure LBool.undef /-- Return `true` if `e` is of the form `fun (x_1 ... x_n) => ?m x_1 ... x_n)`, and `?m` is unassigned. Remark: `n` may be 0. -/ def isEtaUnassignedMVar (e : Expr) : MetaM Bool := match e.etaExpanded? with | some (Expr.mvar mvarId _) => condM (isReadOnlyOrSyntheticOpaqueExprMVar mvarId) (pure false) (condM (isExprMVarAssigned mvarId) (pure false) (pure true)) | _ => pure false /- First pass for `isDefEqArgs`. We unify explicit arguments, *and* easy cases Here, we say a case is easy if it is of the form ?m =?= t or t =?= ?m where `?m` is unassigned. These easy cases are not just an optimization. When `?m` is a function, by assigning it to t, we make sure a unification constraint (in the explicit part) ``` ?m t =?= f s ``` is not higher-order. We also handle the eta-expanded cases: ``` fun x₁ ... xₙ => ?m x₁ ... xₙ =?= t t =?= fun x₁ ... xₙ => ?m x₁ ... xₙ This is important because type inference often produces eta-expanded terms, and without this extra case, we could introduce counter intuitive behavior. Pre: `paramInfo.size <= args₁.size = args₂.size` -/ private partial def isDefEqArgsFirstPass (paramInfo : Array ParamInfo) (args₁ args₂ : Array Expr) : Nat → Array Nat → MetaM (Option (Array Nat)) | i, postponed => if h : i < paramInfo.size then let info := paramInfo.get ⟨i, h⟩; let a₁ := args₁.get! i; let a₂ := args₂.get! i; if info.implicit || info.instImplicit then condM (isEtaUnassignedMVar a₁ <||> isEtaUnassignedMVar a₂) (condM (isExprDefEqAux a₁ a₂) (isDefEqArgsFirstPass (i+1) postponed) (pure none)) (isDefEqArgsFirstPass (i+1) (postponed.push i)) else condM (isExprDefEqAux a₁ a₂) (isDefEqArgsFirstPass (i+1) postponed) (pure none) else pure (some postponed) private partial def isDefEqArgsAux (args₁ args₂ : Array Expr) (h : args₁.size = args₂.size) : Nat → MetaM Bool | i => if h₁ : i < args₁.size then let a₁ := args₁.get ⟨i, h₁⟩; let a₂ := args₂.get ⟨i, h ▸ h₁⟩; condM (isExprDefEqAux a₁ a₂) (isDefEqArgsAux (i+1)) (pure false) else pure true @[specialize] private def trySynthPending (e : Expr) : MetaM Bool := do mvarId? ← getStuckMVar? e; match mvarId? with | some mvarId => synthPending mvarId | none => pure false private def isDefEqArgs (f : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := if h : args₁.size = args₂.size then do finfo ← getFunInfoNArgs f args₁.size; (some postponed) ← isDefEqArgsFirstPass finfo.paramInfo args₁ args₂ 0 #[] | pure false; (isDefEqArgsAux args₁ args₂ h finfo.paramInfo.size) <&&> (postponed.allM $ fun i => do /- Second pass: unify implicit arguments. In the second pass, we make sure we are unfolding at least non reducible definitions (default setting). -/ let a₁ := args₁.get! i; let a₂ := args₂.get! i; let info := finfo.paramInfo.get! i; when info.instImplicit $ do { trySynthPending a₁; trySynthPending a₂; pure () }; withAtLeastTransparency TransparencyMode.default $ isExprDefEqAux a₁ a₂) else pure false /-- Check whether the types of the free variables at `fvars` are definitionally equal to the types at `ds₂`. Pre: `fvars.size == ds₂.size` This method also updates the set of local instances, and invokes the continuation `k` with the updated set. We can't use `withNewLocalInstances` because the `isDeq fvarType d₂` may use local instances. -/ @[specialize] partial def isDefEqBindingDomain (fvars : Array Expr) (ds₂ : Array Expr) : Nat → MetaM Bool → MetaM Bool | i, k => if h : i < fvars.size then do let fvar := fvars.get ⟨i, h⟩; fvarDecl ← getFVarLocalDecl fvar; let fvarType := fvarDecl.type; let d₂ := ds₂.get! i; condM (isExprDefEqAux fvarType d₂) (do c? ← isClass fvarType; match c? with | some className => withNewLocalInstance className fvar $ isDefEqBindingDomain (i+1) k | none => isDefEqBindingDomain (i+1) k) (pure false) else k /- Auxiliary function for `isDefEqBinding` for handling binders `forall/fun`. It accumulates the new free variables in `fvars`, and declare them at `lctx`. We use the domain types of `e₁` to create the new free variables. We store the domain types of `e₂` at `ds₂`. -/ private partial def isDefEqBindingAux : LocalContext → Array Expr → Expr → Expr → Array Expr → MetaM Bool | lctx, fvars, e₁, e₂, ds₂ => let process (n : Name) (d₁ d₂ b₁ b₂ : Expr) : MetaM Bool := do { let d₁ := d₁.instantiateRev fvars; let d₂ := d₂.instantiateRev fvars; fvarId ← mkFreshId; let lctx := lctx.mkLocalDecl fvarId n d₁; let fvars := fvars.push (mkFVar fvarId); isDefEqBindingAux lctx fvars b₁ b₂ (ds₂.push d₂) }; match e₁, e₂ with | Expr.forallE n d₁ b₁ _, Expr.forallE _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | Expr.lam n d₁ b₁ _, Expr.lam _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | _, _ => adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $ isDefEqBindingDomain fvars ds₂ 0 $ isExprDefEqAux (e₁.instantiateRev fvars) (e₂.instantiateRev fvars) @[inline] private def isDefEqBinding (a b : Expr) : MetaM Bool := do lctx ← getLCtx; isDefEqBindingAux lctx #[] a b #[] private def checkTypesAndAssign (mvar : Expr) (v : Expr) : MetaM Bool := traceCtx `Meta.isDefEq.assign.checkTypes $ do -- must check whether types are definitionally equal or not, before assigning and returning true mvarType ← inferType mvar; vType ← inferType v; condM (withTransparency TransparencyMode.default $ isExprDefEqAux mvarType vType) (do trace! `Meta.isDefEq.assign.final (mvar ++ " := " ++ v); assignExprMVar mvar.mvarId! v; pure true) (do trace `Meta.isDefEq.assign.typeMismatch $ fun _ => mvar ++ " : " ++ mvarType ++ " := " ++ v ++ " : " ++ vType; pure false) /- Each metavariable is declared in a particular local context. We use the notation `C |- ?m : t` to denote a metavariable `?m` that was declared at the local context `C` with type `t` (see `MetavarDecl`). We also use `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`. The following method process the unification constraint ?m@C a₁ ... aₙ =?= t We say the unification constraint is a pattern IFF 1) `a₁ ... aₙ` are pairwise distinct free variables that are ​*not*​ let-variables. 2) `a₁ ... aₙ` are not in `C` 3) `t` only contains free variables in `C` and/or `{a₁, ..., aₙ}` 4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C` 5) `?m` does not occur in `t` Claim: we don't have to check free variable declarations. That is, if `t` contains a reference to `x : A := v`, we don't need to check `v`. Reason: The reference to `x` is a free variable, and it must be in `C` (by 1 and 3). If `x` is in `C`, then any metavariable occurring in `v` must have been defined in a strict subprefix of `C`. So, condition 4 and 5 are satisfied. If the conditions above have been satisfied, then the solution for the unification constrain is ?m := fun a₁ ... aₙ => t Now, we consider some workarounds/approximations. A1) Suppose `t` contains a reference to `x : A := v` and `x` is not in `C` (failed condition 3) (precise) solution: unfold `x` in `t`. A2) Suppose some `aᵢ` is in `C` (failed condition 2) (approximated) solution (when `config.foApprox` is set to true) : ignore condition and also use ?m := fun a₁ ... aₙ => t Here is an example where this approximation fails: Given `C` containing `a : nat`, consider the following two constraints ?m@C a =?= a ?m@C b =?= a If we use the approximation in the first constraint, we get ?m := fun x => x when we apply this solution to the second one we get a failure. IMPORTANT: When applying this approximation we need to make sure the abstracted term `fun a₁ ... aₙ => t` is type correct. The check can only be skipped in the pattern case described above. Consider the following example. Given the local context (α : Type) (a : α) we try to solve ?m α =?= @id α a If we use the approximation above we obtain: ?m := (fun α' => @id α' a) which is a type incorrect term. `a` has type `α` but it is expected to have type `α'`. The problem occurs because the right hand side contains a free variable `a` that depends on the free variable `α` being abstracted. Note that this dependency cannot occur in patterns. We can address this by type checking the term after abstraction. This is not a significant performance bottleneck because this case doesn't happen very often in practice (262 times when compiling stdlib on Jan 2018). The second example is trickier, but it also occurs less frequently (8 times when compiling stdlib on Jan 2018, and all occurrences were at Init/Control when we define monads and auxiliary combinators for them). We considered three options for the addressing the issue on the second example: A3) `a₁ ... aₙ` are not pairwise distinct (failed condition 1). In Lean3, we would try to approximate this case using an approach similar to A2. However, this approximation complicates the code, and is never used in the Lean3 stdlib and mathlib. A4) `t` contains a metavariable `?m'@C'` where `C'` is not a subprefix of `C`. If `?m'` is assigned, we substitute. If not, we create an auxiliary metavariable with a smaller scope. Actually, we let `elimMVarDeps` at `MetavarContext.lean` to perform this step. A5) If some `aᵢ` is not a free variable, then we use first-order unification (if `config.foApprox` is set to true) ?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k reduces to ?M a_1 ... a_i =?= f a_{i+1} =?= b_1 ... a_{i+k} =?= b_k A6) If (m =?= v) is of the form ?m a_1 ... a_n =?= ?m b_1 ... b_k then we use first-order unification (if `config.foApprox` is set to true) -/ namespace CheckAssignment structure Context extends Meta.Context := (mvarId : MVarId) (mvarDecl : MetavarDecl) (fvars : Array Expr) (hasCtxLocals : Bool) inductive Exception | occursCheck | useFOApprox | outOfScopeFVar (fvarId : FVarId) | readOnlyMVarWithBiggerLCtx (mvarId : MVarId) | unknownExprMVar (mvarId : MVarId) | meta (ex : Meta.Exception) structure State extends Meta.State := (checkCache : ExprStructMap Expr := {}) abbrev CheckAssignmentM := ReaderT Context (EStateM Exception State) private def findCached? (e : Expr) : CheckAssignmentM (Option Expr) := do s ← get; pure $ s.checkCache.find? e private def cache (e r : Expr) : CheckAssignmentM Unit := modify $ fun s => { checkCache := s.checkCache.insert e r, .. s } instance : MonadCache Expr Expr CheckAssignmentM := { findCached? := findCached?, cache := cache } def liftMetaM {α} (x : MetaM α) : CheckAssignmentM α := fun ctx s => match x ctx.toContext s.toState with | EStateM.Result.ok a newS => EStateM.Result.ok a { toState := newS, .. s } | EStateM.Result.error ex newS => EStateM.Result.error (Exception.meta ex) { toState := newS, .. s } @[inline] private def visit (f : Expr → CheckAssignmentM Expr) (e : Expr) : CheckAssignmentM Expr := if !e.hasExprMVar && !e.hasFVar then pure e else checkCache e f @[specialize] def checkFVar (check : Expr → CheckAssignmentM Expr) (fvar : Expr) : CheckAssignmentM Expr := do ctx ← read; if ctx.mvarDecl.lctx.containsFVar fvar then pure fvar else do let lctx := ctx.lctx; match lctx.findFVar? fvar with | some (LocalDecl.ldecl _ _ _ _ v) => visit check v | _ => if ctx.fvars.contains fvar then pure fvar else throw $ Exception.outOfScopeFVar fvar.fvarId! @[inline] def getMCtx : CheckAssignmentM MetavarContext := do s ← get; pure s.mctx def mkAuxMVar (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) : CheckAssignmentM Expr := do s ← get; let mvarId := s.ngen.curr; modify $ fun s => { ngen := s.ngen.next, mctx := s.mctx.addExprMVarDecl mvarId Name.anonymous lctx localInsts type, .. s }; pure (mkMVar mvarId) @[specialize] def checkMVar (check : Expr → CheckAssignmentM Expr) (mvar : Expr) : CheckAssignmentM Expr := do let mvarId := mvar.mvarId!; ctx ← read; mctx ← getMCtx; if mvarId == ctx.mvarId then throw Exception.occursCheck else match mctx.getExprAssignment? mvarId with | some v => check v | none => match mctx.findDecl? mvarId with | none => throw $ Exception.unknownExprMVar mvarId | some mvarDecl => if ctx.hasCtxLocals then throw $ Exception.useFOApprox -- It is not a pattern, then we fail and fall back to FO unification else if mvarDecl.lctx.isSubPrefixOf ctx.mvarDecl.lctx ctx.fvars then /- The local context of `mvar` - free variables being abstracted is a subprefix of the metavariable being assigned. We "substract" variables being abstracted because we use `elimMVarDeps` -/ pure mvar else if mvarDecl.depth != mctx.depth || mvarDecl.kind.isSyntheticOpaque then throw $ Exception.readOnlyMVarWithBiggerLCtx mvarId else if ctx.config.ctxApprox && ctx.mvarDecl.lctx.isSubPrefixOf mvarDecl.lctx then do mvarType ← check mvarDecl.type; /- Create an auxiliary metavariable with a smaller context and "checked" type. Note that `mvarType` may be different from `mvarDecl.type`. Example: `mvarType` contains a metavariable that we also need to reduce the context. -/ newMVar ← mkAuxMVar ctx.mvarDecl.lctx ctx.mvarDecl.localInstances mvarType; modify $ fun s => { mctx := s.mctx.assignExpr mvarId newMVar, .. s }; pure newMVar else pure mvar /- Auxiliary function used to "fix" subterms of the form `?m x_1 ... x_n` where `x_i`s are free variables, and one of them is out-of-scope. See `Expr.app` case at `check`. If `ctxApprox` is true, then we solve this case by creating a fresh metavariable ?n with the correct scope, an assigning `?m := fun _ ... _ => ?n` -/ def assignToConstFun (mvar : Expr) (numArgs : Nat) (newMVar : Expr) : MetaM Bool := do mvarType ← inferType mvar; forallBoundedTelescope mvarType numArgs $ fun xs _ => if xs.size != numArgs then pure false else do v ← mkLambda xs newMVar; checkTypesAndAssign mvar v partial def check : Expr → CheckAssignmentM Expr | e@(Expr.mdata _ b _) => do b ← visit check b; pure $ e.updateMData! b | e@(Expr.proj _ _ s _) => do s ← visit check s; pure $ e.updateProj! s | e@(Expr.lam _ d b _) => do d ← visit check d; b ← visit check b; pure $ e.updateLambdaE! d b | e@(Expr.forallE _ d b _) => do d ← visit check d; b ← visit check b; pure $ e.updateForallE! d b | e@(Expr.letE _ t v b _) => do t ← visit check t; v ← visit check v; b ← visit check b; pure $ e.updateLet! t v b | e@(Expr.bvar _ _) => pure e | e@(Expr.sort _ _) => pure e | e@(Expr.const _ _ _) => pure e | e@(Expr.lit _ _) => pure e | e@(Expr.fvar _ _) => visit (checkFVar check) e | e@(Expr.mvar _ _) => visit (checkMVar check) e | Expr.localE _ _ _ _ => unreachable! | e@(Expr.app _ _ _) => e.withApp $ fun f args => do ctx ← read; if f.isMVar && ctx.config.ctxApprox && args.all Expr.isFVar then do f ← visit (checkMVar check) f; catch (do args ← args.mapM (visit check); pure $ mkAppN f args) (fun ex => match ex with | Exception.outOfScopeFVar _ => condM (liftMetaM $ isDelayedAssigned f.mvarId!) (throw ex) $ do eType ← liftMetaM $ inferType e; mvarType ← check eType; /- Create an auxiliary metavariable with a smaller context and "checked" type, assign `?f := fun _ => ?newMVar` Note that `mvarType` may be different from `eType`. -/ newMVar ← mkAuxMVar ctx.mvarDecl.lctx ctx.mvarDecl.localInstances mvarType; condM (liftMetaM $ assignToConstFun f args.size newMVar) (pure newMVar) (throw ex) | _ => throw ex) else do f ← visit check f; args ← args.mapM (visit check); pure $ mkAppN f args end CheckAssignment private def checkAssignmentFailure (mvarId : MVarId) (fvars : Array Expr) (v : Expr) (ex : CheckAssignment.Exception) : MetaM (Option Expr) := match ex with | CheckAssignment.Exception.occursCheck => do trace! `Meta.isDefEq.assign.occursCheck (mkMVar mvarId ++ " " ++ fvars ++ " := " ++ v); pure none | CheckAssignment.Exception.useFOApprox => pure none | CheckAssignment.Exception.outOfScopeFVar fvarId => do trace! `Meta.isDefEq.assign.outOfScopeFVar (mkFVar fvarId ++ " @ " ++ mkMVar mvarId ++ " " ++ fvars ++ " := " ++ v); pure none | CheckAssignment.Exception.readOnlyMVarWithBiggerLCtx nestedMVarId => do trace! `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx (mkMVar nestedMVarId ++ " @ " ++ mkMVar mvarId ++ " " ++ fvars ++ " := " ++ v); pure none | CheckAssignment.Exception.unknownExprMVar mvarId => -- This case can only happen if the MetaM API is being misused throwEx $ Exception.unknownExprMVar mvarId | CheckAssignment.Exception.meta ex => throw ex namespace CheckAssignmentQuick @[inline] private def visit (f : Expr → Bool) (e : Expr) : Bool := if !e.hasExprMVar && !e.hasFVar then true else f e partial def check (hasCtxLocals ctxApprox : Bool) (mctx : MetavarContext) (lctx : LocalContext) (mvarDecl : MetavarDecl) (mvarId : MVarId) (fvars : Array Expr) : Expr → Bool | e@(Expr.mdata _ b _) => check b | e@(Expr.proj _ _ s _) => check s | e@(Expr.app f a _) => visit check f && visit check a | e@(Expr.lam _ d b _) => visit check d && visit check b | e@(Expr.forallE _ d b _) => visit check d && visit check b | e@(Expr.letE _ t v b _) => visit check t && visit check v && visit check b | e@(Expr.bvar _ _) => true | e@(Expr.sort _ _) => true | e@(Expr.const _ _ _) => true | e@(Expr.lit _ _) => true | e@(Expr.fvar fvarId _) => if mvarDecl.lctx.contains fvarId then true else match lctx.find? fvarId with | some (LocalDecl.ldecl _ _ _ _ v) => false -- need expensive CheckAssignment.check | _ => if fvars.any $ fun x => x.fvarId! == fvarId then true else false -- We could throw an exception here, but we would have to use ExceptM. So, we let CheckAssignment.check do it | e@(Expr.mvar mvarId' _) => do match mctx.getExprAssignment? mvarId' with | some _ => false -- use CheckAssignment.check to instantiate | none => if mvarId' == mvarId then false -- occurs check failed, use CheckAssignment.check to throw exception else match mctx.findDecl? mvarId' with | none => false | some mvarDecl' => if hasCtxLocals then false -- use CheckAssignment.check else if mvarDecl'.lctx.isSubPrefixOf mvarDecl.lctx fvars then true else if mvarDecl'.depth != mctx.depth || mvarDecl'.kind.isSyntheticOpaque then false -- use CheckAssignment.check else if ctxApprox && mvarDecl.lctx.isSubPrefixOf mvarDecl'.lctx then false -- use CheckAssignment.check else true | Expr.localE _ _ _ _ => unreachable! end CheckAssignmentQuick -- See checkAssignment def checkAssignmentAux (mvarId : MVarId) (mvarDecl : MetavarDecl) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := fun ctx s => let checkCtx : CheckAssignment.Context := { mvarId := mvarId, mvarDecl := s.mctx.getDecl mvarId, fvars := fvars, hasCtxLocals := hasCtxLocals, toContext := ctx }; match (CheckAssignment.check v checkCtx).run { toState := s } with | EStateM.Result.ok e newS => EStateM.Result.ok (some e) newS.toState | EStateM.Result.error ex newS => checkAssignmentFailure mvarId fvars v ex ctx newS.toState /-- Auxiliary function for handling constraints of the form `?m a₁ ... aₙ =?= v`. It will check whether we can perform the assignment ``` ?m := fun fvars => t ``` The result is `none` if the assignment can't be performed. The result is `some newV` where `newV` is a possibly updated `v`. This method may need to unfold let-declarations. -/ def checkAssignment (mvarId : MVarId) (fvars : Array Expr) (v : Expr) : MetaM (Option Expr) := do if !v.hasExprMVar && !v.hasFVar then pure (some v) else do mvarDecl ← getMVarDecl mvarId; let hasCtxLocals := fvars.any $ fun fvar => mvarDecl.lctx.containsFVar fvar; ctx ← read; mctx ← getMCtx; if CheckAssignmentQuick.check hasCtxLocals ctx.config.ctxApprox mctx ctx.lctx mvarDecl mvarId fvars v then pure (some v) else do v ← instantiateMVars v; checkAssignmentAux mvarId mvarDecl fvars hasCtxLocals v private def processAssignmentFOApproxAux (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool := match v with | Expr.app f a _ => isExprDefEqAux args.back a <&&> isExprDefEqAux (mkAppRange mvar 0 (args.size - 1) args) f | _ => pure false /- Auxiliary method for applying first-order unification. It is an approximation. Remark: this method is trying to solve the unification constraint: ?m a₁ ... aₙ =?= v It is uses processAssignmentFOApproxAux, if it fails, it tries to unfold `v`. We have added support for unfolding here because we want to be able to solve unification problems such as ?m Unit =?= ITactic where `ITactic` is defined as def ITactic := Tactic Unit -/ private partial def processAssignmentFOApprox (mvar : Expr) (args : Array Expr) : Expr → MetaM Bool | v => do cfg ← getConfig; if !cfg.foApprox then pure false else do trace! `Meta.isDefEq.foApprox (mvar ++ " " ++ args ++ " := " ++ v); condM (commitWhen $ processAssignmentFOApproxAux mvar args v) (pure true) (do v? ← unfoldDefinition? v; match v? with | none => pure false | some v => processAssignmentFOApprox v) private partial def simpAssignmentArgAux : Expr → MetaM Expr | Expr.mdata _ e _ => simpAssignmentArgAux e | e@(Expr.fvar fvarId _) => do decl ← getLocalDecl fvarId; match decl.value? with | some value => simpAssignmentArgAux value | _ => pure e | e => pure e /- Auxiliary procedure for processing `?m a₁ ... aₙ =?= v`. We apply it to each `aᵢ`. It instantiates assigned metavariables if `aᵢ` is of the form `f[?n] b₁ ... bₘ`, and then removes metadata, and zeta-expand let-decls. -/ private def simpAssignmentArg (arg : Expr) : MetaM Expr := do arg ← if arg.getAppFn.hasExprMVar then instantiateMVars arg else pure arg; simpAssignmentArgAux arg private def processConstApprox (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do cfg ← getConfig; if cfg.constApprox then do let mvarId := mvar.mvarId!; v? ← checkAssignment mvarId #[] v; match v? with | none => pure false | some v => do mvarDecl ← getMVarDecl mvarId; forallBoundedTelescope mvarDecl.type numArgs $ fun xs _ => if xs.size != numArgs then pure false else do v ← mkLambda xs v; checkTypesAndAssign mvar v else pure false private partial def processAssignmentAux (mvar : Expr) (mvarDecl : MetavarDecl) : Nat → Array Expr → Expr → MetaM Bool | i, args, v => do cfg ← getConfig; let useFOApprox (args : Array Expr) : MetaM Bool := processAssignmentFOApprox mvar args v <||> processConstApprox mvar args.size v; if h : i < args.size then do let arg := args.get ⟨i, h⟩; arg ← simpAssignmentArg arg; let args := args.set ⟨i, h⟩ arg; match arg with | Expr.fvar fvarId _ => if args.anyRange 0 i (fun prevArg => prevArg == arg) then useFOApprox args else if mvarDecl.lctx.contains fvarId && !cfg.quasiPatternApprox then useFOApprox args else processAssignmentAux (i+1) args v | _ => useFOApprox args else do v ← instantiateMVars v; -- enforce A4 if v.getAppFn == mvar then -- using A6 useFOApprox args else do let mvarId := mvar.mvarId!; v? ← checkAssignment mvarId args v; match v? with | none => useFOApprox args | some v => do trace `Meta.isDefEq.assign.beforeMkLambda $ fun _ => mvar ++ " " ++ args ++ " := " ++ v; v ← mkLambda args v; if args.any (fun arg => mvarDecl.lctx.containsFVar arg) then /- We need to type check `v` because abstraction using `mkLambda` may have produced a type incorrect term. See discussion at A2 -/ condM (isTypeCorrect v) (checkTypesAndAssign mvar v) (do trace `Meta.isDefEq.assign.typeError $ fun _ => mvar ++ " := " ++ v; useFOApprox args) else checkTypesAndAssign mvar v /-- Tries to solve `?m a₁ ... aₙ =?= v` by assigning `?m`. It assumes `?m` is unassigned. -/ private def processAssignment (mvarApp : Expr) (v : Expr) : MetaM Bool := traceCtx `Meta.isDefEq.assign $ do trace! `Meta.isDefEq.assign (mvarApp ++ " := " ++ v); let mvar := mvarApp.getAppFn; mvarDecl ← getMVarDecl mvar.mvarId!; processAssignmentAux mvar mvarDecl 0 mvarApp.getAppArgs v private def isDeltaCandidate (t : Expr) : MetaM (Option ConstantInfo) := match t.getAppFn with | Expr.const c _ _ => getConst c | _ => pure none /-- Auxiliary method for isDefEqDelta -/ private def isListLevelDefEq (us vs : List Level) : MetaM LBool := toLBoolM $ isListLevelDefEqAux us vs /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeft (fn : Name) (t s : Expr) : MetaM LBool := do trace! `Meta.isDefEq.delta.unfoldLeft fn; toLBoolM $ isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqRight (fn : Name) (t s : Expr) : MetaM LBool := do trace! `Meta.isDefEq.delta.unfoldRight fn; toLBoolM $ isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeftRight (fn : Name) (t s : Expr) : MetaM LBool := do trace! `Meta.isDefEq.delta.unfoldLeftRight fn; toLBoolM $ isExprDefEqAux t s /-- Try to solve `f a₁ ... aₙ =?= f b₁ ... bₙ` by solving `a₁ =?= b₁, ..., aₙ =?= bₙ`. Auxiliary method for isDefEqDelta -/ private def tryHeuristic (t s : Expr) : MetaM Bool := let tFn := t.getAppFn; let sFn := s.getAppFn; traceCtx `Meta.isDefEq.delta $ commitWhen $ do b ← isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels!; unless b $ trace! `Meta.isDefEq.delta ("heuristic failed " ++ t ++ " =?= " ++ s); pure b /-- Auxiliary method for isDefEqDelta -/ private abbrev unfold {α} (e : Expr) (failK : MetaM α) (successK : Expr → MetaM α) : MetaM α := do e? ← unfoldDefinition? e; match e? with | some e => successK e | none => failK /-- Auxiliary method for isDefEqDelta -/ private def unfoldBothDefEq (fn : Name) (t s : Expr) : MetaM LBool := match t, s with | Expr.const _ ls₁ _, Expr.const _ ls₂ _ => isListLevelDefEq ls₁ ls₂ | Expr.app _ _ _, Expr.app _ _ _ => condM (tryHeuristic t s) (pure LBool.true) (unfold t (unfold s (pure LBool.false) (fun s => isDefEqRight fn t s)) (fun t => unfold s (isDefEqLeft fn t s) (fun s => isDefEqLeftRight fn t s))) | _, _ => pure LBool.false private def sameHeadSymbol (t s : Expr) : Bool := match t.getAppFn, s.getAppFn with | Expr.const c₁ _ _, Expr.const c₂ _ _ => true | _, _ => false /-- - If headSymbol (unfold t) == headSymbol s, then unfold t - If headSymbol (unfold s) == headSymbol t, then unfold s - Otherwise unfold t and s if possible. Auxiliary method for isDefEqDelta -/ private def unfoldComparingHeadsDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := unfold t (unfold s (pure LBool.undef) -- `t` and `s` failed to be unfolded (fun s => isDefEqRight sInfo.name t s)) (fun tNew => if sameHeadSymbol tNew s then isDefEqLeft tInfo.name tNew s else unfold s (isDefEqLeft tInfo.name tNew s) (fun sNew => if sameHeadSymbol t sNew then isDefEqRight sInfo.name t sNew else isDefEqLeftRight tInfo.name tNew sNew)) /-- If `t` and `s` do not contain metavariables, then use kernel definitional equality heuristics. Otherwise, use `unfoldComparingHeadsDefEq`. Auxiliary method for isDefEqDelta -/ private def unfoldDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := if !t.hasExprMVar && !s.hasExprMVar then /- If `t` and `s` do not contain metavariables, we simulate strategy used in the kernel. -/ if tInfo.hints.lt sInfo.hints then unfold t (unfoldComparingHeadsDefEq tInfo sInfo t s) $ fun t => isDefEqLeft tInfo.name t s else if sInfo.hints.lt tInfo.hints then unfold s (unfoldComparingHeadsDefEq tInfo sInfo t s) $ fun s => isDefEqRight sInfo.name t s else unfoldComparingHeadsDefEq tInfo sInfo t s else unfoldComparingHeadsDefEq tInfo sInfo t s /-- When `TransparencyMode` is set to `default` or `all`. If `t` is reducible and `s` is not ==> `isDefEqLeft (unfold t) s` If `s` is reducible and `t` is not ==> `isDefEqRight t (unfold s)` Otherwise, use `unfoldDefEq` Auxiliary method for isDefEqDelta -/ private def unfoldReducibeDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := condM shouldReduceReducibleOnly (unfoldDefEq tInfo sInfo t s) (do tReducible ← isReducible tInfo.name; sReducible ← isReducible sInfo.name; if tReducible && !sReducible then unfold t (unfoldDefEq tInfo sInfo t s) $ fun t => isDefEqLeft tInfo.name t s else if !tReducible && sReducible then unfold s (unfoldDefEq tInfo sInfo t s) $ fun s => isDefEqRight sInfo.name t s else unfoldDefEq tInfo sInfo t s) /-- If `t` is a projection function application and `s` is not ==> `isDefEqRight t (unfold s)` If `s` is a projection function application and `t` is not ==> `isDefEqRight (unfold t) s` Otherwise, use `unfoldReducibeDefEq` Auxiliary method for isDefEqDelta -/ private def unfoldNonProjFnDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do env ← getEnv; let tProj? := env.isProjectionFn tInfo.name; let sProj? := env.isProjectionFn sInfo.name; if tProj? && !sProj? then unfold s (unfoldDefEq tInfo sInfo t s) $ fun s => isDefEqRight sInfo.name t s else if !tProj? && sProj? then unfold t (unfoldDefEq tInfo sInfo t s) $ fun t => isDefEqLeft tInfo.name t s else unfoldReducibeDefEq tInfo sInfo t s /-- isDefEq by lazy delta reduction. This method implements many different heuristics: 1- If only `t` can be unfolded => then unfold `t` and continue 2- If only `s` can be unfolded => then unfold `s` and continue 3- If `t` and `s` can be unfolded and they have the same head symbol, then a) First try to solve unification by unifying arguments. b) If it fails, unfold both and continue. Implemented by `unfoldBothDefEq` 4- If `t` is a projection function application and `s` is not => then unfold `s` and continue. 5- If `s` is a projection function application and `t` is not => then unfold `t` and continue. Remark: 4&5 are implemented by `unfoldNonProjFnDefEq` 6- If `t` is reducible and `s` is not => then unfold `t` and continue. 7- If `s` is reducible and `t` is not => then unfold `s` and continue Remark: 6&7 are implemented by `unfoldReducibeDefEq` 8- If `t` and `s` do not contain metavariables, then use heuristic used in the Kernel. Implemented by `unfoldDefEq` 9- If `headSymbol (unfold t) == headSymbol s`, then unfold t and continue. 10- If `headSymbol (unfold s) == headSymbol t`, then unfold s 11- Otherwise, unfold `t` and `s` and continue. Remark: 9&10&11 are implemented by `unfoldComparingHeadsDefEq` -/ private def isDefEqDelta (t s : Expr) : MetaM LBool := do tInfo? ← isDeltaCandidate t.getAppFn; sInfo? ← isDeltaCandidate s.getAppFn; match tInfo?, sInfo? with | none, none => pure LBool.undef | some tInfo, none => unfold t (pure LBool.undef) $ fun t => isDefEqLeft tInfo.name t s | none, some sInfo => unfold s (pure LBool.undef) $ fun s => isDefEqRight sInfo.name t s | some tInfo, some sInfo => if tInfo.name == sInfo.name then unfoldBothDefEq tInfo.name t s else unfoldNonProjFnDefEq tInfo sInfo t s private def isAssigned : Expr → MetaM Bool | Expr.mvar mvarId _ => isExprMVarAssigned mvarId | _ => pure false private def isDelayedAssignedHead (tFn : Expr) (t : Expr) : MetaM Bool := match tFn with | Expr.mvar mvarId _ => do condM (isDelayedAssigned mvarId) (do tNew ← instantiateMVars t; pure $ tNew != t) (pure false) | _ => pure false private def isSynthetic : Expr → MetaM Bool | Expr.mvar mvarId _ => do mvarDecl ← getMVarDecl mvarId; match mvarDecl.kind with | MetavarKind.synthetic => pure true | MetavarKind.syntheticOpaque => pure true | MetavarKind.natural => pure false | _ => pure false private def isAssignable : Expr → MetaM Bool | Expr.mvar mvarId _ => do b ← isReadOnlyOrSyntheticOpaqueExprMVar mvarId; pure (!b) | _ => pure false private def etaEq (t s : Expr) : Bool := match t.etaExpanded? with | some t => t == s | none => false private def isLetFVar (fvarId : FVarId) : MetaM Bool := do decl ← getLocalDecl fvarId; pure decl.isLet private partial def isDefEqQuick : Expr → Expr → MetaM LBool | Expr.lit l₁ _, Expr.lit l₂ _ => pure (l₁ == l₂).toLBool | Expr.sort u _, Expr.sort v _ => toLBoolM $ isLevelDefEqAux u v | t@(Expr.lam _ _ _ _), s@(Expr.lam _ _ _ _) => if t == s then pure LBool.true else toLBoolM $ isDefEqBinding t s | t@(Expr.forallE _ _ _ _), s@(Expr.forallE _ _ _ _) => if t == s then pure LBool.true else toLBoolM $ isDefEqBinding t s | Expr.mdata _ t _, s => isDefEqQuick t s | t, Expr.mdata _ s _ => isDefEqQuick t s | Expr.fvar fvarId₁ _, Expr.fvar fvarId₂ _ => condM (isLetFVar fvarId₁ <||> isLetFVar fvarId₂) (pure LBool.undef) (pure (fvarId₁ == fvarId₂).toLBool) | t, s => cond (t == s) (pure LBool.true) $ cond (etaEq t s || etaEq s t) (pure LBool.true) $ -- t =?= (fun xs => t xs) let tFn := t.getAppFn; let sFn := s.getAppFn; cond (!tFn.isMVar && !sFn.isMVar) (pure LBool.undef) $ condM (isAssigned tFn) (do t ← instantiateMVars t; isDefEqQuick t s) $ condM (isAssigned sFn) (do s ← instantiateMVars s; isDefEqQuick t s) $ condM (isDelayedAssignedHead tFn t) (do t ← instantiateMVars t; isDefEqQuick t s) $ condM (isDelayedAssignedHead sFn s) (do s ← instantiateMVars s; isDefEqQuick t s) $ condM (isSynthetic tFn <&&> trySynthPending tFn) (do t ← instantiateMVars t; isDefEqQuick t s) $ condM (isSynthetic sFn <&&> trySynthPending sFn) (do s ← instantiateMVars s; isDefEqQuick t s) $ do tAssign? ← isAssignable tFn; sAssign? ← isAssignable sFn; trace! `Meta.isDefEq (t ++ (if tAssign? then " [assignable]" else " [nonassignable]") ++ " =?= " ++ s ++ (if sAssign? then " [assignable]" else " [nonassignable]")); let assign (t s : Expr) : MetaM LBool := toLBoolM $ processAssignment t s; cond (tAssign? && !sAssign?) (assign t s) $ cond (!tAssign? && sAssign?) (assign s t) $ cond (!tAssign? && !sAssign?) (if tFn.isMVar || sFn.isMVar then do ctx ← read; if ctx.config.isDefEqStuckEx then do trace! `Meta.isDefEq.stuck (t ++ " =?= " ++ s); throwEx $ Exception.isExprDefEqStuck t s else pure LBool.false else pure LBool.undef) $ do -- Both `t` and `s` are terms of the form `?m ...` tMVarDecl ← getMVarDecl tFn.mvarId!; sMVarDecl ← getMVarDecl sFn.mvarId!; if s.isMVar && !t.isMVar then /- Solve `?m t =?= ?n` by trying first `?n := ?m t`. Reason: this assignment is precise. -/ condM (commitWhen (processAssignment s t)) (pure LBool.true) $ assign t s else condM (commitWhen (processAssignment t s)) (pure LBool.true) $ assign s t private def isDefEqProofIrrel (t s : Expr) : MetaM LBool := do status ← isProofQuick t; match status with | LBool.false => pure LBool.undef | LBool.true => do tType ← inferType t; sType ← inferType s; toLBoolM $ isExprDefEqAux tType sType | LBool.undef => do tType ← inferType t; condM (isProp tType) (do sType ← inferType s; toLBoolM $ isExprDefEqAux tType sType) (pure LBool.undef) @[inline] def whenUndefDo (x : MetaM LBool) (k : MetaM Bool) : MetaM Bool := do status ← x; match status with | LBool.true => pure true | LBool.false => pure false | LBool.undef => k @[specialize] private partial def isDefEqWHNF (t s : Expr) (k : Expr → Expr → MetaM Bool) : MetaM Bool := do t' ← whnfCore t; s' ← whnfCore s; if t == t' && s == s' then k t' s' else whenUndefDo (isDefEqQuick t' s') $ k t' s' @[specialize] private def unstuckMVar (e : Expr) (successK : Expr → MetaM Bool) (failK : MetaM Bool): MetaM Bool := do mvarId? ← getStuckMVar? e; match mvarId? with | some mvarId => condM (synthPending mvarId) (do e ← instantiateMVars e; successK e) failK | none => failK private def isDefEqOnFailure (t s : Expr) : MetaM Bool := unstuckMVar t (fun t => isExprDefEqAux t s) $ unstuckMVar s (fun s => isExprDefEqAux t s) $ pure false /- Remove unnecessary let-decls -/ private def consumeLet : Expr → Expr | e@(Expr.letE _ _ _ b _) => if b.hasLooseBVars then e else consumeLet b | e => e partial def isExprDefEqAuxImpl : Expr → Expr → MetaM Bool | t, s => do let t := consumeLet t; let s := consumeLet s; trace `Meta.isDefEq.step $ fun _ => t ++ " =?= " ++ s; whenUndefDo (isDefEqQuick t s) $ whenUndefDo (isDefEqProofIrrel t s) $ isDefEqWHNF t s $ fun t s => do condM (isDefEqEta t s <||> isDefEqEta s t) (pure true) $ whenUndefDo (isDefEqNative t s) $ do whenUndefDo (isDefEqNat t s) $ do whenUndefDo (isDefEqOffset t s) $ do whenUndefDo (isDefEqDelta t s) $ match t, s with | Expr.const c us _, Expr.const d vs _ => if c == d then isListLevelDefEqAux us vs else pure false | Expr.app _ _ _, Expr.app _ _ _ => let tFn := t.getAppFn; condM (commitWhen (isExprDefEqAux tFn s.getAppFn <&&> isDefEqArgs tFn t.getAppArgs s.getAppArgs)) (pure true) (isDefEqOnFailure t s) | _, _ => whenUndefDo (isDefEqStringLit t s) $ isDefEqOnFailure t s @[init] def setIsExprDefEqAuxRef : IO Unit := isExprDefEqAuxRef.set isExprDefEqAuxImpl @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Meta.isDefEq; registerTraceClass `Meta.isDefEq.foApprox; registerTraceClass `Meta.isDefEq.delta; registerTraceClass `Meta.isDefEq.step; registerTraceClass `Meta.isDefEq.assign end Meta end Lean
50b54b3d7d3526c14ebae892039b76f0c2f039f3
f313d4982feee650661f61ed73f0cb6635326350
/Mathlib/Data/Nat/Basic.lean
b7331a7e1e39930be85cd223013e85e7e8897059
[ "Apache-2.0" ]
permissive
shingtaklam1324/mathlib4
38c6e172eec1385944db5a70a3b5545c924980ee
50610c343b7065e8eec056d641f859ceed608e69
refs/heads/master
1,683,032,333,313
1,621,942,699,000
1,621,942,699,000
371,130,608
0
0
Apache-2.0
1,622,053,166,000
1,622,053,166,000
null
UTF-8
Lean
false
false
30,763
lean
import Mathlib.Tactic.Basic import Mathlib.Logic.Basic notation "ℕ" => Nat namespace Nat -- Edits to the naming convention pending upstream def eq_of_beq_eq_true := @eqOfBeqEqTrue def ne_of_beq_eq_false := @neOfBeqEqFalse @[simp] lemma not_succ_le_zero : ∀ n, ¬ succ n ≤ 0 := @notSuccLeZero def not_lt_zero := @notLtZero def zero_le := @zeroLe def succ_le_succ := @succLeSucc def zero_lt_succ := @zeroLtSucc def le_step := @leStep protected def le_trans := @Nat.leTrans protected def lt_trans := @Nat.ltTrans def le_succ := @leSucc def le_succ_of_le := @leSuccOfLe protected def eq_or_lt_of_le := @Nat.eqOrLtOfLe protected def le_refl := @Nat.leRefl protected def lt_or_le : (n m : ℕ) → n < m ∨ m ≤ n := @Nat.ltOrGe protected def le_antisymm := @Nat.leAntisymm protected def lt_of_le_of_ne := @Nat.ltOfLeAndNe def pred_le_pred := @predLePred def le_of_succ_le_succ := @leOfSuccLeSucc def le_of_lt_succ := @leOfLtSucc def zero_eq := @zero_Eq def succ_eq_add_one := @succ_Eq_add_one protected def mul_add := @Nat.left_distrib protected def add_mul := @Nat.right_distrib def not_succ_le_self := @notSuccLeSelf protected def lt_irrefl := @Nat.ltIrrefl def pred_le := @predLe def pred_lt := @predLt def sub_le := @subLe def sub_lt := @subLt protected def lt_of_lt_of_le := @Nat.ltOfLtOfLe protected def lt_of_lt_of_eq := @Nat.ltOfLtOfEq protected def le_of_eq := @Nat.leOfEq def le_of_succ_le := @leOfSuccLe protected def le_of_lt := @Nat.leOfLt def succ_pos := @succPos lemma eq_zero_or_pos : (n : ℕ) → n = 0 ∨ 0 < n := @eqZeroOrPos def lt_succ_self := @ltSuccSelf protected def le_total := @Nat.leTotal def eq_zero_of_le_zero := @eqZeroOfLeZero def lt_of_succ_lt := @ltOfSuccLt def lt_of_succ_le := @ltOfSuccLe def succ_le_of_lt := @succLeOfLt def lt_or_eq_of_le_succ := @ltOrEqOrLeSucc def le_add_right := @leAddRight def le_add_left := @leAddLeft protected lemma not_le_of_gt : {n m : ℕ} → m < n → ¬ n ≤ m := @Nat.notLeOfGt protected lemma lt_of_not_ge : {n m : ℕ} → ¬ n ≤ m → m < n := @Nat.gtOfNotLe protected def add_le_add_left := @Nat.addLeAddLeft protected def add_le_add_right := @Nat.addLeAddRight protected def add_lt_add_left := @Nat.addLtAddLeft protected def add_lt_add_right := @Nat.addLtAddRight protected def zero_lt_one := @Nat.zeroLtOne protected def add_le_add := @Nat.addLeAdd protected def add_lt_add := @Nat.addLtAdd def nat_zero_eq_zero := @natZeroEqZero protected def one_ne_zero := @Nat.oneNeZero protected def zero_ne_one := @Nat.zeroNeOne def succ_ne_zero := @succNeZero protected def mul_le_mul_left := @mulLeMulLeft protected def mul_le_mul_right := @mulLeMulRight protected def mul_le_mul := @Nat.mulLeMul protected def mul_lt_mul_of_pos_left := @Nat.mulLtMulOfPosLeft protected def mul_lt_mul_of_pos_right := @Nat.mulLtMulOfPosRight protected def mul_pos := @Nat.mulPos def pow_succ := @Nat.powSucc def pow_zero := @Nat.powZero def pow_le_pow_of_le_left := @Nat.powLePowOfLeLeft def pow_le_pow_of_le_right := @Nat.powLePowOfLeRight def pos_pos_of_pos := @Nat.posPowOfPos lemma succ_ne_self : ∀ n : ℕ, succ n ≠ n | 0, h => absurd h (Nat.succ_ne_zero 0) | n+1, h => succ_ne_self n (Nat.noConfusion h id) lemma eq_zero_of_add_eq_zero_right : ∀ {n m : ℕ}, n + m = 0 → n = 0 | 0, m => by simp [Nat.zero_add] | n+1, m => fun h => by exfalso rw [add_one, succ_add] at h apply succ_ne_zero _ h lemma eq_zero_of_add_eq_zero_left {n m : ℕ} (h : n + m = 0) : m = 0 := @eq_zero_of_add_eq_zero_right m n (Nat.add_comm n m ▸ h) @[simp] lemma pred_zero : pred 0 = 0 := rfl @[simp] lemma pred_succ (n : ℕ) : pred (succ n) = n := rfl protected lemma pos_of_ne_zero {n : ℕ} : n ≠ 0 → 0 < n := Or.resolve_left (eq_zero_or_pos n) protected lemma not_lt_of_le {n m : ℕ} (h₁ : m ≤ n) : ¬ n < m | h₂ => Nat.not_le_of_gt h₂ h₁ protected lemma lt_of_not_le {a b : ℕ} : ¬ a ≤ b → b < a := (Nat.lt_or_le b a).resolve_right protected lemma le_or_le (a b : ℕ) : a ≤ b ∨ b ≤ a := (Nat.lt_or_le _ _).imp_left Nat.le_of_lt protected lemma le_of_not_le {a b : ℕ} : ¬ a ≤ b → b ≤ a := (Nat.le_or_le _ _).resolve_left @[simp] protected lemma not_lt {n m : ℕ} : ¬ n < m ↔ m ≤ n := ⟨Nat.lt_of_not_le, Nat.not_lt_of_le⟩ @[simp] protected lemma not_le {n m : ℕ} : ¬ n ≤ m ↔ m < n := ⟨Nat.lt_of_not_le, Nat.not_lt_of_le⟩ protected lemma lt_or_eq_of_le {n m : ℕ} (h : n ≤ m) : n < m ∨ n = m := (Nat.lt_or_le _ _).imp_right (Nat.le_antisymm h) protected lemma lt_of_le_of_lt {n m k : ℕ} (h₁ : n ≤ m) : m < k → n < k := Nat.le_trans (succ_le_succ h₁) protected lemma lt_iff_le_not_le {m n : ℕ} : m < n ↔ m ≤ n ∧ ¬ n ≤ m := ⟨fun h => ⟨Nat.le_of_lt h, Nat.not_le_of_gt h⟩, fun h => Nat.lt_of_not_ge h.2⟩ lemma pred_lt_pred : ∀ {n m : ℕ}, n ≠ 0 → n < m → pred n < pred m | 0, _, h, _ => (h rfl).elim | n+1, m+1, _, h => lt_of_succ_lt_succ h protected lemma add_left_cancel_iff {n m k : ℕ} : n + m = n + k ↔ m = k := ⟨Nat.add_left_cancel, fun | rfl => rfl⟩ protected lemma le_of_add_le_add_left {k n m : ℕ} (h : k + n ≤ k + m) : n ≤ m := by let ⟨w, hw⟩ := le.dest h rw [Nat.add_assoc, Nat.add_left_cancel_iff] at hw exact Nat.le.intro hw protected lemma le_of_add_le_add_right {k n m : ℕ} : n + k ≤ m + k → n ≤ m := by rw [Nat.add_comm _ k, Nat.add_comm _ k] apply Nat.le_of_add_le_add_left protected lemma add_le_add_iff_le_right (k n m : ℕ) : n + k ≤ m + k ↔ n ≤ m := ⟨Nat.le_of_add_le_add_right, fun h => Nat.add_le_add_right h _⟩ protected lemma lt_of_add_lt_add_left {k n m : ℕ} (h : k + n < k + m) : n < m := Nat.lt_of_le_of_ne (Nat.le_of_add_le_add_left (Nat.le_of_lt h)) fun heq => Nat.lt_irrefl (k + m) $ by rwa [heq] at h protected lemma lt_add_of_pos_right {n k : ℕ} (h : 0 < k) : n < n + k := Nat.add_lt_add_left h n protected lemma lt_add_of_pos_left {n k : ℕ} (h : 0 < k) : n < k + n := by rw [Nat.add_comm]; exact Nat.lt_add_of_pos_right h protected lemma le_of_mul_le_mul_left {a b c : ℕ} (h : c * a ≤ c * b) (hc : 0 < c) : a ≤ b := Nat.not_lt.1 fun h1 => Nat.not_le.2 (Nat.mul_lt_mul_of_pos_left h1 hc) h lemma eq_of_mul_eq_mul_left {m k n : ℕ} (Hn : 0 < n) (H : n * m = n * k) : m = k := Nat.le_antisymm (Nat.le_of_mul_le_mul_left (Nat.le_of_eq H) Hn) (Nat.le_of_mul_le_mul_left (Nat.le_of_eq H.symm) Hn) protected lemma add_self_ne_one : ∀ (n : ℕ), n + n ≠ 1 | n+1, h => have h1 : succ (succ (n + n)) = 1 from succ_add n n ▸ h Nat.noConfusion h1 fun. /- sub properties -/ @[simp] protected lemma zero_sub : ∀ a : ℕ, 0 - a = 0 | 0 => rfl | (a+1) => congr_arg pred (Nat.zero_sub a) lemma sub_lt_succ (a b : ℕ) : a - b < succ a := lt_succ_of_le (sub_le a b) protected lemma sub_le_sub_right {n m : ℕ} (h : n ≤ m) : ∀ k, n - k ≤ m - k | 0 => h | z+1 => pred_le_pred (Nat.sub_le_sub_right h z) protected lemma add_sub_add_right : ∀ (n k m : ℕ), (n + k) - (m + k) = n - m | n, 0, m => by rw [Nat.add_zero, Nat.add_zero] | n, k+1, m => by rw [add_succ, add_succ, succ_sub_succ, Nat.add_sub_add_right n k m] protected lemma add_sub_add_left (k n m : ℕ) : (k + n) - (k + m) = n - m := by rw [Nat.add_comm k n, Nat.add_comm k m, Nat.add_sub_add_right] protected lemma add_sub_cancel (n m : ℕ) : n + m - m = n := suffices n + m - (0 + m) = n by rwa [Nat.zero_add] at this by rw [Nat.add_sub_add_right, Nat.sub_zero] protected lemma add_sub_cancel_left (n m : ℕ) : n + m - n = m := show n + m - (n + 0) = m by rw [Nat.add_sub_add_left, Nat.sub_zero] protected lemma sub_sub : ∀ (n m k : ℕ), n - m - k = n - (m + k) | n, m, 0 => by rw [Nat.add_zero, Nat.sub_zero] | n, m, (succ k) => by rw [add_succ, sub_succ, sub_succ, Nat.sub_sub n m k] lemma sub_self_add (n m : ℕ) : n - (n + m) = 0 := show (n + 0) - (n + m) = 0 by rw [Nat.add_sub_add_left, Nat.zero_sub] lemma sub_lt_self {a b : ℕ} (h₀ : 0 < a) (h₁ : a ≤ b) : b - a < b := by apply sub_lt _ h₀ apply Nat.lt_of_lt_of_le h₀ h₁ lemma sub_one (n : ℕ) : n - 1 = pred n := rfl lemma succ_sub_one (n : ℕ) : succ n - 1 = n := rfl lemma succ_pred_eq_of_pos : ∀ {n : ℕ}, 0 < n → succ (pred n) = n | n+1, _ => rfl lemma succ_sub (h : n ≤ m) : succ m - n = succ (m - n) := let ⟨k, hk⟩ := Nat.le.dest h by rw [← hk, Nat.add_sub_cancel_left, ← add_succ, Nat.add_sub_cancel_left] lemma sub_eq_zero_of_le (h : n ≤ m) : n - m = 0 := let ⟨k, hk⟩ := Nat.le.dest h; by rw [← hk, sub_self_add] protected lemma le_of_sub_eq_zero : {n m : ℕ} → n - m = 0 → n ≤ m | n, 0, H => by rw [Nat.sub_zero] at H; simp [H] | 0, m+1, H => zero_le _ | n+1, m+1, H => Nat.add_le_add_right (Nat.le_of_sub_eq_zero $ by simp [Nat.add_sub_add_right] at H; exact H) _ protected lemma sub_eq_zero_iff_le : n - m = 0 ↔ n ≤ m := ⟨Nat.le_of_sub_eq_zero, Nat.sub_eq_zero_of_le⟩ lemma add_sub_of_le {n m : ℕ} (h : n ≤ m) : n + (m - n) = m := let ⟨k, hk⟩ := Nat.le.dest h; by rw [← hk, Nat.add_sub_cancel_left] protected lemma sub_add_cancel : {a b : ℕ} → a ≤ b → b - a + a = b | 0, b, _ => rfl | a+1, b+1, h => congrArg Nat.succ $ show (b + 1) - (a + 1) + a = b by rw [Nat.add_comm a, ← Nat.sub_sub] exact Nat.sub_add_cancel h protected lemma add_sub_cancel' {n m : ℕ} (h : m ≤ n) : m + (n - m) = n := by rw [Nat.add_comm, Nat.sub_add_cancel h] protected lemma add_sub_assoc {m k : ℕ} (h : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) := let ⟨l, hl⟩ := Nat.le.dest h by rw [← hl, Nat.add_sub_cancel_left, Nat.add_comm k, ← Nat.add_assoc, Nat.add_sub_cancel] protected lemma sub_eq_iff_eq_add {a b c : ℕ} (ab : b ≤ a) : a - b = c ↔ a = c + b := ⟨fun c_eq => by rw [c_eq.symm, Nat.sub_add_cancel ab], fun a_eq => by rw [a_eq, Nat.add_sub_cancel]⟩ protected lemma lt_of_sub_eq_succ (H : m - n = succ l) : n < m := Nat.not_le.1 fun H' => by simp [Nat.sub_eq_zero_of_le H'] at H protected lemma lt_of_add_lt_add_right {a b c : ℕ} (h : a + b < c + b) : a < c := Nat.lt_of_not_le fun h' => Nat.not_le_of_gt h (Nat.add_le_add_right h' _) protected lemma sub_pos_of_lt (h : m < n) : 0 < n - m := by apply Nat.lt_of_add_lt_add_right (b := m) rw [Nat.zero_add, Nat.sub_add_cancel (Nat.leOfLt h)]; exact h protected lemma sub_lt_sub_left : ∀ {k m n : ℕ} (H : k < m) (h : k < n), m - n < m - k | 0, m+1, n+1, _, _ => by rw [Nat.add_sub_add_right]; exact lt_succ_of_le (Nat.sub_le _ _) | k+1, m+1, n+1, h1, h2 => by rw [Nat.add_sub_add_right, Nat.add_sub_add_right] exact Nat.sub_lt_sub_left h1 h2 protected lemma sub_lt_left_of_lt_add {n k m : ℕ} (H : n ≤ k) (h : k < n + m) : k - n < m := by have _ from Nat.sub_le_sub_right (succ_le_of_lt h) n rwa [Nat.add_sub_cancel_left, Nat.succ_sub H] at this protected lemma add_le_of_le_sub_left {n k m : ℕ} (H : m ≤ k) (h : n ≤ k - m) : m + n ≤ k := Nat.not_lt.1 fun h' => Nat.not_le.2 h (Nat.sub_lt_left_of_lt_add H h') lemma le_of_le_of_sub_le_sub_right {n m k : ℕ} (h₀ : k ≤ m) (h₁ : n - k ≤ m - k) : n ≤ m := Nat.not_lt.1 fun h' => by have _ from Nat.add_le_of_le_sub_left h₀ h₁ rw [Nat.add_sub_cancel'] at this; exact Nat.not_le.2 h' this exact Nat.le_trans h₀ (Nat.le_of_lt h') protected lemma sub_le_sub_right_iff {n m k : ℕ} (h : k ≤ m) : n - k ≤ m - k ↔ n ≤ m := ⟨le_of_le_of_sub_le_sub_right h, fun h => Nat.sub_le_sub_right h k⟩ lemma le_sub_iff_add_le {x y k : ℕ} (h : k ≤ y) : x ≤ y - k ↔ x + k ≤ y := by rw [← Nat.add_sub_cancel x k, Nat.sub_le_sub_right_iff h, Nat.add_sub_cancel] protected lemma min_comm (a b : ℕ) : Nat.min a b = Nat.min b a := by simp [Nat.min] by_cases h₁ : a ≤ b <;> by_cases h₂ : b ≤ a <;> simp [h₁, h₂] - (exact Nat.le_antisymm h₁ h₂) - cases not_or_intro h₁ h₂ (Nat.le_or_le _ _) protected lemma min_le_left (a b : ℕ) : Nat.min a b ≤ a := by simp [Nat.min]; by_cases a ≤ b <;> simp [h] - (exact Nat.le_refl _) - exact Nat.le_of_not_le h protected lemma min_eq_left (h : a ≤ b) : Nat.min a b = a := by simp [Nat.min, h] protected lemma min_eq_right (h : b ≤ a) : Nat.min a b = b := by rw [Nat.min_comm a b]; exact Nat.min_eq_left h protected lemma zero_min (a : ℕ) : Nat.min 0 a = 0 := Nat.min_eq_left (zero_le a) protected lemma min_zero (a : ℕ) : Nat.min a 0 = 0 := Nat.min_eq_right (zero_le a) lemma sub_eq_sub_min (n m : ℕ) : n - m = n - Nat.min n m := if h : n ≥ m then by rw [Nat.min_eq_right h] else by rw [sub_eq_zero_of_le (Nat.le_of_not_le h), Nat.min_eq_left (Nat.le_of_not_le h), Nat.sub_self] @[simp] lemma sub_add_min_cancel (n m : ℕ) : n - m + Nat.min n m = n := by rw [sub_eq_sub_min, Nat.sub_add_cancel (Nat.min_le_left n m)] protected def lt_wf := @Nat.ltWf protected def strong_rec_on {p : ℕ → Sort u} (n : ℕ) (H : ∀ n, (∀ m, m < n → p m) → p n) : p n := Nat.lt_wf.fix' H n protected def case_strong_rec_on {p : ℕ → Sort u} (a : ℕ) (hz : p 0) (hi : ∀ n, (∀ m, m ≤ n → p m) → p (succ n)) : p a := Nat.strong_rec_on a fun | 0, _ => hz | n+1, ih => hi n ih lemma mod_add_div (m k : ℕ) : m % k + k * (m / k) = m := by induction m, k using mod.inductionOn with rw [div_eq, mod_eq] | base x y h => simp [h] | ind x y h IH => simp [h]; rw [Nat.mul_succ, ← Nat.add_assoc, IH, Nat.sub_add_cancel h.2] /- div -/ @[simp] protected lemma div_one (n : ℕ) : n / 1 = n := have n % 1 + 1 * (n / 1) = n from mod_add_div _ _ by rwa [mod_one, Nat.zero_add, Nat.one_mul] at this @[simp] protected lemma div_zero (n : ℕ) : n / 0 = 0 := by rw [div_eq]; simp [Nat.lt_irrefl] @[simp] protected lemma zero_div (b : ℕ) : 0 / b = 0 := (div_eq 0 b).trans $ if_neg $ And.rec Nat.not_le_of_gt lemma le_div_iff_mul_le (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y := by induction y, k using mod.inductionOn generalizing x with (rw [div_eq]; simp [h]; cases x with simp [zero_le] | succ x => ?_) | base y k h => simp [succ_mul, Nat.add_comm] refine Nat.lt_of_lt_of_le ?_ (Nat.le_add_right _ _) exact Nat.lt_of_not_le fun h' => h ⟨k0, h'⟩ | ind y k h IH => rw [← add_one, Nat.add_le_add_iff_le_right, IH k0, succ_mul, le_sub_iff_add_le h.2] lemma div_lt_iff_lt_mul (Hk : 0 < k) : x / k < y ↔ x < y * k := by rw [← Nat.not_le, ← Nat.not_le]; apply not_congr; apply le_div_iff_mul_le Hk lemma mul_div_le (m n : ℕ) : n * (m / n) ≤ m := by match n, Nat.eq_zero_or_pos n with | _, Or.inl rfl => rw [Nat.zero_mul]; exact m.zero_le | n, Or.inr h => rw [Nat.mul_comm, ← Nat.le_div_iff_mul_le h]; exact Nat.le_refl _ protected lemma div_le_of_le_mul : ∀ {k : ℕ}, m ≤ k * n → m / k ≤ n | 0, h => by simp [Nat.div_zero]; apply zero_le | k+1, h => Nat.le_of_mul_le_mul_left (Nat.le_trans (mul_div_le _ _) h) (zero_lt_succ _) protected lemma div_le_self : ∀ (m n : ℕ), m / n ≤ m | m, 0 => by simp [Nat.div_zero]; apply zero_le | m, n+1 => Nat.div_le_of_le_mul $ by have _ from Nat.mul_le_mul_right m (succ_pos n); rwa [Nat.one_mul] at this lemma div_eq_sub_div (h₁ : 0 < b) (h₂ : b ≤ a) : a / b = (a - b) / b + 1 := by rw [div_eq a, if_pos]; split <;> assumption lemma div_eq_of_lt (h₀ : a < b) : a / b = 0 := by rw [div_eq a, if_neg] intro h₁ apply Nat.not_le_of_gt h₀ h₁.right /- successor and predecessor -/ lemma add_one_ne_zero (n : ℕ) : n + 1 ≠ 0 := succ_ne_zero _ lemma eq_zero_or_eq_succ_pred (n : ℕ) : n = 0 ∨ n = succ (pred n) := by cases n <;> simp lemma exists_eq_succ_of_ne_zero (H : n ≠ 0) : ∃k : ℕ, n = succ k := ⟨_, (eq_zero_or_eq_succ_pred _).resolve_left H⟩ def discriminate (H1: n = 0 → α) (H2 : ∀m, n = succ m → α) : α := match e: n with | 0 => H1 e | succ m => H2 m e lemma one_succ_zero : 1 = succ 0 := rfl def two_step_induction {P : ℕ → Sort u} (H1 : P 0) (H2 : P 1) (H3 : ∀ (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : (a : ℕ) → P a | 0 => H1 | 1 => H2 | n+2 => H3 _ (two_step_induction H1 H2 H3 _) (two_step_induction H1 H2 H3 _) def sub_induction {P : ℕ → ℕ → Sort u} (H1 : ∀m, P 0 m) (H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : (n m : ℕ) → P n m | 0, m => H1 _ | n+1, 0 => H2 _ | n+1, m+1 => H3 _ _ (sub_induction H1 H2 H3 n m) /- addition -/ lemma succ_add_eq_succ_add (n m : ℕ) : succ n + m = n + succ m := by simp [succ_add, add_succ] lemma one_add (n : ℕ) : 1 + n = succ n := by simp [Nat.add_comm] lemma eq_zero_of_add_eq_zero (H : n + m = 0) : n = 0 ∧ m = 0 := ⟨Nat.eq_zero_of_add_eq_zero_right H, Nat.eq_zero_of_add_eq_zero_left H⟩ lemma eq_zero_of_mul_eq_zero : ∀ {n m : ℕ}, n * m = 0 → n = 0 ∨ m = 0 | 0, m, _ => Or.inl rfl | n+1, m, h => by rw [succ_mul] at h; exact Or.inr (eq_zero_of_add_eq_zero_left h) /- properties of inequality -/ lemma le_succ_of_pred_le : pred n ≤ m → n ≤ succ m := match n with | 0 => fun _ => zero_le _ | a+1 => succ_le_succ lemma le_lt_antisymm {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n) : False := Nat.lt_irrefl n (Nat.lt_of_le_of_lt h₁ h₂) lemma lt_le_antisymm {n m : ℕ} (h₁ : n < m) (h₂ : m ≤ n) : False := le_lt_antisymm h₂ h₁ protected lemma lt_asymm {n m : ℕ} (h₁ : n < m) : ¬ m < n := le_lt_antisymm (Nat.le_of_lt h₁) protected def lt_ge_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : b ≤ a → C) : C := if h : a < b then h₁ h else h₂ (Nat.not_lt.1 h) protected def lt_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a = b → C) (h₃ : b < a → C) : C := Nat.lt_ge_by_cases h₁ fun h₁ => Nat.lt_ge_by_cases h₃ fun h => h₂ (Nat.le_antisymm h h₁) protected lemma lt_trichotomy (a b : ℕ) : a < b ∨ a = b ∨ b < a := Nat.lt_by_cases Or.inl (Or.inr ∘ Or.inl) (Or.inr ∘ Or.inr) protected lemma eq_or_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ∨ b < a := (Nat.lt_trichotomy a b).resolve_left hnlt lemma lt_succ_of_lt (h : a < b) : a < succ b := le_succ_of_le h lemma one_pos : 0 < 1 := Nat.zero_lt_one /- subtraction -/ protected lemma sub_le_sub_left (k : ℕ) (h : n ≤ m) : k - m ≤ k - n := match m, le.dest h with | _, ⟨a, rfl⟩ => by rw [← Nat.sub_sub]; apply sub_le protected lemma sub.right_comm (m n k : ℕ) : m - n - k = m - k - n := by rw [Nat.sub_sub, Nat.sub_sub, Nat.add_comm] lemma succ_sub_sub_succ (n m k : ℕ) : succ n - m - succ k = n - m - k := by rw [sub.right_comm, succ_sub_succ, sub.right_comm] lemma mul_pred_left : ∀ (n m : ℕ), pred n * m = n * m - m | 0, m => by simp [Nat.zero_sub, pred_zero, Nat.zero_mul] | n+1, m => by rw [pred_succ, succ_mul, Nat.add_sub_cancel] lemma mul_pred_right (n m : ℕ) : n * pred m = n * m - n := by rw [Nat.mul_comm, mul_pred_left, Nat.mul_comm] protected lemma mul_sub_right_distrib (n) : ∀ (m k : ℕ), (n - m) * k = n * k - m * k | 0, k => by simp [Nat.sub_zero, Nat.zero_mul] | m+1, k => by rw [Nat.sub_succ, mul_pred_left, Nat.mul_sub_right_distrib, succ_mul, Nat.sub_sub] protected lemma mul_sub_left_distrib (n m k : ℕ) : n * (m - k) = n * m - n * k := by rw [Nat.mul_comm, Nat.mul_sub_right_distrib, Nat.mul_comm m n, Nat.mul_comm n k] protected lemma mul_self_sub_mul_self_eq (a b : Nat) : a * a - b * b = (a + b) * (a - b) := by rw [Nat.mul_sub_left_distrib, Nat.right_distrib, Nat.right_distrib, Nat.mul_comm b a, Nat.add_comm (a*a) (a*b), Nat.add_sub_add_left] lemma succ_mul_succ_eq (a b : Nat) : succ a * succ b = a*b + a + b + 1 := by rw [mul_succ, succ_mul, Nat.add_right_comm _ a]; rfl protected lemma sub_sub_self {n m : ℕ} (h : m ≤ n) : n - (n - m) = m := (Nat.sub_eq_iff_eq_add (Nat.sub_le _ _)).2 (add_sub_of_le h).symm protected lemma sub_add_comm {n m k : ℕ} (h : k ≤ n) : n + m - k = n - k + m := (Nat.sub_eq_iff_eq_add (Nat.le_trans h (Nat.le_add_right _ _))).2 (by rwa [Nat.add_right_comm, Nat.sub_add_cancel]) lemma sub_one_sub_lt (h : i < n) : n - 1 - i < n := by rw [Nat.sub_sub] apply Nat.sub_lt apply Nat.lt_of_lt_of_le (Nat.zero_lt_succ _) h rw [Nat.add_comm] apply Nat.zero_lt_succ lemma pred_inj : ∀ {a b : ℕ}, 0 < a → 0 < b → Nat.pred a = Nat.pred b → a = b | a+1, b+1, ha, hb, h => have a = b from h; by rw [this] | a+1, 0, ha, hb, h => absurd hb (Nat.lt_irrefl _) | 0, b+1, ha, hb, h => absurd ha (Nat.lt_irrefl _) | 0, 0, ha, hb, h => rfl /- find -/ section find variable (p : ℕ → Prop) private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k, k ≤ n → ¬p k variable [DecidablePred p] (H : ∃ n, p n) private def wf_lbp : WellFounded (lbp p) := by refine ⟨let ⟨n, pn⟩ := H; ?_⟩ suffices ∀ m k, n ≤ k + m → Acc (lbp p) k from fun a => this _ _ (Nat.le_add_left _ _) intro m induction m with refine fun k kn => ⟨_, fun | _, ⟨rfl, a⟩ => ?_⟩ | zero => exact absurd pn (a _ kn) | succ m IH => exact IH _ (by rw [Nat.add_right_comm]; exact kn) protected def find_x : {n // p n ∧ ∀ m, m < n → ¬p m} := (wf_lbp p H).fix' (C := fun k => (∀n, n < k → ¬p n) → {n // p n ∧ ∀ m, m < n → ¬p m}) (fun m IH al => if pm : p m then ⟨m, pm, al⟩ else have ∀ n, n ≤ m → ¬p n from fun n h => (Nat.lt_or_eq_of_le h).elim (al n) fun e => by rw [e]; exact pm IH _ ⟨rfl, this⟩ fun n h => this n $ Nat.le_of_succ_le_succ h) 0 fun n h => absurd h (Nat.not_lt_zero _) /-- If `p` is a (decidable) predicate on `ℕ` and `hp : ∃ (n : ℕ), p n` is a proof that there exists some natural number satisfying `p`, then `nat.find hp` is the smallest natural number satisfying `p`. Note that `nat.find` is protected, meaning that you can't just write `find`, even if the `nat` namespace is open. The API for `nat.find` is: * `nat.find_spec` is the proof that `nat.find hp` satisfies `p`. * `nat.find_min` is the proof that if `m < nat.find hp` then `m` does not satisfy `p`. * `nat.find_min'` is the proof that if `m` does satisfy `p` then `nat.find hp ≤ m`. -/ protected def find : ℕ := (Nat.find_x p H).1 protected lemma find_spec : p (Nat.find p H) := (Nat.find_x p H).2.1 protected lemma find_min : ∀ {m : ℕ}, m < Nat.find p H → ¬p m := @(Nat.find_x p H).2.2 protected lemma find_min' {m : ℕ} (h : p m) : Nat.find p H ≤ m := Nat.not_lt.1 fun l => Nat.find_min p H l h end find /- Up -/ /-- A well-ordered relation for "upwards" induction on the ℕural numbers up to some bound `ub`. -/ def Up (ub a i : ℕ) := i < a ∧ i < ub lemma Up.next {ub i} (h : i < ub) : Up ub (i+1) i := ⟨Nat.lt_succ_self _, h⟩ lemma Up.WF (ub) : WellFounded (Up ub) := Subrelation.wf (h₂ := measureWf (ub - .)) @fun a i ⟨ia, iu⟩ => Nat.sub_lt_sub_left iu ia /- mod -/ @[simp] lemma add_mod_right (x z : ℕ) : (x + z) % z = x % z := by rw [mod_eq_sub_mod (Nat.le_add_left _ _), Nat.add_sub_cancel] @[simp] lemma add_mod_left (x z : ℕ) : (x + z) % x = z % x := by rw [Nat.add_comm, add_mod_right] @[simp] lemma add_mul_mod_self_left (x y z : ℕ) : (x + y * z) % y = x % y := by induction z with | zero => rw [Nat.mul_zero, Nat.add_zero] | succ z ih => rw [mul_succ, ← Nat.add_assoc, add_mod_right, ih] @[simp] lemma add_mul_mod_self_right (x y z : ℕ) : (x + y * z) % z = x % z := by rw [Nat.mul_comm, add_mul_mod_self_left] @[simp] lemma mul_mod_right (m n : ℕ) : (m * n) % m = 0 := by rw [← Nat.zero_add (m*n), add_mul_mod_self_left, zero_mod] @[simp] lemma mul_mod_left (m n : ℕ) : (m * n) % n = 0 := by rw [Nat.mul_comm, mul_mod_right] lemma mul_mod_mul_left (z x y : ℕ) : (z * x) % (z * y) = z * (x % y) := if y0 : y = 0 then by rw [y0, Nat.mul_zero, mod_zero, mod_zero] else if z0 : z = 0 then by rw [z0, Nat.zero_mul, Nat.zero_mul, Nat.zero_mul, mod_zero] else by induction x using Nat.strong_rec_on with | _ n IH => have y0 : y > 0 from Nat.pos_of_ne_zero y0 have z0 : z > 0 from Nat.pos_of_ne_zero z0 cases Nat.lt_or_le n y with | inl yn => rw [mod_eq_of_lt yn, mod_eq_of_lt (Nat.mul_lt_mul_of_pos_left yn z0)] | inr yn => rw [mod_eq_sub_mod yn, mod_eq_sub_mod (Nat.mul_le_mul_left z yn), ← Nat.mul_sub_left_distrib] exact IH _ (sub_lt (Nat.lt_of_lt_of_le y0 yn) y0) lemma mul_mod_mul_right (z x y : ℕ) : (x * z) % (y * z) = (x % y) * z := by rw [Nat.mul_comm x z, Nat.mul_comm y z, Nat.mul_comm (x % y) z]; apply mul_mod_mul_left lemma sub_mul_mod (x k n : ℕ) (h₁ : n*k ≤ x) : (x - n*k) % n = x % n := by induction k with | zero => rw [Nat.mul_zero, Nat.sub_zero] | succ k IH => have h₂ : n * k ≤ x by rw [mul_succ] at h₁ apply Nat.le_trans _ h₁ apply le_add_right _ n have h₄ : x - n * k ≥ n by apply Nat.le_of_add_le_add_right (k := n*k) rw [Nat.sub_add_cancel h₂] simp [mul_succ, Nat.add_comm] at h₁; simp [h₁] rw [mul_succ, ← Nat.sub_sub, ← mod_eq_sub_mod h₄, IH h₂] /- div -/ lemma sub_mul_div (x n p : ℕ) (h₁ : n*p ≤ x) : (x - n*p) / n = x / n - p := by cases eq_zero_or_pos n with | inl h₀ => rw [h₀, Nat.div_zero, Nat.div_zero, Nat.zero_sub] | inr h₀ => induction p with | zero => rw [Nat.mul_zero, Nat.sub_zero, Nat.sub_zero] | succ p IH => have h₂ : n*p ≤ x by transitivity - (apply Nat.mul_le_mul_left; apply le_succ) - apply h₁ have h₃ : x - n * p ≥ n by apply Nat.le_of_add_le_add_right rw [Nat.sub_add_cancel h₂, Nat.add_comm] rw [mul_succ] at h₁ apply h₁ rw [sub_succ, ← IH h₂] rw [div_eq_sub_div h₀ h₃] simp [add_one, pred_succ, mul_succ, Nat.sub_sub] lemma div_mul_le_self : ∀ (m n : ℕ), m / n * n ≤ m | m, 0 => by simp; apply zero_le | m, n+1 => (le_div_iff_mul_le (Nat.succ_pos _)).1 (Nat.le_refl _) @[simp] lemma add_div_right (x : ℕ) {z : ℕ} (H : 0 < z) : (x + z) / z = succ (x / z) := by rw [div_eq_sub_div H (Nat.le_add_left _ _), Nat.add_sub_cancel] @[simp] lemma add_div_left (x : ℕ) {z : ℕ} (H : 0 < z) : (z + x) / z = succ (x / z) := by rw [Nat.add_comm, add_div_right x H] @[simp] lemma mul_div_right (n : ℕ) {m : ℕ} (H : 0 < m) : m * n / m = n := by induction n <;> simp_all [mul_succ] @[simp] lemma mul_div_left (m : ℕ) {n : ℕ} (H : 0 < n) : m * n / n = m := by rw [Nat.mul_comm, mul_div_right _ H] protected lemma div_self (H : 0 < n) : n / n = 1 := let t := add_div_right 0 H; by rwa [Nat.zero_add, Nat.zero_div] at t lemma add_mul_div_left (x z : ℕ) {y : ℕ} (H : 0 < y) : (x + y * z) / y = x / y + z := by induction z with | zero => rw [Nat.mul_zero, Nat.add_zero, Nat.add_zero] | succ z ih => rw [mul_succ, ← Nat.add_assoc, add_div_right _ H, ih]; rfl lemma add_mul_div_right (x y : ℕ) {z : ℕ} (H : 0 < z) : (x + y * z) / z = x / z + y := by rw [Nat.mul_comm, add_mul_div_left _ _ H] protected lemma mul_div_cancel (m : ℕ) {n : ℕ} (H : 0 < n) : m * n / n = m := let t := add_mul_div_right 0 m H; by rwa [Nat.zero_add, Nat.zero_div, Nat.zero_add] at t protected lemma mul_div_cancel_left (m : ℕ) {n : ℕ} (H : 0 < n) : n * m / n = m := by rw [Nat.mul_comm, Nat.mul_div_cancel _ H] protected lemma div_eq_of_eq_mul_left (H1 : 0 < n) (H2 : m = k * n) : m / n = k := by rw [H2, Nat.mul_div_cancel _ H1] protected lemma div_eq_of_eq_mul_right (H1 : 0 < n) (H2 : m = n * k) : m / n = k := by rw [H2, Nat.mul_div_cancel_left _ H1] protected lemma div_eq_of_lt_le (lo : k * n ≤ m) (hi : m < succ k * n) : m / n = k := have npos : 0 < n from (eq_zero_or_pos _).resolve_left fun hn => by rw [hn, Nat.mul_zero] at hi lo; exact absurd lo (Nat.not_le_of_gt hi) Nat.le_antisymm (le_of_lt_succ ((Nat.div_lt_iff_lt_mul npos).2 hi)) ((Nat.le_div_iff_mul_le npos).2 lo) lemma mul_sub_div (x n p : ℕ) (h₁ : x < n*p) : (n * p - succ x) / n = p - succ (x / n) := by have npos : 0 < n from (eq_zero_or_pos _).resolve_left fun n0 => by rw [n0, Nat.zero_mul] at h₁; exact not_lt_zero _ h₁ (apply Nat.div_eq_of_lt_le) - rw [Nat.mul_sub_right_distrib, Nat.mul_comm] apply Nat.sub_le_sub_left (exact (div_lt_iff_lt_mul npos).1 (lt_succ_self _)) - change succ (pred (n * p - x)) ≤ (succ (pred (p - x / n))) * n rw [succ_pred_eq_of_pos (Nat.sub_pos_of_lt h₁), fun h => succ_pred_eq_of_pos (Nat.sub_pos_of_lt h)] -- TODO: why is the function needed? - rw [Nat.mul_sub_right_distrib, Nat.mul_comm] (apply Nat.sub_le_sub_left; apply div_mul_le_self) - apply (div_lt_iff_lt_mul npos).2; rwa [Nat.mul_comm] protected lemma div_div_eq_div_mul (m n k : ℕ) : m / n / k = m / (n * k) := by cases eq_zero_or_pos k with | inl k0 => rw [k0, Nat.mul_zero, Nat.div_zero, Nat.div_zero] | inr kpos => ?_ cases eq_zero_or_pos n with | inl n0 => rw [n0, Nat.zero_mul, Nat.div_zero, Nat.zero_div] | inr npos => ?_ (apply Nat.le_antisymm) - apply (le_div_iff_mul_le (Nat.mul_pos npos kpos)).2 rw [Nat.mul_comm n k, ← Nat.mul_assoc] apply (le_div_iff_mul_le npos).1 apply (le_div_iff_mul_le kpos).1 (apply Nat.le_refl) - apply (le_div_iff_mul_le kpos).2 apply (le_div_iff_mul_le npos).2 rw [Nat.mul_assoc, Nat.mul_comm n k] apply (le_div_iff_mul_le (Nat.mul_pos kpos npos)).1 apply Nat.le_refl protected lemma mul_div_mul {m : ℕ} (n k : ℕ) (H : 0 < m) : m * n / (m * k) = n / k := by rw [← Nat.div_div_eq_div_mul, Nat.mul_div_cancel_left _ H] protected lemma mul_le_mul_of_nonneg_left {a b c : ℕ} (h₁ : a ≤ b) : c * a ≤ c * b := by by_cases hba: b ≤ a; { simp [Nat.le_antisymm hba h₁]; apply Nat.le_refl } by_cases hc0 : c ≤ 0; { simp [Nat.le_antisymm hc0 (zero_le c), Nat.zero_mul] } exact Nat.le_of_lt (Nat.mul_lt_mul_of_pos_left (Nat.not_le.1 hba) (Nat.not_le.1 hc0)) protected lemma mul_le_mul_of_nonneg_right {a b c : ℕ} (h₁ : a ≤ b) : a * c ≤ b * c := by by_cases hba : b ≤ a; { simp [Nat.le_antisymm hba h₁]; apply Nat.le_refl } by_cases hc0 : c ≤ 0; { simp [Nat.le_antisymm hc0 (zero_le c), Nat.mul_zero] } exact Nat.le_of_lt (Nat.mul_lt_mul_of_pos_right (Nat.not_le.1 hba) (Nat.not_le.1 hc0)) protected lemma mul_lt_mul (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) : a * b < c * d := Nat.lt_of_lt_of_le (Nat.mul_lt_mul_of_pos_right hac pos_b) (Nat.mul_le_mul_of_nonneg_left hbd) protected lemma mul_lt_mul' (h1 : a ≤ c) (h2 : b < d) (h3 : 0 < c) : a * b < c * d := Nat.lt_of_le_of_lt (Nat.mul_le_mul_of_nonneg_right h1) (Nat.mul_lt_mul_of_pos_left h2 h3) lemma div_lt_self (h₁ : 0 < n) (h₂ : 1 < m) : n / m < n := by have m_pos : 0 < m from Nat.lt_trans (by rfl) h₂ suffices 1 * n < m * n by rw [Nat.one_mul, Nat.mul_comm] at this exact (Nat.div_lt_iff_lt_mul m_pos).2 this exact Nat.mul_lt_mul h₂ (Nat.le_refl _) h₁ end Nat
fcefd256b534d2d78180dc8f9c0a6e628d7a1391
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/preadditive/endo_functor.lean
9bdf2f5e3cbf76ade10b5eac7dc58845c7a868bf
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,669
lean
/- Copyright (c) 2022 Julian Kuelshammer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Julian Kuelshammer -/ import category_theory.preadditive.basic import category_theory.endofunctor.algebra import category_theory.preadditive.additive_functor /-! # Preadditive structure on algebras over a monad > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. If `C` is a preadditive categories and `F` is an additive endofunctor on `C` then `algebra F` is also preadditive. Dually, the category `coalgebra F` is also preadditive. -/ universes v₁ u₁ -- morphism levels before object levels. See note [category_theory universes]. namespace category_theory variables (C : Type u₁) [category.{v₁} C] [preadditive C] (F : C ⥤ C) [functor.additive (F : C ⥤ C)] open category_theory.limits preadditive /-- The category of algebras over an additive endofunctor on a preadditive category is preadditive. -/ @[simps] instance endofunctor.algebra_preadditive : preadditive (endofunctor.algebra F) := { hom_group := λ A₁ A₂, { add := λ α β, { f := α.f + β.f, h' := by simp only [functor.map_add, add_comp, endofunctor.algebra.hom.h, comp_add] }, zero := { f := 0, h' := by simp only [functor.map_zero, zero_comp, comp_zero] }, nsmul := λ n α, { f := n • α.f, h' := by rw [comp_nsmul, functor.map_nsmul, nsmul_comp, endofunctor.algebra.hom.h] }, neg := λ α, { f := -α.f, h' := by simp only [functor.map_neg, neg_comp, endofunctor.algebra.hom.h, comp_neg] }, sub := λ α β, { f := α.f - β.f, h' := by simp only [functor.map_sub, sub_comp, endofunctor.algebra.hom.h, comp_sub] }, zsmul := λ r α, { f := r • α.f, h' := by rw [comp_zsmul, functor.map_zsmul, zsmul_comp, endofunctor.algebra.hom.h] }, add_assoc := by { intros, ext, apply add_assoc }, zero_add := by { intros, ext, apply zero_add }, add_zero := by { intros, ext, apply add_zero }, nsmul_zero' := by { intros, ext, apply zero_smul }, nsmul_succ' := by { intros, ext, apply succ_nsmul }, sub_eq_add_neg := by { intros, ext, apply sub_eq_add_neg }, zsmul_zero' := by { intros, ext, apply zero_smul }, zsmul_succ' := by { intros, ext, dsimp, simp only [coe_nat_zsmul, succ_nsmul], refl, }, zsmul_neg' := by { intros, ext, simp only [zsmul_neg_succ_of_nat, neg_inj, nsmul_eq_smul_cast ℤ] }, add_left_neg := by { intros, ext, apply add_left_neg }, add_comm := by { intros, ext, apply add_comm } }, add_comp' := by { intros, ext, apply add_comp }, comp_add' := by { intros, ext, apply comp_add } } instance algebra.forget_additive : (endofunctor.algebra.forget F).additive := {} @[simps] instance endofunctor.coalgebra_preadditive : preadditive (endofunctor.coalgebra F) := { hom_group := λ A₁ A₂, { add := λ α β, { f := α.f + β.f, h' := by simp only [functor.map_add, comp_add, endofunctor.coalgebra.hom.h, add_comp] }, zero := { f := 0, h' := by simp only [functor.map_zero, zero_comp, comp_zero] }, nsmul := λ n α, { f := n • α.f, h' := by rw [functor.map_nsmul, comp_nsmul, endofunctor.coalgebra.hom.h, nsmul_comp] }, neg := λ α, { f := -α.f, h' := by simp only [functor.map_neg, comp_neg, endofunctor.coalgebra.hom.h, neg_comp] }, sub := λ α β, { f := α.f - β.f, h' := by simp only [functor.map_sub, comp_sub, endofunctor.coalgebra.hom.h, sub_comp] }, zsmul := λ r α, { f := r • α.f, h' := by rw [functor.map_zsmul, comp_zsmul, endofunctor.coalgebra.hom.h, zsmul_comp] }, add_assoc := by { intros, ext, apply add_assoc }, zero_add := by { intros, ext, apply zero_add }, add_zero := by { intros, ext, apply add_zero }, nsmul_zero' := by { intros, ext, apply zero_smul }, nsmul_succ' := by { intros, ext, apply succ_nsmul }, sub_eq_add_neg := by { intros, ext, apply sub_eq_add_neg }, zsmul_zero' := by { intros, ext, apply zero_smul }, zsmul_succ' := by { intros, ext, dsimp, simp only [coe_nat_zsmul, succ_nsmul], refl, }, zsmul_neg' := by { intros, ext, simp only [zsmul_neg_succ_of_nat, neg_inj, nsmul_eq_smul_cast ℤ] }, add_left_neg := by { intros, ext, apply add_left_neg }, add_comm := by { intros, ext, apply add_comm } }, add_comp' := by { intros, ext, apply add_comp }, comp_add' := by { intros, ext, apply comp_add } } instance coalgebra.forget_additive : (endofunctor.coalgebra.forget F).additive := {} end category_theory
ec329e74a31c07e4fecd72621f21fb0160bfb8d0
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/1918.lean
bcc0189def793e4ef6c205d458ec8942943340b7
[ "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
54
lean
inductive Bug | mk : (Unit → Nat → Bug) → Bug
04446165f996521b65de4bb1641cc7e9951df3bb
3618c6e11aa822fd542440674dfb9a7b9921dba0
/src/choose_letters.lean
8bb153d7e3141a6304c40fe5f8e0e4a9bd0f53c0
[]
no_license
ChrisHughes24/single_relation
99ceedcc02d236ce46d6c65d72caa669857533c5
057e157a59de6d0e43b50fcb537d66792ec20450
refs/heads/master
1,683,652,062,698
1,683,360,089,000
1,683,360,089,000
279,346,432
0
0
null
null
null
null
UTF-8
Lean
false
false
3,708
lean
import coprod.free_group import data.list.min_max import order.lexicographic /-! # Choosing letters for the one relator algorithm This file contains `choose_t_and_x` which selects letters with the appropriate properties for the one relator group algorithm, used in the `group_thingy` tactic. -/ open free_group multiplicative variables {ι : Type} [decidable_eq ι] (r : free_group ι) variables (T : set ι) [decidable_pred T] -- Want `x` to have least occurences in `w` -- `t` with smallest `exp_sum`, tie break is large sum of nat_abs in `r`, /-- The list of variables contained in a word in the `free_group` -/ def vars : list ι := (r.to_list.map sigma.fst).erase_dup /-- `exp_sum_and_occs r i` returns the exponent sum of the letter `i` in `r`, as well as the number of occurences, the sum of the absolute values of the exponents. -/ def exp_sum_and_occs (i : ι) : C∞ × ℕ := r.to_list.foldl (λ n j, if j.1 = i then (n.1 * j.2, n.2 + to_add j.2.nat_abs) else n) (1, 0) def occs (w : free_group ι) (i : ι) : ℕ := w.to_list.foldl (λ n j, if j.1 = i then n + to_add j.2.nat_abs else n) 0 /-- `choose_t_and_x r T` returns a pair of letters and their exponent sum in `r`. If there is `t` with exponent sum zero in `r`, then this `t` is chosen. If `t ∈ T`, then `x` is chosen to not be in `T`, if `t ∉ T` then any `x ≠ t` is chosen. If there is no `t` with exponent sum zero, then `x` is chosen first such that `x ∉ T`. Then `t` is chosen such that `t ≠ x`. Within the conditions defined above `t` is chosen with the most occurences and `x` is chosen with the least occurences. -/ def choose_t_and_x (vars_r : list ι) : option $ (ι × C∞) × -- t and its exponent sum (ι × C∞) -- x and its exponent sum. := let lr := vars_r.map (λ i, (i, exp_sum_and_occs r i)) in do t ← lr.argmin (λ i : ι × (C∞ × ℕ), show lex ℕ (order_dual ℕ), from ((to_add i.2.1).nat_abs, i.2.2)), if t.2.1 = 1 then if t.1 ∈ T then do x ← ((lr.filter (λ p : ι × C∞ × ℕ, p.1 ∉ T)).argmin (λ i : ι × (C∞ × ℕ), i.2.2)), return ((t.1, 1), (x.1, x.2.1)) else do x ← ((lr.filter (λ p : ι × C∞ × ℕ, p.1 ≠ t.1)).argmin (λ i : ι × (C∞ × ℕ), i.2.2)), return ((t.1, 1), (x.1, x.2.1)) else do x ← ((lr.filter (λ p : ι × C∞ × ℕ, p.1 ∉ T)).argmin (λ i : ι × (C∞ × ℕ), i.2.2)), return ((t.1, t.2.1), (x.1, x.2.1)), t' ← ((lr.filter (λ p : ι × C∞ × ℕ, p.1 ≠ x.1)).argmax (λ i : ι × (C∞ × ℕ), i.2.2)), return ((t'.1, t'.2.1), (x.1, x.2.1)) def choose_t_and_x' (vars_r vars_w : list ι) : option $ (ι × C∞) × -- t and its exponent sum (ι × C∞) -- x and its exponent sum. := let lr := vars_r.map (λ i, (i, exp_sum_and_occs r i)) in let lw := vars_w.map (λ i, (i, occs r i)) in do t ← lr.argmin (λ i : ι × (C∞ × ℕ), show lex ℕ (order_dual ℕ), from ((to_add i.2.1).nat_abs, i.2.2)), if t.2.1 = 1 then if t.1 ∈ T then do x ← ((lr.filter (λ p : ι × C∞ × ℕ, p.1 ∉ T)).argmin (λ i : ι × (C∞ × ℕ), i.2.2)), return ((t.1, 1), (x.1, x.2.1)) else do x ← ((lr.filter (λ p : ι × C∞ × ℕ, p.1 ≠ t.1)).argmin (λ i : ι × (C∞ × ℕ), i.2.2)), return ((t.1, 1), (x.1, x.2.1)) else do x ← ((lr.filter (λ p : ι × C∞ × ℕ, p.1 ∉ T)).argmin (λ i : ι × (C∞ × ℕ), i.2.2)), return ((t.1, t.2.1), (x.1, x.2.1)), t' ← ((lr.filter (λ p : ι × C∞ × ℕ, p.1 ≠ x.1)).argmax (λ i : ι × (C∞ × ℕ), i.2.2)), return ((t'.1, t'.2.1), (x.1, x.2.1))
c3b7aef93001162aa83009d60bb5e5b5035a249e
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/notation6.lean
07b91d5743db87e6361f0be4a53791de198a134e
[ "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
127
lean
-- open num notation `o` := (10:num) check 11 constant f : num → num check o + 1 check f o + o + o eval 9 + (1:num) eval o+4
b2480a604c45da6e5d05b84b597ba2f7647f8c7b
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Server/Completion.lean
723b69c7f76b8abf2ce99529ad50f54f40feb5a2
[ "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", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
22,297
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.Environment import Lean.Parser.Term import Lean.Data.FuzzyMatching import Lean.Data.Lsp.LanguageFeatures import Lean.Data.Lsp.Capabilities import Lean.Data.Lsp.Utf16 import Lean.Meta.Tactic.Apply import Lean.Meta.Match.MatcherInfo import Lean.Server.InfoUtils import Lean.Parser.Extension namespace Lean.Server.Completion open Lsp open Elab open Meta open FuzzyMatching builtin_initialize completionBlackListExt : TagDeclarationExtension ← mkTagDeclarationExtension @[export lean_completion_add_to_black_list] def addToBlackList (env : Environment) (declName : Name) : Environment := completionBlackListExt.tag env declName private def isBlackListed (declName : Name) : MetaM Bool := do let env ← getEnv (pure (declName.isInternal && !isPrivateName declName)) <||> (pure <| isAuxRecursor env declName) <||> (pure <| isNoConfusion env declName) <||> isRec declName <||> (pure <| completionBlackListExt.isTagged env declName) <||> isMatcher declName private partial def consumeImplicitPrefix (e : Expr) (k : Expr → MetaM α) : MetaM α := do match e with | Expr.forallE n d b c => -- We do not consume instance implicit arguments because the user probably wants be aware of this dependency if c == .implicit then withLocalDecl n c d fun arg => consumeImplicitPrefix (b.instantiate1 arg) k else k e | _ => k e private def isTypeApplicable (type : Expr) (expectedType? : Option Expr) : MetaM Bool := try match expectedType? with | none => return true | some expectedType => let mut (numArgs, hasMVarHead) ← getExpectedNumArgsAux type unless hasMVarHead do let targetTypeNumArgs ← getExpectedNumArgs expectedType numArgs := numArgs - targetTypeNumArgs let (_, _, type) ← forallMetaTelescopeReducing type (some numArgs) -- TODO take coercions into account -- We use `withReducible` to make sure we don't spend too much time unfolding definitions -- Alternative: use default and small number of heartbeats withReducible <| withoutModifyingState <| isDefEq type expectedType catch _ => return false private def sortCompletionItems (items : Array (CompletionItem × Float)) : Array CompletionItem := items.qsort (fun (i1, s1) (i2, s2) => if s1 == s2 then i1.label < i2.label else s1 > s2) |>.map (·.1) private def mkCompletionItem (label : Name) (type : Expr) (docString? : Option String) (kind : CompletionItemKind) : MetaM CompletionItem := do let doc? := docString?.map fun docString => { value := docString, kind := MarkupKind.markdown : MarkupContent } let detail ← consumeImplicitPrefix type fun type => return toString (← Meta.ppExpr type) return { label := label.getString!, detail? := detail, documentation? := doc?, kind? := kind } structure State where itemsMain : Array (CompletionItem × Float) := #[] itemsOther : Array (CompletionItem × Float) := #[] abbrev M := OptionT $ StateRefT State MetaM private def addCompletionItem (label : Name) (type : Expr) (expectedType? : Option Expr) (declName? : Option Name) (kind : CompletionItemKind) (score : Float) : M Unit := do let docString? ← if let some declName := declName? then findDocString? (← getEnv) declName else pure none let item ← mkCompletionItem label type docString? kind if (← isTypeApplicable type expectedType?) then modify fun s => { s with itemsMain := s.itemsMain.push (item, score) } else modify fun s => { s with itemsOther := s.itemsOther.push (item, score) } private def getCompletionKindForDecl (constInfo : ConstantInfo) : M CompletionItemKind := do let env ← getEnv if constInfo.isCtor then return CompletionItemKind.constructor else if constInfo.isInductive then if isClass env constInfo.name then return CompletionItemKind.class else if (← isEnumType constInfo.name) then return CompletionItemKind.enum else return CompletionItemKind.struct else if (← isProjectionFn constInfo.name) then return CompletionItemKind.field else if (← whnf constInfo.type).isForall then return CompletionItemKind.function else return CompletionItemKind.constant private def addCompletionItemForDecl (label : Name) (declName : Name) (expectedType? : Option Expr) (score : Float) : M Unit := do if let some c := (← getEnv).find? declName then addCompletionItem label c.type expectedType? (some declName) (← getCompletionKindForDecl c) score private def addKeywordCompletionItem (keyword : String) : M Unit := do let item := { label := keyword, detail? := "keyword", documentation? := none, kind? := CompletionItemKind.keyword } modify fun s => { s with itemsMain := s.itemsMain.push (item, 1) } private def addNamespaceCompletionItem (ns : Name) (score : Float) : M Unit := do let item := { label := ns.toString, detail? := "namespace", documentation? := none, kind? := CompletionItemKind.module } modify fun s => { s with itemsMain := s.itemsMain.push (item, score) } private def runM (ctx : ContextInfo) (lctx : LocalContext) (x : M Unit) : IO (Option CompletionList) := ctx.runMetaM lctx do match (← x.run |>.run {}) with | (none, _) => return none | (some _, s) => return some { items := sortCompletionItems s.itemsMain ++ sortCompletionItems s.itemsOther, isIncomplete := true } private def matchAtomic (id : Name) (declName : Name) : Option Float := match id, declName with | .str .anonymous s₁, .str .anonymous s₂ => fuzzyMatchScoreWithThreshold? s₁ s₂ | _, _ => none private def normPrivateName (declName : Name) : MetaM Name := do match privateToUserName? declName with | none => return declName | some userName => if mkPrivateName (← getEnv) userName == declName then return userName else return declName /-- Return the auto-completion label if `id` can be auto completed using `declName` assuming namespace `ns` is open. This function only succeeds with atomic labels. BTW, it seems most clients only use the last part. Remark: `danglingDot == true` when the completion point is an identifier followed by `.`. -/ private def matchDecl? (ns : Name) (id : Name) (danglingDot : Bool) (declName : Name) : MetaM (Option (Name × Float)) := do -- dbg_trace "{ns}, {id}, {declName}, {danglingDot}" let declName ← normPrivateName declName if !ns.isPrefixOf declName then return none else let declName := declName.replacePrefix ns Name.anonymous if id.isPrefixOf declName && danglingDot then let declName := declName.replacePrefix id Name.anonymous if declName.isAtomic && !declName.isAnonymous then return some (declName, 1) else return none else if !danglingDot then match id, declName with | .str p₁ s₁, .str p₂ s₂ => if p₁ == p₂ then return fuzzyMatchScoreWithThreshold? s₁ s₂ |>.map (s₂, ·) else return none | _, _ => return none else return none /-- Truncate the given identifier and make sure it has length `≤ newLength`. This function assumes `id` does not contain `Name.num` constructors. -/ private partial def truncate (id : Name) (newLen : Nat) : Name := let rec go (id : Name) : Name × Nat := match id with | Name.anonymous => (id, 0) | Name.num .. => unreachable! | .str p s => let (p', len) := go p if len + 1 >= newLen then (p', len) else let optDot := if p.isAnonymous then 0 else 1 let len' := len + optDot + s.length if len' ≤ newLen then (id, len') else (Name.mkStr p (s.extract 0 ⟨newLen - optDot - len⟩), newLen) (go id).1 inductive HoverInfo where | after | inside (delta : Nat) def matchNamespace (ns : Name) (nsFragment : Name) (danglingDot : Bool) : Option Float := if danglingDot then if nsFragment != ns && nsFragment.isPrefixOf ns then some 1 else none else match ns, nsFragment with | .str p₁ s₁, .str p₂ s₂ => if p₁ == p₂ then fuzzyMatchScoreWithThreshold? s₂ s₁ else none | _, _ => none def completeNamespaces (ctx : ContextInfo) (id : Name) (danglingDot : Bool) : M Unit := do let env ← getEnv let add (ns : Name) (ns' : Name) (score : Float) : M Unit := if danglingDot then addNamespaceCompletionItem (ns.replacePrefix (ns' ++ id) Name.anonymous) score else addNamespaceCompletionItem (ns.replacePrefix ns' Name.anonymous) score env.getNamespaceSet |>.forM fun ns => do unless ns.isInternal || env.contains ns do -- Ignore internal and namespaces that are also declaration names for openDecl in ctx.openDecls do match openDecl with | OpenDecl.simple ns' _ => if let some score := matchNamespace ns (ns' ++ id) danglingDot then add ns ns' score return () | _ => pure () -- use current namespace let rec visitNamespaces (ns' : Name) : M Unit := do if let some score := matchNamespace ns (ns' ++ id) danglingDot then add ns ns' score else match ns' with | Name.str p .. => visitNamespaces p | _ => return () visitNamespaces ctx.currNamespace private def idCompletionCore (ctx : ContextInfo) (id : Name) (hoverInfo : HoverInfo) (danglingDot : Bool) (expectedType? : Option Expr) : M Unit := do let mut id := id.eraseMacroScopes let mut danglingDot := danglingDot if let HoverInfo.inside delta := hoverInfo then id := truncate id delta danglingDot := false -- dbg_trace ">> id {id} : {expectedType?}" if id.isAtomic then -- search for matches in the local context for localDecl in (← getLCtx) do if let some score := matchAtomic id localDecl.userName then addCompletionItem localDecl.userName localDecl.type expectedType? none (kind := CompletionItemKind.variable) score -- search for matches in the environment let env ← getEnv env.constants.forM fun declName c => do unless (← isBlackListed declName) do let matchUsingNamespace (ns : Name): M Bool := do if let some (label, score) ← matchDecl? ns id danglingDot declName then -- dbg_trace "matched with {id}, {declName}, {label}" addCompletionItem label c.type expectedType? declName (← getCompletionKindForDecl c) score return true else return false if (← matchUsingNamespace Name.anonymous) then return () -- use current namespace let rec visitNamespaces (ns : Name) : M Bool := do match ns with | Name.str p .. => matchUsingNamespace ns <||> visitNamespaces p | _ => return false if (← visitNamespaces ctx.currNamespace) then return () -- use open decls for openDecl in ctx.openDecls do match openDecl with | OpenDecl.simple ns exs => unless exs.contains declName do if (← matchUsingNamespace ns) then return () | _ => pure () -- Recall that aliases may not be atomic and include the namespace where they were created. let matchAlias (ns : Name) (alias : Name) : Option Float := if ns.isPrefixOf alias then matchAtomic id (alias.replacePrefix ns Name.anonymous) else none -- Auxiliary function for `alias` let addAlias (alias : Name) (declNames : List Name) (score : Float) : M Unit := do declNames.forM fun declName => do unless (← isBlackListed declName) do addCompletionItemForDecl alias declName expectedType? score -- search explicitily open `ids` for openDecl in ctx.openDecls do match openDecl with | OpenDecl.explicit openedId resolvedId => unless (← isBlackListed resolvedId) do if let some score := matchAtomic id openedId then addCompletionItemForDecl openedId resolvedId expectedType? score | OpenDecl.simple ns _ => getAliasState env |>.forM fun alias declNames => do if let some score := matchAlias ns alias then addAlias alias declNames score -- search for aliases getAliasState env |>.forM fun alias declNames => do -- use current namespace let rec searchAlias (ns : Name) : M Unit := do if let some score := matchAlias ns alias then addAlias alias declNames score else match ns with | Name.str p .. => searchAlias p | _ => return () searchAlias ctx.currNamespace -- Search keywords if let .str .anonymous s := id then let keywords := Parser.getTokenTable env for keyword in keywords.findPrefix s do addKeywordCompletionItem keyword -- Search namespaces completeNamespaces ctx id danglingDot private def idCompletion (ctx : ContextInfo) (lctx : LocalContext) (id : Name) (hoverInfo : HoverInfo) (danglingDot : Bool) (expectedType? : Option Expr) : IO (Option CompletionList) := runM ctx lctx do idCompletionCore ctx id hoverInfo danglingDot expectedType? private def unfoldeDefinitionGuarded? (e : Expr) : MetaM (Option Expr) := try unfoldDefinition? e catch _ => pure none /-- Return `true` if `e` is a `declName`-application, or can be unfolded (delta-reduced) to one. -/ private partial def isDefEqToAppOf (e : Expr) (declName : Name) : MetaM Bool := do if e.getAppFn.isConstOf declName then return true let some e ← unfoldeDefinitionGuarded? e | return false isDefEqToAppOf e declName private def isDotCompletionMethod (typeName : Name) (info : ConstantInfo) : MetaM Bool := forallTelescopeReducing info.type fun xs _ => do for x in xs do let localDecl ← x.fvarId!.getDecl let type := localDecl.type.consumeMData if (← isDefEqToAppOf type typeName) then return true return false /-- Given a type, try to extract relevant type names for dot notation field completion. We extract the type name, parent struct names, and unfold the type. The process mimics the dot notation elaboration procedure at `App.lean` -/ private partial def getDotCompletionTypeNames (type : Expr) : MetaM NameSet := return (← visit type |>.run {}).2 where visit (type : Expr) : StateRefT NameSet MetaM Unit := do let .const typeName _ := type.getAppFn | return () modify fun s => s.insert typeName if isStructure (← getEnv) typeName then for parentName in getAllParentStructures (← getEnv) typeName do modify fun s => s.insert parentName let some type ← unfoldeDefinitionGuarded? type | return () visit type private def dotCompletion (ctx : ContextInfo) (info : TermInfo) (hoverInfo : HoverInfo) (expectedType? : Option Expr) : IO (Option CompletionList) := runM ctx info.lctx do let nameSet ← try getDotCompletionTypeNames (← instantiateMVars (← inferType info.expr)) catch _ => pure {} if nameSet.isEmpty then if info.stx.isIdent then idCompletionCore ctx info.stx.getId hoverInfo (danglingDot := false) expectedType? else if info.stx.getKind == ``Lean.Parser.Term.completion && info.stx[0].isIdent then -- TODO: truncation when there is a dangling dot idCompletionCore ctx info.stx[0].getId HoverInfo.after (danglingDot := true) expectedType? else failure else (← getEnv).constants.forM fun declName c => do let typeName := (← normPrivateName declName).getPrefix if nameSet.contains typeName then unless (← isBlackListed c.name) do if (← isDotCompletionMethod typeName c) then addCompletionItem c.name.getString! c.type expectedType? c.name (kind := (← getCompletionKindForDecl c)) 1 private def dotIdCompletion (ctx : ContextInfo) (lctx : LocalContext) (id : Name) (expectedType? : Option Expr) : IO (Option CompletionList) := runM ctx lctx do let some expectedType := expectedType? | return () let resultTypeFn := (← instantiateMVars expectedType).cleanupAnnotations.getAppFn let .const typeName .. := resultTypeFn.cleanupAnnotations | return () (← getEnv).constants.forM fun declName c => do let some (label, score) ← matchDecl? typeName id (danglingDot := false) declName | pure () addCompletionItem label c.type expectedType? declName (← getCompletionKindForDecl c) score private def fieldIdCompletion (ctx : ContextInfo) (lctx : LocalContext) (id : Name) (structName : Name) : IO (Option CompletionList) := runM ctx lctx do let idStr := id.toString let fieldNames := getStructureFieldsFlattened (← getEnv) structName (includeSubobjectFields := false) for fieldName in fieldNames do let .str _ fieldName := fieldName | continue let some score := fuzzyMatchScoreWithThreshold? idStr fieldName | continue let item := { label := fieldName, detail? := "field", documentation? := none, kind? := CompletionItemKind.field } modify fun s => { s with itemsMain := s.itemsMain.push (item, score) } private def optionCompletion (ctx : ContextInfo) (stx : Syntax) (caps : ClientCapabilities) : IO (Option CompletionList) := ctx.runMetaM {} do let (partialName, trailingDot) := -- `stx` is from `"set_option" >> ident` match stx[1].getSubstring? (withLeading := false) (withTrailing := false) with | none => ("", false) -- the `ident` is `missing`, list all options | some ss => if !ss.str.atEnd ss.stopPos && ss.str.get ss.stopPos == '.' then -- include trailing dot, which is not parsed by `ident` (ss.toString ++ ".", true) else (ss.toString, false) -- HACK(WN): unfold the type so ForIn works let (decls : RBMap _ _ _) ← getOptionDecls let opts ← getOptions let mut items := #[] for ⟨name, decl⟩ in decls do if let some score := fuzzyMatchScoreWithThreshold? partialName name.toString then let textEdit := if !caps.textDocument?.any (·.completion?.any (·.completionItem?.any (·.insertReplaceSupport?.any (·)))) then none -- InsertReplaceEdit not supported by client else if let some ⟨start, stop⟩ := stx[1].getRange? then let stop := if trailingDot then stop + ' ' else stop let range := ⟨ctx.fileMap.utf8PosToLspPos start, ctx.fileMap.utf8PosToLspPos stop⟩ some { newText := name.toString, insert := range, replace := range : InsertReplaceEdit } else none items := items.push ({ label := name.toString detail? := s!"({opts.get name decl.defValue}), {decl.descr}" documentation? := none, kind? := CompletionItemKind.property -- TODO: investigate whether this is the best kind for options. textEdit? := textEdit }, score) return some { items := sortCompletionItems items, isIncomplete := true } private def tacticCompletion (ctx : ContextInfo) : IO (Option CompletionList) := -- Just return the list of tactics for now. ctx.runMetaM {} do let table := Parser.getCategory (Parser.parserExtension.getState (← getEnv)).categories `tactic |>.get!.tables.leadingTable let items : Array (CompletionItem × Float) := table.fold (init := #[]) fun items tk _ => -- TODO pretty print tactic syntax items.push ({ label := tk.toString, detail? := none, documentation? := none, kind? := CompletionItemKind.keyword }, 1) return some { items := sortCompletionItems items, isIncomplete := true } partial def find? (fileMap : FileMap) (hoverPos : String.Pos) (infoTree : InfoTree) (caps : ClientCapabilities) : IO (Option CompletionList) := do let ⟨hoverLine, _⟩ := fileMap.toPosition hoverPos match infoTree.foldInfo (init := none) (choose fileMap hoverLine) with | some (hoverInfo, ctx, Info.ofCompletionInfo info) => match info with | .dot info (expectedType? := expectedType?) .. => dotCompletion ctx info hoverInfo expectedType? | .id _ id danglingDot lctx expectedType? => idCompletion ctx lctx id hoverInfo danglingDot expectedType? | .dotId _ id lctx expectedType? => dotIdCompletion ctx lctx id expectedType? | .fieldId _ id lctx structName => fieldIdCompletion ctx lctx id structName | .option stx => optionCompletion ctx stx caps | .tactic .. => tacticCompletion ctx | _ => return none | _ => -- TODO try to extract id from `fileMap` and some `ContextInfo` from `InfoTree` return none where choose (fileMap : FileMap) (hoverLine : Nat) (ctx : ContextInfo) (info : Info) (best? : Option (HoverInfo × ContextInfo × Info)) : Option (HoverInfo × ContextInfo × Info) := if !info.isCompletion then best? else if info.occursInside? hoverPos |>.isSome then let headPos := info.pos?.get! let ⟨headPosLine, _⟩ := fileMap.toPosition headPos let ⟨tailPosLine, _⟩ := fileMap.toPosition info.tailPos?.get! if headPosLine != hoverLine || headPosLine != tailPosLine then best? else match best? with | none => (HoverInfo.inside (hoverPos - headPos).byteIdx, ctx, info) | some (HoverInfo.after, _, _) => (HoverInfo.inside (hoverPos - headPos).byteIdx, ctx, info) | some (_, _, best) => if info.isSmaller best then (HoverInfo.inside (hoverPos - headPos).byteIdx, ctx, info) else best? else if let some (HoverInfo.inside _, _, _) := best? then -- We assume the "inside matches" have precedence over "before ones". best? else if let some d := info.occursBefore? hoverPos then let pos := info.tailPos?.get! let ⟨line, _⟩ := fileMap.toPosition pos if line != hoverLine then best? else match best? with | none => (HoverInfo.after, ctx, info) | some (_, _, best) => let dBest := best.occursBefore? hoverPos |>.get! if d < dBest || (d == dBest && info.isSmaller best) then (HoverInfo.after, ctx, info) else best? else best? end Lean.Server.Completion
cf9be54698caa3a251149d6e122b331fd53f45b4
626e312b5c1cb2d88fca108f5933076012633192
/src/analysis/convex/basic.lean
b3b97d59cae864a17f55088edfbadda9f88019dc
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
71,068
lean
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudriashov -/ import data.complex.module import data.set.intervals.image_preimage import linear_algebra.affine_space.affine_map import order.closure /-! # Convex sets and functions on real vector spaces In a real vector space, we define the following objects and properties. * `segment x y` is the closed segment joining `x` and `y`. * `open_segment x y` is the open segment joining `x` and `y`. * A set `s` is `convex` if for any two points `x y ∈ s` it includes `segment x y`; * A function `f : E → β` is `convex_on` a set `s` if `s` is itself a convex set, and for any two points `x y ∈ s` the segment joining `(x, f x)` to `(y, f y)` is (non-strictly) above the graph of `f`; equivalently, `convex_on f s` means that the epigraph `{p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2}` is a convex set; * Center mass of a finite set of points with prescribed weights. * Convex hull of a set `s` is the minimal convex set that includes `s`. * Standard simplex `std_simplex ι [fintype ι]` is the intersection of the positive quadrant with the hyperplane `s.sum = 1` in the space `ι → ℝ`. We also provide various equivalent versions of the definitions above, prove that some specific sets are convex, and prove Jensen's inequality. Note: To define convexity for functions `f : E → β`, we need `β` to be an ordered vector space, defined using the instance `ordered_smul ℝ β`. ## Notations We use the following local notations: * `I = Icc (0:ℝ) 1`; * `[x, y] = segment x y`. They are defined using `local notation`, so they are not available outside of this file. ## Implementation notes `convex_hull` is defined as a closure operator. This gives access to the `closure_operator` API while the impact on writing code is minimal as `convex_hull s` is automatically elaborated as `⇑convex_hull s`. -/ universes u' u v v' w x variables {E : Type u} {F : Type v} {ι : Type w} {ι' : Type x} {α : Type v'} [add_comm_group E] [module ℝ E] [add_comm_group F] [module ℝ F] [linear_ordered_field α] {s : set E} open set linear_map open_locale classical big_operators pointwise local notation `I` := (Icc 0 1 : set ℝ) section sets /-! ### Segment -/ /-- Segments in a vector space. -/ def segment (x y : E) : set E := {z : E | ∃ (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), a • x + b • y = z} local notation `[`x `, ` y `]` := segment x y lemma segment_symm (x y : E) : [x, y] = [y, x] := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ lemma left_mem_segment (x y : E) : x ∈ [x, y] := ⟨1, 0, zero_le_one, le_refl 0, add_zero 1, by rw [zero_smul, one_smul, add_zero]⟩ lemma right_mem_segment (x y : E) : y ∈ [x, y] := segment_symm y x ▸ left_mem_segment y x lemma segment_same (x : E) : [x, x] = {x} := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [(add_smul _ _ _).symm, mem_singleton_iff, hab, one_smul, eq_comm] using hz, λ h, mem_singleton_iff.1 h ▸ left_mem_segment z z⟩ lemma segment_eq_image (x y : E) : [x, y] = (λ θ : ℝ, (1 - θ) • x + θ • y) '' I := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab ▸ le_add_of_nonneg_left ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩, λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1-θ, θ, sub_nonneg.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩ lemma segment_eq_image' (x y : E) : [x, y] = (λ (θ : ℝ), x + θ • (y - x)) '' I := by { convert segment_eq_image x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel } lemma segment_eq_image₂ (x y : E) : [x, y] = (λ p : ℝ×ℝ, p.1 • x + p.2 • y) '' {p | 0 ≤ p.1 ∧ 0 ≤ p.2 ∧ p.1 + p.2 = 1} := by simp only [segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] lemma segment_eq_Icc {a b : ℝ} (h : a ≤ b) : [a, b] = Icc a b := begin rw [segment_eq_image'], show (((+) a) ∘ (λ t, t * (b - a))) '' Icc 0 1 = Icc a b, rw [image_comp, image_mul_right_Icc (@zero_le_one ℝ _) (sub_nonneg.2 h), image_const_add_Icc], simp end lemma segment_eq_Icc' (a b : ℝ) : [a, b] = Icc (min a b) (max a b) := by cases le_total a b; [skip, rw segment_symm]; simp [segment_eq_Icc, *] lemma segment_eq_interval (a b : ℝ) : segment a b = interval a b := segment_eq_Icc' _ _ lemma mem_segment_translate (a : E) {x b c} : a + x ∈ [a + b, a + c] ↔ x ∈ [b, c] := begin rw [segment_eq_image', segment_eq_image'], refine exists_congr (λ θ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj] end lemma segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' [a + b, a + c] = [b, c] := set.ext $ λ x, mem_segment_translate a lemma segment_translate_image (a b c : E) : (λx, a + x) '' [b, c] = [a + b, a + c] := segment_translate_preimage a b c ▸ image_preimage_eq _ $ add_left_surjective a lemma segment_image (f : E →ₗ[ℝ] F) (a b : E) : f '' [a, b] = [f a, f b] := set.ext (λ x, by simp [segment_eq_image]) /-- Open segment in a vector space. Note that `open_segment x x = {x}` instead of being `∅`. -/ def open_segment (x y : E) : set E := {z : E | ∃ (a b : ℝ) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1), a • x + b • y = z} lemma open_segment_subset_segment (x y : E) : open_segment x y ⊆ [x, y] := λ z ⟨a, b, ha, hb, hab, hz⟩, ⟨a, b, ha.le, hb.le, hab, hz⟩ lemma mem_open_segment_of_ne_left_right {x y z : E} (hx : x ≠ z) (hy : y ≠ z) (hz : z ∈ [x, y]) : z ∈ open_segment x y := begin obtain ⟨a, b, ha, hb, hab, hz⟩ := hz, by_cases ha' : a ≠ 0, by_cases hb' : b ≠ 0, { exact ⟨a, b, ha.lt_of_ne (ne.symm ha'), hb.lt_of_ne (ne.symm hb'), hab, hz⟩ }, all_goals { simp only [*, add_zero, not_not, one_smul, zero_smul, zero_add] at * } end lemma open_segment_symm (x y : E) : open_segment x y = open_segment y x := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ @[simp] lemma open_segment_same (x : E) : open_segment x x = {x} := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [← add_smul, mem_singleton_iff, hab, one_smul, eq_comm] using hz, λ h, mem_singleton_iff.1 h ▸ ⟨1/2, 1/2, one_half_pos, one_half_pos, add_halves 1, by rw [←add_smul, add_halves, one_smul]⟩⟩ @[simp] lemma left_mem_open_segment_iff {x y : E} : x ∈ open_segment x y ↔ x = y := begin split, { rintro ⟨a, b, ha, hb, hab, hx⟩, refine smul_right_injective _ hb.ne' ((add_right_inj (a • x)).1 _), rw [hx, ←add_smul, hab, one_smul] }, rintro rfl, simp only [open_segment_same, mem_singleton], end @[simp] lemma right_mem_open_segment_iff {x y : E} : y ∈ open_segment x y ↔ x = y := by rw [open_segment_symm, left_mem_open_segment_iff, eq_comm] lemma open_segment_eq_image (x y : E) : open_segment x y = (λ (θ : ℝ), (1 - θ) • x + θ • y) '' (Ioo 0 1 : set ℝ) := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab ▸ lt_add_of_pos_left _ ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩, λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1 - θ, θ, sub_pos.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩ lemma open_segment_eq_image' (x y : E) : open_segment x y = (λ (θ : ℝ), x + θ • (y - x)) '' (Ioo 0 1 : set ℝ) := by { convert open_segment_eq_image x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel } lemma open_segment_eq_image₂ (x y : E) : open_segment x y = (λ p:ℝ×ℝ, p.1 • x + p.2 • y) '' {p | 0 < p.1 ∧ 0 < p.2 ∧ p.1 + p.2 = 1} := by simp only [open_segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] @[simp] lemma open_segment_eq_Ioo {a b : ℝ} (h : a < b) : open_segment a b = Ioo a b := begin rw open_segment_eq_image', show (((+) a) ∘ (λ t, t * (b - a))) '' Ioo 0 1 = Ioo a b, rw [image_comp, image_mul_right_Ioo _ _ (sub_pos.2 h), image_const_add_Ioo], simp end lemma open_segment_eq_Ioo' {a b : ℝ} (hab : a ≠ b) : open_segment a b = Ioo (min a b) (max a b) := begin cases le_total a b, { rw open_segment_eq_Ioo (h.lt_of_ne hab), simp * }, rw [open_segment_symm, open_segment_eq_Ioo (h.lt_of_ne hab.symm)], simp *, end @[simp] lemma mem_open_segment_translate (a : E) {x b c : E} : a + x ∈ open_segment (a + b) (a + c) ↔ x ∈ open_segment b c := begin rw [open_segment_eq_image', open_segment_eq_image'], refine exists_congr (λ θ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj], end @[simp] lemma open_segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' open_segment (a + b) (a + c) = open_segment b c := set.ext $ λ x, mem_open_segment_translate a lemma open_segment_translate_image (a b c : E) : (λ x, a + x) '' open_segment b c = open_segment (a + b) (a + c) := open_segment_translate_preimage a b c ▸ image_preimage_eq _ $ add_left_surjective a @[simp] lemma open_segment_image (f : E →ₗ[ℝ] F) (a b : E) : f '' open_segment a b = open_segment (f a) (f b) := set.ext (λ x, by simp [open_segment_eq_image]) /-! ### Convexity of sets -/ /-- Convexity of sets. -/ def convex (s : set E) := ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • x + b • y ∈ s lemma convex_iff_forall_pos : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ s := begin refine ⟨λ h x y hx hy a b ha hb hab, h hx hy (le_of_lt ha) (le_of_lt hb) hab, _⟩, intros h x y hx hy a b ha hb hab, cases eq_or_lt_of_le ha with ha ha, { subst a, rw [zero_add] at hab, simp [hab, hy] }, cases eq_or_lt_of_le hb with hb hb, { subst b, rw [add_zero] at hab, simp [hab, hx] }, exact h hx hy ha hb hab end lemma convex_iff_segment_subset : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → [x, y] ⊆ s := by simp only [convex, segment_eq_image₂, subset_def, ball_image_iff, prod.forall, mem_set_of_eq, and_imp] lemma convex_iff_open_segment_subset : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → open_segment x y ⊆ s := by simp only [convex_iff_forall_pos, open_segment_eq_image₂, subset_def, ball_image_iff, prod.forall, mem_set_of_eq, and_imp] lemma convex.segment_subset (h : convex s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) : [x, y] ⊆ s := convex_iff_segment_subset.1 h hx hy lemma convex.open_segment_subset (h : convex s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) : open_segment x y ⊆ s := convex_iff_open_segment_subset.1 h hx hy lemma convex.add_smul_sub_mem (h : convex s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) {t : ℝ} (ht : t ∈ Icc (0 : ℝ) 1) : x + t • (y - x) ∈ s := begin apply h.segment_subset hx hy, rw segment_eq_image', apply mem_image_of_mem, exact ht end lemma convex.add_smul_mem (h : convex s) {x y : E} (hx : x ∈ s) (hy : x + y ∈ s) {t : ℝ} (ht : t ∈ Icc (0 : ℝ) 1) : x + t • y ∈ s := by { convert h.add_smul_sub_mem hx hy ht, abel } lemma convex.smul_mem_of_zero_mem (h : convex s) {x : E} (zero_mem : (0:E) ∈ s) (hx : x ∈ s) {t : ℝ} (ht : t ∈ Icc (0 : ℝ) 1) : t • x ∈ s := by simpa using h.add_smul_mem zero_mem (by simpa using hx) ht lemma convex.mem_smul_of_zero_mem (h : convex s) {x : E} (zero_mem : (0:E) ∈ s) (hx : x ∈ s) {t : ℝ} (ht : 1 ≤ t) : x ∈ t • s := begin rw mem_smul_set_iff_inv_smul_mem (zero_lt_one.trans_le ht).ne', exact h.smul_mem_of_zero_mem zero_mem hx ⟨inv_nonneg.2 (zero_le_one.trans ht), inv_le_one ht⟩, end /-- Alternative definition of set convexity, in terms of pointwise set operations. -/ lemma convex_iff_pointwise_add_subset: convex s ↔ ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • s + b • s ⊆ s := iff.intro begin rintros hA a b ha hb hab w ⟨au, bv, ⟨u, hu, rfl⟩, ⟨v, hv, rfl⟩, rfl⟩, exact hA hu hv ha hb hab end (λ h x y hx hy a b ha hb hab, (h ha hb hab) (set.add_mem_add ⟨_, hx, rfl⟩ ⟨_, hy, rfl⟩)) /-- Alternative definition of set convexity, using division. -/ lemma convex_iff_div: convex s ↔ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • x + (b/(a+b)) • y ∈ s := ⟨begin assume h x y hx hy a b ha hb hab, apply h hx hy, have ha', from mul_le_mul_of_nonneg_left ha (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at ha', have hb', from mul_le_mul_of_nonneg_left hb (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at hb', rw [←add_div], exact div_self (ne_of_lt hab).symm end, begin assume h x y hx hy a b ha hb hab, have h', from h hx hy ha hb, rw [hab, div_one, div_one] at h', exact h' zero_lt_one end⟩ /-! ### Examples of convex sets -/ lemma convex_empty : convex (∅ : set E) := by finish lemma convex_singleton (c : E) : convex ({c} : set E) := begin intros x y hx hy a b ha hb hab, rw [set.eq_of_mem_singleton hx, set.eq_of_mem_singleton hy, ←add_smul, hab, one_smul], exact mem_singleton c end lemma convex_univ : convex (set.univ : set E) := λ _ _ _ _ _ _ _ _ _, trivial lemma convex.inter {t : set E} (hs: convex s) (ht: convex t) : convex (s ∩ t) := λ x y (hx : x ∈ s ∩ t) (hy : y ∈ s ∩ t) a b (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), ⟨hs hx.left hy.left ha hb hab, ht hx.right hy.right ha hb hab⟩ lemma convex_sInter {S : set (set E)} (h : ∀ s ∈ S, convex s) : convex (⋂₀ S) := assume x y hx hy a b ha hb hab s hs, h s hs (hx s hs) (hy s hs) ha hb hab lemma convex_Inter {ι : Sort*} {s : ι → set E} (h : ∀ i : ι, convex (s i)) : convex (⋂ i, s i) := (sInter_range s) ▸ convex_sInter $ forall_range_iff.2 h lemma convex.prod {s : set E} {t : set F} (hs : convex s) (ht : convex t) : convex (s.prod t) := begin intros x y hx hy a b ha hb hab, apply mem_prod.2, exact ⟨hs (mem_prod.1 hx).1 (mem_prod.1 hy).1 ha hb hab, ht (mem_prod.1 hx).2 (mem_prod.1 hy).2 ha hb hab⟩ end lemma directed.convex_Union {ι : Sort*} {s : ι → set E} (hdir : directed has_subset.subset s) (hc : ∀ ⦃i : ι⦄, convex (s i)) : convex (⋃ i, s i) := begin rintro x y hx hy a b ha hb hab, rw mem_Union at ⊢ hx hy, obtain ⟨i, hx⟩ := hx, obtain ⟨j, hy⟩ := hy, obtain ⟨k, hik, hjk⟩ := hdir i j, exact ⟨k, hc (hik hx) (hjk hy) ha hb hab⟩, end lemma directed_on.convex_sUnion {c : set (set E)} (hdir : directed_on has_subset.subset c) (hc : ∀ ⦃A : set E⦄, A ∈ c → convex A) : convex (⋃₀c) := begin rw sUnion_eq_Union, exact (directed_on_iff_directed.1 hdir).convex_Union (λ A, hc A.2), end lemma convex.combo_to_vadd {a b : ℝ} {x y : E} (h : a + b = 1) : a • x + b • y = b • (y - x) + x := calc a • x + b • y = (b • y - b • x) + (a • x + b • x) : by abel ... = b • (y - x) + (a + b) • x : by rw [smul_sub, add_smul] ... = b • (y - x) + (1 : ℝ) • x : by rw [h] ... = b • (y - x) + x : by rw [one_smul] /-- Applying an affine map to an affine combination of two points yields an affine combination of the images. -/ lemma convex.combo_affine_apply {a b : ℝ} {x y : E} {f : E →ᵃ[ℝ] F} (h : a + b = 1) : f (a • x + b • y) = a • f x + b • f y := begin simp only [convex.combo_to_vadd h, ← vsub_eq_sub], exact f.apply_line_map _ _ _, end /-- The preimage of a convex set under an affine map is convex. -/ lemma convex.affine_preimage (f : E →ᵃ[ℝ] F) {s : set F} (hs : convex s) : convex (f ⁻¹' s) := begin intros x y xs ys a b ha hb hab, rw [mem_preimage, convex.combo_affine_apply hab], exact hs xs ys ha hb hab, end /-- The image of a convex set under an affine map is convex. -/ lemma convex.affine_image (f : E →ᵃ[ℝ] F) {s : set E} (hs : convex s) : convex (f '' s) := begin rintros x y ⟨x', ⟨hx', hx'f⟩⟩ ⟨y', ⟨hy', hy'f⟩⟩ a b ha hb hab, refine ⟨a • x' + b • y', ⟨hs hx' hy' ha hb hab, _⟩⟩, rw [convex.combo_affine_apply hab, hx'f, hy'f] end lemma convex.linear_image (hs : convex s) (f : E →ₗ[ℝ] F) : convex (image f s) := hs.affine_image f.to_affine_map lemma convex.is_linear_image (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (f '' s) := hs.linear_image $ hf.mk' f lemma convex.linear_preimage {s : set F} (hs : convex s) (f : E →ₗ[ℝ] F) : convex (preimage f s) := hs.affine_preimage f.to_affine_map lemma convex.is_linear_preimage {s : set F} (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (preimage f s) := hs.linear_preimage $ hf.mk' f lemma convex.neg (hs : convex s) : convex ((λ z, -z) '' s) := hs.is_linear_image is_linear_map.is_linear_map_neg lemma convex.neg_preimage (hs : convex s) : convex ((λ z, -z) ⁻¹' s) := hs.is_linear_preimage is_linear_map.is_linear_map_neg lemma convex.smul (c : ℝ) (hs : convex s) : convex (c • s) := hs.linear_image (linear_map.lsmul _ _ c) lemma convex.smul_preimage (c : ℝ) (hs : convex s) : convex ((λ z, c • z) ⁻¹' s) := hs.linear_preimage (linear_map.lsmul _ _ c) lemma convex.add {t : set E} (hs : convex s) (ht : convex t) : convex (s + t) := by { rw ← add_image_prod, exact (hs.prod ht).is_linear_image is_linear_map.is_linear_map_add } lemma convex.sub {t : set E} (hs : convex s) (ht : convex t) : convex ((λx : E × E, x.1 - x.2) '' (s.prod t)) := (hs.prod ht).is_linear_image is_linear_map.is_linear_map_sub lemma convex.add_smul (h_conv : convex s) {p q : ℝ} (hple : 0 ≤ p) (hqle : 0 ≤ q) : (p + q) • s = p • s + q • s := begin rcases hple.lt_or_eq with hp | rfl, rcases hqle.lt_or_eq with hq | rfl, { have hpq : 0 < p + q, from add_pos hp hq, ext, split; intro h, { rcases h with ⟨v, hv, rfl⟩, use [p • v, q • v], refine ⟨smul_mem_smul_set hv, smul_mem_smul_set hv, _⟩, rw add_smul, }, { rcases h with ⟨v₁, v₂, ⟨v₁₁, h₁₂, rfl⟩, ⟨v₂₁, h₂₂, rfl⟩, rfl⟩, have := h_conv h₁₂ h₂₂ (le_of_lt $ div_pos hp hpq) (le_of_lt $ div_pos hq hpq) (by {field_simp, rw [div_self (ne_of_gt hpq)]} : p / (p + q) + q / (p + q) = 1), rw mem_smul_set, refine ⟨_, this, _⟩, simp only [← mul_smul, smul_add, mul_div_cancel' _ hpq.ne'], }, }, all_goals { rcases s.eq_empty_or_nonempty with rfl | hne, { simp, }, rw zero_smul_set hne, simp, }, end lemma convex.translate (hs : convex s) (z : E) : convex ((λx, z + x) '' s) := hs.affine_image $ affine_map.const ℝ E z +ᵥ affine_map.id ℝ E /-- The translation of a convex set is also convex. -/ lemma convex.translate_preimage_right (hs : convex s) (a : E) : convex ((λ z, a + z) ⁻¹' s) := hs.affine_preimage $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- The translation of a convex set is also convex. -/ lemma convex.translate_preimage_left (hs : convex s) (a : E) : convex ((λ z, z + a) ⁻¹' s) := by simpa only [add_comm] using hs.translate_preimage_right a lemma convex.affinity (hs : convex s) (z : E) (c : ℝ) : convex ((λx, z + c • x) '' s) := hs.affine_image $ affine_map.const ℝ E z +ᵥ c • affine_map.id ℝ E lemma real.convex_iff_ord_connected {s : set ℝ} : convex s ↔ ord_connected s := begin simp only [convex_iff_segment_subset, segment_eq_interval, ord_connected_iff_interval_subset], exact forall_congr (λ x, forall_swap) end alias real.convex_iff_ord_connected ↔ convex.ord_connected set.ord_connected.convex lemma convex_Iio (r : ℝ) : convex (Iio r) := ord_connected_Iio.convex lemma convex_Ioi (r : ℝ) : convex (Ioi r) := ord_connected_Ioi.convex lemma convex_Iic (r : ℝ) : convex (Iic r) := ord_connected_Iic.convex lemma convex_Ici (r : ℝ) : convex (Ici r) := ord_connected_Ici.convex lemma convex_Ioo (r s : ℝ) : convex (Ioo r s) := ord_connected_Ioo.convex lemma convex_Ico (r s : ℝ) : convex (Ico r s) := ord_connected_Ico.convex lemma convex_Ioc (r : ℝ) (s : ℝ) : convex (Ioc r s) := ord_connected_Ioc.convex lemma convex_Icc (r : ℝ) (s : ℝ) : convex (Icc r s) := ord_connected_Icc.convex lemma convex_interval (r : ℝ) (s : ℝ) : convex (interval r s) := ord_connected_interval.convex lemma convex_segment (a b : E) : convex [a, b] := begin have : (λ (t : ℝ), a + t • (b - a)) = (λ z : E, a + z) ∘ (λ t : ℝ, t • (b - a)) := rfl, rw [segment_eq_image', this, image_comp], refine ((convex_Icc _ _).is_linear_image _).translate _, exact is_linear_map.is_linear_map_smul' _ end lemma convex_open_segment (a b : E) : convex (open_segment a b) := begin have : (λ (t : ℝ), a + t • (b - a)) = (λ z : E, a + z) ∘ (λ t : ℝ, t • (b - a)) := rfl, rw [open_segment_eq_image', this, image_comp], refine ((convex_Ioo _ _).is_linear_image _).translate _, exact is_linear_map.is_linear_map_smul' _, end lemma convex_halfspace_lt {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w < r} := (convex_Iio r).is_linear_preimage h lemma convex_halfspace_le {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w ≤ r} := (convex_Iic r).is_linear_preimage h lemma convex_halfspace_gt {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r < f w} := (convex_Ioi r).is_linear_preimage h lemma convex_halfspace_ge {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r ≤ f w} := (convex_Ici r).is_linear_preimage h lemma convex_hyperplane {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w = r} := begin show convex (f ⁻¹' {p | p = r}), rw set_of_eq_eq_singleton, exact (convex_singleton r).is_linear_preimage h end lemma convex_halfspace_re_lt (r : ℝ) : convex {c : ℂ | c.re < r} := convex_halfspace_lt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_le (r : ℝ) : convex {c : ℂ | c.re ≤ r} := convex_halfspace_le (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_gt (r : ℝ) : convex {c : ℂ | r < c.re } := convex_halfspace_gt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_lge (r : ℝ) : convex {c : ℂ | r ≤ c.re} := convex_halfspace_ge (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_im_lt (r : ℝ) : convex {c : ℂ | c.im < r} := convex_halfspace_lt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_le (r : ℝ) : convex {c : ℂ | c.im ≤ r} := convex_halfspace_le (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_gt (r : ℝ) : convex {c : ℂ | r < c.im } := convex_halfspace_gt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_lge (r : ℝ) : convex {c : ℂ | r ≤ c.im} := convex_halfspace_ge (is_linear_map.mk complex.add_im complex.smul_im) _ /-! ### Convex combinations in intervals -/ lemma convex.combo_self (a : α) {x y : α} (h : x + y = 1) : a = x * a + y * a := calc a = 1 * a : by rw [one_mul] ... = (x + y) * a : by rw [h] ... = x * a + y * a : by rw [add_mul] /-- If `x` is in an `Ioo`, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ioo {a b x : α} (h : a < b) : x ∈ Ioo a b ↔ ∃ (x_a x_b : α), 0 < x_a ∧ 0 < x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases hab : ¬a < b, { exfalso; exact hab h }, { refine ⟨(b-x) / (b-a), (x-a) / (b-a), _⟩, refine ⟨div_pos (by linarith) (by linarith), div_pos (by linarith) (by linarith),_,_⟩; { field_simp [show b - a ≠ 0, by linarith], ring } } }, { rw [mem_Ioo], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If `x` is in an `Ioc`, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ioc {a b x : α} (h : a < b) : x ∈ Ioc a b ↔ ∃ (x_a x_b : α), 0 ≤ x_a ∧ 0 < x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases h_x : x = b, { exact ⟨0, 1, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioo h).mp ⟨h_ax, lt_of_le_of_ne h_bx h_x⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, by linarith, Ioo_case.2⟩ } }, { rw [mem_Ioc], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If `x` is in an `Ico`, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ico {a b x : α} (h : a < b) : x ∈ Ico a b ↔ ∃ (x_a x_b : α), 0 < x_a ∧ 0 ≤ x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases h_x : x = a, { exact ⟨1, 0, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioo h).mp ⟨lt_of_le_of_ne h_ax (ne.symm h_x), h_bx⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, Ioo_case.1, by linarith, (Ioo_case.2).2⟩ } }, { rw [mem_Ico], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If `x` is in an `Icc`, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Icc {a b x : α} (h : a ≤ b) : x ∈ Icc a b ↔ ∃ (x_a x_b : α), 0 ≤ x_a ∧ 0 ≤ x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { intro x_in_I, rw [Icc, mem_set_of_eq] at x_in_I, rcases x_in_I with ⟨h_ax, h_bx⟩, by_cases hab' : a = b, { exact ⟨0, 1, le_refl 0, by linarith, by ring, by linarith⟩ }, change a ≠ b at hab', replace h : a < b, exact lt_of_le_of_ne h hab', by_cases h_x : x = a, { exact ⟨1, 0, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioc h).mp ⟨lt_of_le_of_ne h_ax (ne.symm h_x), h_bx⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, Ioo_case.1, by linarith, (Ioo_case.2).2⟩ } }, { rw [mem_Icc], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end section submodule open submodule lemma submodule.convex (K : submodule ℝ E) : convex (↑K : set E) := by { repeat {intro}, refine add_mem _ (smul_mem _ _ _) (smul_mem _ _ _); assumption } lemma subspace.convex (K : subspace ℝ E) : convex (↑K : set E) := K.convex end submodule end sets /-! ### Convex and concave functions -/ section functions variables {β : Type*} [ordered_add_comm_monoid β] [module ℝ β] local notation `[`x `, ` y `]` := segment x y /-- Convexity of functions -/ def convex_on (s : set E) (f : E → β) : Prop := convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y /-- Concavity of functions -/ def concave_on (s : set E) (f : E → β) : Prop := convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y) section variables [ordered_smul ℝ β] /-- A function `f` is concave iff `-f` is convex. -/ @[simp] lemma neg_convex_on_iff {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] (s : set E) (f : E → γ) : convex_on s (-f) ↔ concave_on s f := begin split, { rintros ⟨hconv, h⟩, refine ⟨hconv, _⟩, intros x y xs ys a b ha hb hab, specialize h xs ys ha hb hab, simp [neg_apply, neg_le, add_comm] at h, exact h }, { rintros ⟨hconv, h⟩, refine ⟨hconv, _⟩, intros x y xs ys a b ha hb hab, specialize h xs ys ha hb hab, simp [neg_apply, neg_le, add_comm, h] } end /-- A function `f` is concave iff `-f` is convex. -/ @[simp] lemma neg_concave_on_iff {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] (s : set E) (f : E → γ) : concave_on s (-f) ↔ convex_on s f:= by rw [← neg_convex_on_iff s (-f), neg_neg f] end lemma convex_on_id {s : set ℝ} (hs : convex s) : convex_on s id := ⟨hs, by { intros, refl }⟩ lemma concave_on_id {s : set ℝ} (hs : convex s) : concave_on s id := ⟨hs, by { intros, refl }⟩ lemma convex_on_const (c : β) (hs : convex s) : convex_on s (λ x:E, c) := ⟨hs, by { intros, simp only [← add_smul, *, one_smul] }⟩ lemma concave_on_const (c : β) (hs : convex s) : concave_on s (λ x:E, c) := @convex_on_const _ _ _ _ (order_dual β) _ _ c hs variables {t : set E} lemma convex_on_iff_div {f : E → β} : convex_on s f ↔ convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → f ((a/(a+b)) • x + (b/(a+b)) • y) ≤ (a/(a+b)) • f x + (b/(a+b)) • f y := and_congr iff.rfl ⟨begin intros h x y hx hy a b ha hb hab, apply h hx hy (div_nonneg ha $ le_of_lt hab) (div_nonneg hb $ le_of_lt hab), rw [←add_div], exact div_self (ne_of_gt hab) end, begin intros h x y hx hy a b ha hb hab, simpa [hab, zero_lt_one] using h hx hy ha hb, end⟩ lemma concave_on_iff_div {f : E → β} : concave_on s f ↔ convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • f x + (b/(a+b)) • f y ≤ f ((a/(a+b)) • x + (b/(a+b)) • y) := @convex_on_iff_div _ _ _ _ (order_dual β) _ _ _ /-- For a function on a convex set in a linear ordered space, in order to prove that it is convex it suffices to verify the inequality `f (a • x + b • y) ≤ a • f x + b • f y` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.convex_on_of_lt {f : E → β} [linear_order E] (hs : convex s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y) : convex_on s f := begin use hs, intros x y hx hy a b ha hb hab, wlog hxy : x<=y using [x y a b, y x b a], { exact le_total _ _ }, { cases eq_or_lt_of_le hxy with hxy hxy, by { subst y, rw [← add_smul, ← add_smul, hab, one_smul, one_smul] }, cases eq_or_lt_of_le ha with ha ha, by { subst a, rw [zero_add] at hab, subst b, simp }, cases eq_or_lt_of_le hb with hb hb, by { subst b, rw [add_zero] at hab, subst a, simp }, exact hf hx hy hxy ha hb hab } end /-- For a function on a convex set in a linear ordered space, in order to prove that it is concave it suffices to verify the inequality `a • f x + b • f y ≤ f (a • x + b • y)` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.concave_on_of_lt {f : E → β} [linear_order E] (hs : convex s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y)) : concave_on s f := @linear_order.convex_on_of_lt _ _ _ _ (order_dual β) _ _ f _ hs hf /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is convex on `D`. This way of proving convexity of a function is used in the proof of convexity of a function with a monotone derivative. -/ lemma convex_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} (hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f y - f x) / (y - x) ≤ (f z - f y) / (z - y)) : convex_on s f := linear_order.convex_on_of_lt hs begin assume x z hx hz hxz a b ha hb hab, let y := a * x + b * z, have hxy : x < y, { rw [← one_mul x, ← hab, add_mul], exact add_lt_add_left ((mul_lt_mul_left hb).2 hxz) _ }, have hyz : y < z, { rw [← one_mul z, ← hab, add_mul], exact add_lt_add_right ((mul_lt_mul_left ha).2 hxz) _ }, have : (f y - f x) * (z - y) ≤ (f z - f y) * (y - x), from (div_le_div_iff (sub_pos.2 hxy) (sub_pos.2 hyz)).1 (hf hx hz hxy hyz), have A : z - y + (y - x) = z - x, by abel, have B : 0 < z - x, from sub_pos.2 (lt_trans hxy hyz), rw [sub_mul, sub_mul, sub_le_iff_le_add', ← add_sub_assoc, le_sub_iff_add_le, ← mul_add, A, ← le_div_iff B, add_div, mul_div_assoc, mul_div_assoc, mul_comm (f x), mul_comm (f z)] at this, rw [eq_comm, ← sub_eq_iff_eq_add] at hab; subst a, convert this; symmetry; simp only [div_eq_iff (ne_of_gt B), y]; ring end /-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is convex on `D`, then for any three points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma convex_on.slope_mono_adjacent {s : set ℝ} {f : ℝ → ℝ} (hf : convex_on s f) {x y z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) : (f y - f x) / (y - x) ≤ (f z - f y) / (z - y) := begin have h₁ : 0 < y - x := by linarith, have h₂ : 0 < z - y := by linarith, have h₃ : 0 < z - x := by linarith, suffices : f y / (y - x) + f y / (z - y) ≤ f x / (y - x) + f z / (z - y), by { ring_nf at this ⊢, linarith }, set a := (z - y) / (z - x), set b := (y - x) / (z - x), have heqz : a • x + b • z = y, by { field_simp, rw div_eq_iff; [ring, linarith], }, have key, from hf.2 hx hz (show 0 ≤ a, by apply div_nonneg; linarith) (show 0 ≤ b, by apply div_nonneg; linarith) (show a + b = 1, by { field_simp, rw div_eq_iff; [ring, linarith], }), rw heqz at key, replace key := mul_le_mul_of_nonneg_left key (le_of_lt h₃), field_simp [ne_of_gt h₁, ne_of_gt h₂, ne_of_gt h₃, mul_comm (z - x) _] at key ⊢, rw div_le_div_right, { linarith, }, { nlinarith, }, end /-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is convex on `D` iff for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma convex_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} : convex_on s f ↔ (∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f y - f x) / (y - x) ≤ (f z - f y) / (z - y)) := ⟨convex_on.slope_mono_adjacent, convex_on_real_of_slope_mono_adjacent hs⟩ /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is concave on `D`. -/ lemma concave_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} (hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f z - f y) / (z - y) ≤ (f y - f x) / (y - x)) : concave_on s f := begin rw [←neg_convex_on_iff], apply convex_on_real_of_slope_mono_adjacent hs, intros x y z xs zs xy yz, rw [←neg_le_neg_iff, ←neg_div, ←neg_div, neg_sub, neg_sub], simp only [hf xs zs xy yz, neg_sub_neg, pi.neg_apply], end /-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is concave on `D`, then for any three points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma concave_on.slope_mono_adjacent {s : set ℝ} {f : ℝ → ℝ} (hf : concave_on s f) {x y z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) : (f z - f y) / (z - y) ≤ (f y - f x) / (y - x) := begin rw [←neg_le_neg_iff, ←neg_div, ←neg_div, neg_sub, neg_sub], rw [←neg_sub_neg (f y), ←neg_sub_neg (f z)], simp_rw [←pi.neg_apply], rw [←neg_convex_on_iff] at hf, apply convex_on.slope_mono_adjacent hf; assumption, end /-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is concave on `D` iff for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma concave_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} : concave_on s f ↔ (∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f z - f y) / (z - y) ≤ (f y - f x) / (y - x)) := ⟨concave_on.slope_mono_adjacent, concave_on_real_of_slope_mono_adjacent hs⟩ lemma convex_on.subset {f : E → β} (h_convex_on : convex_on t f) (h_subset : s ⊆ t) (h_convex : convex s) : convex_on s f := begin apply and.intro h_convex, intros x y hx hy, exact h_convex_on.2 (h_subset hx) (h_subset hy), end lemma concave_on.subset {f : E → β} (h_concave_on : concave_on t f) (h_subset : s ⊆ t) (h_convex : convex s) : concave_on s f := @convex_on.subset _ _ _ _ (order_dual β) _ _ t f h_concave_on h_subset h_convex lemma convex_on.add {f g : E → β} (hf : convex_on s f) (hg : convex_on s g) : convex_on s (λx, f x + g x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc f (a • x + b • y) + g (a • x + b • y) ≤ (a • f x + b • f y) + (a • g x + b • g y) : add_le_add (hf.2 hx hy ha hb hab) (hg.2 hx hy ha hb hab) ... = a • f x + a • g x + b • f y + b • g y : by abel ... = a • (f x + g x) + b • (f y + g y) : by simp [smul_add, add_assoc] end lemma concave_on.add {f g : E → β} (hf : concave_on s f) (hg : concave_on s g) : concave_on s (λx, f x + g x) := @convex_on.add _ _ _ _ (order_dual β) _ _ f g hf hg lemma convex_on.smul [ordered_smul ℝ β] {f : E → β} {c : ℝ} (hc : 0 ≤ c) (hf : convex_on s f) : convex_on s (λx, c • f x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc c • f (a • x + b • y) ≤ c • (a • f x + b • f y) : smul_le_smul_of_nonneg (hf.2 hx hy ha hb hab) hc ... = a • (c • f x) + b • (c • f y) : by simp only [smul_add, smul_comm c] end lemma concave_on.smul [ordered_smul ℝ β] {f : E → β} {c : ℝ} (hc : 0 ≤ c) (hf : concave_on s f) : concave_on s (λx, c • f x) := @convex_on.smul _ _ _ _ (order_dual β) _ _ _ f c hc hf section linear_order section monoid variables {γ : Type*} [linear_ordered_add_comm_monoid γ] [module ℝ γ] [ordered_smul ℝ γ] {f g : E → γ} /-- The pointwise maximum of convex functions is convex. -/ lemma convex_on.sup (hf : convex_on s f) (hg : convex_on s g) : convex_on s (f ⊔ g) := begin refine ⟨hf.left, λ x y hx hy a b ha hb hab, sup_le _ _⟩, { calc f (a • x + b • y) ≤ a • f x + b • f y : hf.right hx hy ha hb hab ... ≤ a • (f x ⊔ g x) + b • (f y ⊔ g y) : add_le_add (smul_le_smul_of_nonneg le_sup_left ha) (smul_le_smul_of_nonneg le_sup_left hb) }, { calc g (a • x + b • y) ≤ a • g x + b • g y : hg.right hx hy ha hb hab ... ≤ a • (f x ⊔ g x) + b • (f y ⊔ g y) : add_le_add (smul_le_smul_of_nonneg le_sup_right ha) (smul_le_smul_of_nonneg le_sup_right hb) } end /-- The pointwise minimum of concave functions is concave. -/ lemma concave_on.inf (hf : concave_on s f) (hg : concave_on s g) : concave_on s (f ⊓ g) := @convex_on.sup _ _ _ _ (order_dual γ) _ _ _ _ _ hf hg /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ lemma convex_on.le_on_segment' (hf : convex_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : f (a • x + b • y) ≤ max (f x) (f y) := calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab ... ≤ a • max (f x) (f y) + b • max (f x) (f y) : add_le_add (smul_le_smul_of_nonneg (le_max_left _ _) ha) (smul_le_smul_of_nonneg (le_max_right _ _) hb) ... = max (f x) (f y) : by rw [←add_smul, hab, one_smul] /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ lemma concave_on.le_on_segment' (hf : concave_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : min (f x) (f y) ≤ f (a • x + b • y) := @convex_on.le_on_segment' _ _ _ _ (order_dual γ) _ _ _ f hf x y a b hx hy ha hb hab /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ lemma convex_on.le_on_segment (hf : convex_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x, y]) : f z ≤ max (f x) (f y) := let ⟨a, b, ha, hb, hab, hz⟩ := hz in hz ▸ hf.le_on_segment' hx hy ha hb hab /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ lemma concave_on.le_on_segment {f : E → γ} (hf : concave_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x, y]) : min (f x) (f y) ≤ f z := @convex_on.le_on_segment _ _ _ _ (order_dual γ) _ _ _ f hf x y z hx hy hz end monoid variables {γ : Type*} [linear_ordered_cancel_add_comm_monoid γ] [module ℝ γ] [ordered_smul ℝ γ] {f : E → γ} -- could be shown without contradiction but yeah lemma convex_on.le_left_of_right_le' (hf : convex_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) (hxy : f y ≤ f (a • x + b • y)) : f (a • x + b • y) ≤ f x := begin apply le_of_not_lt (λ h, lt_irrefl (f (a • x + b • y)) _), calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha.le hb hab ... < a • f (a • x + b • y) + b • f (a • x + b • y) : add_lt_add_of_lt_of_le (smul_lt_smul_of_pos h ha) (smul_le_smul_of_nonneg hxy hb) ... = f (a • x + b • y) : by rw [←add_smul, hab, one_smul], end lemma concave_on.left_le_of_le_right' (hf : concave_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) (hxy : f (a • x + b • y) ≤ f y) : f x ≤ f (a • x + b • y) := @convex_on.le_left_of_right_le' _ _ _ _ (order_dual γ) _ _ _ f hf x y a b hx hy ha hb hab hxy lemma convex_on.le_right_of_left_le' (hf : convex_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) (hxy : f x ≤ f (a • x + b • y)) : f (a • x + b • y) ≤ f y := begin rw add_comm at ⊢ hab hxy, exact hf.le_left_of_right_le' hy hx hb ha hab hxy, end lemma concave_on.le_right_of_left_le' (hf : concave_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) (hxy : f (a • x + b • y) ≤ f x) : f y ≤ f (a • x + b • y) := @convex_on.le_right_of_left_le' _ _ _ _ (order_dual γ) _ _ _ f hf x y a b hx hy ha hb hab hxy lemma convex_on.le_left_of_right_le (hf : convex_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment x y) (hyz : f y ≤ f z) : f z ≤ f x := begin obtain ⟨a, b, ha, hb, hab, rfl⟩ := hz, exact hf.le_left_of_right_le' hx hy ha hb.le hab hyz, end lemma concave_on.left_le_of_le_right (hf : concave_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment x y) (hyz : f z ≤ f y) : f x ≤ f z := @convex_on.le_left_of_right_le _ _ _ _ (order_dual γ) _ _ _ f hf x y z hx hy hz hyz lemma convex_on.le_right_of_left_le (hf : convex_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment x y) (hxz : f x ≤ f z) : f z ≤ f y := begin obtain ⟨a, b, ha, hb, hab, rfl⟩ := hz, exact hf.le_right_of_left_le' hx hy ha.le hb hab hxz, end lemma concave_on.le_right_of_left_le (hf : concave_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment x y) (hxz : f z ≤ f x) : f y ≤ f z := @convex_on.le_right_of_left_le _ _ _ _ (order_dual γ) _ _ _ f hf x y z hx hy hz hxz end linear_order lemma convex_on.convex_le [ordered_smul ℝ β] {f : E → β} (hf : convex_on s f) (r : β) : convex {x ∈ s | f x ≤ r} := λ x y hx hy a b ha hb hab, begin refine ⟨hf.1 hx.1 hy.1 ha hb hab, _⟩, calc f (a • x + b • y) ≤ a • (f x) + b • (f y) : hf.2 hx.1 hy.1 ha hb hab ... ≤ a • r + b • r : add_le_add (smul_le_smul_of_nonneg hx.2 ha) (smul_le_smul_of_nonneg hy.2 hb) ... ≤ r : by simp [←add_smul, hab] end lemma concave_on.concave_le [ordered_smul ℝ β] {f : E → β} (hf : concave_on s f) (r : β) : convex {x ∈ s | r ≤ f x} := @convex_on.convex_le _ _ _ _ (order_dual β) _ _ _ f hf r lemma convex_on.convex_lt {γ : Type*} [ordered_cancel_add_comm_monoid γ] [module ℝ γ] [ordered_smul ℝ γ] {f : E → γ} (hf : convex_on s f) (r : γ) : convex {x ∈ s | f x < r} := begin intros a b as bs xa xb hxa hxb hxaxb, refine ⟨hf.1 as.1 bs.1 hxa hxb hxaxb, _⟩, by_cases H : xa = 0, { have H' : xb = 1 := by rwa [H, zero_add] at hxaxb, rw [H, H', zero_smul, one_smul, zero_add], exact bs.2 }, { calc f (xa • a + xb • b) ≤ xa • (f a) + xb • (f b) : hf.2 as.1 bs.1 hxa hxb hxaxb ... < xa • r + xb • (f b) : (add_lt_add_iff_right (xb • (f b))).mpr (smul_lt_smul_of_pos as.2 (lt_of_le_of_ne hxa (ne.symm H))) ... ≤ xa • r + xb • r : (add_le_add_iff_left (xa • r)).mpr (smul_le_smul_of_nonneg bs.2.le hxb) ... = r : by simp only [←add_smul, hxaxb, one_smul] } end lemma concave_on.convex_lt {γ : Type*} [ordered_cancel_add_comm_monoid γ] [module ℝ γ] [ordered_smul ℝ γ] {f : E → γ} (hf : concave_on s f) (r : γ) : convex {x ∈ s | r < f x} := @convex_on.convex_lt _ _ _ _ (order_dual γ) _ _ _ f hf r lemma convex_on.convex_epigraph {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] [ordered_smul ℝ γ] {f : E → γ} (hf : convex_on s f) : convex {p : E × γ | p.1 ∈ s ∧ f p.1 ≤ p.2} := begin rintros ⟨x, r⟩ ⟨y, t⟩ ⟨hx, hr⟩ ⟨hy, ht⟩ a b ha hb hab, refine ⟨hf.1 hx hy ha hb hab, _⟩, calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab ... ≤ a • r + b • t : add_le_add (smul_le_smul_of_nonneg hr ha) (smul_le_smul_of_nonneg ht hb) end lemma concave_on.convex_hypograph {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] [ordered_smul ℝ γ] {f : E → γ} (hf : concave_on s f) : convex {p : E × γ | p.1 ∈ s ∧ p.2 ≤ f p.1} := @convex_on.convex_epigraph _ _ _ _ (order_dual γ) _ _ _ f hf lemma convex_on_iff_convex_epigraph {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] [ordered_smul ℝ γ] {f : E → γ} : convex_on s f ↔ convex {p : E × γ | p.1 ∈ s ∧ f p.1 ≤ p.2} := begin refine ⟨convex_on.convex_epigraph, λ h, ⟨_, _⟩⟩, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).1 }, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).2 } end lemma concave_on_iff_convex_hypograph {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] [ordered_smul ℝ γ] {f : E → γ} : concave_on s f ↔ convex {p : E × γ | p.1 ∈ s ∧ p.2 ≤ f p.1} := @convex_on_iff_convex_epigraph _ _ _ _ (order_dual γ) _ _ _ f /- A linear map is convex. -/ lemma linear_map.convex_on (f : E →ₗ[ℝ] β) {s : set E} (hs : convex s) : convex_on s f := ⟨hs, λ _ _ _ _ _ _ _ _ _, by rw [f.map_add, f.map_smul, f.map_smul]⟩ /- A linear map is concave. -/ lemma linear_map.concave_on (f : E →ₗ[ℝ] β) {s : set E} (hs : convex s) : concave_on s f := ⟨hs, λ _ _ _ _ _ _ _ _ _, by rw [f.map_add, f.map_smul, f.map_smul]⟩ /-- If a function is convex on `s`, it remains convex when precomposed by an affine map. -/ lemma convex_on.comp_affine_map {f : F → β} (g : E →ᵃ[ℝ] F) {s : set F} (hf : convex_on s f) : convex_on (g ⁻¹' s) (f ∘ g) := begin refine ⟨hf.1.affine_preimage _,_⟩, intros x y xs ys a b ha hb hab, calc (f ∘ g) (a • x + b • y) = f (g (a • x + b • y)) : rfl ... = f (a • (g x) + b • (g y)) : by rw [convex.combo_affine_apply hab] ... ≤ a • f (g x) + b • f (g y) : hf.2 xs ys ha hb hab ... = a • (f ∘ g) x + b • (f ∘ g) y : rfl end /-- If a function is concave on `s`, it remains concave when precomposed by an affine map. -/ lemma concave_on.comp_affine_map {f : F → β} (g : E →ᵃ[ℝ] F) {s : set F} (hf : concave_on s f) : concave_on (g ⁻¹' s) (f ∘ g) := @convex_on.comp_affine_map _ _ _ _ _ _ (order_dual β) _ _ f g s hf /-- If `g` is convex on `s`, so is `(g ∘ f)` on `f ⁻¹' s` for a linear `f`. -/ lemma convex_on.comp_linear_map {g : F → β} {s : set F} (hg : convex_on s g) (f : E →ₗ[ℝ] F) : convex_on (f ⁻¹' s) (g ∘ f) := hg.comp_affine_map f.to_affine_map /-- If `g` is concave on `s`, so is `(g ∘ f)` on `f ⁻¹' s` for a linear `f`. -/ lemma concave_on.comp_linear_map {g : F → β} {s : set F} (hg : concave_on s g) (f : E →ₗ[ℝ] F) : concave_on (f ⁻¹' s) (g ∘ f) := hg.comp_affine_map f.to_affine_map /-- If a function is convex on `s`, it remains convex after a translation. -/ lemma convex_on.translate_right {f : E → β} {s : set E} {a : E} (hf : convex_on s f) : convex_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, a + z)) := hf.comp_affine_map $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- If a function is concave on `s`, it remains concave after a translation. -/ lemma concave_on.translate_right {f : E → β} {s : set E} {a : E} (hf : concave_on s f) : concave_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, a + z)) := hf.comp_affine_map $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- If a function is convex on `s`, it remains convex after a translation. -/ lemma convex_on.translate_left {f : E → β} {s : set E} {a : E} (hf : convex_on s f) : convex_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, z + a)) := by simpa only [add_comm] using hf.translate_right /-- If a function is concave on `s`, it remains concave after a translation. -/ lemma concave_on.translate_left {f : E → β} {s : set E} {a : E} (hf : concave_on s f) : concave_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, z + a)) := by simpa only [add_comm] using hf.translate_right end functions /-! ### Center of mass -/ section center_mass /-- Center of mass of a finite collection of points with prescribed weights. Note that we require neither `0 ≤ w i` nor `∑ w = 1`. -/ noncomputable def finset.center_mass (t : finset ι) (w : ι → ℝ) (z : ι → E) : E := (∑ i in t, w i)⁻¹ • (∑ i in t, w i • z i) variables (i j : ι) (c : ℝ) (t : finset ι) (w : ι → ℝ) (z : ι → E) open finset lemma finset.center_mass_empty : (∅ : finset ι).center_mass w z = 0 := by simp only [center_mass, sum_empty, smul_zero] lemma finset.center_mass_pair (hne : i ≠ j) : ({i, j} : finset ι).center_mass w z = (w i / (w i + w j)) • z i + (w j / (w i + w j)) • z j := by simp only [center_mass, sum_pair hne, smul_add, (mul_smul _ _ _).symm, div_eq_inv_mul] variable {w} lemma finset.center_mass_insert (ha : i ∉ t) (hw : ∑ j in t, w j ≠ 0) : (insert i t).center_mass w z = (w i / (w i + ∑ j in t, w j)) • z i + ((∑ j in t, w j) / (w i + ∑ j in t, w j)) • t.center_mass w z := begin simp only [center_mass, sum_insert ha, smul_add, (mul_smul _ _ _).symm, ← div_eq_inv_mul], congr' 2, rw [div_mul_eq_mul_div, mul_inv_cancel hw, one_div] end lemma finset.center_mass_singleton (hw : w i ≠ 0) : ({i} : finset ι).center_mass w z = z i := by rw [center_mass, sum_singleton, sum_singleton, ← mul_smul, inv_mul_cancel hw, one_smul] lemma finset.center_mass_eq_of_sum_1 (hw : ∑ i in t, w i = 1) : t.center_mass w z = ∑ i in t, w i • z i := by simp only [finset.center_mass, hw, inv_one, one_smul] lemma finset.center_mass_smul : t.center_mass w (λ i, c • z i) = c • t.center_mass w z := by simp only [finset.center_mass, finset.smul_sum, (mul_smul _ _ _).symm, mul_comm c, mul_assoc] /-- A convex combination of two centers of mass is a center of mass as well. This version deals with two different index types. -/ lemma finset.center_mass_segment' (s : finset ι) (t : finset ι') (ws : ι → ℝ) (zs : ι → E) (wt : ι' → ℝ) (zt : ι' → E) (hws : ∑ i in s, ws i = 1) (hwt : ∑ i in t, wt i = 1) (a b : ℝ) (hab : a + b = 1) : a • s.center_mass ws zs + b • t.center_mass wt zt = (s.map function.embedding.inl ∪ t.map function.embedding.inr).center_mass (sum.elim (λ i, a * ws i) (λ j, b * wt j)) (sum.elim zs zt) := begin rw [s.center_mass_eq_of_sum_1 _ hws, t.center_mass_eq_of_sum_1 _ hwt, smul_sum, smul_sum, ← finset.sum_sum_elim, finset.center_mass_eq_of_sum_1], { congr' with ⟨⟩; simp only [sum.elim_inl, sum.elim_inr, mul_smul] }, { rw [sum_sum_elim, ← mul_sum, ← mul_sum, hws, hwt, mul_one, mul_one, hab] } end /-- A convex combination of two centers of mass is a center of mass as well. This version works if two centers of mass share the set of original points. -/ lemma finset.center_mass_segment (s : finset ι) (w₁ w₂ : ι → ℝ) (z : ι → E) (hw₁ : ∑ i in s, w₁ i = 1) (hw₂ : ∑ i in s, w₂ i = 1) (a b : ℝ) (hab : a + b = 1) : a • s.center_mass w₁ z + b • s.center_mass w₂ z = s.center_mass (λ i, a * w₁ i + b * w₂ i) z := have hw : ∑ i in s, (a * w₁ i + b * w₂ i) = 1, by simp only [mul_sum.symm, sum_add_distrib, mul_one, *], by simp only [finset.center_mass_eq_of_sum_1, smul_sum, sum_add_distrib, add_smul, mul_smul, *] lemma finset.center_mass_ite_eq (hi : i ∈ t) : t.center_mass (λ j, if (i = j) then 1 else 0) z = z i := begin rw [finset.center_mass_eq_of_sum_1], transitivity ∑ j in t, if (i = j) then z i else 0, { congr' with i, split_ifs, exacts [h ▸ one_smul _ _, zero_smul _ _] }, { rw [sum_ite_eq, if_pos hi] }, { rw [sum_ite_eq, if_pos hi] } end variables {t w} lemma finset.center_mass_subset {t' : finset ι} (ht : t ⊆ t') (h : ∀ i ∈ t', i ∉ t → w i = 0) : t.center_mass w z = t'.center_mass w z := begin rw [center_mass, sum_subset ht h, smul_sum, center_mass, smul_sum], apply sum_subset ht, assume i hit' hit, rw [h i hit' hit, zero_smul, smul_zero] end lemma finset.center_mass_filter_ne_zero : (t.filter (λ i, w i ≠ 0)).center_mass w z = t.center_mass w z := finset.center_mass_subset z (filter_subset _ _) $ λ i hit hit', by simpa only [hit, mem_filter, true_and, ne.def, not_not] using hit' variable {z} /-- The center of mass of a finite subset of a convex set belongs to the set provided that all weights are non-negative, and the total weight is positive. -/ lemma convex.center_mass_mem (hs : convex s) : (∀ i ∈ t, 0 ≤ w i) → (0 < ∑ i in t, w i) → (∀ i ∈ t, z i ∈ s) → t.center_mass w z ∈ s := begin induction t using finset.induction with i t hi ht, { simp [lt_irrefl] }, intros h₀ hpos hmem, have zi : z i ∈ s, from hmem _ (mem_insert_self _ _), have hs₀ : ∀ j ∈ t, 0 ≤ w j, from λ j hj, h₀ j $ mem_insert_of_mem hj, rw [sum_insert hi] at hpos, by_cases hsum_t : ∑ j in t, w j = 0, { have ws : ∀ j ∈ t, w j = 0, from (sum_eq_zero_iff_of_nonneg hs₀).1 hsum_t, have wz : ∑ j in t, w j • z j = 0, from sum_eq_zero (λ i hi, by simp [ws i hi]), simp only [center_mass, sum_insert hi, wz, hsum_t, add_zero], simp only [hsum_t, add_zero] at hpos, rw [← mul_smul, inv_mul_cancel (ne_of_gt hpos), one_smul], exact zi }, { rw [finset.center_mass_insert _ _ _ hi hsum_t], refine convex_iff_div.1 hs zi (ht hs₀ _ _) _ (sum_nonneg hs₀) hpos, { exact lt_of_le_of_ne (sum_nonneg hs₀) (ne.symm hsum_t) }, { intros j hj, exact hmem j (mem_insert_of_mem hj) }, { exact h₀ _ (mem_insert_self _ _) } } end lemma convex.sum_mem (hs : convex s) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i in t, w i = 1) (hz : ∀ i ∈ t, z i ∈ s) : ∑ i in t, w i • z i ∈ s := by simpa only [h₁, center_mass, inv_one, one_smul] using hs.center_mass_mem h₀ (h₁.symm ▸ zero_lt_one) hz lemma convex_iff_sum_mem : convex s ↔ (∀ (t : finset E) (w : E → ℝ), (∀ i ∈ t, 0 ≤ w i) → ∑ i in t, w i = 1 → (∀ x ∈ t, x ∈ s) → ∑ x in t, w x • x ∈ s ) := begin refine ⟨λ hs t w hw₀ hw₁ hts, hs.sum_mem hw₀ hw₁ hts, _⟩, intros h x y hx hy a b ha hb hab, by_cases h_cases: x = y, { rw [h_cases, ←add_smul, hab, one_smul], exact hy }, { convert h {x, y} (λ z, if z = y then b else a) _ _ _, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl] }, { simp_intros i hi, cases hi; subst i; simp [ha, hb, if_neg h_cases] }, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl, hab] }, { simp_intros i hi, cases hi; subst i; simp [hx, hy, if_neg h_cases] } } end /-- Jensen's inequality, `finset.center_mass` version. -/ lemma convex_on.map_center_mass_le {f : E → ℝ} (hf : convex_on s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (hpos : 0 < ∑ i in t, w i) (hmem : ∀ i ∈ t, z i ∈ s) : f (t.center_mass w z) ≤ t.center_mass w (f ∘ z) := begin have hmem' : ∀ i ∈ t, (z i, (f ∘ z) i) ∈ {p : E × ℝ | p.1 ∈ s ∧ f p.1 ≤ p.2}, from λ i hi, ⟨hmem i hi, le_refl _⟩, convert (hf.convex_epigraph.center_mass_mem h₀ hpos hmem').2; simp only [center_mass, function.comp, prod.smul_fst, prod.fst_sum, prod.smul_snd, prod.snd_sum] end /-- Jensen's inequality, `finset.sum` version. -/ lemma convex_on.map_sum_le {f : E → ℝ} (hf : convex_on s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i in t, w i = 1) (hmem : ∀ i ∈ t, z i ∈ s) : f (∑ i in t, w i • z i) ≤ ∑ i in t, w i * (f (z i)) := by simpa only [center_mass, h₁, inv_one, one_smul] using hf.map_center_mass_le h₀ (h₁.symm ▸ zero_lt_one) hmem /-- If a function `f` is convex on `s` takes value `y` at the center of mass of some points `z i ∈ s`, then for some `i` we have `y ≤ f (z i)`. -/ lemma convex_on.exists_ge_of_center_mass {f : E → ℝ} (h : convex_on s f) (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hws : 0 < ∑ i in t, w i) (hz : ∀ i ∈ t, z i ∈ s) : ∃ i ∈ t, f (t.center_mass w z) ≤ f (z i) := begin set y := t.center_mass w z, have : f y ≤ t.center_mass w (f ∘ z) := h.map_center_mass_le hw₀ hws hz, rw ← sum_filter_ne_zero at hws, rw [← finset.center_mass_filter_ne_zero (f ∘ z), center_mass, smul_eq_mul, ← div_eq_inv_mul, le_div_iff hws, mul_sum] at this, replace : ∃ i ∈ t.filter (λ i, w i ≠ 0), f y * w i ≤ w i • (f ∘ z) i := exists_le_of_sum_le (nonempty_of_sum_ne_zero (ne_of_gt hws)) this, rcases this with ⟨i, hi, H⟩, rw [mem_filter] at hi, use [i, hi.1], simp only [smul_eq_mul, mul_comm (w i)] at H, refine (mul_le_mul_right _).1 H, exact lt_of_le_of_ne (hw₀ i hi.1) hi.2.symm end end center_mass /-! ### Convex hull -/ section convex_hull variable {t : set E} /-- The convex hull of a set `s` is the minimal convex set that includes `s`. -/ def convex_hull : closure_operator (set E) := closure_operator.mk₃ (λ s, ⋂ (t : set E) (hst : s ⊆ t) (ht : convex t), t) convex (λ s, set.subset_Inter (λ t, set.subset_Inter $ λ hst, set.subset_Inter $ λ ht, hst)) (λ s, convex_Inter $ λ t, convex_Inter $ λ ht, convex_Inter id) (λ s t hst ht, set.Inter_subset_of_subset t $ set.Inter_subset_of_subset hst $ set.Inter_subset _ ht) variable (s) lemma subset_convex_hull : s ⊆ convex_hull s := convex_hull.le_closure s lemma convex_convex_hull : convex (convex_hull s) := closure_operator.closure_mem_mk₃ s variable {s} lemma convex_hull_min (hst : s ⊆ t) (ht : convex t) : convex_hull s ⊆ t := closure_operator.closure_le_mk₃_iff (show s ≤ t, from hst) ht lemma convex_hull_mono (hst : s ⊆ t) : convex_hull s ⊆ convex_hull t := convex_hull.monotone hst lemma convex.convex_hull_eq {s : set E} (hs : convex s) : convex_hull s = s := closure_operator.mem_mk₃_closed hs @[simp] lemma convex_hull_empty : convex_hull (∅ : set E) = ∅ := convex_empty.convex_hull_eq @[simp] lemma convex_hull_empty_iff : convex_hull s = ∅ ↔ s = ∅ := begin split, { intro h, rw [←set.subset_empty_iff, ←h], exact subset_convex_hull _ }, { rintro rfl, exact convex_hull_empty } end @[simp] lemma convex_hull_nonempty_iff : (convex_hull s).nonempty ↔ s.nonempty := begin rw [←ne_empty_iff_nonempty, ←ne_empty_iff_nonempty, ne.def, ne.def], exact not_congr convex_hull_empty_iff, end @[simp] lemma convex_hull_singleton {x : E} : convex_hull ({x} : set E) = {x} := (convex_singleton x).convex_hull_eq lemma convex.convex_remove_iff_not_mem_convex_hull_remove {s : set E} (hs : convex s) (x : E) : convex (s \ {x}) ↔ x ∉ convex_hull (s \ {x}) := begin split, { rintro hsx hx, rw hsx.convex_hull_eq at hx, exact hx.2 (mem_singleton _) }, rintro hx, suffices h : s \ {x} = convex_hull (s \ {x}), { convert convex_convex_hull _ }, exact subset.antisymm (subset_convex_hull _) (λ y hy, ⟨convex_hull_min (diff_subset _ _) hs hy, by { rintro (rfl : y = x), exact hx hy }⟩), end lemma is_linear_map.image_convex_hull {f : E → F} (hf : is_linear_map ℝ f) : f '' (convex_hull s) = convex_hull (f '' s) := begin refine set.subset.antisymm _ _, { rw [set.image_subset_iff], exact convex_hull_min (set.image_subset_iff.1 $ subset_convex_hull $ f '' s) ((convex_convex_hull (f '' s)).is_linear_preimage hf) }, { exact convex_hull_min (set.image_subset _ $ subset_convex_hull s) ((convex_convex_hull s).is_linear_image hf) } end lemma linear_map.image_convex_hull (f : E →ₗ[ℝ] F) : f '' (convex_hull s) = convex_hull (f '' s) := f.is_linear.image_convex_hull lemma finset.center_mass_mem_convex_hull (t : finset ι) {w : ι → ℝ} (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hws : 0 < ∑ i in t, w i) {z : ι → E} (hz : ∀ i ∈ t, z i ∈ s) : t.center_mass w z ∈ convex_hull s := (convex_convex_hull s).center_mass_mem hw₀ hws (λ i hi, subset_convex_hull s $ hz i hi) -- TODO : Do we need other versions of the next lemma? /-- Convex hull of `s` is equal to the set of all centers of masses of `finset`s `t`, `z '' t ⊆ s`. This version allows finsets in any type in any universe. -/ lemma convex_hull_eq (s : set E) : convex_hull s = {x : E | ∃ (ι : Type u') (t : finset ι) (w : ι → ℝ) (z : ι → E) (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hw₁ : ∑ i in t, w i = 1) (hz : ∀ i ∈ t, z i ∈ s), t.center_mass w z = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, use [punit, {punit.star}, λ _, 1, λ _, x, λ _ _, zero_le_one, finset.sum_singleton, λ _ _, hx], simp only [finset.center_mass, finset.sum_singleton, inv_one, one_smul] }, { rintros x y ⟨ι, sx, wx, zx, hwx₀, hwx₁, hzx, rfl⟩ ⟨ι', sy, wy, zy, hwy₀, hwy₁, hzy, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment' _ _ _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, _, _, _, _, rfl⟩, { rintros i hi, rw [finset.mem_union, finset.mem_map, finset.mem_map] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; simp only [sum.elim_inl, sum.elim_inr]; apply_rules [mul_nonneg, hwx₀, hwy₀] }, { simp [finset.sum_sum_elim, finset.mul_sum.symm, *] }, { intros i hi, rw [finset.mem_union, finset.mem_map, finset.mem_map] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; apply_rules [hzx, hzy] } }, { rintros _ ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩, exact t.center_mass_mem_convex_hull hw₀ (hw₁.symm ▸ zero_lt_one) hz } end /-- Maximum principle for convex functions. If a function `f` is convex on the convex hull of `s`, then `f` can't have a maximum on `convex_hull s` outside of `s`. -/ lemma convex_on.exists_ge_of_mem_convex_hull {f : E → ℝ} (hf : convex_on (convex_hull s) f) {x} (hx : x ∈ convex_hull s) : ∃ y ∈ s, f x ≤ f y := begin rw convex_hull_eq at hx, rcases hx with ⟨α, t, w, z, hw₀, hw₁, hz, rfl⟩, rcases hf.exists_ge_of_center_mass hw₀ (hw₁.symm ▸ zero_lt_one) (λ i hi, subset_convex_hull s (hz i hi)) with ⟨i, hit, Hi⟩, exact ⟨z i, hz i hit, Hi⟩ end lemma finset.convex_hull_eq (s : finset E) : convex_hull ↑s = {x : E | ∃ (w : E → ℝ) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : ∑ y in s, w y = 1), s.center_mass w id = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, rw [finset.mem_coe] at hx, refine ⟨_, _, _, finset.center_mass_ite_eq _ _ _ hx⟩, { intros, split_ifs, exacts [zero_le_one, le_refl 0] }, { rw [finset.sum_ite_eq, if_pos hx] } }, { rintros x y ⟨wx, hwx₀, hwx₁, rfl⟩ ⟨wy, hwy₀, hwy₁, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, rfl⟩, { rintros i hi, apply_rules [add_nonneg, mul_nonneg, hwx₀, hwy₀], }, { simp only [finset.sum_add_distrib, finset.mul_sum.symm, mul_one, *] } }, { rintros _ ⟨w, hw₀, hw₁, rfl⟩, exact s.center_mass_mem_convex_hull (λ x hx, hw₀ _ hx) (hw₁.symm ▸ zero_lt_one) (λ x hx, hx) } end lemma set.finite.convex_hull_eq {s : set E} (hs : finite s) : convex_hull s = {x : E | ∃ (w : E → ℝ) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : ∑ y in hs.to_finset, w y = 1), hs.to_finset.center_mass w id = x} := by simpa only [set.finite.coe_to_finset, set.finite.mem_to_finset, exists_prop] using hs.to_finset.convex_hull_eq lemma convex_hull_eq_union_convex_hull_finite_subsets (s : set E) : convex_hull s = ⋃ (t : finset E) (w : ↑t ⊆ s), convex_hull ↑t := begin refine subset.antisymm _ _, { rw [convex_hull_eq.{u}], rintros x ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩, simp only [mem_Union], refine ⟨t.image z, _, _⟩, { rw [finset.coe_image, image_subset_iff], exact hz }, { apply t.center_mass_mem_convex_hull hw₀, { simp only [hw₁, zero_lt_one] }, { exact λ i hi, finset.mem_coe.2 (finset.mem_image_of_mem _ hi) } } }, { exact Union_subset (λ i, Union_subset convex_hull_mono), }, end lemma is_linear_map.convex_hull_image {f : E → F} (hf : is_linear_map ℝ f) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := set.subset.antisymm (convex_hull_min (image_subset _ (subset_convex_hull s)) $ (convex_convex_hull s).is_linear_image hf) (image_subset_iff.2 $ convex_hull_min (image_subset_iff.1 $ subset_convex_hull _) ((convex_convex_hull _).is_linear_preimage hf)) lemma linear_map.convex_hull_image (f : E →ₗ[ℝ] F) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := f.is_linear.convex_hull_image s end convex_hull /-! ### Simplex -/ section simplex variables (ι) [fintype ι] {f : ι → ℝ} /-- The standard simplex in the space of functions `ι → ℝ` is the set of vectors with non-negative coordinates with total sum `1`. -/ def std_simplex (ι : Type*) [fintype ι] : set (ι → ℝ) := {f | (∀ x, 0 ≤ f x) ∧ ∑ x, f x = 1} lemma std_simplex_eq_inter : std_simplex ι = (⋂ x, {f | 0 ≤ f x}) ∩ {f | ∑ x, f x = 1} := by { ext f, simp only [std_simplex, set.mem_inter_eq, set.mem_Inter, set.mem_set_of_eq] } lemma convex_std_simplex : convex (std_simplex ι) := begin refine λ f g hf hg a b ha hb hab, ⟨λ x, _, _⟩, { apply_rules [add_nonneg, mul_nonneg, hf.1, hg.1] }, { erw [finset.sum_add_distrib, ← finset.smul_sum, ← finset.smul_sum, hf.2, hg.2, smul_eq_mul, smul_eq_mul, mul_one, mul_one], exact hab } end variable {ι} lemma ite_eq_mem_std_simplex (i : ι) : (λ j, ite (i = j) (1:ℝ) 0) ∈ std_simplex ι := ⟨λ j, by simp only; split_ifs; norm_num, by rw [finset.sum_ite_eq, if_pos (finset.mem_univ _)]⟩ /-- `std_simplex ι` is the convex hull of the canonical basis in `ι → ℝ`. -/ lemma convex_hull_basis_eq_std_simplex : convex_hull (range $ λ(i j:ι), if i = j then (1:ℝ) else 0) = std_simplex ι := begin refine subset.antisymm (convex_hull_min _ (convex_std_simplex ι)) _, { rintros _ ⟨i, rfl⟩, exact ite_eq_mem_std_simplex i }, { rintros w ⟨hw₀, hw₁⟩, rw [pi_eq_sum_univ w, ← finset.univ.center_mass_eq_of_sum_1 _ hw₁], exact finset.univ.center_mass_mem_convex_hull (λ i hi, hw₀ i) (hw₁.symm ▸ zero_lt_one) (λ i hi, mem_range_self i) } end variable {ι} /-- The convex hull of a finite set is the image of the standard simplex in `s → ℝ` under the linear map sending each function `w` to `∑ x in s, w x • x`. Since we have no sums over finite sets, we use sum over `@finset.univ _ hs.fintype`. The map is defined in terms of operations on `(s → ℝ) →ₗ[ℝ] ℝ` so that later we will not need to prove that this map is linear. -/ lemma set.finite.convex_hull_eq_image {s : set E} (hs : finite s) : convex_hull s = by haveI := hs.fintype; exact (⇑(∑ x : s, (@linear_map.proj ℝ s _ (λ i, ℝ) _ _ x).smul_right x.1)) '' (std_simplex s) := begin rw [← convex_hull_basis_eq_std_simplex, ← linear_map.convex_hull_image, ← set.range_comp, (∘)], apply congr_arg, convert subtype.range_coe.symm, ext x, simp [linear_map.sum_apply, ite_smul, finset.filter_eq] end /-- All values of a function `f ∈ std_simplex ι` belong to `[0, 1]`. -/ lemma mem_Icc_of_mem_std_simplex (hf : f ∈ std_simplex ι) (x) : f x ∈ I := ⟨hf.1 x, hf.2 ▸ finset.single_le_sum (λ y hy, hf.1 y) (finset.mem_univ x)⟩ end simplex
422ec5fa44667bd5a29e9819abcc99f058acec78
36938939954e91f23dec66a02728db08a7acfcf9
/lean4/simulator/Translate.lean
dc008eee1e6a4a399c7de4b60a5509d22c21bc94
[]
no_license
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
11,773
lean
import X86Semantics.Instructions import X86Semantics.BackendAPI import X86Semantics.Evaluator import DecodeX86.DecodeX86 open mc_semantics open mc_semantics.type -- lemma {u} find_index_lt {α : Type u} (p : α -> Prop) [decidable_pred p] : Π(ls : list α), list.find_index p ls ≤ ls.length := -- begin -- intros, -- induction ls, -- { simp [list.find_index] }, -- { simp [list.find_index], -- by_cases (p ls_hd), -- { simp [h] }, -- { simp [h, nat.one_add], apply nat.succ_le_succ, exact ls_ih } -- } -- end -- lemma {u} index_of_lt {α : Type u} [decidable_eq α] (ls : list α) (x : α) -- : list.index_of x ls ≤ ls.length := by apply find_index_lt namespace List universe u protected def indexOfAux {α : Type u} [DecidableEq α] (v : α) : Nat -> List α -> Nat | n, [] => n | n, (x :: xs) => if x = v then n else indexOfAux (n + 1) xs def indexOf {α : Type u} [DecidableEq α] (xs : List α) (v : α) : Nat := List.indexOfAux v 0 xs end List namespace x86 @[reducible] def some_gpr := Sigma (fun (tp : gpreg_type) => concrete_reg (bv tp.width)) def register_to_reg (r : decodex86.register) : Option some_gpr := let idx := reg.r64_names.indexOf r.top; if H : idx = reg.r64_names.length then none else let prf : idx < 16 := I_am_really_sorry _; let idx' := @Fin.mk 16 idx prf; -- (begin -- destruct (lt_or_eq_of_le (index_of_lt reg.r64_names r.top)); intros Hle, -- exact Hle, -- contradiction -- end) let mk : ∀(tp : gpreg_type), Option some_gpr := fun (tp : gpreg_type) => some ⟨tp, concrete_reg.gpreg idx' tp⟩; match (r.width, r.offset) with | (8, 0) => mk gpreg_type.reg8l | (8, 8) => mk gpreg_type.reg8h | (16, 0) => mk gpreg_type.reg16 | (32, 0) => mk gpreg_type.reg32 | (0, 0) => mk gpreg_type.reg64 -- 0 0 means full reg. | _ => none open decodex86 def throw_if {m} {ε} [Monad m] [MonadExcept ε m] (P : Prop) [Decidable P] (what : ε) : m Unit := if P then throw what else pure () -- instance {α : Type} : decidable_pred (@option.is_none α) := -- begin -- unfold decidable_pred, -- intros, -- cases a, -- { simp [is_none], apply is_true, constructor}, -- { simp [is_none], apply is_false, simp} -- end -- instance is_some_decidable {α : Type} : decidable_pred (@option.is_some α) := -- begin -- unfold decidable_pred, -- intros, -- cases a, -- { simp [is_some], apply is_false, simp}, -- { simp [is_some], apply is_true, constructor} -- end def guard_some {m} [Monad m] [MonadExcept String m] {α β : Type} (reason : String) (x : Option α) (f : α -> m β) : m β := match x with | none => throw (String.append "guard_some: none: " reason) | (some y) => f y section Backend variables (backend : Backend) def option_register_to_bv64 (opt_r : Option decodex86.register) : M backend (backend.s_bv 64) := match opt_r with | none => pure (backend.s_bv_imm 64 0) | (some r) => (match String.decEq r.top "rip" with -- FIXME: compiler bug with ite? | isTrue _ => backend.s_get_ip | isFalse _ => guard_some "option_register_to_bv64" (register_to_reg r) (fun (r' : some_gpr) => match r' with | (Sigma.mk gpreg_type.reg64 rr) => concrete_reg.from_state rr | _ => throw "not a 64bit reg" )) def operand_to_arg_lval (tp : type) (otp : decodex86.operand_type) : decodex86.operand_value -> M backend (@arg_lval backend) -- FIXME: check width? | (operand_value.register r) => do sgpr <- guard_some "operand_to_arg_lval register" (register_to_reg r) pure; assert_types (bv sgpr.fst.width) tp; pure (arg_lval.reg sgpr.snd) -- FIXME: check width? | (operand_value.segment opt_r r) => do throw_if (Option.isSome opt_r) "got a segment reg"; -- FIXME: clag sgpr <- guard_some "operand_to_arg_value_lhs register" (register_to_reg r) pure; assert_types (bv sgpr.fst.width) tp; pure (arg_lval.reg sgpr.snd) | (operand_value.immediate nbytes val) => throw "operand_to_arg_lval: got an immdiate" -- FIXME: we use ip out of the state, we could use the value encoded in the decoded instruction | (operand_value.rel_immediate next_addr nbytes val) => throw "operand_to_arg_lval: got an immdeiate" -- base + scale * idx + disp | (operand_value.memloc opt_seg opt_base scale opt_idx disp) => do n <- match otp with | (operand_type.mem n) => pure n | other => throw "memloc not of mem type"; assert_types (bv n) tp; throw_if (Option.isSome opt_seg) "got a segment reg"; b_v <- option_register_to_bv64 backend opt_base; idx_v <- option_register_to_bv64 backend opt_idx; pure (arg_lval.memloc n (backend.s_bvadd _ b_v (backend.s_bvadd _ (backend.s_bvmul _ (backend.s_bv_imm _ scale) idx_v) (backend.s_bv_imm _ disp)))) def operand_to_arg_value_lhs (tp : type) (op : decodex86.operand) : M backend (@arg_value backend) := arg_value.lval <$> operand_to_arg_lval backend tp op.type op.value def nat_to_signed_bitvec (val : Nat) (nbytes_in : Nat) (n : Nat) : backend.s_bv n := backend.s_sext _ n (backend.s_bv_imm (8 * nbytes_in) val) def operand_to_value (tp : type) (op : decodex86.operand) : M backend (@value backend tp) := match op.value with | (operand_value.immediate nbytes val) => do -- FIXME: rather than failing here, we will sign extend/truncate. This may be the wrong approach. -- We could also extend operand_type (match tp with | (bv e) => pure (nat_to_signed_bitvec backend val nbytes e) | _ => throw "Immediate should be a bv") -- FIXME: we use ip out of the state, we could use the value encoded in the decoded instruction | (operand_value.rel_immediate next_addr nbytes val) => do -- checks for width = 64 bit, basically -- @value.type_check nenv m _ _ (bv 64) (s.ip + nat_to_signed_bitvec val nbytes 64) tp ip <- backend.s_get_ip; value.type_check (bv 64) (backend.s_bvadd _ ip (nat_to_signed_bitvec backend val nbytes 64)) tp | _ => do lval <- operand_to_arg_lval backend tp op.type op.value; arg_lval.to_value' lval tp def operand_to_arg_value_expr (tp : type) (op : decodex86.operand) : M backend (@arg_value backend) := arg_value.rval <$> operand_to_value backend tp op def first_comb.{u,v,w} {ε : Type u} {m : Type v → Type w} [MonadExcept ε m] {α : Type v} (e : ε) (f : ε -> ε -> ε) : List (m α) -> m α | [] => throw e | [x] => x | (x :: xs) => catch x $ fun e1 => catch (first_comb xs) $ fun e2 => throw (f e1 e2) /- def test_pattern := match mov.patterns with | [x] := x | _ => sorry end #eval possible_nat_envs test_pattern.context.bindings.reverse -/ def make_environment_helper : List binding -> List decodex86.operand -> M backend (@environment backend) | [], [] => pure [] | (binding.reg tp :: rest), (op :: ops) => annotate' "reg" $ do av <- operand_to_arg_value_lhs backend tp op; -- Mainly to check things are of the right form match av with | (arg_value.lval (arg_lval.reg r)) => pure () | _ => throw "Not a register"; e <- make_environment_helper rest ops; pure (av :: e) | (binding.addr tp :: rest), (op :: ops) => annotate' "addr" $ do av <- operand_to_arg_value_lhs backend tp op; -- Mainly to check things are of the right form match av with | (arg_value.lval (arg_lval.memloc _ _)) => pure () | _ => throw "Not a memloc"; e <- make_environment_helper rest ops; pure (av :: e) | (binding.imm tp :: rest), (op :: ops) => annotate' "imm" $ do -- FIXME: check that it is, in fact, an immediate av <- operand_to_arg_value_expr backend tp op; e <- make_environment_helper rest ops; pure (av :: e) | (binding.lhs tp :: rest), (op :: ops) => annotate' "lhs" $ do av <- operand_to_arg_value_lhs backend tp op; e <- make_environment_helper rest ops; pure (av :: e) | (binding.expression tp :: rest), (op :: ops) => annotate' "expression" $ do av <- operand_to_arg_value_expr backend tp op; e <- make_environment_helper rest ops; pure (av :: e) | _, _ => throw "binding/operand mismatch" /- inductive binding | one_of : list nat → binding | reg : type → binding | addr : type → binding | imm : type → binding | lhs : type → binding | expression : type → binding -/ def instantiate_pattern (inst : instruction) (i : decodex86.instruction) : M backend (@environment backend × x86.pattern) := first_comb "instantiate_pattern: no patterns" (fun l r => r) -- l ++ ", " ++ r) (List.map (fun (p : x86.pattern) => do e <- make_environment_helper backend p.context.bindings.reverse i.operands; pure (e, p)) inst.patterns) def instruction_family (inst : decodex86.instruction) : String := let (pfx, rest) := List.span Char.isUpper inst.mnemonic.toList; (List.map Char.toLower pfx).asString def instruction_map : RBMap String instruction (fun x y => decide (x < y)) := RBMap.fromList (List.map (fun (i : instruction) => (i.mnemonic, i)) all_instructions) (fun x y => decide (x < y)) def eval_instruction (i : decodex86.instruction) : M backend Unit := match instruction_map.find? (instruction_family i) with | none => throw ("Unknown instruction: " ++ i.mnemonic) | (some inst) => do (env, p) <- annotate' "pattern" (instantiate_pattern backend inst i); annotate' "pattern.eval" (pattern.eval p env) /- testing -/ -- def get_sexp : String -> sexp := fun st => -- match sexp.from_string st with -- | (sum.inr s) => s -- | _ => sexp.list [] -- end -- def string_to_instruction (s : String) : Option decodex86.instruction := -- decodex86.exec_parser decodex86.parser.instructionp (get_sexp s) -- def go (s : String) : String := -- match string_to_instruction s with -- | none => "No parse" -- | (some i) => repr i.operands -- end -- namespace except -- def to_sum {a} {b} : except a b -> sum a b -- | (except.error e) => sum.inl e -- | (except.ok v) => sum.inr v -- end except -- def go2 (s : String) (si : instruction) : String := -- match string_to_instruction s with -- | none => "No parse" -- | (some i) => match ((eval_simple_instruction si i).run evaluator_state.empty) with -- | (except.error e) => "error: " ++ e -- | (except.ok (e, _)) => has_repr.repr e -- end -- end -- def run_get_rax (s : String) : String := -- match string_to_instruction s with -- | none => "No parse" -- | (some i) => match (eval_instruction machine_state.empty i) with -- | (except.error e) => "error: " ++ e -- | (except.ok s) => s.print_regs -- has_repr.repr (s.get_gpreg 0) -- end -- end -- #eval instruction_family <$> string_to_instruction "(instruction MOV32ri (register rax eax 32 0) (immediate 4 1))" -- #eval run_get_rax "(instruction MOV64ri32 (other (register rax rax 0 0)) (other (immediate 4 4294967295)))" -- #eval run_get_rax "(instruction MOV32mi (i32mem (memloc no-register (register rax rax 0 0) 1 no-register 0)) (i32imm (immediate 4 65535)))" end Backend end x86
ebcb1a9f6ecde1bc90e042c3a74c53198c292026
6d50885e7b3f72447a03f21d5268d6af87c0a404
/instructor-notes/000_2020/notes.lean
b60746675a614d0c724625af3f0341ed967649fd
[]
no_license
kevinsullivan/uva-cs-dm-s20-old
583c756cded281fcee7f1afc42cb3e08f89c2493
797672cb0ffae6a42a3518c9225d5807191fd113
refs/heads/master
1,607,500,914,982
1,578,752,991,000
1,578,752,991,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
201
lean
axiom Swan : Type axiom White : Swan → Prop #check ∀ (s : Swan), White s axiom Object : Type axiom isSwan : Object → Prop axiom isWhite : Object → Prop #check ∀ s, isSwan s → isWhite s
da324f6d22a1acc2f5bc4d6231cc8c1764d7ff44
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Compiler/Check.lean
80a0cbfd729b5e22cbac162ea764e91f3303102f
[ "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
5,117
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.InferType import Lean.Compiler.Util namespace Lean.Compiler open InferType /-! Type checker for LCNF expressions -/ structure Check.Config where terminalCasesOnly : Bool := true def lambdaBoundedTelescope (e : Expr) (n : Nat) (k : Array Expr → Expr → InferTypeM α) : InferTypeM α := go e n #[] where go (e : Expr) (i : Nat) (xs : Array Expr) : InferTypeM α := match i with | 0 => k xs (e.instantiateRev xs) | i+1 => match e with | .lam n d b bi => withLocalDecl n (d.instantiateRev xs) bi fun x => go b i (xs.push x) | _ => throwError "lambda expected" partial def check (e : Expr) (cfg : Check.Config := {}) : InferTypeM Unit := do checkBlock e #[] false where checkBlock (e : Expr) (xs : Array Expr) (foundLet : Bool) : InferTypeM Unit := do match e with | .lam n d b bi => if foundLet then throwError "invalid occurrence of lambda-expression at the end of a let-declaration block{indentExpr (e.instantiateRev xs)}" withLocalDecl n (d.instantiateRev xs) bi fun x => checkBlock b (xs.push x) false | .letE n t v b _ => let value := v.instantiateRev xs if value.isAppOf ``lcUnreachable then throwError "invalid occurrence of `lcUnreachable` in let-declaration `{n}`" checkValue value (isTerminal := false) let type := t.instantiateRev xs let valueType ← inferType value unless compatibleTypes type valueType do throwError "type mismatch at let-declaration `{n}`, value has type{indentExpr valueType}\nbut is expected to have type{indentExpr type}" withLocalDecl n type .default fun x => checkBlock b (xs.push x) true | _ => checkValue (e.instantiateRev xs) (isTerminal := true) checkValue (e : Expr) (isTerminal : Bool) : InferTypeM Unit := do match e with | .lit _ => pure () | .lam .. => checkBlock e #[] (foundLet := false) | .app .. => checkApp e isTerminal | .proj _ _ (.fvar _) => pure () | .mdata _ (.fvar _) => pure () | .const _ _ => pure () -- TODO: check number of universe level parameters | .fvar _ => pure () -- TODO: report unnecessary fvar? | _ => throwError "unexpected expression at LCNF{indentExpr e}" checkApp (e : Expr) (isTerminal : Bool) : InferTypeM Unit := do let f := e.getAppFn let args := e.getAppArgs unless f.isConst || f.isFVar do throwError "unexpected function application, function must be a constant or free variable{indentExpr e}" if let some casesInfo ← isCasesApp? e then unless isTerminal || !cfg.terminalCasesOnly do throwError "non-terminal occurrence of cases-like term{indentExpr e}" checkCases casesInfo args else let mut fType ← inferType f let mut j := 0 for i in [:args.size] do let arg := args[i]! if fType.isAnyType then return () fType := fType.headBeta let (d, b) ← match fType with | .forallE _ d b _ => pure (d, b) | _ => fType := fType.instantiateRevRange j i args |>.headBeta match fType with | .forallE _ d b _ => j := i; pure (d, b) | _ => if fType.isAnyType then return () throwError "function expected at{indentExpr e}\narrow type expected{indentExpr fType}" let argType ← inferType arg let expectedType := d.instantiateRevRange j i args unless compatibleTypes argType expectedType do throwError "type mismatch at LCNF application{indentExpr e}\nargument {arg} has type{indentExpr argType}\nbut is expected to have type{indentExpr expectedType}" unless isTypeFormerType expectedType || expectedType.erased do unless arg.isFVar do throwError "invalid LCNF application{indentExpr e}\nargument{indentExpr arg}\nmust be a free variable" fType := b checkCases (casesInfo : CasesInfo) (args : Array Expr) : InferTypeM Unit := do let mut motive := args[casesInfo.motivePos]! for i in casesInfo.discrsRange do let discr := args[i]! let discrType ← inferType discr if let .lam _ d b _ := motive then unless compatibleTypes d discrType do throwError "type mismatch at LCNF `cases` discriminant{indentExpr discr}\nhas type{indentExpr discrType}\nbut is expected to have type{indentExpr d}" motive := b let expectedType := motive for i in casesInfo.altsRange, numParams in casesInfo.altNumParams do let alt := args[i]! lambdaBoundedTelescope alt numParams fun _ altBody => do let altBodyType ← inferType altBody unless compatibleTypes expectedType altBodyType do throwError "type mismatch at LCNF `cases` alternative{indentExpr altBody}\nhas type{indentExpr altBodyType}\nbut is expected to have type{indentExpr expectedType}" checkBlock altBody #[] (foundLet := true) end Lean.Compiler
6478964d067435269af641d6ca266b0fa0c56d75
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/order/preorder_hom.lean
546010046f7c56d7d81e7f9474cbdd22a3da0806
[ "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
5,338
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin # Preorder homomorphisms Bundled monotone functions, `x ≤ y → f x ≤ f y`. -/ import order.basic import order.bounded_lattice import order.complete_lattice import tactic.monotonicity /-! # Category of preorders -/ /-- Bundled monotone (aka, increasing) function -/ structure preorder_hom (α β : Type*) [preorder α] [preorder β] := (to_fun : α → β) (monotone' : monotone to_fun) infixr ` →ₘ `:25 := preorder_hom namespace preorder_hom variables {α : Type*} {β : Type*} {γ : Type*} [preorder α] [preorder β] [preorder γ] instance : has_coe_to_fun (preorder_hom α β) := { F := λ f, α → β, coe := preorder_hom.to_fun } @[mono] lemma monotone (f : α →ₘ β) : monotone f := preorder_hom.monotone' f @[simp] lemma coe_fun_mk {f : α → β} (hf : _root_.monotone f) (x : α) : mk f hf x = f x := rfl @[ext] lemma ext (f g : preorder_hom α β) (h : ∀ a, f a = g a) : f = g := by { cases f, cases g, congr, funext, exact h _ } lemma coe_inj (f g : preorder_hom α β) (h : (f : α → β) = g) : f = g := by { ext, rw h } /-- The identity function as bundled monotone function. -/ @[simps] def id : preorder_hom α α := ⟨id, monotone_id⟩ instance : inhabited (preorder_hom α α) := ⟨id⟩ @[simp] lemma coe_id : (@id α _ : α → α) = id := rfl /-- The composition of two bundled monotone functions. -/ @[simps] def comp (g : preorder_hom β γ) (f : preorder_hom α β) : preorder_hom α γ := ⟨g ∘ f, g.monotone.comp f.monotone⟩ @[simp] lemma comp_id (f : preorder_hom α β) : f.comp id = f := by { ext, refl } @[simp] lemma id_comp (f : preorder_hom α β) : id.comp f = f := by { ext, refl } /-- The preorder structure of `α →ₘ β` is pointwise inequality: `f ≤ g ↔ ∀ a, f a ≤ g a`. -/ instance : preorder (α →ₘ β) := preorder.lift preorder_hom.to_fun instance {β : Type*} [partial_order β] : partial_order (α →ₘ β) := partial_order.lift preorder_hom.to_fun $ by rintro ⟨⟩ ⟨⟩ h; congr; exact h @[simps] instance {β : Type*} [semilattice_sup β] : has_sup (α →ₘ β) := { sup := λ f g, ⟨λ a, f a ⊔ g a, λ x y h, sup_le_sup (f.monotone h) (g.monotone h)⟩ } instance {β : Type*} [semilattice_sup β] : semilattice_sup (α →ₘ β) := { sup := has_sup.sup, le_sup_left := λ a b x, le_sup_left, le_sup_right := λ a b x, le_sup_right, sup_le := λ a b c h₀ h₁ x, sup_le (h₀ x) (h₁ x), .. (_ : partial_order (α →ₘ β)) } @[simps] instance {β : Type*} [semilattice_inf β] : has_inf (α →ₘ β) := { inf := λ f g, ⟨λ a, f a ⊓ g a, λ x y h, inf_le_inf (f.monotone h) (g.monotone h)⟩ } instance {β : Type*} [semilattice_inf β] : semilattice_inf (α →ₘ β) := { inf := has_inf.inf, inf_le_left := λ a b x, inf_le_left, inf_le_right := λ a b x, inf_le_right, le_inf := λ a b c h₀ h₁ x, le_inf (h₀ x) (h₁ x), .. (_ : partial_order (α →ₘ β)) } instance {β : Type*} [lattice β] : lattice (α →ₘ β) := { .. (_ : semilattice_sup (α →ₘ β)), .. (_ : semilattice_inf (α →ₘ β)) } @[simps] instance {β : Type*} [order_bot β] : has_bot (α →ₘ β) := { bot := ⟨λ a, ⊥, λ a b h, le_refl _⟩ } instance {β : Type*} [order_bot β] : order_bot (α →ₘ β) := { bot := has_bot.bot, bot_le := λ a x, bot_le, .. (_ : partial_order (α →ₘ β)) } @[simps] instance {β : Type*} [order_top β] : has_top (α →ₘ β) := { top := ⟨λ a, ⊤, λ a b h, le_refl _⟩ } instance {β : Type*} [order_top β] : order_top (α →ₘ β) := { top := has_top.top, le_top := λ a x, le_top, .. (_ : partial_order (α →ₘ β)) } @[simps] instance {β : Type*} [complete_lattice β] : has_Inf (α →ₘ β) := { Inf := λ s, ⟨ λ x, Inf ((λ f : _ →ₘ _, f x) '' s), λ x y h, Inf_le_Inf_of_forall_exists_le (by simp only [and_imp, exists_prop, set.mem_image, exists_exists_and_eq_and, exists_imp_distrib]; intros; subst_vars; refine ⟨_,by assumption, monotone _ h⟩) ⟩ } @[simps] instance {β : Type*} [complete_lattice β] : has_Sup (α →ₘ β) := { Sup := λ s, ⟨ λ x, Sup ((λ f : _ →ₘ _, f x) '' s), λ x y h, Sup_le_Sup_of_forall_exists_le (by simp only [and_imp, exists_prop, set.mem_image, exists_exists_and_eq_and, exists_imp_distrib]; intros; subst_vars; refine ⟨_,by assumption, monotone _ h⟩) ⟩ } @[simps Sup Inf] instance {β : Type*} [complete_lattice β] : complete_lattice (α →ₘ β) := { Sup := has_Sup.Sup, le_Sup := λ s f hf x, @le_Sup β _ ((λ f : _ →ₘ _, f x) '' s) (f x) ⟨f, hf, rfl⟩, Sup_le := λ s f hf x, @Sup_le β _ _ _ $ λ b (h : b ∈ (λ (f : α →ₘ β), f x) '' s), by rcases h with ⟨g, h, ⟨ ⟩⟩; apply hf _ h, Inf := has_Inf.Inf, le_Inf := λ s f hf x, @le_Inf β _ _ _ $ λ b (h : b ∈ (λ (f : α →ₘ β), f x) '' s), by rcases h with ⟨g, h, ⟨ ⟩⟩; apply hf _ h, Inf_le := λ s f hf x, @Inf_le β _ ((λ f : _ →ₘ _, f x) '' s) (f x) ⟨f, hf, rfl⟩, .. (_ : lattice (α →ₘ β)), .. (_ : order_top (α →ₘ β)), .. (_ : order_bot (α →ₘ β)) } end preorder_hom
dcdb3cfc73f0a999edf4fdb7fecefe1ef658c8d8
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/hott/433.hlean
a92e364601be15a90f9e30b311c60ef9f7f74898
[ "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
4,834
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Ported from Coq HoTT Theorems about pi-types (dependent function spaces) -/ import types.sigma open eq equiv is_equiv funext namespace pi universe variables l k variables {A A' : Type.{l}} {B : A → Type.{k}} {B' : A' → Type.{k}} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {f g : Πa, B a} /- Paths -/ /- Paths [p : f ≈ g] in a function type [Πx:X, P x] are equivalent to functions taking values in path types, [H : Πx:X, f x ≈ g x], or concisely, [H : f ∼ g]. This equivalence, however, is just the combination of [apD10] and function extensionality [funext], and as such, [path_forall], et seq. are given in axioms.funext and path: -/ /- Now we show how these things compute. -/ definition apd10_path_pi (H : funext) (h : f ~ g) : apd10 (eq_of_homotopy h) ~ h := apd10 (right_inv apd10 h) definition path_pi_eta (H : funext) (p : f = g) : eq_of_homotopy (apd10 p) = p := left_inv apd10 p print classes definition path_pi_idp (H : funext) : eq_of_homotopy (λx : A, refl (f x)) = refl f := path_pi_eta H _ /- The identification of the path space of a dependent function space, up to equivalence, is of course just funext. -/ definition path_equiv_homotopy (H : funext) (f g : Πx, B x) : (f = g) ≃ (f ~ g) := equiv.mk _ !is_equiv_apdt definition is_equiv_path_pi [instance] (H : funext) (f g : Πx, B x) : is_equiv (@eq_of_homotopy _ _ f g) := is_equiv_inv apd10 definition homotopy_equiv_path (H : funext) (f g : Πx, B x) : (f ~ g) ≃ (f = g) := equiv.mk _ (is_equiv_path_pi H f g) /- Transport -/ protected definition transport (p : a = a') (f : Π(b : B a), C a b) : (transport (λa, Π(b : B a), C a b) p f) ~ (λb, transport (C a') !tr_inv_tr (transportD _ p _ (f (p⁻¹ ▸ b)))) := eq.rec_on p (λx, idp) /- A special case of [transport_pi] where the type [B] does not depend on [A], and so it is just a fixed type [B]. -/ definition transport_constant {C : A → A' → Type} (p : a = a') (f : Π(b : A'), C a b) : (eq.transport (λa, Π(b : A'), C a b) p f) ~ (λb, eq.transport (λa, C a b) p (f b)) := eq.rec_on p (λx, idp) /- Maps on paths -/ /- The action of maps given by lambda. -/ definition ap_lambdaD (H : funext) {C : A' → Type} (p : a = a') (f : Πa b, C b) : ap (λa b, f a b) p = eq_of_homotopy (λb, ap (λa, f a b) p) := begin apply (eq.rec_on p), apply inverse, apply (path_pi_idp H) end /- Dependent paths -/ /- with more implicit arguments the conclusion of the following theorem is (Π(b : B a), transportD B C p b (f b) = g (eq.transport B p b)) ≃ (eq.transport (λa, Π(b : B a), C a b) p f = g) -/ definition dpath_pi (H : funext) (p : a = a') (f : Π(b : B a), C a b) (g : Π(b' : B a'), C a' b') : (Π(b : B a), p ▸D (f b) = g (p ▸ b)) ≃ (p ▸ f = g) := eq.rec_on p (λg, homotopy_equiv_path H f g) g section open sigma sigma.ops /- more implicit arguments: (Π(b : B a), eq.transport C (sigma.path p idp) (f b) = g (p ▸ b)) ≃ (Π(b : B a), transportD B (λ(a : A) (b : B a), C ⟨a, b⟩) p b (f b) = g (eq.transport B p b)) -/ definition dpath_pi_sigma {C : (Σa, B a) → Type} (p : a = a') (f : Π(b : B a), C ⟨a, b⟩) (g : Π(b' : B a'), C ⟨a', b'⟩) : (Π(b : B a), (sigma.sigma_eq p !pathover_tr) ▸ (f b) = g (p ▸ b)) ≃ (Π(b : B a), p ▸D (f b) = g (p ▸ b)) := eq.rec_on p (λg, !equiv.refl) g end variables (f0 : A' → A) (f1 : Π(a':A'), B (f0 a') → B' a') definition transport_V [reducible] (P : A → Type) {x y : A} (p : x = y) (u : P y) : P x := p⁻¹ ▸ u definition functor_pi : (Π(a:A), B a) → (Π(a':A'), B' a') := (λg a', f1 a' (g (f0 a'))) /- Equivalences -/ definition isequiv_functor_pi [instance] (f0 : A' → A) (f1 : Π(a':A'), B (f0 a') → B' a') [H0 : is_equiv f0] [H1 : Πa', @is_equiv (B (f0 a')) (B' a') (f1 a')] : is_equiv (functor_pi f0 f1) := begin apply (adjointify (functor_pi f0 f1) (functor_pi (f0⁻¹) (λ(a : A) (b' : B' (f0⁻¹ a)), transport B (right_inv f0 a) ((f1 (f0⁻¹ a))⁻¹ b')))), intro h, apply eq_of_homotopy, esimp [functor_pi, function.compose], -- simplify (and unfold function_pi and function.compose) --first subgoal intro a', esimp, rewrite adj, rewrite -tr_compose, rewrite {f1 a' _}(fn_tr_eq_tr_fn _ f1 _), rewrite (right_inv (f1 _) _), apply apdt, intro h, apply eq_of_homotopy, intro a, esimp, apply (transport_V (λx, right_inv f0 a ▸ x = h a) (left_inv (f1 _) _)), apply apdt end end pi
142d6324c0a57c99b063219f4247dbd5ca4f33fa
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/09_Type_Classes.org.25.lean
333c741e70b5871e05eb58b1134ef3760245938e
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
350
lean
import standard import standard inductive has_add [class] (A : Type) : Type := mk : (A → A → A) → has_add A definition add {A : Type} [s : has_add A] := has_add.rec (λ x, x) s notation a `+` b := add a b -- BEGIN section variables {A : Type} [H : has_add A] (a b : A) include H definition foo : a + b = a + b := rfl check @foo end -- END
39ac9367884d748f124fbcd8a8e17bc37728a61a
94e33a31faa76775069b071adea97e86e218a8ee
/src/computability/turing_machine.lean
0a69783e0f4619f67831bab671051168f4ac3d49
[ "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
109,672
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fintype.basic import data.pfun import logic.function.iterate import order.basic import tactic.apply_fun /-! # 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 → part 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, add_tsub_cancel_of_le 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, tsub_add_cancel_of_le], 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 [add_tsub_cancel_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] } } 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 `part.none`. -/ def eval {σ} (f : σ → option σ) : σ → part σ := pfun.fix (λ s, part.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} (hab : reaches f a b) (hac : reaches f a c) : reaches f b c ∨ reaches f c b := refl_trans_gen.total_of_right_unique (λ _ _ _, option.mem_unique) hab hac 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', f a = some a' → C a') → C a) : C a := pfun.fix_induction h (λ a' ha' h', H _ ha' $ λ b' e, h' _ $ part.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 part.mem_unique h (pfun.mem_fix_iff.2 $ or.inl $ part.mem_some_iff.2 $ by rw e; refl), exact ⟨refl_trans_gen.refl, e⟩ }, { rcases pfun.mem_fix_iff.1 h with h | ⟨_, h, _⟩; rw e at h; cases part.mem_some_iff.1 h, cases IH a' (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 part.mem_some }, { refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH⟩), rw show f a = _, from h, apply part.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 := part.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₁ := part.ext $ λ b₂, ⟨λ h, let ⟨b₁, bb, hb⟩ := tr_eval_rev H rfl h in (part.mem_map_iff _).2 ⟨b₁, hb, bb⟩, λ h, begin rcases (part.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 Γ) : part (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 Γ) : part (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 [part.map_eq_map, part.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 letI := classical.dec_eq Γ, let n := fintype.card Γ, obtain ⟨F⟩ := fintype.trunc_equiv_fin Γ, 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)) : part (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 (λ l, _), simp 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 Λ' | (TM2.stmt.push k f q) := {go k (st_act.push f) q, ret q} ∪ tr_stmts₁ q | (TM2.stmt.peek k f q) := {go k (st_act.peek f) q, ret q} ∪ tr_stmts₁ q | (TM2.stmt.pop k f q) := {go k (st_act.pop f) q, ret q} ∪ tr_stmts₁ q | (TM2.stmt.load a q) := tr_stmts₁ 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 lt_or_gt_of_ne h with h h, { rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h }, { rw gt_iff_lt at 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 lt_or_gt_of_ne h with h h, { rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h }, { rw gt_iff_lt at 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_rfl, 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⟩ := (part.mem_map_iff _).1 H₁, obtain ⟨c₂, h₂, rfl⟩ := (part.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 part.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
43af90a24e69177d6071377c6c5b3a48e402581b
4727251e0cd73359b15b664c3170e5d754078599
/src/data/list/prime.lean
9fa1305b4c4103cd925d82009103314ecf1de7e6
[ "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,030
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, Jens Wagemaker, Anne Baanen -/ import algebra.associated import data.list.big_operators import data.list.perm /-! # Products of lists of prime elements. This file contains some theorems relating `prime` and products of `list`s. -/ open list section comm_monoid_with_zero variables {M : Type*} [comm_monoid_with_zero M] /-- Prime `p` divides the product of a list `L` iff it divides some `a ∈ L` -/ lemma prime.dvd_prod_iff {p : M} {L : list M} (pp : prime p) : p ∣ L.prod ↔ ∃ a ∈ L, p ∣ a := begin split, { intros h, induction L with L_hd L_tl L_ih, { rw prod_nil at h, exact absurd h pp.not_dvd_one }, { rw prod_cons at h, cases pp.dvd_or_dvd h with hd hd, { exact ⟨L_hd, mem_cons_self L_hd L_tl, hd⟩ }, { obtain ⟨x, hx1, hx2⟩ := L_ih hd, exact ⟨x, mem_cons_of_mem L_hd hx1, hx2⟩ } } }, { exact λ ⟨a, ha1, ha2⟩, dvd_trans ha2 (dvd_prod ha1) }, end lemma prime.not_dvd_prod {p : M} {L : list M} (pp : prime p) (hL : ∀ a ∈ L, ¬ p ∣ a) : ¬ p ∣ L.prod := mt (prime.dvd_prod_iff pp).mp $ not_bex.mpr hL end comm_monoid_with_zero section cancel_comm_monoid_with_zero variables {M : Type*} [cancel_comm_monoid_with_zero M] [unique (units M)] lemma mem_list_primes_of_dvd_prod {p : M} (hp : prime p) {L : list M} (hL : ∀ q ∈ L, prime q) (hpL : p ∣ L.prod) : p ∈ L := begin obtain ⟨x, hx1, hx2⟩ := hp.dvd_prod_iff.mp hpL, rwa (prime_dvd_prime_iff_eq hp (hL x hx1)).mp hx2 end lemma perm_of_prod_eq_prod : ∀ {l₁ l₂ : list M}, l₁.prod = l₂.prod → (∀ p ∈ l₁, prime p) → (∀ p ∈ l₂, prime p) → perm l₁ l₂ | [] [] _ _ _ := perm.nil | [] (a :: l) h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil M _ ▸ h₁.symm ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₃ a (mem_cons_self _ _))) | (a :: l) [] h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil M _ ▸ h₁ ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₂ a (mem_cons_self _ _))) | (a :: l₁) (b :: l₂) h hl₁ hl₂ := begin classical, have hl₁' : ∀ p ∈ l₁, prime p := λ p hp, hl₁ p (mem_cons_of_mem _ hp), have hl₂' : ∀ p ∈ (b :: l₂).erase a, prime p := λ p hp, hl₂ p (mem_of_mem_erase hp), have ha : a ∈ (b :: l₂) := mem_list_primes_of_dvd_prod (hl₁ a (mem_cons_self _ _)) hl₂ (h ▸ by rw prod_cons; exact dvd_mul_right _ _), have hb : b :: l₂ ~ a :: (b :: l₂).erase a := perm_cons_erase ha, have hl : prod l₁ = prod ((b :: l₂).erase a) := ((mul_right_inj' (hl₁ a (mem_cons_self _ _)).ne_zero).1 $ by rwa [← prod_cons, ← prod_cons, ← hb.prod_eq]), exact perm.trans ((perm_of_prod_eq_prod hl hl₁' hl₂').cons _) hb.symm end end cancel_comm_monoid_with_zero
759908d8604fe0a2889c76547dacb4f85f72a01a
12dabd587ce2621d9a4eff9f16e354d02e206c8e
/world04/level07.lean
687805fe896cd58a7a4ffc46862db438ccb2e606
[]
no_license
abdelq/natural-number-game
a1b5b8f1d52625a7addcefc97c966d3f06a48263
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
refs/heads/master
1,668,606,478,691
1,594,175,058,000
1,594,175,058,000
278,673,209
0
1
null
null
null
null
UTF-8
Lean
false
false
175
lean
lemma pow_pow (a m n : mynat) : (a ^ m) ^ n = a ^ (m * n) := begin induction n with h hd, rw mul_zero, repeat {rw pow_zero}, rw pow_succ, rw hd, rw mul_succ, rwa pow_add, end
24840f1cecf4011573d16f5089d32c3713869265
46125763b4dbf50619e8846a1371029346f4c3db
/src/analysis/convex/basic.lean
fbd8087f9aafb70cf4155b9c2fb58f728f9758e0
[ "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
37,468
lean
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudriashov -/ import data.complex.basic import data.set.intervals import tactic.interactive import tactic.linarith import linear_algebra.basic import ring_theory.algebra import algebra.pointwise /-! # Convex sets and functions on real vector spaces In a real vector space, we define the following objects and properties. * `segment x y` is the closed segment joining `x` and `y`. * A set `s` is `convex` if for any two points `x y ∈ s` it includes `segment x y`; * A function `f` is `convex_on` a set `s` if `s` is itself a convex set, and for any two points `x y ∈ s` the segment joining `(x, f x)` to `(y, f y)` is (non-strictly) above the graph of `f`; equivalently, `convex_on f s` means that the epigraph `{p : E × ℝ | p.1 ∈ s ∧ f p.1 ≤ p.2}` is a convex set; * Center mass of a finite set of points with prescribed weights. * Convex hull of a set `s` is the minimal convex set that includes `s`. * Standard simplex `std_simplex ι [fintype ι]` is the intersection of the positive quadrant with the hyperplane `s.sum = 1` in the space `ι → ℝ`. We also provide various equivalent versions of the definitions above, prove that some specific sets are convex, and prove Jensen's inequality. ## Notations We use the following local notations: * `I = Icc (0:ℝ) 1`; * `[x, y] = segment x y`. They are defined using `local notation`, so they are not available outside of this file. -/ universes u' u v w x variables {E : Type u} {F : Type v} {ι : Type w} {ι' : Type x} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] {s : set E} open set open_locale classical local notation `I` := (Icc 0 1 : set ℝ) local attribute [instance] set.pointwise_add set.smul_set section sets /-! ### Segment -/ /-- Segments in a vector space -/ def segment (x y : E) : set E := {z : E | ∃ (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), a • x + b • y = z} local notation `[`x `, ` y `]` := segment x y lemma segment_symm (x y : E) : [x, y] = [y, x] := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ lemma left_mem_segment (x y : E) : x ∈ [x, y] := ⟨1, 0, zero_le_one, le_refl 0, add_zero 1, by rw [zero_smul, one_smul, add_zero]⟩ lemma right_mem_segment (x y : E) : y ∈ [x, y] := segment_symm y x ▸ left_mem_segment y x lemma segment_same (x : E) : [x, x] = {x} := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [(add_smul _ _ _).symm, mem_singleton_iff, hab, one_smul, eq_comm] using hz, λ h, mem_singleton_iff.1 h ▸ left_mem_segment z z⟩ lemma segment_eq_image (x y : E) : segment x y = (λ (θ : ℝ), (1 - θ) • x + θ • y) '' I := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab ▸ le_add_of_nonneg_left ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩, λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1-θ, θ, sub_nonneg.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩ lemma segment_eq_image' (x y : E) : segment x y = (λ (θ : ℝ), x + θ • (y - x)) '' I := by { convert segment_eq_image x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel } lemma segment_eq_image₂ (x y : E) : segment x y = (λ p:ℝ×ℝ, p.1 • x + p.2 • y) '' {p | 0 ≤ p.1 ∧ 0 ≤ p.2 ∧ p.1 + p.2 = 1} := by simp only [segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] lemma segment_eq_Icc {a b : ℝ} (h : a ≤ b) : [a, b] = Icc a b := begin rw [segment_eq_image'], show (((+) a) ∘ (λ t, t * (b - a))) '' Icc 0 1 = Icc a b, rw [image_comp, image_mul_right_Icc (@zero_le_one ℝ _) (sub_nonneg.2 h), image_add_left_Icc], simp end lemma segment_eq_Icc' (a b : ℝ) : [a, b] = Icc (min a b) (max a b) := by cases le_total a b; [skip, rw segment_symm]; simp [segment_eq_Icc, *] lemma segment_eq_interval (a b : ℝ) : segment a b = interval a b := segment_eq_Icc' _ _ lemma mem_segment_translate (a : E) {x b c} : a + x ∈ [a + b, a + c] ↔ x ∈ [b, c] := begin rw [segment_eq_image', segment_eq_image'], refine exists_congr (λ θ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_left_inj] end lemma segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' [a + b, a + c] = [b, c] := set.ext $ λ x, mem_segment_translate a lemma segment_translate_image (a b c: E) : (λx, a + x) '' [b, c] = [a + b, a + c] := segment_translate_preimage a b c ▸ image_preimage_eq $ add_left_surjective a /-! ### Convexity of sets -/ /-- Convexity of sets -/ def convex (s : set E) := ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • x + b • y ∈ s lemma convex_iff_segment_subset : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → [x, y] ⊆ s := by simp only [convex, segment_eq_image₂, subset_def, ball_image_iff, prod.forall, mem_set_of_eq, and_imp] lemma convex.segment_subset (h : convex s) {x y:E} (hx : x ∈ s) (hy : y ∈ s) : [x, y] ⊆ s := convex_iff_segment_subset.1 h hx hy /-- Alternative definition of set convexity, in terms of pointwise set operations. -/ lemma convex_iff_pointwise_add_subset: convex s ↔ ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • s + b • s ⊆ s := iff.intro begin rintros hA a b ha hb hab w ⟨au, ⟨u, hu, rfl⟩, bv, ⟨v, hv, rfl⟩, rfl⟩, exact hA hu hv ha hb hab end (λ h x y hx hy a b ha hb hab, (h ha hb hab) (set.add_mem_pointwise_add ⟨_, hx, rfl⟩ ⟨_, hy, rfl⟩)) /-- Alternative definition of set convexity, using division -/ lemma convex_iff_div: convex s ↔ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • x + (b/(a+b)) • y ∈ s := ⟨begin assume h x y hx hy a b ha hb hab, apply h hx hy, have ha', from mul_le_mul_of_nonneg_left ha (le_of_lt (inv_pos hab)), rwa [mul_zero, ←div_eq_inv_mul] at ha', have hb', from mul_le_mul_of_nonneg_left hb (le_of_lt (inv_pos hab)), rwa [mul_zero, ←div_eq_inv_mul] at hb', rw [←add_div], exact div_self (ne_of_lt hab).symm end, begin assume h x y hx hy a b ha hb hab, have h', from h hx hy ha hb, rw [hab, div_one, div_one] at h', exact h' zero_lt_one end⟩ /-! ### Examples of convex sets -/ lemma convex_empty : convex (∅ : set E) := by finish lemma convex_singleton (c : E) : convex ({c} : set E) := begin intros x y hx hy a b ha hb hab, rw [set.eq_of_mem_singleton hx, set.eq_of_mem_singleton hy, ←add_smul, hab, one_smul], exact mem_singleton c end lemma convex_univ : convex (set.univ : set E) := λ _ _ _ _ _ _ _ _ _, trivial lemma convex.inter {t : set E} (hs: convex s) (ht: convex t) : convex (s ∩ t) := λ x y (hx : x ∈ s ∩ t) (hy : y ∈ s ∩ t) a b (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), ⟨hs hx.left hy.left ha hb hab, ht hx.right hy.right ha hb hab⟩ lemma convex_sInter {S : set (set E)} (h : ∀ s ∈ S, convex s) : convex (⋂₀ S) := assume x y hx hy a b ha hb hab s hs, h s hs (hx s hs) (hy s hs) ha hb hab lemma convex_Inter {ι : Sort*} {s: ι → set E} (h: ∀ i : ι, convex (s i)) : convex (⋂ i, s i) := (sInter_range s) ▸ convex_sInter $ forall_range_iff.2 h lemma convex.prod {s : set E} {t : set F} (hs : convex s) (ht : convex t) : convex (s.prod t) := begin intros x y hx hy a b ha hb hab, apply mem_prod.2, exact ⟨hs (mem_prod.1 hx).1 (mem_prod.1 hy).1 ha hb hab, ht (mem_prod.1 hx).2 (mem_prod.1 hy).2 ha hb hab⟩ end lemma convex.is_linear_image (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (f '' s) := begin rintros _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩ a b ha hb hab, exact ⟨a • x + b • y, hs hx hy ha hb hab, by simp only [hf.add,hf.smul]⟩ end lemma convex.linear_image (hs : convex s) (f : E →ₗ[ℝ] F) : convex (image f s) := hs.is_linear_image f.is_linear lemma convex.is_linear_preimage {s : set F} (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (preimage f s) := begin intros x y hx hy a b ha hb hab, convert hs hx hy ha hb hab, simp only [mem_preimage, hf.add, hf.smul] end lemma convex.linear_preimage {s : set F} (hs : convex s) (f : E →ₗ[ℝ] F) : convex (preimage f s) := hs.is_linear_preimage f.is_linear lemma convex.neg (hs : convex s) : convex ((λ z, -z) '' s) := hs.is_linear_image is_linear_map.is_linear_map_neg lemma convex.neg_preimage (hs : convex s) : convex ((λ z, -z) ⁻¹' s) := hs.is_linear_preimage is_linear_map.is_linear_map_neg lemma convex.smul (c : ℝ) (hs : convex s) : convex (c • s) := begin rw smul_set_eq_image, exact hs.is_linear_image (is_linear_map.is_linear_map_smul c) end lemma convex.smul_preimage (c : ℝ) (hs : convex s) : convex ((λ z, c • z) ⁻¹' s) := hs.is_linear_preimage (is_linear_map.is_linear_map_smul c) lemma convex.add {t : set E} (hs : convex s) (ht : convex t) : convex (s + t) := by { rw pointwise_add_eq_image, exact (hs.prod ht).is_linear_image is_linear_map.is_linear_map_add } lemma convex.sub {t : set E} (hs : convex s) (ht : convex t) : convex ((λx : E × E, x.1 - x.2) '' (s.prod t)) := (hs.prod ht).is_linear_image is_linear_map.is_linear_map_sub lemma convex.translate (hs : convex s) (z : E) : convex ((λx, z + x) '' s) := begin convert (convex_singleton z).add hs, ext x, simp [set.mem_image, mem_pointwise_add, eq_comm] end lemma convex.affinity (hs : convex s) (z : E) (c : ℝ) : convex ((λx, z + c • x) '' s) := begin convert (hs.smul c).translate z using 1, erw [smul_set_eq_image, ←image_comp] end lemma convex_real_iff {s : set ℝ} : convex s ↔ ∀ {x y}, x ∈ s → y ∈ s → Icc x y ⊆ s := begin simp only [convex_iff_segment_subset, segment_eq_Icc'], split; intros h x y hx hy, { cases le_or_lt x y with hxy hxy, { simpa [hxy] using h hx hy }, { simp [hxy] } }, { apply h; cases le_total x y; simp [*] } end lemma convex_Iio (r : ℝ) : convex (Iio r) := convex_real_iff.2 $ λ x y hx hy z hz, lt_of_le_of_lt hz.2 hy lemma convex_Ioi (r : ℝ) : convex (Ioi r) := convex_real_iff.2 $ λ x y hx hy z hz, lt_of_lt_of_le hx hz.1 lemma convex_Iic (r : ℝ) : convex (Iic r) := convex_real_iff.2 $ λ x y hx hy z hz, le_trans hz.2 hy lemma convex_Ici (r : ℝ) : convex (Ici r) := convex_real_iff.2 $ λ x y hx hy z hz, le_trans hx hz.1 lemma convex_Ioo (r : ℝ) (s : ℝ) : convex (Ioo r s) := (convex_Ioi _).inter (convex_Iio _) lemma convex_Ico (r : ℝ) (s : ℝ) : convex (Ico r s) := (convex_Ici _).inter (convex_Iio _) lemma convex_Ioc (r : ℝ) (s : ℝ) : convex (Ioc r s) := (convex_Ioi _).inter (convex_Iic _) lemma convex_Icc (r : ℝ) (s : ℝ) : convex (Icc r s) := (convex_Ici _).inter (convex_Iic _) lemma convex_segment (a b : E) : convex [a, b] := begin have : (λ (t : ℝ), a + t • (b - a)) = (λz : E, a + z) ∘ (λt:ℝ, t • (b - a)) := rfl, rw [segment_eq_image', this, image_comp], refine ((convex_Icc _ _).is_linear_image _).translate _, exact is_linear_map.is_linear_map_smul' _ end lemma convex_halfspace_lt {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w < r} := (convex_Iio r).is_linear_preimage h lemma convex_halfspace_le {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w ≤ r} := (convex_Iic r).is_linear_preimage h lemma convex_halfspace_gt {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r < f w} := (convex_Ioi r).is_linear_preimage h lemma convex_halfspace_ge {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r ≤ f w} := (convex_Ici r).is_linear_preimage h lemma convex_hyperplane {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w = r} := begin show convex (f ⁻¹' {p | p = r}), rw set_of_eq_eq_singleton, exact (convex_singleton r).is_linear_preimage h end lemma convex_halfspace_re_lt (r : ℝ) : convex {c : ℂ | c.re < r} := convex_halfspace_lt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_le (r : ℝ) : convex {c : ℂ | c.re ≤ r} := convex_halfspace_le (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_gt (r : ℝ) : convex {c : ℂ | r < c.re } := convex_halfspace_gt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_lge (r : ℝ) : convex {c : ℂ | r ≤ c.re} := convex_halfspace_ge (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_im_lt (r : ℝ) : convex {c : ℂ | c.im < r} := convex_halfspace_lt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_le (r : ℝ) : convex {c : ℂ | c.im ≤ r} := convex_halfspace_le (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_gt (r : ℝ) : convex {c : ℂ | r < c.im } := convex_halfspace_gt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_lge (r : ℝ) : convex {c : ℂ | r ≤ c.im} := convex_halfspace_ge (is_linear_map.mk complex.add_im complex.smul_im) _ section submodule open submodule lemma submodule.convex (K : submodule ℝ E) : convex (↑K : set E) := by { repeat {intro}, refine add_mem _ (smul_mem _ _ _) (smul_mem _ _ _); assumption } lemma subspace.convex (K : subspace ℝ E) : convex (↑K : set E) := K.convex end submodule end sets section functions local notation `[`x `, ` y `]` := segment x y /-! ### Convex functions -/ /-- Convexity of functions -/ def convex_on (s : set E) (f : E → ℝ) : Prop := convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → f (a • x + b • y) ≤ a * f x + b * f y variables {t : set E} {f g : E → ℝ} lemma convex_on_iff_div: convex_on s f ↔ convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → f ((a/(a+b)) • x + (b/(a+b)) • y) ≤ (a/(a+b)) * f x + (b/(a+b)) * f y := and_congr iff.rfl ⟨begin intros h x y hx hy a b ha hb hab, apply h hx hy (div_nonneg ha hab) (div_nonneg hb hab), rw [←add_div], exact div_self (ne_of_gt hab) end, begin intros h x y hx hy a b ha hb hab, simpa [hab, zero_lt_one] using h hx hy ha hb, end⟩ /-- For a function on a convex set in a linear ordered space, in order to prove that it is convex it suffices to verify the inequality `f (a • x + b • y) ≤ a * f x + b * f y` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.convex_on_of_lt [linear_order E] (hs : convex s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → f (a • x + b • y) ≤ a * f x + b * f y) : convex_on s f := begin use hs, intros x y hx hy a b ha hb hab, wlog hxy : x<=y using [x y a b, y x b a], { exact le_total _ _ }, { cases eq_or_lt_of_le hxy with hxy hxy, by { subst y, rw [← add_smul, ← add_mul, hab, one_smul, one_mul] }, cases eq_or_lt_of_le ha with ha ha, by { subst a, rw [zero_add] at hab, subst b, simp }, cases eq_or_lt_of_le hb with hb hb, by { subst b, rw [add_zero] at hab, subst a, simp }, exact hf hx hy hxy ha hb hab } end /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is convex on `D`. This way of proving convexity of a function is used in the proof of convexity of a function with a monotone derivative. -/ lemma convex_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} (hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f y - f x) / (y - x) ≤ (f z - f y) / (z - y)) : convex_on s f := linear_order.convex_on_of_lt hs begin assume x z hx hz hxz a b ha hb hab, let y := a * x + b * z, have hxy : x < y, { rw [← one_mul x, ← hab, add_mul], exact add_lt_add_left ((mul_lt_mul_left hb).2 hxz) _ }, have hyz : y < z, { rw [← one_mul z, ← hab, add_mul], exact add_lt_add_right ((mul_lt_mul_left ha).2 hxz) _ }, have : (f y - f x) * (z - y) ≤ (f z - f y) * (y - x), from (div_le_div_iff (sub_pos.2 hxy) (sub_pos.2 hyz)).1 (hf hx hz hxy hyz), have A : z - y + (y - x) = z - x, by abel, have B : 0 < z - x, from sub_pos.2 (lt_trans hxy hyz), rw [sub_mul, sub_mul, sub_le_iff_le_add', ← add_sub_assoc, le_sub_iff_add_le, ← mul_add, A, ← le_div_iff B, add_div, mul_div_assoc, mul_div_assoc, mul_comm (f x), mul_comm (f z)] at this, rw [eq_comm, ← sub_eq_iff_eq_add] at hab; subst a, convert this; symmetry; simp only [div_eq_iff (ne_of_gt B), y]; ring end lemma convex_on.subset (h_convex_on : convex_on t f) (h_subset : s ⊆ t) (h_convex : convex s) : convex_on s f := begin apply and.intro h_convex, intros x y hx hy, exact h_convex_on.2 (h_subset hx) (h_subset hy), end lemma convex_on.add (hf : convex_on s f) (hg : convex_on s g) : convex_on s (λx, f x + g x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc f (a • x + b • y) + g (a • x + b • y) ≤ (a * f x + b * f y) + (a * g x + b * g y) : add_le_add (hf.2 hx hy ha hb hab) (hg.2 hx hy ha hb hab) ... = a * f x + a * g x + b * f y + b * g y : by linarith ... = a * (f x + g x) + b * (f y + g y) : by simp [mul_add] end lemma convex_on.smul {c : ℝ} (hc : 0 ≤ c) (hf : convex_on s f) : convex_on s (λx, c * f x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc c * f (a • x + b • y) ≤ c * (a * f x + b * f y) : mul_le_mul_of_nonneg_left (hf.2 hx hy ha hb hab) hc ... = a * (c * f x) + b * (c * f y) : by rw mul_add; ac_refl end lemma convex_on.le_on_segment' {x y : E} {a b : ℝ} (hf : convex_on s f) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : f (a • x + b • y) ≤ max (f x) (f y) := calc f (a • x + b • y) ≤ a * f x + b * f y : hf.2 hx hy ha hb hab ... ≤ a * max (f x) (f y) + b * max (f x) (f y) : add_le_add (mul_le_mul_of_nonneg_left (le_max_left _ _) ha) (mul_le_mul_of_nonneg_left (le_max_right _ _) hb) ... ≤ max (f x) (f y) : by rw [←add_mul, hab, one_mul] lemma convex_on.le_on_segment (hf : convex_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x, y]) : f z ≤ max (f x) (f y) := let ⟨a, b, ha, hb, hab, hz⟩ := hz in hz ▸ hf.le_on_segment' hx hy ha hb hab lemma convex_on.convex_le (hf : convex_on s f) (r : ℝ) : convex {x ∈ s | f x ≤ r} := convex_iff_segment_subset.2 $ λ x y hx hy z hz, ⟨hf.1.segment_subset hx.1 hy.1 hz, le_trans (hf.le_on_segment hx.1 hy.1 hz) $ max_le hx.2 hy.2⟩ lemma convex_on.convex_lt (hf : convex_on s f) (r : ℝ) : convex {x ∈ s | f x < r} := convex_iff_segment_subset.2 $ λ x y hx hy z hz, ⟨hf.1.segment_subset hx.1 hy.1 hz, lt_of_le_of_lt (hf.le_on_segment hx.1 hy.1 hz) $ max_lt hx.2 hy.2⟩ lemma convex_on.convex_epigraph (hf : convex_on s f) : convex {p : E × ℝ | p.1 ∈ s ∧ f p.1 ≤ p.2} := begin rintros ⟨x, r⟩ ⟨y, t⟩ ⟨hx, hr⟩ ⟨hy, ht⟩ a b ha hb hab, refine ⟨hf.1 hx hy ha hb hab, _⟩, calc f (a • x + b • y) ≤ a * f x + b * f y : hf.2 hx hy ha hb hab ... ≤ a * r + b * t : add_le_add (mul_le_mul_of_nonneg_left hr ha) (mul_le_mul_of_nonneg_left ht hb) end lemma convex_on_iff_convex_epigraph : convex_on s f ↔ convex {p : E × ℝ | p.1 ∈ s ∧ f p.1 ≤ p.2} := begin refine ⟨convex_on.convex_epigraph, λ h, ⟨_, _⟩⟩, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).1 }, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).2 } end end functions section center_mass /-- Center mass of a finite collection of points with prescribed weights. Note that we require neither `0 ≤ w i` nor `∑ w = 1`. -/ noncomputable def finset.center_mass (t : finset ι) (w : ι → ℝ) (z : ι → E) : E := (t.sum w)⁻¹ • (t.sum (λ i, w i • z i)) variables (i j : ι) (c : ℝ) (t : finset ι) (w : ι → ℝ) (z : ι → E) open finset (hiding singleton) lemma finset.center_mass_empty : (∅ : finset ι).center_mass w z = 0 := by simp only [center_mass, sum_empty, smul_zero] lemma finset.center_mass_pair (hne : i ≠ j) : ({i, j} : finset ι).center_mass w z = (w i / (w i + w j)) • z i + (w j / (w i + w j)) • z j := by simp only [center_mass, sum_pair hne, smul_add, (mul_smul _ _ _).symm, div_eq_inv_mul] variable {w} lemma finset.center_mass_insert (ha : i ∉ t) (hw : t.sum w ≠ 0) : (insert i t).center_mass w z = (w i / (w i + t.sum w)) • z i + (t.sum w / (w i + t.sum w)) • t.center_mass w z := begin simp only [center_mass, sum_insert ha, smul_add, (mul_smul _ _ _).symm], congr' 2, { apply mul_comm }, { rw [div_mul_eq_mul_div, mul_inv_cancel hw, one_div_eq_inv] } end lemma finset.center_mass_singleton (hw : w i ≠ 0) : (finset.singleton i).center_mass w z = z i := by rw [center_mass, sum_singleton, sum_singleton, ← mul_smul, inv_mul_cancel hw, one_smul] lemma finset.center_mass_eq_of_sum_1 (hw : t.sum w = 1) : t.center_mass w z = t.sum (λ i, w i • z i) := by simp only [finset.center_mass, hw, inv_one, one_smul] lemma finset.center_mass_smul : t.center_mass w (λ i, c • z i) = c • t.center_mass w z := by simp only [finset.center_mass, finset.smul_sum, (mul_smul _ _ _).symm, mul_comm c, mul_assoc] /-- A convex combination of two centers of mass is a center of mass as well. This version deals with two different index types. -/ lemma finset.center_mass_segment' (s : finset ι) (t : finset ι') (ws : ι → ℝ) (zs : ι → E) (wt : ι' → ℝ) (zt : ι' → E) (hws : s.sum ws = 1) (hwt : t.sum wt = 1) (a b : ℝ) (hab : a + b = 1): a • s.center_mass ws zs + b • t.center_mass wt zt = (s.image sum.inl ∪ t.image sum.inr).center_mass (sum.elim (λ i, a * ws i) (λ j, b * wt j)) (sum.elim zs zt) := begin rw [s.center_mass_eq_of_sum_1 _ hws, t.center_mass_eq_of_sum_1 _ hwt, smul_sum, smul_sum, ← finset.sum_sum_elim, finset.center_mass_eq_of_sum_1], { congr, ext i, cases i; simp only [sum.elim_inl, sum.elim_inr, mul_smul] }, { rw [sum_sum_elim, ← mul_sum, ← mul_sum, hws, hwt, mul_one, mul_one, hab] } end /-- A convex combination of two centers of mass is a center of mass as well. This version works if two centers of mass share the set of original points. -/ lemma finset.center_mass_segment (s : finset ι) (w₁ w₂ : ι → ℝ) (z : ι → E) (hw₁ : s.sum w₁ = 1) (hw₂ : s.sum w₂ = 1) (a b : ℝ) (hab : a + b = 1): a • s.center_mass w₁ z + b • s.center_mass w₂ z = s.center_mass (λ i, a * w₁ i + b * w₂ i) z := have hw : s.sum (λ i, a * w₁ i + b * w₂ i) = 1, by simp only [mul_sum.symm, sum_add_distrib, mul_one, *], by simp only [finset.center_mass_eq_of_sum_1, smul_sum, sum_add_distrib, add_smul, mul_smul, *] lemma finset.center_mass_ite_eq (hi : i ∈ t) : t.center_mass (λ j, if (i = j) then 1 else 0) z = z i := begin rw [finset.center_mass_eq_of_sum_1], transitivity t.sum (λ j, if (i = j) then z i else 0), { congr, ext i, split_ifs, exacts [h ▸ one_smul _ _, zero_smul _ _] }, { rw [sum_ite_eq, if_pos hi] }, { rw [sum_ite_eq, if_pos hi] } end variables {t w} lemma finset.center_mass_subset {t' : finset ι} (ht : t ⊆ t') (h : ∀ i ∈ t', i ∉ t → w i = 0) : t.center_mass w z = t'.center_mass w z := begin rw [center_mass, sum_subset ht h, smul_sum, center_mass, smul_sum], apply sum_subset ht, assume i hit' hit, rw [h i hit' hit, zero_smul, smul_zero] end lemma finset.center_mass_filter_ne_zero : (t.filter (λ i, w i ≠ 0)).center_mass w z = t.center_mass w z := finset.center_mass_subset z (filter_subset _) $ λ i hit hit', by simpa only [hit, mem_filter, true_and, ne.def, not_not] using hit' variable {z} /-- Center mass of a finite subset of a convex set belongs to the set provided that all weights are non-negative, and the total weight is positive. -/ lemma convex.center_mass_mem (hs : convex s) : (∀ i ∈ t, 0 ≤ w i) → (0 < t.sum w) → (∀ i ∈ t, z i ∈ s) → t.center_mass w z ∈ s := begin refine finset.induction (by simp [lt_irrefl]) (λ i t hi ht h₀ hpos hmem, _) t, have zi : z i ∈ s, from hmem _ (mem_insert_self _ _), have hs₀ : ∀ j ∈ t, 0 ≤ w j, from λ j hj, h₀ j $ mem_insert_of_mem hj, rw [sum_insert hi] at hpos, by_cases hsum_t : t.sum w = 0, { have ws : ∀ j ∈ t, w j = 0, from (sum_eq_zero_iff_of_nonneg hs₀).1 hsum_t, have wz : t.sum (λ j, w j • z j) = 0, from sum_eq_zero (λ i hi, by simp [ws i hi]), simp only [center_mass, sum_insert hi, wz, hsum_t, add_zero], simp only [hsum_t, add_zero] at hpos, rw [← mul_smul, inv_mul_cancel (ne_of_gt hpos), one_smul], exact zi }, { rw [finset.center_mass_insert _ _ _ hi hsum_t], refine convex_iff_div.1 hs zi (ht hs₀ _ _) _ (sum_nonneg hs₀) hpos, { exact lt_of_le_of_ne (sum_nonneg hs₀) (ne.symm hsum_t) }, { intros j hj, exact hmem j (mem_insert_of_mem hj) }, { exact h₀ _ (mem_insert_self _ _) } } end lemma convex.sum_mem (hs : convex s) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : t.sum w = 1) (hz : ∀ i ∈ t, z i ∈ s) : t.sum (λ i, w i • z i) ∈ s := by simpa only [h₁, center_mass, inv_one, one_smul] using hs.center_mass_mem h₀ (h₁.symm ▸ zero_lt_one) hz lemma convex_iff_sum_mem : convex s ↔ (∀ (t : finset E) (w : E → ℝ), (∀ i ∈ t, 0 ≤ w i) → t.sum w = 1 → (∀ x ∈ t, x ∈ s) → t.sum (λx, w x • x) ∈ s ) := begin refine ⟨λ hs t w hw₀ hw₁ hts, hs.sum_mem hw₀ hw₁ hts, _⟩, intros h x y hx hy a b ha hb hab, by_cases h_cases: x = y, { rw [h_cases, ←add_smul, hab, one_smul], exact hy }, { convert h {x, y} (λ z, if z = y then b else a) _ _ _, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl] }, { simp_intros i hi, cases hi; subst i; simp [ha, hb, if_neg h_cases] }, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl, hab] }, { simp_intros i hi, cases hi; subst i; simp [hx, hy, if_neg h_cases] } } end /-- Jensen's inequality, `finset.center_mass` version. -/ lemma convex_on.map_center_mass_le {f : E → ℝ} (hf : convex_on s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (hpos : 0 < t.sum w) (hmem : ∀ i ∈ t, z i ∈ s) : f (t.center_mass w z) ≤ t.center_mass w (f ∘ z) := begin have hmem' : ∀ i ∈ t, (z i, (f ∘ z) i) ∈ {p : E × ℝ | p.1 ∈ s ∧ f p.1 ≤ p.2}, from λ i hi, ⟨hmem i hi, le_refl _⟩, convert (hf.convex_epigraph.center_mass_mem h₀ hpos hmem').2; simp only [center_mass, function.comp, prod.smul_fst, prod.fst_sum, prod.smul_snd, prod.snd_sum] end /-- Jensen's inequality, `finset.sum` version. -/ lemma convex_on.map_sum_le {f : E → ℝ} (hf : convex_on s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : t.sum w = 1) (hmem : ∀ i ∈ t, z i ∈ s) : f (t.sum (λ i, w i • z i)) ≤ t.sum (λ i, w i * (f (z i))) := by simpa only [center_mass, h₁, inv_one, one_smul] using hf.map_center_mass_le h₀ (h₁.symm ▸ zero_lt_one) hmem /-- If a function `f` is convex on `s` takes value `y` at the center mass of some points `z i ∈ s`, then for some `i` we have `y ≤ f (z i)`. -/ lemma convex_on.exists_ge_of_center_mass {f : E → ℝ} (h : convex_on s f) (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hws : 0 < t.sum w) (hz : ∀ i ∈ t, z i ∈ s) : ∃ i ∈ t, f (t.center_mass w z) ≤ f (z i) := begin set y := t.center_mass w z, have : f y ≤ t.center_mass w (f ∘ z) := h.map_center_mass_le hw₀ hws hz, rw ← sum_filter_ne_zero at hws, rw [← finset.center_mass_filter_ne_zero (f ∘ z), center_mass, smul_eq_mul, ← div_eq_inv_mul, le_div_iff hws, mul_sum] at this, replace : ∃ i ∈ t.filter (λ i, w i ≠ 0), f y * w i ≤ w i • (f ∘ z) i := exists_le_of_sum_le (nonempty_of_sum_ne_zero (ne_of_gt hws)) this, rcases this with ⟨i, hi, H⟩, rw [mem_filter] at hi, use [i, hi.1], simp only [smul_eq_mul, mul_comm (w i)] at H, refine (mul_le_mul_right _).1 H, exact lt_of_le_of_ne (hw₀ i hi.1) hi.2.symm end end center_mass section convex_hull variable {t : set E} /-- Convex hull of a set `s` is the minimal convex set that includes `s` -/ def convex_hull (s : set E) : set E := ⋂ (t : set E) (hst : s ⊆ t) (ht : convex t), t variable (s) lemma subset_convex_hull : s ⊆ convex_hull s := set.subset_Inter $ λ t, set.subset_Inter $ λ hst, set.subset_Inter $ λ ht, hst lemma convex_convex_hull : convex (convex_hull s) := convex_Inter $ λ t, convex_Inter $ λ ht, convex_Inter id variable {s} lemma convex_hull_min (hst : s ⊆ t) (ht : convex t) : convex_hull s ⊆ t := set.Inter_subset_of_subset t $ set.Inter_subset_of_subset hst $ set.Inter_subset _ ht lemma convex_hull_mono (hst : s ⊆ t) : convex_hull s ⊆ convex_hull t := convex_hull_min (set.subset.trans hst $ subset_convex_hull t) (convex_convex_hull t) lemma convex.convex_hull_eq {s : set E} (hs : convex s) : convex_hull s = s := set.subset.antisymm (convex_hull_min (set.subset.refl _) hs) (subset_convex_hull s) lemma is_linear_map.image_convex_hull {f : E → F} (hf : is_linear_map ℝ f) : f '' (convex_hull s) = convex_hull (f '' s) := begin refine set.subset.antisymm _ _, { rw [set.image_subset_iff], exact convex_hull_min (set.image_subset_iff.1 $ subset_convex_hull $ f '' s) ((convex_convex_hull (f '' s)).is_linear_preimage hf) }, { exact convex_hull_min (set.image_subset _ $ subset_convex_hull s) ((convex_convex_hull s).is_linear_image hf) } end lemma linear_map.image_convex_hull (f : E →ₗ[ℝ] F) : f '' (convex_hull s) = convex_hull (f '' s) := f.is_linear.image_convex_hull lemma finset.center_mass_mem_convex_hull (t : finset ι) {w : ι → ℝ} (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hws : 0 < t.sum w) {z : ι → E} (hz : ∀ i ∈ t, z i ∈ s) : t.center_mass w z ∈ convex_hull s := (convex_convex_hull s).center_mass_mem hw₀ hws (λ i hi, subset_convex_hull s $ hz i hi) -- TODO : Do we need other versions of the next lemma? /-- Convex hull of `s` is equal to the set of all centers of masses of `finset`s `t`, `z '' t ⊆ s`. This version allows finsets in any type in any universe. -/ lemma convex_hull_eq (s : set E) : convex_hull s = {x : E | ∃ (ι : Type u') (t : finset ι) (w : ι → ℝ) (z : ι → E) (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hw₁ : t.sum w = 1) (hz : ∀ i ∈ t, z i ∈ s) , t.center_mass w z = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, use [punit, finset.singleton punit.star, λ _, 1, λ _, x, λ _ _, zero_le_one, finset.sum_singleton, λ _ _, hx], simp only [finset.center_mass, finset.sum_singleton, inv_one, one_smul] }, { rintros x y ⟨ι, sx, wx, zx, hwx₀, hwx₁, hzx, rfl⟩ ⟨ι', sy, wy, zy, hwy₀, hwy₁, hzy, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment' _ _ _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, _, _, _, _, rfl⟩, { rintros i hi, rw [finset.mem_union, finset.mem_image, finset.mem_image] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; simp only [sum.elim_inl, sum.elim_inr]; apply_rules [mul_nonneg, hwx₀, hwy₀] }, { simp [finset.sum_sum_elim, finset.mul_sum.symm, *] }, { intros i hi, rw [finset.mem_union, finset.mem_image, finset.mem_image] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; simp only [sum.elim_inl, sum.elim_inr]; apply_rules [hzx, hzy] } }, { rintros _ ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩, exact t.center_mass_mem_convex_hull hw₀ (hw₁.symm ▸ zero_lt_one) hz } end /-- Maximum principle for convex functions. If a function `f` is convex on the convex hull of `s`, then `f` can't have a maximum on `convex_hull s` outside of `s`. -/ lemma convex_on.exists_ge_of_mem_convex_hull {f : E → ℝ} (hf : convex_on (convex_hull s) f) {x} (hx : x ∈ convex_hull s) : ∃ y ∈ s, f x ≤ f y := begin rw convex_hull_eq at hx, rcases hx with ⟨α, t, w, z, hw₀, hw₁, hz, rfl⟩, rcases hf.exists_ge_of_center_mass hw₀ (hw₁.symm ▸ zero_lt_one) (λ i hi, subset_convex_hull s (hz i hi)) with ⟨i, hit, Hi⟩, exact ⟨z i, hz i hit, Hi⟩ end lemma set.finite.convex_hull_eq {s : set E} (hs : finite s) : convex_hull s = {x : E | ∃ (w : E → ℝ) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : hs.to_finset.sum w = 1), hs.to_finset.center_mass w id = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, replace hx : x ∈ hs.to_finset, from finite.mem_to_finset.2 hx, refine ⟨_, _, _, finset.center_mass_ite_eq _ _ _ hx⟩, { intros, split_ifs, exacts [zero_le_one, le_refl 0] }, { rw [finset.sum_ite_eq, if_pos hx] } }, { rintros x y ⟨wx, hwx₀, hwx₁, rfl⟩ ⟨wy, hwy₀, hwy₁, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, rfl⟩, { rintros i hi, apply_rules [add_nonneg, mul_nonneg, hwx₀, hwy₀], }, { simp only [finset.sum_add_distrib, finset.mul_sum.symm, mul_one, *] } }, { rintros _ ⟨w, hw₀, hw₁, rfl⟩, exact hs.to_finset.center_mass_mem_convex_hull (λ x hx, hw₀ _ $ finite.mem_to_finset.1 hx) (hw₁.symm ▸ zero_lt_one) (λ x hx, finite.mem_to_finset.1 hx) } end lemma is_linear_map.convex_hull_image {f : E → F} (hf : is_linear_map ℝ f) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := set.subset.antisymm (convex_hull_min (image_subset _ (subset_convex_hull s)) $ (convex_convex_hull s).is_linear_image hf) (image_subset_iff.2 $ convex_hull_min (image_subset_iff.1 $ subset_convex_hull _) ((convex_convex_hull _).is_linear_preimage hf)) lemma linear_map.convex_hull_image (f : E →ₗ[ℝ] F) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := f.is_linear.convex_hull_image s end convex_hull /-! ### Simplex -/ section simplex variables (ι) [fintype ι] {f : ι → ℝ} /-- Standard simplex in the space of functions `ι → ℝ` is the set of vectors with non-negative coordinates with total sum `1`. -/ def std_simplex (ι : Type*) [fintype ι] : set (ι → ℝ) := { f | (∀ x, 0 ≤ f x) ∧ finset.univ.sum f = 1 } lemma std_simplex_eq_inter : std_simplex ι = (⋂ x, {f | 0 ≤ f x}) ∩ {f | finset.univ.sum f = 1} := by { ext f, simp only [std_simplex, set.mem_inter_eq, set.mem_Inter, set.mem_set_of_eq] } lemma convex_std_simplex : convex (std_simplex ι) := begin refine λ f g hf hg a b ha hb hab, ⟨λ x, _, _⟩, { apply_rules [add_nonneg, mul_nonneg, hf.1, hg.1] }, { erw [finset.sum_add_distrib, ← finset.smul_sum, ← finset.smul_sum, hf.2, hg.2, smul_eq_mul, smul_eq_mul, mul_one, mul_one], exact hab } end variable {ι} lemma ite_eq_mem_std_simplex (i : ι) : (λ j, ite (i = j) (1:ℝ) 0) ∈ std_simplex ι := ⟨λ j, by simp only []; split_ifs; norm_num, by rw [finset.sum_ite_eq, if_pos (finset.mem_univ _)] ⟩ /-- `std_simplex ι` is the convex hull of the canonical basis in `ι → ℝ`. -/ lemma convex_hull_basis_eq_std_simplex : convex_hull (range $ λ(i j:ι), if i = j then (1:ℝ) else 0) = std_simplex ι := begin refine subset.antisymm (convex_hull_min _ (convex_std_simplex ι)) _, { rintros _ ⟨i, rfl⟩, exact ite_eq_mem_std_simplex i }, { rintros w ⟨hw₀, hw₁⟩, rw [pi_eq_sum_univ w, ← finset.univ.center_mass_eq_of_sum_1 _ hw₁], exact finset.univ.center_mass_mem_convex_hull (λ i hi, hw₀ i) (hw₁.symm ▸ zero_lt_one) (λ i hi, mem_range_self i) } end variable {ι} /-- Convex hull of a finite set is the image of the standard simplex in `s → ℝ` under the linear map sending each function `w` to `s.sum (λ x, w x • x)`. Since we have no sums over finite sets, we use sum over `@finset.univ _ hs.fintype`. The map is defined in terms of operations on `(s → ℝ) →ₗ[ℝ] ℝ` so that later we will not need to prove that this map is linear. -/ lemma set.finite.convex_hull_eq_image {s : set E} (hs : finite s) : convex_hull s = (⇑((@finset.univ _ hs.fintype).sum (λ x, (linear_map.proj x : (s → ℝ) →ₗ[ℝ] ℝ).smul_right x.1))) '' (@std_simplex _ hs.fintype) := begin rw [← convex_hull_basis_eq_std_simplex, ← linear_map.convex_hull_image, ← range_comp, (∘)], apply congr_arg, convert (subtype.range_val s).symm, ext x, simp [linear_map.sum_apply, ite_smul, finset.sum_ite _ _ (λ x, x), finset.filter_eq] end /-- All values of a function `f ∈ std_simplex ι` belong to `[0, 1]`. -/ lemma mem_Icc_of_mem_std_simplex (hf : f ∈ std_simplex ι) (x) : f x ∈ I := ⟨hf.1 x, hf.2 ▸ finset.single_le_sum (λ y hy, hf.1 y) (finset.mem_univ x)⟩ end simplex
e9f2ac62db82641b9acd5df6cb81b939c29aa97e
c777c32c8e484e195053731103c5e52af26a25d1
/src/probability/martingale/convergence.lean
f670120fad772f7fb21fde9ced6bfa14e95c97df
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
25,468
lean
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import probability.martingale.upcrossing import measure_theory.function.uniform_integrable import measure_theory.constructions.polish /-! # Martingale convergence theorems The martingale convergence theorems are a collection of theorems characterizing the convergence of a martingale provided it satisfies some boundedness conditions. This file contains the almost everywhere martingale convergence theorem which provides an almost everywhere limit to an L¹ bounded submartingale. It also contains the L¹ martingale convergence theorem which provides an L¹ limit to a uniformly integrable submartingale. Finally, it also contains the Lévy upwards theorems. ## Main results * `measure_theory.submartingale.ae_tendsto_limit_process`: the almost everywhere martingale convergence theorem: an L¹-bounded submartingale adapted to the filtration `ℱ` converges almost everywhere to its limit process. * `measure_theory.submartingale.mem_ℒp_limit_process`: the limit process of an Lᵖ-bounded submartingale is Lᵖ. * `measure_theory.submartingale.tendsto_snorm_one_limit_process`: part a of the L¹ martingale convergence theorem: a uniformly integrable submartingale adapted to the filtration `ℱ` converges almost everywhere and in L¹ to an integrable function which is measurable with respect to the σ-algebra `⨆ n, ℱ n`. * `measure_theory.martingale.ae_eq_condexp_limit_process`: part b the L¹ martingale convergence theorem: if `f` is a uniformly integrable martingale adapted to the filtration `ℱ`, then `f n` equals `𝔼[g | ℱ n]` almost everywhere where `g` is the limiting process of `f`. * `measure_theory.integrable.tendsto_ae_condexp`: part c the L¹ martingale convergence theorem: given a `⨆ n, ℱ n`-measurable function `g` where `ℱ` is a filtration, `𝔼[g | ℱ n]` converges almost everywhere to `g`. * `measure_theory.integrable.tendsto_snorm_condexp`: part c the L¹ martingale convergence theorem: given a `⨆ n, ℱ n`-measurable function `g` where `ℱ` is a filtration, `𝔼[g | ℱ n]` converges in L¹ to `g`. -/ open topological_space filter measure_theory.filtration open_locale nnreal ennreal measure_theory probability_theory big_operators topology namespace measure_theory variables {Ω ι : Type*} {m0 : measurable_space Ω} {μ : measure Ω} {ℱ : filtration ℕ m0} variables {a b : ℝ} {f : ℕ → Ω → ℝ} {ω : Ω} {R : ℝ≥0} section ae_convergence /-! ### Almost everywhere martingale convergence theorem We will now prove the almost everywhere martingale convergence theorem. The a.e. martingale convergence theorem states: if `f` is an L¹-bounded `ℱ`-submartingale, then it converges almost everywhere to an integrable function which is measurable with respect to the σ-algebra `ℱ∞ := ⨆ n, ℱ n`. Mathematically, we proceed by first noting that a real sequence $(x_n)$ converges if (a) $\limsup_{n \to \infty} |x_n| < \infty$, (b) for all $a < b \in \mathbb{Q}$ we have the number of upcrossings of $(x_n)$ from below $a$ to above $b$ is finite. Thus, for all $\omega$ satisfying $\limsup_{n \to \infty} |f_n(\omega)| < \infty$ and the number of upcrossings of $(f_n(\omega))$ from below $a$ to above $b$ is finite for all $a < b \in \mathbb{Q}$, we have $(f_n(\omega))$ is convergent. Hence, assuming $(f_n)$ is L¹-bounded, using Fatou's lemma, we have $$ \mathbb{E} \limsup_{n \to \infty} |f_n| \le \limsup_{n \to \infty} \mathbb{E}|f_n| < \infty $$ implying $\limsup_{n \to \infty} |f_n| < \infty$ a.e. Furthermore, by the upcrossing estimate, the number of upcrossings is finite almost everywhere implying $f$ converges pointwise almost everywhere. Thus, denoting $g$ the a.e. limit of $(f_n)$, $g$ is $\mathcal{F}_\infty$-measurable as for all $n$, $f_n$ is $\mathcal{F}_n$-measurable and $\mathcal{F}_n \le \mathcal{F}_\infty$. Finally, $g$ is integrable as $|g| \le \liminf_{n \to \infty} |f_n|$ so $$ \mathbb{E}|g| \le \mathbb{E} \limsup_{n \to \infty} |f_n| \le \limsup_{n \to \infty} \mathbb{E}|f_n| < \infty $$ as required. Implementation wise, we have `tendsto_of_no_upcrossings` which showed that a bounded sequence converges if it does not visit below $a$ and above $b$ infinitely often for all $a, b ∈ s$ for some dense set $s$. So, we may skip the first step provided we can prove that the realizations are bounded almost everywhere. Indeed, suppose $(|f_n(\omega)|)$ is not bounded, then either $f_n(\omega) \to \pm \infty$ or one of $\limsup f_n(\omega)$ or $\liminf f_n(\omega)$ equals $\pm \infty$ while the other is finite. But the first case contradicts $\liminf |f_n(\omega)| < \infty$ while the second case contradicts finite upcrossings. Furthermore, we introduced `filtration.limit_process` which chooses the limiting random variable of a stochastic process if it exists, otherwise it returns 0. Hence, instead of showing an existence statement, we phrased the a.e. martingale convergence theorem by showed that a submartingale converges to its `limit_process` almost everywhere. -/ /-- If a stochastic process has bounded upcrossing from below `a` to above `b`, then it does not frequently visit both below `a` and above `b`. -/ lemma not_frequently_of_upcrossings_lt_top (hab : a < b) (hω : upcrossings a b f ω ≠ ∞) : ¬((∃ᶠ n in at_top, f n ω < a) ∧ (∃ᶠ n in at_top, b < f n ω)) := begin rw [← lt_top_iff_ne_top, upcrossings_lt_top_iff] at hω, replace hω : ∃ k, ∀ N, upcrossings_before a b f N ω < k, { obtain ⟨k, hk⟩ := hω, exact ⟨k + 1, λ N, lt_of_le_of_lt (hk N) k.lt_succ_self⟩ }, rintro ⟨h₁, h₂⟩, rw frequently_at_top at h₁ h₂, refine not_not.2 hω _, push_neg, intro k, induction k with k ih, { simp only [zero_le', exists_const] }, { obtain ⟨N, hN⟩ := ih, obtain ⟨N₁, hN₁, hN₁'⟩ := h₁ N, obtain ⟨N₂, hN₂, hN₂'⟩ := h₂ N₁, exact ⟨(N₂ + 1), nat.succ_le_of_lt $ lt_of_le_of_lt hN (upcrossings_before_lt_of_exists_upcrossing hab hN₁ hN₁' hN₂ hN₂')⟩ } end /-- A stochastic process that frequently visits below `a` and above `b` have infinite upcrossings. -/ lemma upcrossings_eq_top_of_frequently_lt (hab : a < b) (h₁ : ∃ᶠ n in at_top, f n ω < a) (h₂ : ∃ᶠ n in at_top, b < f n ω) : upcrossings a b f ω = ∞ := classical.by_contradiction (λ h, not_frequently_of_upcrossings_lt_top hab h ⟨h₁, h₂⟩) /-- A realization of a stochastic process with bounded upcrossings and bounded liminfs is convergent. We use the spelling `< ∞` instead of the standard `≠ ∞` in the assumptions since it is not as easy to change `<` to `≠` under binders. -/ lemma tendsto_of_uncrossing_lt_top (hf₁ : liminf (λ n, (‖f n ω‖₊ : ℝ≥0∞)) at_top < ∞) (hf₂ : ∀ a b : ℚ, a < b → upcrossings a b f ω < ∞) : ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) := begin by_cases h : is_bounded_under (≤) at_top (λ n, |f n ω|), { rw is_bounded_under_le_abs at h, refine tendsto_of_no_upcrossings rat.dense_range_cast _ h.1 h.2, { intros a ha b hb hab, obtain ⟨⟨a, rfl⟩, ⟨b, rfl⟩⟩ := ⟨ha, hb⟩, exact not_frequently_of_upcrossings_lt_top hab (hf₂ a b (rat.cast_lt.1 hab)).ne } }, { obtain ⟨a, b, hab, h₁, h₂⟩ := ennreal.exists_upcrossings_of_not_bounded_under hf₁.ne h, exact false.elim ((hf₂ a b hab).ne (upcrossings_eq_top_of_frequently_lt (rat.cast_lt.2 hab) h₁ h₂)) } end /-- An L¹-bounded submartingale has bounded upcrossings almost everywhere. -/ lemma submartingale.upcrossings_ae_lt_top' [is_finite_measure μ] (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) 1 μ ≤ R) (hab : a < b) : ∀ᵐ ω ∂μ, upcrossings a b f ω < ∞ := begin refine ae_lt_top (hf.adapted.measurable_upcrossings hab) _, have := hf.mul_lintegral_upcrossings_le_lintegral_pos_part a b, rw [mul_comm, ← ennreal.le_div_iff_mul_le] at this, { refine (lt_of_le_of_lt this (ennreal.div_lt_top _ _)).ne, { have hR' : ∀ n, ∫⁻ ω, ‖f n ω - a‖₊ ∂μ ≤ R + ‖a‖₊ * μ set.univ, { simp_rw snorm_one_eq_lintegral_nnnorm at hbdd, intro n, refine (lintegral_mono _ : ∫⁻ ω, ‖f n ω - a‖₊ ∂μ ≤ ∫⁻ ω, ‖f n ω‖₊ + ‖a‖₊ ∂μ).trans _, { intro ω, simp_rw [sub_eq_add_neg, ← nnnorm_neg a, ← ennreal.coe_add, ennreal.coe_le_coe], exact nnnorm_add_le _ _ }, { simp_rw [ lintegral_add_right _ measurable_const, lintegral_const], exact add_le_add (hbdd _) le_rfl } }, refine ne_of_lt (supr_lt_iff.2 ⟨R + ‖a‖₊ * μ set.univ, ennreal.add_lt_top.2 ⟨ennreal.coe_lt_top, ennreal.mul_lt_top ennreal.coe_lt_top.ne (measure_ne_top _ _)⟩, λ n, le_trans _ (hR' n)⟩), refine lintegral_mono (λ ω, _), rw [ennreal.of_real_le_iff_le_to_real, ennreal.coe_to_real, coe_nnnorm], by_cases hnonneg : 0 ≤ f n ω - a, { rw [lattice_ordered_comm_group.pos_of_nonneg _ hnonneg, real.norm_eq_abs, abs_of_nonneg hnonneg] }, { rw lattice_ordered_comm_group.pos_of_nonpos _ (not_le.1 hnonneg).le, exact norm_nonneg _ }, { simp only [ne.def, ennreal.coe_ne_top, not_false_iff] } }, { simp only [hab, ne.def, ennreal.of_real_eq_zero, sub_nonpos, not_le] } }, { simp only [hab, ne.def, ennreal.of_real_eq_zero, sub_nonpos, not_le, true_or]}, { simp only [ne.def, ennreal.of_real_ne_top, not_false_iff, true_or] } end lemma submartingale.upcrossings_ae_lt_top [is_finite_measure μ] (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) 1 μ ≤ R) : ∀ᵐ ω ∂μ, ∀ a b : ℚ, a < b → upcrossings a b f ω < ∞ := begin simp only [ae_all_iff, eventually_imp_distrib_left], rintro a b hab, exact hf.upcrossings_ae_lt_top' hbdd (rat.cast_lt.2 hab), end /-- An L¹-bounded submartingale converges almost everywhere. -/ lemma submartingale.exists_ae_tendsto_of_bdd [is_finite_measure μ] (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) 1 μ ≤ R) : ∀ᵐ ω ∂μ, ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) := begin filter_upwards [hf.upcrossings_ae_lt_top hbdd, ae_bdd_liminf_at_top_of_snorm_bdd one_ne_zero (λ n, (hf.strongly_measurable n).measurable.mono (ℱ.le n) le_rfl) hbdd] with ω h₁ h₂, exact tendsto_of_uncrossing_lt_top h₂ h₁, end lemma submartingale.exists_ae_trim_tendsto_of_bdd [is_finite_measure μ] (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) 1 μ ≤ R) : ∀ᵐ ω ∂(μ.trim (Sup_le (λ m ⟨n, hn⟩, hn ▸ ℱ.le _) : (⨆ n, ℱ n) ≤ m0)), ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) := begin rw [ae_iff, trim_measurable_set_eq], { exact hf.exists_ae_tendsto_of_bdd hbdd }, { exact measurable_set.compl (@measurable_set_exists_tendsto _ _ _ _ _ _ (⨆ n, ℱ n) _ _ _ _ _ (λ n, ((hf.strongly_measurable n).measurable.mono (le_Sup ⟨n, rfl⟩) le_rfl))) } end /-- **Almost everywhere martingale convergence theorem**: An L¹-bounded submartingale converges almost everywhere to a `⨆ n, ℱ n`-measurable function. -/ lemma submartingale.ae_tendsto_limit_process [is_finite_measure μ] (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) 1 μ ≤ R) : ∀ᵐ ω ∂μ, tendsto (λ n, f n ω) at_top (𝓝 (ℱ.limit_process f μ ω)) := begin classical, suffices : ∃ g, strongly_measurable[⨆ n, ℱ n] g ∧ ∀ᵐ ω ∂μ, tendsto (λ n, f n ω) at_top (𝓝 (g ω)), { rw [limit_process, dif_pos this], exact (classical.some_spec this).2 }, set g' : Ω → ℝ := λ ω, if h : ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) then h.some else 0, have hle : (⨆ n, ℱ n) ≤ m0 := Sup_le (λ m ⟨n, hn⟩, hn ▸ ℱ.le _), have hg' : ∀ᵐ ω ∂(μ.trim hle), tendsto (λ n, f n ω) at_top (𝓝 (g' ω)), { filter_upwards [hf.exists_ae_trim_tendsto_of_bdd hbdd] with ω hω, simp_rw [g', dif_pos hω], exact hω.some_spec }, have hg'm : @ae_strongly_measurable _ _ _ (⨆ n, ℱ n) g' (μ.trim hle) := (@ae_measurable_of_tendsto_metrizable_ae' _ _ (⨆ n, ℱ n) _ _ _ _ _ _ _ (λ n, ((hf.strongly_measurable n).measurable.mono (le_Sup ⟨n, rfl⟩ : ℱ n ≤ ⨆ n, ℱ n) le_rfl).ae_measurable) hg').ae_strongly_measurable, obtain ⟨g, hgm, hae⟩ := hg'm, have hg : ∀ᵐ ω ∂μ.trim hle, tendsto (λ n, f n ω) at_top (𝓝 (g ω)), { filter_upwards [hae, hg'] with ω hω hg'ω, exact hω ▸ hg'ω }, exact ⟨g, hgm, measure_eq_zero_of_trim_eq_zero hle hg⟩, end /-- The limiting process of an Lᵖ-bounded submartingale is Lᵖ. -/ lemma submartingale.mem_ℒp_limit_process {p : ℝ≥0∞} (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) p μ ≤ R) : mem_ℒp (ℱ.limit_process f μ) p μ := mem_ℒp_limit_process_of_snorm_bdd (λ n, ((hf.strongly_measurable n).mono (ℱ.le n)).ae_strongly_measurable) hbdd end ae_convergence section L1_convergence variables [is_finite_measure μ] {g : Ω → ℝ} /-! ### L¹ martingale convergence theorem We will now prove the L¹ martingale convergence theorems. The L¹ martingale convergence theorem states that: (a) if `f` is a uniformly integrable (in the probability sense) submartingale adapted to the filtration `ℱ`, it converges in L¹ to an integrable function `g` which is measurable with respect to `ℱ∞ := ⨆ n, ℱ n` and (b) if `f` is actually a martingale, `f n = 𝔼[g | ℱ n]` almost everywhere. (c) Finally, if `h` is integrable and measurable with respect to `ℱ∞`, `(𝔼[h | ℱ n])ₙ` is a uniformly integrable martingale which converges to `h` almost everywhere and in L¹. The proof is quite simple. (a) follows directly from the a.e. martingale convergence theorem and the Vitali convergence theorem as our definition of uniform integrability (in the probability sense) directly implies L¹-uniform boundedness. We note that our definition of uniform integrability is slightly non-standard but is equivalent to the usual literary definition. This equivalence is provided by `measure_theory.uniform_integrable_iff`. (b) follows since given $n$, we have for all $m \ge n$, $$ \|f_n - \mathbb{E}[g \mid \mathcal{F}_n]\|_1 = \|\mathbb{E}[f_m - g \mid \mathcal{F}_n]\|_1 \le \|\|f_m - g\|_1. $$ Thus, taking $m \to \infty$ provides the almost everywhere equality. Finally, to prove (c), we define $f_n := \mathbb{E}[h \mid \mathcal{F}_n]$. It is clear that $(f_n)_n$ is a martingale by the tower property for conditional expectations. Furthermore, $(f_n)_n$ is uniformly integrable in the probability sense. Indeed, as a single function is uniformly integrable in the measure theory sense, for all $\epsilon > 0$, there exists some $\delta > 0$ such that for all measurable set $A$ with $\mu(A) < δ$, we have $\mathbb{E}|h|\mathbf{1}_A < \epsilon$. So, since for sufficently large $\lambda$, by the Markov inequality, we have for all $n$, $$ \mu(|f_n| \ge \lambda) \le \lambda^{-1}\mathbb{E}|f_n| \le \lambda^{-1}\mathbb|g| < \delta, $$ we have for sufficently large $\lambda$, for all $n$, $$ \mathbb{E}|f_n|\mathbf{1}_{|f_n| \ge \lambda} \le \mathbb|g|\mathbf{1}_{|f_n| \ge \lambda} < \epsilon, $$ implying $(f_n)_n$ is uniformly integrable. Now, to prove $f_n \to h$ almost everywhere and in L¹, it suffices to show that $h = g$ almost everywhere where $g$ is the almost everywhere and L¹ limit of $(f_n)_n$ from part (b) of the theorem. By noting that, for all $s \in \mathcal{F}_n$, we have $$ \mathbb{E}g\mathbf{1}_s = \mathbb{E}[\mathbb{E}[g \mid \mathcal{F}_n]\mathbf{1}_s] = \mathbb{E}[\mathbb{E}[h \mid \mathcal{F}_n]\mathbf{1}_s] = \mathbb{E}h\mathbf{1}_s $$ where $\mathbb{E}[g \mid \mathcal{F}_n = \mathbb{E}[h \mid \mathcal{F}_n]$ almost everywhere by part (b); the equality also holds for all $s \in \mathcal{F}_\infty$ by Dynkin's theorem. Thus, as both $h$ and $g$ are $\mathcal{F}_\infty$-measurable, $h = g$ almost everywhere as required. Similar to the a.e. martingale convergence theorem, rather than showing the existence of the limiting process, we phrased the L¹-martingale convergence theorem by proving that a submartingale does converge in L¹ to its `limit_process`. However, in contrast to the a.e. martingale convergence theorem, we do not need to introduce a L¹ version of `filtration.limit_process` as the L¹ limit and the a.e. limit of a submartingale coincide. -/ /-- Part a of the **L¹ martingale convergence theorem**: a uniformly integrable submartingale adapted to the filtration `ℱ` converges a.e. and in L¹ to an integrable function which is measurable with respect to the σ-algebra `⨆ n, ℱ n`. -/ lemma submartingale.tendsto_snorm_one_limit_process (hf : submartingale f ℱ μ) (hunif : uniform_integrable f 1 μ) : tendsto (λ n, snorm (f n - ℱ.limit_process f μ) 1 μ) at_top (𝓝 0) := begin obtain ⟨R, hR⟩ := hunif.2.2, have hmeas : ∀ n, ae_strongly_measurable (f n) μ := λ n, ((hf.strongly_measurable n).mono (ℱ.le _)).ae_strongly_measurable, exact tendsto_Lp_of_tendsto_in_measure _ le_rfl ennreal.one_ne_top hmeas (mem_ℒp_limit_process_of_snorm_bdd hmeas hR) hunif.2.1 (tendsto_in_measure_of_tendsto_ae hmeas $ hf.ae_tendsto_limit_process hR), end lemma submartingale.ae_tendsto_limit_process_of_uniform_integrable (hf : submartingale f ℱ μ) (hunif : uniform_integrable f 1 μ) : ∀ᵐ ω ∂μ, tendsto (λ n, f n ω) at_top (𝓝 (ℱ.limit_process f μ ω)) := let ⟨R, hR⟩ := hunif.2.2 in hf.ae_tendsto_limit_process hR /-- If a martingale `f` adapted to `ℱ` converges in L¹ to `g`, then for all `n`, `f n` is almost everywhere equal to `𝔼[g | ℱ n]`. -/ lemma martingale.eq_condexp_of_tendsto_snorm {μ : measure Ω} (hf : martingale f ℱ μ) (hg : integrable g μ) (hgtends : tendsto (λ n, snorm (f n - g) 1 μ) at_top (𝓝 0)) (n : ℕ) : f n =ᵐ[μ] μ[g | ℱ n] := begin rw [← sub_ae_eq_zero, ← snorm_eq_zero_iff ((((hf.strongly_measurable n).mono (ℱ.le _)).sub (strongly_measurable_condexp.mono (ℱ.le _))).ae_strongly_measurable) one_ne_zero], have ht : tendsto (λ m, snorm (μ[f m - g | ℱ n]) 1 μ) at_top (𝓝 0), { have hint : ∀ m, integrable (f m - g) μ := λ m, (hf.integrable m).sub hg, exact tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds hgtends (λ m, zero_le _) (λ m, snorm_one_condexp_le_snorm _) }, have hev : ∀ m ≥ n, snorm (μ[f m - g | ℱ n]) 1 μ = snorm (f n - μ[g | ℱ n]) 1 μ, { refine λ m hm, snorm_congr_ae ((condexp_sub (hf.integrable m) hg).trans _), filter_upwards [hf.2 n m hm] with x hx, simp only [hx, pi.sub_apply] }, exact tendsto_nhds_unique (tendsto_at_top_of_eventually_const hev) ht, end /-- Part b of the **L¹ martingale convergence theorem**: if `f` is a uniformly integrable martingale adapted to the filtration `ℱ`, then for all `n`, `f n` is almost everywhere equal to the conditional expectation of its limiting process wrt. `ℱ n`. -/ lemma martingale.ae_eq_condexp_limit_process (hf : martingale f ℱ μ) (hbdd : uniform_integrable f 1 μ) (n : ℕ) : f n =ᵐ[μ] μ[ℱ.limit_process f μ | ℱ n] := let ⟨R, hR⟩ := hbdd.2.2 in hf.eq_condexp_of_tendsto_snorm ((mem_ℒp_limit_process_of_snorm_bdd hbdd.1 hR).integrable le_rfl) (hf.submartingale.tendsto_snorm_one_limit_process hbdd) n /-- Part c of the **L¹ martingale convergnce theorem**: Given a integrable function `g` which is measurable with respect to `⨆ n, ℱ n` where `ℱ` is a filtration, the martingale defined by `𝔼[g | ℱ n]` converges almost everywhere to `g`. This martingale also converges to `g` in L¹ and this result is provided by `measure_theory.integrable.tendsto_snorm_condexp` -/ lemma integrable.tendsto_ae_condexp (hg : integrable g μ) (hgmeas : strongly_measurable[⨆ n, ℱ n] g) : ∀ᵐ x ∂μ, tendsto (λ n, μ[g | ℱ n] x) at_top (𝓝 (g x)) := begin have hle : (⨆ n, ℱ n) ≤ m0 := Sup_le (λ m ⟨n, hn⟩, hn ▸ ℱ.le _), have hunif : uniform_integrable (λ n, μ[g | ℱ n]) 1 μ := hg.uniform_integrable_condexp_filtration, obtain ⟨R, hR⟩ := hunif.2.2, have hlimint : integrable (ℱ.limit_process (λ n, μ[g | ℱ n]) μ) μ := (mem_ℒp_limit_process_of_snorm_bdd hunif.1 hR).integrable le_rfl, suffices : g =ᵐ[μ] ℱ.limit_process (λ n x, μ[g | ℱ n] x) μ, { filter_upwards [this, (martingale_condexp g ℱ μ).submartingale.ae_tendsto_limit_process hR] with x heq ht, rwa heq }, have : ∀ n s, measurable_set[ℱ n] s → ∫ x in s, g x ∂μ = ∫ x in s, ℱ.limit_process (λ n x, μ[g | ℱ n] x) μ x ∂μ, { intros n s hs, rw [← set_integral_condexp (ℱ.le n) hg hs, ← set_integral_condexp (ℱ.le n) hlimint hs], refine set_integral_congr_ae (ℱ.le _ _ hs) _, filter_upwards [(martingale_condexp g ℱ μ).ae_eq_condexp_limit_process hunif n] with x hx _, rwa hx }, refine ae_eq_of_forall_set_integral_eq_of_sigma_finite' hle (λ s _ _, hg.integrable_on) (λ s _ _, hlimint.integrable_on) (λ s hs, _) hgmeas.ae_strongly_measurable' strongly_measurable_limit_process.ae_strongly_measurable', refine @measurable_space.induction_on_inter _ _ _ (⨆ n, ℱ n) (measurable_space.measurable_space_supr_eq ℱ) _ _ _ _ _ _ hs, { rintro s ⟨n, hs⟩ t ⟨m, ht⟩ -, by_cases hnm : n ≤ m, { exact ⟨m, (ℱ.mono hnm _ hs).inter ht⟩ }, { exact ⟨n, hs.inter (ℱ.mono (not_le.1 hnm).le _ ht)⟩ } }, { simp only [measure_empty, with_top.zero_lt_top, measure.restrict_empty, integral_zero_measure, forall_true_left] }, { rintro t ⟨n, ht⟩ -, exact this n _ ht }, { rintro t htmeas ht -, have hgeq := @integral_add_compl _ _ (⨆ n, ℱ n) _ _ _ _ _ _ htmeas (hg.trim hle hgmeas), have hheq := @integral_add_compl _ _ (⨆ n, ℱ n) _ _ _ _ _ _ htmeas (hlimint.trim hle strongly_measurable_limit_process), rw [add_comm, ← eq_sub_iff_add_eq] at hgeq hheq, rw [set_integral_trim hle hgmeas htmeas.compl, set_integral_trim hle strongly_measurable_limit_process htmeas.compl, hgeq, hheq, ← set_integral_trim hle hgmeas htmeas, ← set_integral_trim hle strongly_measurable_limit_process htmeas, ← integral_trim hle hgmeas, ← integral_trim hle strongly_measurable_limit_process, ← integral_univ, this 0 _ measurable_set.univ, integral_univ, ht (measure_lt_top _ _)] }, { rintro f hf hfmeas heq -, rw [integral_Union (λ n, hle _ (hfmeas n)) hf hg.integrable_on, integral_Union (λ n, hle _ (hfmeas n)) hf hlimint.integrable_on], exact tsum_congr (λ n, heq _ (measure_lt_top _ _)) } end /-- Part c of the **L¹ martingale convergnce theorem**: Given a integrable function `g` which is measurable with respect to `⨆ n, ℱ n` where `ℱ` is a filtration, the martingale defined by `𝔼[g | ℱ n]` converges in L¹ to `g`. This martingale also converges to `g` almost everywhere and this result is provided by `measure_theory.integrable.tendsto_ae_condexp` -/ lemma integrable.tendsto_snorm_condexp (hg : integrable g μ) (hgmeas : strongly_measurable[⨆ n, ℱ n] g) : tendsto (λ n, snorm (μ[g | ℱ n] - g) 1 μ) at_top (𝓝 0) := tendsto_Lp_of_tendsto_in_measure _ le_rfl ennreal.one_ne_top (λ n, (strongly_measurable_condexp.mono (ℱ.le n)).ae_strongly_measurable) (mem_ℒp_one_iff_integrable.2 hg) (hg.uniform_integrable_condexp_filtration).2.1 (tendsto_in_measure_of_tendsto_ae (λ n,(strongly_measurable_condexp.mono (ℱ.le n)).ae_strongly_measurable) (hg.tendsto_ae_condexp hgmeas)) /-- **Lévy's upward theorem**, almost everywhere version: given a function `g` and a filtration `ℱ`, the sequence defined by `𝔼[g | ℱ n]` converges almost everywhere to `𝔼[g | ⨆ n, ℱ n]`. -/ lemma tendsto_ae_condexp (g : Ω → ℝ) : ∀ᵐ x ∂μ, tendsto (λ n, μ[g | ℱ n] x) at_top (𝓝 (μ[g | ⨆ n, ℱ n] x)) := begin have ht : ∀ᵐ x ∂μ, tendsto (λ n, μ[μ[g | ⨆ n, ℱ n] | ℱ n] x) at_top (𝓝 (μ[g | ⨆ n, ℱ n] x)) := integrable_condexp.tendsto_ae_condexp strongly_measurable_condexp, have heq : ∀ n, ∀ᵐ x ∂μ, μ[μ[g | ⨆ n, ℱ n] | ℱ n] x = μ[g | ℱ n] x := λ n, condexp_condexp_of_le (le_supr _ n) (supr_le (λ n, ℱ.le n)), rw ← ae_all_iff at heq, filter_upwards [heq, ht] with x hxeq hxt, exact hxt.congr hxeq, end /-- **Lévy's upward theorem**, L¹ version: given a function `g` and a filtration `ℱ`, the sequence defined by `𝔼[g | ℱ n]` converges in L¹ to `𝔼[g | ⨆ n, ℱ n]`. -/ lemma tendsto_snorm_condexp (g : Ω → ℝ) : tendsto (λ n, snorm (μ[g | ℱ n] - μ[g | ⨆ n, ℱ n]) 1 μ) at_top (𝓝 0) := begin have ht : tendsto (λ n, snorm (μ[μ[g | ⨆ n, ℱ n] | ℱ n] - μ[g | ⨆ n, ℱ n]) 1 μ) at_top (𝓝 0) := integrable_condexp.tendsto_snorm_condexp strongly_measurable_condexp, have heq : ∀ n, ∀ᵐ x ∂μ, μ[μ[g | ⨆ n, ℱ n] | ℱ n] x = μ[g | ℱ n] x := λ n, condexp_condexp_of_le (le_supr _ n) (supr_le (λ n, ℱ.le n)), refine ht.congr (λ n, snorm_congr_ae _), filter_upwards [heq n] with x hxeq, simp only [hxeq, pi.sub_apply], end end L1_convergence end measure_theory
ffe1635c032e176ba32e1d98b6dff79f94b57d1b
cc060cf567f81c404a13ee79bf21f2e720fa6db0
/lean/20170705-failed_to_generate_bytecode.lean
ad2c5d2ad83d3923bd8bbfffa9e5a37c91bda376
[ "Apache-2.0" ]
permissive
semorrison/proof
cf0a8c6957153bdb206fd5d5a762a75958a82bca
5ee398aa239a379a431190edbb6022b1a0aa2c70
refs/heads/master
1,610,414,502,842
1,518,696,851,000
1,518,696,851,000
78,375,937
2
1
null
null
null
null
UTF-8
Lean
false
false
1,041
lean
open tactic meta def fsplit : tactic unit := do [c] ← target >>= get_constructors_for | tactic.fail "fsplit tactic failed, target is not an inductive datatype with only one constructor", mk_const c >>= fapply structure Bijection ( U V : Type ) := ( morphism : U → V ) ( inverse : V → U ) ( witness_1 : ∀ u : U, inverse (morphism u) = u ) ( witness_2 : ∀ v : V, morphism (inverse v) = v ) class Finite ( α : Type ) := ( cardinality : nat ) ( bijection : Bijection α (fin cardinality) ) lemma empty_exfalso (x : false) : empty := begin exfalso, trivial end instance empty_is_Finite : Finite empty := { cardinality := 0, bijection := begin fsplit, intros, induction a, intros, induction a, apply empty_exfalso, cases is_lt, intros, induction u, intros, induction v, cases is_lt, end }
0cf71cee8e12824ca31d395db4131a6c29f4bcc2
f4bff2062c030df03d65e8b69c88f79b63a359d8
/src/game/sup_inf/level04.lean
beccf8fcce877e924562d8e067a572b884a156b2
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,221
lean
import game.sup_inf.level03 import data.real.basic namespace xena -- hide /- # Chapter 3 : Sup and Inf ## Level 4 -/ /- A generalization of the result in the previous level. -/ -- begin hide -- these three helper results to go in sidebar lemma two_real_ne_zero : (2:ℝ) ≠ 0 := begin intro, linarith, end lemma avg_lt_max {mn mx: ℝ} (H : mn < mx) : (mn+mx) / 2 < mx := begin apply (mul_lt_mul_right (show (0:ℝ)<2, by norm_num)).1, rw [div_mul_cancel _ (two_real_ne_zero)], simp [H,mul_two], end lemma min_lt_avg {mn mx: ℝ} (H : mn < mx) : mn < (mn+mx) / 2 := begin apply (mul_lt_mul_right (show (0:ℝ)<2, by norm_num)).1, rw [div_mul_cancel _ (two_real_ne_zero)], simp [H,mul_two], end -- end hide /- Lemma A more general version of the previous level... -/ lemma lub_open (y : ℝ) : is_lub {x : ℝ | x < y} y := begin split, { intros a ha, exact le_of_lt ha, }, --unfold lower_bounds, intro b, intro Hb, refine le_of_not_gt _, intro Hnb, let c:=(b+y)/2, --unfold upper_bounds at Hb, have H2 := Hb c, clear Hb, have H : c ∈ {x : ℝ | x < y}, { exact avg_lt_max Hnb, }, have Hcleb := H2 H, have Hbltc : b < c := min_lt_avg Hnb, exact not_lt.2 Hcleb Hbltc, end end xena -- hide
2914be793b4f5ddc7e70d0c2f197d7a9b3daaa3d
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/coe4.lean
3ab9b7530708f2d744f541a0b40c41ab76d0f65b
[ "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
427
lean
universe variables u structure Functor (A : Type u) := (fn : A → A → A) (inj : ∀ x y, fn x = fn y → x = y) attribute [instance] definition coe_functor_to_fn (A : Type u) : has_coe_to_fun (Functor A) := { F := λ f, A → A → A, coe := Functor.fn } constant f : Functor nat check f 0 1 set_option pp.coercions false check f 0 1 set_option pp.coercions true check f 0 1 set_option pp.all true check f 0 1
a4cd50afeb6020c7b268b2e50e4a54cbabd3a509
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/basic.lean
d00c9d0d8830914d1725b558459b328d65501057
[ "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
51,240
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Jeremy Avigad -/ import order.filter.ultrafilter import order.filter.partial noncomputable theory /-! # Basic theory of topological spaces. The main definition is the type class `topological space α` which endows a type `α` with a topology. Then `set α` gets predicates `is_open`, `is_closed` and functions `interior`, `closure` and `frontier`. Each point `x` of `α` gets a neighborhood filter `𝓝 x`. A filter `F` on `α` has `x` as a cluster point if `is_cluster_pt x F : 𝓝 x ⊓ F ≠ ⊥`. A map `f : ι → α` clusters at `x` along `F : filter ι` if `map_cluster_pt x F f : cluster_pt x (map f F)`. In particular the notion of cluster point of a sequence `u` is `map_cluster_pt x at_top u`. This file also defines locally finite families of subsets of `α`. For topological spaces `α` and `β`, a function `f : α → β` and a point `a : α`, `continuous_at f a` means `f` is continuous at `a`, and global continuity is `continuous f`. There is also a version of continuity `pcontinuous` for partially defined functions. ## Notation * `𝓝 x`: the filter of neighborhoods of a point `x`; * `𝓟 s`: the principal filter of a set `s`; ## Implementation notes Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in <https://leanprover-community.github.io/theories/topology.html>. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] ## Tags topological space, interior, closure, frontier, neighborhood, continuity, continuous function -/ open set filter classical open_locale classical filter universes u v w /-! ### Topological spaces -/ /-- A topology on `α`. -/ @[protect_proj] structure topological_space (α : Type u) := (is_open : set α → Prop) (is_open_univ : is_open univ) (is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t)) (is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s)) attribute [class] topological_space /-- A constructor for topologies by specifying the closed sets, and showing that they satisfy the appropriate conditions. -/ def topological_space.of_closed {α : Type u} (T : set (set α)) (empty_mem : ∅ ∈ T) (sInter_mem : ∀ A ⊆ T, ⋂₀ A ∈ T) (union_mem : ∀ A B ∈ T, A ∪ B ∈ T) : topological_space α := { is_open := λ X, Xᶜ ∈ T, is_open_univ := by simp [empty_mem], is_open_inter := λ s t hs ht, by simpa [set.compl_inter] using union_mem sᶜ tᶜ hs ht, is_open_sUnion := λ s hs, by rw set.compl_sUnion; exact sInter_mem (set.compl '' s) (λ z ⟨y, hy, hz⟩, by simpa [hz.symm] using hs y hy) } section topological_space variables {α : Type u} {β : Type v} {ι : Sort w} {a : α} {s s₁ s₂ : set α} {p p₁ p₂ : α → Prop} @[ext] lemma topological_space_eq : ∀ {f g : topological_space α}, f.is_open = g.is_open → f = g | ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl section variables [t : topological_space α] include t /-- `is_open s` means that `s` is open in the ambient topological space on `α` -/ def is_open (s : set α) : Prop := topological_space.is_open t s @[simp] lemma is_open_univ : is_open (univ : set α) := topological_space.is_open_univ t lemma is_open_inter (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∩ s₂) := topological_space.is_open_inter t s₁ s₂ h₁ h₂ lemma is_open_sUnion {s : set (set α)} (h : ∀t ∈ s, is_open t) : is_open (⋃₀ s) := topological_space.is_open_sUnion t s h end lemma is_open_fold {s : set α} {t : topological_space α} : t.is_open s = @is_open α t s := rfl variables [topological_space α] lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) := is_open_sUnion $ by rintro _ ⟨i, rfl⟩; exact h i lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) : is_open (⋃i∈s, f i) := is_open_Union $ assume i, is_open_Union $ assume hi, h i hi lemma is_open_union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) := by rw union_eq_Union; exact is_open_Union (bool.forall_bool.2 ⟨h₂, h₁⟩) @[simp] lemma is_open_empty : is_open (∅ : set α) := by rw ← sUnion_empty; exact is_open_sUnion (assume a, false.elim) lemma is_open_sInter {s : set (set α)} (hs : finite s) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) := finite.induction_on hs (λ _, by rw sInter_empty; exact is_open_univ) $ λ a s has hs ih h, by rw sInter_insert; exact is_open_inter (h _ $ mem_insert _ _) (ih $ λ t, h t ∘ mem_insert_of_mem _) lemma is_open_bInter {s : set β} {f : β → set α} (hs : finite s) : (∀i∈s, is_open (f i)) → is_open (⋂i∈s, f i) := finite.induction_on hs (λ _, by rw bInter_empty; exact is_open_univ) (λ a s has hs ih h, by rw bInter_insert; exact is_open_inter (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_open_Inter [fintype β] {s : β → set α} (h : ∀ i, is_open (s i)) : is_open (⋂ i, s i) := suffices is_open (⋂ (i : β) (hi : i ∈ @univ β), s i), by simpa, is_open_bInter finite_univ (λ i _, h i) lemma is_open_Inter_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_open (s h)) : is_open (Inter s) := by by_cases p; simp * lemma is_open_const {p : Prop} : is_open {a : α | p} := by_cases (assume : p, begin simp only [this]; exact is_open_univ end) (assume : ¬ p, begin simp only [this]; exact is_open_empty end) lemma is_open_and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} := is_open_inter /-- A set is closed if its complement is open -/ def is_closed (s : set α) : Prop := is_open sᶜ @[simp] lemma is_closed_empty : is_closed (∅ : set α) := by unfold is_closed; rw compl_empty; exact is_open_univ @[simp] lemma is_closed_univ : is_closed (univ : set α) := by unfold is_closed; rw compl_univ; exact is_open_empty lemma is_closed_union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) := λ h₁ h₂, by unfold is_closed; rw compl_union; exact is_open_inter h₁ h₂ lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) := by simp only [is_closed, compl_sInter, sUnion_image]; exact assume h, is_open_Union $ assume t, is_open_Union $ assume ht, h t ht lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) := is_closed_sInter $ assume t ⟨i, (heq : f i = t)⟩, heq ▸ h i @[simp] lemma is_open_compl_iff {s : set α} : is_open sᶜ ↔ is_closed s := iff.rfl @[simp] lemma is_closed_compl_iff {s : set α} : is_closed sᶜ ↔ is_open s := by rw [←is_open_compl_iff, compl_compl] lemma is_open_diff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s \ t) := is_open_inter h₁ $ is_open_compl_iff.mpr h₂ lemma is_closed_inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) := by rw [is_closed, compl_inter]; exact is_open_union h₁ h₂ lemma is_closed_bUnion {s : set β} {f : β → set α} (hs : finite s) : (∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) := finite.induction_on hs (λ _, by rw bUnion_empty; exact is_closed_empty) (λ a s has hs ih h, by rw bUnion_insert; exact is_closed_union (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_closed_Union [fintype β] {s : β → set α} (h : ∀ i, is_closed (s i)) : is_closed (Union s) := suffices is_closed (⋃ (i : β) (hi : i ∈ @univ β), s i), by convert this; simp [set.ext_iff], is_closed_bUnion finite_univ (λ i _, h i) lemma is_closed_Union_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_closed (s h)) : is_closed (Union s) := by by_cases p; simp * lemma is_closed_imp {p q : α → Prop} (hp : is_open {x | p x}) (hq : is_closed {x | q x}) : is_closed {x | p x → q x} := have {x | p x → q x} = {x | p x}ᶜ ∪ {x | q x}, from set.ext $ λ x, imp_iff_not_or, by rw [this]; exact is_closed_union (is_closed_compl_iff.mpr hp) hq lemma is_open_neg : is_closed {a | p a} → is_open {a | ¬ p a} := is_open_compl_iff.mpr /-! ### Interior of a set -/ /-- The interior of a set `s` is the largest open subset of `s`. -/ def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s} lemma mem_interior {s : set α} {x : α} : x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t := by simp only [interior, mem_set_of_eq, exists_prop, and_assoc, and.left_comm] @[simp] lemma is_open_interior {s : set α} : is_open (interior s) := is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁ lemma interior_subset {s : set α} : interior s ⊆ s := sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂ lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s := subset_sUnion_of_mem ⟨h₂, h₁⟩ lemma is_open.interior_eq {s : set α} (h : is_open s) : interior s = s := subset.antisymm interior_subset (interior_maximal (subset.refl s) h) lemma interior_eq_iff_open {s : set α} : interior s = s ↔ is_open s := ⟨assume h, h ▸ is_open_interior, is_open.interior_eq⟩ lemma subset_interior_iff_open {s : set α} : s ⊆ interior s ↔ is_open s := by simp only [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset, true_and] lemma subset_interior_iff_subset_of_open {s t : set α} (h₁ : is_open s) : s ⊆ interior t ↔ s ⊆ t := ⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩ lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t := interior_maximal (subset.trans interior_subset h) is_open_interior @[simp] lemma interior_empty : interior (∅ : set α) = ∅ := is_open_empty.interior_eq @[simp] lemma interior_univ : interior (univ : set α) = univ := is_open_univ.interior_eq @[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s := is_open_interior.interior_eq @[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t := subset.antisymm (subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t)) (interior_maximal (inter_subset_inter interior_subset interior_subset) $ is_open_inter is_open_interior is_open_interior) lemma interior_union_is_closed_of_interior_empty {s t : set α} (h₁ : is_closed s) (h₂ : interior t = ∅) : interior (s ∪ t) = interior s := have interior (s ∪ t) ⊆ s, from assume x ⟨u, ⟨(hu₁ : is_open u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩, classical.by_contradiction $ assume hx₂ : x ∉ s, have u \ s ⊆ t, from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂, have u \ s ⊆ interior t, by rwa subset_interior_iff_subset_of_open (is_open_diff hu₁ h₁), have u \ s ⊆ ∅, by rwa h₂ at this, this ⟨hx₁, hx₂⟩, subset.antisymm (interior_maximal this is_open_interior) (interior_mono $ subset_union_left _ _) lemma is_open_iff_forall_mem_open : is_open s ↔ ∀ x ∈ s, ∃ t ⊆ s, is_open t ∧ x ∈ t := by rw ← subset_interior_iff_open; simp only [subset_def, mem_interior] /-! ### Closure of a set -/ /-- The closure of `s` is the smallest closed set containing `s`. -/ def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t} @[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) := is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁ lemma subset_closure {s : set α} : s ⊆ closure s := subset_sInter $ assume t ⟨h₁, h₂⟩, h₂ lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t := sInter_subset_of_mem ⟨h₂, h₁⟩ lemma is_closed.closure_eq {s : set α} (h : is_closed s) : closure s = s := subset.antisymm (closure_minimal (subset.refl s) h) subset_closure lemma is_closed.closure_subset {s : set α} (hs : is_closed s) : closure s ⊆ s := closure_minimal (subset.refl _) hs lemma is_closed.closure_subset_iff {s t : set α} (h₁ : is_closed t) : closure s ⊆ t ↔ s ⊆ t := ⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩ lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t := closure_minimal (subset.trans h subset_closure) is_closed_closure lemma monotone_closure (α : Type*) [topological_space α] : monotone (@closure α _) := λ _ _, closure_mono lemma closure_inter_subset_inter_closure (s t : set α) : closure (s ∩ t) ⊆ closure s ∩ closure t := (monotone_closure α).map_inf_le s t lemma is_closed_of_closure_subset {s : set α} (h : closure s ⊆ s) : is_closed s := by rw subset.antisymm subset_closure h; exact is_closed_closure lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s := ⟨assume h, h ▸ is_closed_closure, is_closed.closure_eq⟩ lemma closure_subset_iff_is_closed {s : set α} : closure s ⊆ s ↔ is_closed s := ⟨is_closed_of_closure_subset, is_closed.closure_subset⟩ @[simp] lemma closure_empty : closure (∅ : set α) = ∅ := is_closed_empty.closure_eq @[simp] lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ := ⟨subset_eq_empty subset_closure, λ h, h.symm ▸ closure_empty⟩ lemma set.nonempty.closure {s : set α} (h : s.nonempty) : set.nonempty (closure s) := let ⟨x, hx⟩ := h in ⟨x, subset_closure hx⟩ @[simp] lemma closure_univ : closure (univ : set α) = univ := is_closed_univ.closure_eq @[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s := is_closed_closure.closure_eq @[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t := subset.antisymm (closure_minimal (union_subset_union subset_closure subset_closure) $ is_closed_union is_closed_closure is_closed_closure) ((monotone_closure α).le_map_sup s t) lemma interior_subset_closure {s : set α} : interior s ⊆ closure s := subset.trans interior_subset subset_closure lemma closure_eq_compl_interior_compl {s : set α} : closure s = (interior sᶜ)ᶜ := begin unfold interior closure is_closed, rw [compl_sUnion, compl_image_set_of], simp only [compl_subset_compl] end @[simp] lemma interior_compl {s : set α} : interior sᶜ = (closure s)ᶜ := by simp [closure_eq_compl_interior_compl] @[simp] lemma closure_compl {s : set α} : closure sᶜ = (interior s)ᶜ := by simp [closure_eq_compl_interior_compl] theorem mem_closure_iff {s : set α} {a : α} : a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → (o ∩ s).nonempty := ⟨λ h o oo ao, classical.by_contradiction $ λ os, have s ⊆ oᶜ, from λ x xs xo, os ⟨x, xo, xs⟩, closure_minimal this (is_closed_compl_iff.2 oo) h ao, λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc, let ⟨x, hc, hs⟩ := (H _ h₁ nc) in hc (h₂ hs)⟩ /-- A set is dense in a topological space if every point belongs to its closure. -/ def dense (s : set α) : Prop := ∀ x, x ∈ closure s lemma dense_iff_closure_eq {s : set α} : dense s ↔ closure s = univ := eq_univ_iff_forall.symm lemma dense.closure_eq {s : set α} (h : dense s) : closure s = univ := dense_iff_closure_eq.mp h /-- The closure of a set `s` is dense if and only if `s` is dense. -/ @[simp] lemma dense_closure {s : set α} : dense (closure s) ↔ dense s := by rw [dense, dense, closure_closure] alias dense_closure ↔ dense.of_closure dense.closure @[simp] lemma dense_univ : dense (univ : set α) := λ x, subset_closure trivial /-- A set is dense if and only if it has a nonempty intersection with each nonempty open set. -/ lemma dense_iff_inter_open {s : set α} : dense s ↔ ∀ U, is_open U → U.nonempty → (U ∩ s).nonempty := begin split ; intro h, { rintros U U_op ⟨x, x_in⟩, exact mem_closure_iff.1 (by simp only [h.closure_eq]) U U_op x_in }, { intro x, rw mem_closure_iff, intros U U_op x_in, exact h U U_op ⟨_, x_in⟩ }, end alias dense_iff_inter_open ↔ dense.inter_open_nonempty _ lemma dense.nonempty_iff {s : set α} (hs : dense s) : s.nonempty ↔ nonempty α := ⟨λ ⟨x, hx⟩, ⟨x⟩, λ ⟨x⟩, let ⟨y, hy⟩ := hs.inter_open_nonempty _ is_open_univ ⟨x, trivial⟩ in ⟨y, hy.2⟩⟩ lemma dense.nonempty [h : nonempty α] {s : set α} (hs : dense s) : s.nonempty := hs.nonempty_iff.2 h @[mono] lemma dense.mono {s₁ s₂ : set α} (h : s₁ ⊆ s₂) (hd : dense s₁) : dense s₂ := λ x, closure_mono h (hd x) /-! ### Frontier of a set -/ /-- The frontier of a set is the set of points between the closure and interior. -/ def frontier (s : set α) : set α := closure s \ interior s lemma frontier_eq_closure_inter_closure {s : set α} : frontier s = closure s ∩ closure sᶜ := by rw [closure_compl, frontier, diff_eq] /-- The complement of a set has the same frontier as the original set. -/ @[simp] lemma frontier_compl (s : set α) : frontier sᶜ = frontier s := by simp only [frontier_eq_closure_inter_closure, compl_compl, inter_comm] lemma frontier_inter_subset (s t : set α) : frontier (s ∩ t) ⊆ (frontier s ∩ closure t) ∪ (closure s ∩ frontier t) := begin simp only [frontier_eq_closure_inter_closure, compl_inter, closure_union], convert inter_subset_inter_left _ (closure_inter_subset_inter_closure s t), simp only [inter_distrib_left, inter_distrib_right, inter_assoc], congr' 2, apply inter_comm end lemma frontier_union_subset (s t : set α) : frontier (s ∪ t) ⊆ (frontier s ∩ closure tᶜ) ∪ (closure sᶜ ∩ frontier t) := by simpa only [frontier_compl, ← compl_union] using frontier_inter_subset sᶜ tᶜ lemma is_closed.frontier_eq {s : set α} (hs : is_closed s) : frontier s = s \ interior s := by rw [frontier, hs.closure_eq] lemma is_open.frontier_eq {s : set α} (hs : is_open s) : frontier s = closure s \ s := by rw [frontier, hs.interior_eq] /-- The frontier of a set is closed. -/ lemma is_closed_frontier {s : set α} : is_closed (frontier s) := by rw frontier_eq_closure_inter_closure; exact is_closed_inter is_closed_closure is_closed_closure /-- The frontier of a closed set has no interior point. -/ lemma interior_frontier {s : set α} (h : is_closed s) : interior (frontier s) = ∅ := begin have A : frontier s = s \ interior s, from h.frontier_eq, have B : interior (frontier s) ⊆ interior s, by rw A; exact interior_mono (diff_subset _ _), have C : interior (frontier s) ⊆ frontier s := interior_subset, have : interior (frontier s) ⊆ (interior s) ∩ (s \ interior s) := subset_inter B (by simpa [A] using C), rwa [inter_diff_self, subset_empty_iff] at this, end lemma closure_eq_interior_union_frontier (s : set α) : closure s = interior s ∪ frontier s := (union_diff_cancel interior_subset_closure).symm lemma closure_eq_self_union_frontier (s : set α) : closure s = s ∪ frontier s := (union_diff_cancel' interior_subset subset_closure).symm /-! ### Neighborhoods -/ /-- A set is called a neighborhood of `a` if it contains an open set around `a`. The set of all neighborhoods of `a` forms a filter, the neighborhood filter at `a`, is here defined as the infimum over the principal filters of all open sets containing `a`. -/ def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) localized "notation `𝓝` := nhds" in topological_space lemma nhds_def (a : α) : 𝓝 a = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) := rfl /-- The open sets containing `a` are a basis for the neighborhood filter. See `nhds_basis_opens'` for a variant using open neighborhoods instead. -/ lemma nhds_basis_opens (a : α) : (𝓝 a).has_basis (λ s : set α, a ∈ s ∧ is_open s) (λ x, x) := has_basis_binfi_principal (λ s ⟨has, hs⟩ t ⟨hat, ht⟩, ⟨s ∩ t, ⟨⟨has, hat⟩, is_open_inter hs ht⟩, ⟨inter_subset_left _ _, inter_subset_right _ _⟩⟩) ⟨univ, ⟨mem_univ a, is_open_univ⟩⟩ /-- A filter lies below the neighborhood filter at `a` iff it contains every open set around `a`. -/ lemma le_nhds_iff {f a} : f ≤ 𝓝 a ↔ ∀ s : set α, a ∈ s → is_open s → s ∈ f := by simp [nhds_def] /-- To show a filter is above the neighborhood filter at `a`, it suffices to show that it is above the principal filter of some open set `s` containing `a`. -/ lemma nhds_le_of_le {f a} {s : set α} (h : a ∈ s) (o : is_open s) (sf : 𝓟 s ≤ f) : 𝓝 a ≤ f := by rw nhds_def; exact infi_le_of_le s (infi_le_of_le ⟨h, o⟩ sf) lemma mem_nhds_sets_iff {a : α} {s : set α} : s ∈ 𝓝 a ↔ ∃t⊆s, is_open t ∧ a ∈ t := (nhds_basis_opens a).mem_iff.trans ⟨λ ⟨t, ⟨hat, ht⟩, hts⟩, ⟨t, hts, ht, hat⟩, λ ⟨t, hts, ht, hat⟩, ⟨t, ⟨hat, ht⟩, hts⟩⟩ /-- A predicate is true in a neighborhood of `a` iff it is true for all the points in an open set containing `a`. -/ lemma eventually_nhds_iff {a : α} {p : α → Prop} : (∀ᶠ x in 𝓝 a, p x) ↔ ∃ (t : set α), (∀ x ∈ t, p x) ∧ is_open t ∧ a ∈ t := mem_nhds_sets_iff.trans $ by simp only [subset_def, exists_prop, mem_set_of_eq] lemma map_nhds {a : α} {f : α → β} : map f (𝓝 a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 (image f s)) := ((nhds_basis_opens a).map f).eq_binfi attribute [irreducible] nhds lemma mem_of_nhds {a : α} {s : set α} : s ∈ 𝓝 a → a ∈ s := λ H, let ⟨t, ht, _, hs⟩ := mem_nhds_sets_iff.1 H in ht hs /-- If a predicate is true in a neighborhood of `a`, then it is true for `a`. -/ lemma filter.eventually.self_of_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) : p a := mem_of_nhds h lemma mem_nhds_sets {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : s ∈ 𝓝 a := mem_nhds_sets_iff.2 ⟨s, subset.refl _, hs, ha⟩ lemma is_open.eventually_mem {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : ∀ᶠ x in 𝓝 a, x ∈ s := mem_nhds_sets hs ha /-- The open neighborhoods of `a` are a basis for the neighborhood filter. See `nhds_basis_opens` for a variant using open sets around `a` instead. -/ lemma nhds_basis_opens' (a : α) : (𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_open s) (λ x, x) := begin convert nhds_basis_opens a, ext s, split, { rintros ⟨s_in, s_op⟩, exact ⟨mem_of_nhds s_in, s_op⟩ }, { rintros ⟨a_in, s_op⟩, exact ⟨mem_nhds_sets s_op a_in, s_op⟩ }, end /-- If a predicate is true in a neighbourhood of `a`, then for `y` sufficiently close to `a` this predicate is true in a neighbourhood of `y`. -/ lemma filter.eventually.eventually_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) : ∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x := let ⟨t, htp, hto, ha⟩ := eventually_nhds_iff.1 h in eventually_nhds_iff.2 ⟨t, λ x hx, eventually_nhds_iff.2 ⟨t, htp, hto, hx⟩, hto, ha⟩ @[simp] lemma eventually_eventually_nhds {p : α → Prop} {a : α} : (∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x) ↔ ∀ᶠ x in 𝓝 a, p x := ⟨λ h, h.self_of_nhds, λ h, h.eventually_nhds⟩ @[simp] lemma nhds_bind_nhds : (𝓝 a).bind 𝓝 = 𝓝 a := filter.ext $ λ s, eventually_eventually_nhds @[simp] lemma eventually_eventually_eq_nhds {f g : α → β} {a : α} : (∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g) ↔ f =ᶠ[𝓝 a] g := eventually_eventually_nhds lemma filter.eventually_eq.eq_of_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : f a = g a := h.self_of_nhds @[simp] lemma eventually_eventually_le_nhds [has_le β] {f g : α → β} {a : α} : (∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g) ↔ f ≤ᶠ[𝓝 a] g := eventually_eventually_nhds /-- If two functions are equal in a neighbourhood of `a`, then for `y` sufficiently close to `a` these functions are equal in a neighbourhood of `y`. -/ lemma filter.eventually_eq.eventually_eq_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : ∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g := h.eventually_nhds /-- If `f x ≤ g x` in a neighbourhood of `a`, then for `y` sufficiently close to `a` we have `f x ≤ g x` in a neighbourhood of `y`. -/ lemma filter.eventually_le.eventually_le_nhds [has_le β] {f g : α → β} {a : α} (h : f ≤ᶠ[𝓝 a] g) : ∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g := h.eventually_nhds theorem all_mem_nhds (x : α) (P : set α → Prop) (hP : ∀ s t, s ⊆ t → P s → P t) : (∀ s ∈ 𝓝 x, P s) ↔ (∀ s, is_open s → x ∈ s → P s) := ((nhds_basis_opens x).forall_iff hP).trans $ by simp only [and_comm (x ∈ _), and_imp] theorem all_mem_nhds_filter (x : α) (f : set α → set β) (hf : ∀ s t, s ⊆ t → f s ⊆ f t) (l : filter β) : (∀ s ∈ 𝓝 x, f s ∈ l) ↔ (∀ s, is_open s → x ∈ s → f s ∈ l) := all_mem_nhds _ _ (λ s t ssubt h, mem_sets_of_superset h (hf s t ssubt)) theorem rtendsto_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.core s ∈ l) := all_mem_nhds_filter _ _ (λ s t, id) _ theorem rtendsto'_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto' r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.preimage s ∈ l) := by { rw [rtendsto'_def], apply all_mem_nhds_filter, apply rel.preimage_mono } theorem ptendsto_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.core s ∈ l) := rtendsto_nhds theorem ptendsto'_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto' f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.preimage s ∈ l) := rtendsto'_nhds theorem tendsto_nhds {f : β → α} {l : filter β} {a : α} : tendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f ⁻¹' s ∈ l) := all_mem_nhds_filter _ _ (λ s t h, preimage_mono h) _ lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (𝓝 a) := tendsto_nhds.mpr $ assume s hs ha, univ_mem_sets' $ assume _, ha lemma pure_le_nhds : pure ≤ (𝓝 : α → filter α) := assume a s hs, mem_pure_sets.2 $ mem_of_nhds hs lemma tendsto_pure_nhds {α : Type*} [topological_space β] (f : α → β) (a : α) : tendsto f (pure a) (𝓝 (f a)) := (tendsto_pure_pure f a).mono_right (pure_le_nhds _) lemma order_top.tendsto_at_top_nhds {α : Type*} [order_top α] [topological_space β] (f : α → β) : tendsto f at_top (𝓝 $ f ⊤) := (tendsto_at_top_pure f).mono_right (pure_le_nhds _) @[simp] instance nhds_ne_bot {a : α} : ne_bot (𝓝 a) := ne_bot_of_le (pure_le_nhds a) /-! ### Cluster points In this section we define [cluster points](https://en.wikipedia.org/wiki/Limit_point) (also known as limit points and accumulation points) of a filter and of a sequence. -/ /-- A point `x` is a cluster point of a filter `F` if 𝓝 x ⊓ F ≠ ⊥. Also known as an accumulation point or a limit point. -/ def cluster_pt (x : α) (F : filter α) : Prop := ne_bot (𝓝 x ⊓ F) lemma cluster_pt.ne_bot {x : α} {F : filter α} (h : cluster_pt x F) : ne_bot (𝓝 x ⊓ F) := h lemma cluster_pt_iff {x : α} {F : filter α} : cluster_pt x F ↔ ∀ ⦃U : set α⦄ (hU : U ∈ 𝓝 x) ⦃V⦄ (hV : V ∈ F), (U ∩ V).nonempty := inf_ne_bot_iff /-- `x` is a cluster point of a set `s` if every neighbourhood of `x` meets `s` on a nonempty set. -/ lemma cluster_pt_principal_iff {x : α} {s : set α} : cluster_pt x (𝓟 s) ↔ ∀ U ∈ 𝓝 x, (U ∩ s).nonempty := inf_principal_ne_bot_iff lemma cluster_pt_principal_iff_frequently {x : α} {s : set α} : cluster_pt x (𝓟 s) ↔ ∃ᶠ y in 𝓝 x, y ∈ s := by simp only [cluster_pt_principal_iff, frequently_iff, set.nonempty, exists_prop, mem_inter_iff] lemma cluster_pt.of_le_nhds {x : α} {f : filter α} (H : f ≤ 𝓝 x) [ne_bot f] : cluster_pt x f := by rwa [cluster_pt, inf_eq_right.mpr H] lemma cluster_pt.of_le_nhds' {x : α} {f : filter α} (H : f ≤ 𝓝 x) (hf : ne_bot f) : cluster_pt x f := cluster_pt.of_le_nhds H lemma cluster_pt.of_nhds_le {x : α} {f : filter α} (H : 𝓝 x ≤ f) : cluster_pt x f := by simp only [cluster_pt, inf_eq_left.mpr H, nhds_ne_bot] lemma cluster_pt.mono {x : α} {f g : filter α} (H : cluster_pt x f) (h : f ≤ g) : cluster_pt x g := ne_bot_of_le_ne_bot H $ inf_le_inf_left _ h lemma cluster_pt.of_inf_left {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x f := H.mono inf_le_left lemma cluster_pt.of_inf_right {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x g := H.mono inf_le_right /-- A point `x` is a cluster point of a sequence `u` along a filter `F` if it is a cluster point of `map u F`. -/ def map_cluster_pt {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : Prop := cluster_pt x (map u F) lemma map_cluster_pt_iff {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : map_cluster_pt x F u ↔ ∀ s ∈ 𝓝 x, ∃ᶠ a in F, u a ∈ s := by { simp_rw [map_cluster_pt, cluster_pt, inf_ne_bot_iff_frequently_left, frequently_map], refl } lemma map_cluster_pt_of_comp {ι δ :Type*} {F : filter ι} {φ : δ → ι} {p : filter δ} {x : α} {u : ι → α} [ne_bot p] (h : tendsto φ p F) (H : tendsto (u ∘ φ) p (𝓝 x)) : map_cluster_pt x F u := begin have := calc map (u ∘ φ) p = map u (map φ p) : map_map ... ≤ map u F : map_mono h, have : map (u ∘ φ) p ≤ 𝓝 x ⊓ map u F, from le_inf H this, exact ne_bot_of_le this end /-! ### Interior, closure and frontier in terms of neighborhoods -/ lemma interior_eq_nhds' {s : set α} : interior s = {a | s ∈ 𝓝 a} := set.ext $ λ x, by simp only [mem_interior, mem_nhds_sets_iff, mem_set_of_eq] lemma interior_eq_nhds {s : set α} : interior s = {a | 𝓝 a ≤ 𝓟 s} := interior_eq_nhds'.trans $ by simp only [le_principal_iff] lemma mem_interior_iff_mem_nhds {s : set α} {a : α} : a ∈ interior s ↔ s ∈ 𝓝 a := by rw [interior_eq_nhds', mem_set_of_eq] lemma interior_set_of_eq {p : α → Prop} : interior {x | p x} = {x | ∀ᶠ y in 𝓝 x, p y} := interior_eq_nhds' lemma is_open_set_of_eventually_nhds {p : α → Prop} : is_open {x | ∀ᶠ y in 𝓝 x, p y} := by simp only [← interior_set_of_eq, is_open_interior] lemma subset_interior_iff_nhds {s V : set α} : s ⊆ interior V ↔ ∀ x ∈ s, V ∈ 𝓝 x := show (∀ x, x ∈ s → x ∈ _) ↔ _, by simp_rw mem_interior_iff_mem_nhds lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, 𝓝 a ≤ 𝓟 s := calc is_open s ↔ s ⊆ interior s : subset_interior_iff_open.symm ... ↔ (∀a∈s, 𝓝 a ≤ 𝓟 s) : by rw [interior_eq_nhds]; refl lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ 𝓝 a := is_open_iff_nhds.trans $ forall_congr $ λ _, imp_congr_right $ λ _, le_principal_iff theorem is_open_iff_ultrafilter {s : set α} : is_open s ↔ (∀ (x ∈ s) (l : filter α), is_ultrafilter l → l ≤ 𝓝 x → s ∈ l) := by simp_rw [is_open_iff_mem_nhds, @mem_iff_ultrafilter _ (𝓝 _)] lemma mem_closure_iff_frequently {s : set α} {a : α} : a ∈ closure s ↔ ∃ᶠ x in 𝓝 a, x ∈ s := by rw [filter.frequently, filter.eventually, ← mem_interior_iff_mem_nhds, closure_eq_compl_interior_compl]; refl alias mem_closure_iff_frequently ↔ _ filter.frequently.mem_closure /-- The set of cluster points of a filter is closed. In particular, the set of limit points of a sequence is closed. -/ lemma is_closed_set_of_cluster_pt {f : filter α} : is_closed {x | cluster_pt x f} := begin simp only [cluster_pt, inf_ne_bot_iff_frequently_left, set_of_forall, imp_iff_not_or], refine is_closed_Inter (λ p, is_closed_union _ _); apply is_closed_compl_iff.2, exacts [is_open_set_of_eventually_nhds, is_open_const] end theorem mem_closure_iff_cluster_pt {s : set α} {a : α} : a ∈ closure s ↔ cluster_pt a (𝓟 s) := mem_closure_iff_frequently.trans cluster_pt_principal_iff_frequently.symm lemma closure_eq_cluster_pts {s : set α} : closure s = {a | cluster_pt a (𝓟 s)} := set.ext $ λ x, mem_closure_iff_cluster_pt theorem mem_closure_iff_nhds {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ 𝓝 a, (t ∩ s).nonempty := mem_closure_iff_cluster_pt.trans cluster_pt_principal_iff theorem mem_closure_iff_nhds' {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ 𝓝 a, ∃ y : s, ↑y ∈ t := by simp only [mem_closure_iff_nhds, set.nonempty_inter_iff_exists_right] theorem mem_closure_iff_comap_ne_bot {A : set α} {x : α} : x ∈ closure A ↔ ne_bot (comap (coe : A → α) (𝓝 x)) := by simp_rw [mem_closure_iff_nhds, comap_ne_bot_iff, set.nonempty_inter_iff_exists_right] theorem mem_closure_iff_nhds_basis {a : α} {p : β → Prop} {s : β → set α} (h : (𝓝 a).has_basis p s) {t : set α} : a ∈ closure t ↔ ∀ i, p i → ∃ y ∈ t, y ∈ s i := mem_closure_iff_nhds.trans ⟨λ H i hi, let ⟨x, hx⟩ := (H _ $ h.mem_of_mem hi) in ⟨x, hx.2, hx.1⟩, λ H t' ht', let ⟨i, hi, hit⟩ := h.mem_iff.1 ht', ⟨x, xt, hx⟩ := H i hi in ⟨x, hit hx, xt⟩⟩ /-- `x` belongs to the closure of `s` if and only if some ultrafilter supported on `s` converges to `x`. -/ lemma mem_closure_iff_ultrafilter {s : set α} {x : α} : x ∈ closure s ↔ ∃ (u : ultrafilter α), s ∈ u.val ∧ u.val ≤ 𝓝 x := begin rw closure_eq_cluster_pts, change cluster_pt x (𝓟 s) ↔ _, symmetry, convert exists_ultrafilter_iff _, ext u, rw [←le_principal_iff, inf_comm, le_inf_iff] end lemma is_closed_iff_cluster_pt {s : set α} : is_closed s ↔ ∀a, cluster_pt a (𝓟 s) → a ∈ s := calc is_closed s ↔ closure s ⊆ s : closure_subset_iff_is_closed.symm ... ↔ (∀a, cluster_pt a (𝓟 s) → a ∈ s) : by simp only [subset_def, mem_closure_iff_cluster_pt] lemma is_closed_iff_nhds {s : set α} : is_closed s ↔ ∀ x, (∀ U ∈ 𝓝 x, (U ∩ s).nonempty) → x ∈ s := by simp_rw [is_closed_iff_cluster_pt, cluster_pt, inf_principal_ne_bot_iff] lemma closure_inter_open {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) := assume a ⟨hs, ht⟩, have s ∈ 𝓝 a, from mem_nhds_sets h hs, have 𝓝 a ⊓ 𝓟 s = 𝓝 a, by rwa [inf_eq_left, le_principal_iff], have cluster_pt a (𝓟 (s ∩ t)), from calc 𝓝 a ⊓ 𝓟 (s ∩ t) = 𝓝 a ⊓ (𝓟 s ⊓ 𝓟 t) : by rw inf_principal ... = 𝓝 a ⊓ 𝓟 t : by rw [←inf_assoc, this] ... ≠ ⊥ : by rw [closure_eq_cluster_pts] at ht; assumption, by rwa [closure_eq_cluster_pts] /-- The intersection of an open dense set with a dense set is a dense set. -/ lemma dense.inter_of_open_left {s t : set α} (hs : dense s) (ht : dense t) (hso : is_open s) : dense (s ∩ t) := λ x, (closure_minimal (closure_inter_open hso) is_closed_closure) $ by simp [hs.closure_eq, ht.closure_eq] /-- The intersection of a dense set with an open dense set is a dense set. -/ lemma dense.inter_of_open_right {s t : set α} (hs : dense s) (ht : dense t) (hto : is_open t) : dense (s ∩ t) := inter_comm t s ▸ ht.inter_of_open_left hs hto lemma closure_diff {s t : set α} : closure s \ closure t ⊆ closure (s \ t) := calc closure s \ closure t = (closure t)ᶜ ∩ closure s : by simp only [diff_eq, inter_comm] ... ⊆ closure ((closure t)ᶜ ∩ s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure ... = closure (s \ closure t) : by simp only [diff_eq, inter_comm] ... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure lemma filter.frequently.mem_of_closed {a : α} {s : set α} (h : ∃ᶠ x in 𝓝 a, x ∈ s) (hs : is_closed s) : a ∈ s := hs.closure_subset h.mem_closure lemma is_closed.mem_of_frequently_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} (hs : is_closed s) (h : ∃ᶠ x in b, f x ∈ s) (hf : tendsto f b (𝓝 a)) : a ∈ s := (hf.frequently $ show ∃ᶠ x in b, (λ y, y ∈ s) (f x), from h).mem_of_closed hs lemma is_closed.mem_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} [ne_bot b] (hs : is_closed s) (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ s := hs.mem_of_frequently_of_tendsto h.frequently hf lemma mem_closure_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} [ne_bot b] (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ closure s := is_closed_closure.mem_of_tendsto hf $ h.mono (preimage_mono subset_closure) /-- Suppose that `f` sends the complement to `s` to a single point `a`, and `l` is some filter. Then `f` tends to `a` along `l` restricted to `s` if and only if it tends to `a` along `l`. -/ lemma tendsto_inf_principal_nhds_iff_of_forall_eq {f : β → α} {l : filter β} {s : set β} {a : α} (h : ∀ x ∉ s, f x = a) : tendsto f (l ⊓ 𝓟 s) (𝓝 a) ↔ tendsto f l (𝓝 a) := begin rw [tendsto_iff_comap, tendsto_iff_comap], replace h : 𝓟 sᶜ ≤ comap f (𝓝 a), { rintros U ⟨t, ht, htU⟩ x hx, have : f x ∈ t, from (h x hx).symm ▸ mem_of_nhds ht, exact htU this }, refine ⟨λ h', _, le_trans inf_le_left⟩, have := sup_le h' h, rw [sup_inf_right, sup_principal, union_compl_self, principal_univ, inf_top_eq, sup_le_iff] at this, exact this.1 end /-! ### Limits of filters in topological spaces -/ section lim /-- If `f` is a filter, then `Lim f` is a limit of the filter, if it exists. -/ noncomputable def Lim [nonempty α] (f : filter α) : α := epsilon $ λa, f ≤ 𝓝 a /-- If `f` is a filter satisfying `ne_bot f`, then `Lim' f` is a limit of the filter, if it exists. -/ def Lim' (f : filter α) [ne_bot f] : α := @Lim _ _ (nonempty_of_ne_bot f) f -- Note: `ultrafilter` is inside the `filter` namespace. /-- If `F` is an ultrafilter, then `filter.ultrafilter.Lim F` is a limit of the filter, if it exists. Note that dot notation `F.Lim` can be used for `F : ultrafilter α`. -/ def filter.ultrafilter.Lim : ultrafilter α → α := λ F, Lim' F.1 /-- If `f` is a filter in `β` and `g : β → α` is a function, then `lim f` is a limit of `g` at `f`, if it exists. -/ noncomputable def lim [nonempty α] (f : filter β) (g : β → α) : α := Lim (f.map g) /-- If a filter `f` is majorated by some `𝓝 a`, then it is majorated by `𝓝 (Lim f)`. We formulate this lemma with a `[nonempty α]` argument of `Lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma le_nhds_Lim {f : filter α} (h : ∃a, f ≤ 𝓝 a) : f ≤ 𝓝 (@Lim _ _ (nonempty_of_exists h) f) := epsilon_spec h /-- If `g` tends to some `𝓝 a` along `f`, then it tends to `𝓝 (lim f g)`. We formulate this lemma with a `[nonempty α]` argument of `lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma tendsto_nhds_lim {f : filter β} {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) : tendsto g f (𝓝 $ @lim _ _ _ (nonempty_of_exists h) f g) := le_nhds_Lim h end lim /-! ### Locally finite families -/ /- locally finite family [General Topology (Bourbaki, 1995)] -/ section locally_finite /-- A family of sets in `set α` is locally finite if at every point `x:α`, there is a neighborhood of `x` which meets only finitely many sets in the family -/ def locally_finite (f : β → set α) := ∀x:α, ∃t ∈ 𝓝 x, finite {i | (f i ∩ t).nonempty } lemma locally_finite_of_finite {f : β → set α} (h : finite (univ : set β)) : locally_finite f := assume x, ⟨univ, univ_mem_sets, h.subset $ subset_univ _⟩ lemma locally_finite_subset {f₁ f₂ : β → set α} (hf₂ : locally_finite f₂) (hf : ∀b, f₁ b ⊆ f₂ b) : locally_finite f₁ := assume a, let ⟨t, ht₁, ht₂⟩ := hf₂ a in ⟨t, ht₁, ht₂.subset $ assume i hi, hi.mono $ inter_subset_inter (hf i) $ subset.refl _⟩ lemma is_closed_Union_of_locally_finite {f : β → set α} (h₁ : locally_finite f) (h₂ : ∀i, is_closed (f i)) : is_closed (⋃i, f i) := is_open_iff_nhds.mpr $ assume a, assume h : a ∉ (⋃i, f i), have ∀i, a ∈ (f i)ᶜ, from assume i hi, h $ mem_Union.2 ⟨i, hi⟩, have ∀i, (f i)ᶜ ∈ (𝓝 a), by simp only [mem_nhds_sets_iff]; exact assume i, ⟨(f i)ᶜ, subset.refl _, h₂ i, this i⟩, let ⟨t, h_sets, (h_fin : finite {i | (f i ∩ t).nonempty })⟩ := h₁ a in calc 𝓝 a ≤ 𝓟 (t ∩ (⋂ i∈{i | (f i ∩ t).nonempty }, (f i)ᶜ)) : begin rw [le_principal_iff], apply @filter.inter_mem_sets _ (𝓝 a) _ _ h_sets, apply @filter.Inter_mem_sets _ (𝓝 a) _ _ _ h_fin, exact assume i h, this i end ... ≤ 𝓟 (⋃i, f i)ᶜ : begin simp only [principal_mono, subset_def, mem_compl_eq, mem_inter_eq, mem_Inter, mem_set_of_eq, mem_Union, and_imp, not_exists, exists_imp_distrib, ne_empty_iff_nonempty, set.nonempty], exact assume x xt ht i xfi, ht i x xfi xt xfi end end locally_finite end topological_space /-! ### Continuity -/ section continuous variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] open_locale topological_space /-- A function between topological spaces is continuous if the preimage of every open set is open. -/ def continuous (f : α → β) := ∀s, is_open s → is_open (f ⁻¹' s) lemma is_open.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_open s) : is_open (f ⁻¹' s) := hf s h /-- A function between topological spaces is continuous at a point `x₀` if `f x` tends to `f x₀` when `x` tends to `x₀`. -/ def continuous_at (f : α → β) (x : α) := tendsto f (𝓝 x) (𝓝 (f x)) lemma continuous_at.tendsto {f : α → β} {x : α} (h : continuous_at f x) : tendsto f (𝓝 x) (𝓝 (f x)) := h lemma continuous_at.preimage_mem_nhds {f : α → β} {x : α} {t : set β} (h : continuous_at f x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝 x := h ht lemma preimage_interior_subset_interior_preimage {f : α → β} {s : set β} (hf : continuous f) : f⁻¹' (interior s) ⊆ interior (f⁻¹' s) := interior_maximal (preimage_mono interior_subset) (hf _ is_open_interior) lemma continuous_id : continuous (id : α → α) := assume s h, h lemma continuous.comp {g : β → γ} {f : α → β} (hg : continuous g) (hf : continuous f) : continuous (g ∘ f) := assume s h, hf _ (hg s h) lemma continuous.iterate {f : α → α} (h : continuous f) (n : ℕ) : continuous (f^[n]) := nat.rec_on n continuous_id (λ n ihn, ihn.comp h) lemma continuous_at.comp {g : β → γ} {f : α → β} {x : α} (hg : continuous_at g (f x)) (hf : continuous_at f x) : continuous_at (g ∘ f) x := hg.comp hf lemma continuous.tendsto {f : α → β} (hf : continuous f) (x) : tendsto f (𝓝 x) (𝓝 (f x)) := ((nhds_basis_opens x).tendsto_iff $ nhds_basis_opens $ f x).2 $ λ t ⟨hxt, ht⟩, ⟨f ⁻¹' t, ⟨hxt, hf _ ht⟩, subset.refl _⟩ lemma continuous.continuous_at {f : α → β} {x : α} (h : continuous f) : continuous_at f x := h.tendsto x lemma continuous_iff_continuous_at {f : α → β} : continuous f ↔ ∀ x, continuous_at f x := ⟨continuous.tendsto, assume hf : ∀x, tendsto f (𝓝 x) (𝓝 (f x)), assume s, assume hs : is_open s, have ∀a, f a ∈ s → s ∈ 𝓝 (f a), from λ a ha, mem_nhds_sets hs ha, show is_open (f ⁻¹' s), from is_open_iff_nhds.2 $ λ a ha, le_principal_iff.2 $ hf _ (this a ha)⟩ lemma continuous_const {b : β} : continuous (λa:α, b) := continuous_iff_continuous_at.mpr $ assume a, tendsto_const_nhds lemma continuous_at_const {x : α} {b : β} : continuous_at (λ a:α, b) x := continuous_const.continuous_at lemma continuous_at_id {x : α} : continuous_at id x := continuous_id.continuous_at lemma continuous_at.iterate {f : α → α} {x : α} (hf : continuous_at f x) (hx : f x = x) (n : ℕ) : continuous_at (f^[n]) x := nat.rec_on n continuous_at_id $ λ n ihn, show continuous_at (f^[n] ∘ f) x, from continuous_at.comp (hx.symm ▸ ihn) hf lemma continuous_iff_is_closed {f : α → β} : continuous f ↔ (∀s, is_closed s → is_closed (f ⁻¹' s)) := ⟨assume hf s hs, hf sᶜ hs, assume hf s, by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩ lemma is_closed.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_closed s) : is_closed (f ⁻¹' s) := continuous_iff_is_closed.mp hf s h lemma continuous_at_iff_ultrafilter {f : α → β} (x) : continuous_at f x ↔ ∀ g, is_ultrafilter g → g ≤ 𝓝 x → g.map f ≤ 𝓝 (f x) := tendsto_iff_ultrafilter f (𝓝 x) (𝓝 (f x)) lemma continuous_iff_ultrafilter {f : α → β} : continuous f ↔ ∀ x g, is_ultrafilter g → g ≤ 𝓝 x → g.map f ≤ 𝓝 (f x) := by simp only [continuous_iff_continuous_at, continuous_at_iff_ultrafilter] /-- A piecewise defined function `if p then f else g` is continuous, if both `f` and `g` are continuous, and they coincide on the frontier (boundary) of the set `{a | p a}`. -/ lemma continuous_if {p : α → Prop} {f g : α → β} {h : ∀a, decidable (p a)} (hp : ∀a∈frontier {a | p a}, f a = g a) (hf : continuous f) (hg : continuous g) : continuous (λa, @ite (p a) (h a) β (f a) (g a)) := continuous_iff_is_closed.mpr $ assume s hs, have (λa, ite (p a) (f a) (g a)) ⁻¹' s = (closure {a | p a} ∩ f ⁻¹' s) ∪ (closure {a | ¬ p a} ∩ g ⁻¹' s), from set.ext $ assume a, classical.by_cases (assume : a ∈ frontier {a | p a}, have hac : a ∈ closure {a | p a}, from this.left, have hai : a ∈ closure {a | ¬ p a}, from have a ∈ (interior {a | p a})ᶜ, from this.right, by rwa [←closure_compl] at this, by by_cases p a; simp [h, hp a this, hac, hai, iff_def] {contextual := tt}) (assume hf : a ∈ (frontier {a | p a})ᶜ, classical.by_cases (assume : p a, have hc : a ∈ closure {a | p a}, from subset_closure this, have hnc : a ∉ closure {a | ¬ p a}, by show a ∉ closure {a | p a}ᶜ; rw [closure_compl]; simpa [frontier, hc] using hf, by simp [this, hc, hnc]) (assume : ¬ p a, have hc : a ∈ closure {a | ¬ p a}, from subset_closure this, have hnc : a ∉ closure {a | p a}, begin have hc : a ∈ closure {a | p a}ᶜ, from hc, simp [closure_compl] at hc, simpa [frontier, hc] using hf end, by simp [this, hc, hnc])), by rw [this]; exact is_closed_union (is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hf s hs) (is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hg s hs) /- Continuity and partial functions -/ /-- Continuity of a partial function -/ def pcontinuous (f : α →. β) := ∀ s, is_open s → is_open (f.preimage s) lemma open_dom_of_pcontinuous {f : α →. β} (h : pcontinuous f) : is_open f.dom := by rw [←pfun.preimage_univ]; exact h _ is_open_univ lemma pcontinuous_iff' {f : α →. β} : pcontinuous f ↔ ∀ {x y} (h : y ∈ f x), ptendsto' f (𝓝 x) (𝓝 y) := begin split, { intros h x y h', simp only [ptendsto'_def, mem_nhds_sets_iff], rintros s ⟨t, tsubs, opent, yt⟩, exact ⟨f.preimage t, pfun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩ }, intros hf s os, rw is_open_iff_nhds, rintros x ⟨y, ys, fxy⟩ t, rw [mem_principal_sets], assume h : f.preimage s ⊆ t, change t ∈ 𝓝 x, apply mem_sets_of_superset _ h, have h' : ∀ s ∈ 𝓝 y, f.preimage s ∈ 𝓝 x, { intros s hs, have : ptendsto' f (𝓝 x) (𝓝 y) := hf fxy, rw ptendsto'_def at this, exact this s hs }, show f.preimage s ∈ 𝓝 x, apply h', rw mem_nhds_sets_iff, exact ⟨s, set.subset.refl _, os, ys⟩ end lemma image_closure_subset_closure_image {f : α → β} {s : set α} (h : continuous f) : f '' closure s ⊆ closure (f '' s) := have ∀ (a : α), cluster_pt a (𝓟 s) → cluster_pt (f a) (𝓟 (f '' s)), from assume a ha, have h₁ : ¬ map f (𝓝 a ⊓ 𝓟 s) = ⊥, by rwa[map_eq_bot_iff], have h₂ : map f (𝓝 a ⊓ 𝓟 s) ≤ 𝓝 (f a) ⊓ 𝓟 (f '' s), from le_inf (le_trans (map_mono inf_le_left) $ by rw [continuous_iff_continuous_at] at h; exact h a) (le_trans (map_mono inf_le_right) $ by simp [subset_preimage_image] ), ne_bot_of_le_ne_bot h₁ h₂, by simp [image_subset_iff, closure_eq_cluster_pts]; assumption lemma mem_closure {s : set α} {t : set β} {f : α → β} {a : α} (hf : continuous f) (ha : a ∈ closure s) (ht : ∀a∈s, f a ∈ t) : f a ∈ closure t := subset.trans (image_closure_subset_closure_image hf) (closure_mono $ image_subset_iff.2 ht) $ (mem_image_of_mem f ha) /-! ### Function with dense range -/ section dense_range variables {κ ι : Type*} (f : κ → β) (g : β → γ) /-- `f : ι → β` has dense range if its range (image) is a dense subset of β. -/ def dense_range := dense (range f) variables {f} /-- A surjective map has dense range. -/ lemma function.surjective.dense_range (hf : function.surjective f) : dense_range f := λ x, by simp [hf.range_eq] lemma dense_range_iff_closure_range : dense_range f ↔ closure (range f) = univ := dense_iff_closure_eq lemma dense_range.closure_range (h : dense_range f) : closure (range f) = univ := h.closure_eq lemma continuous.range_subset_closure_image_dense {f : α → β} (hf : continuous f) {s : set α} (hs : dense s) : range f ⊆ closure (f '' s) := by { rw [← image_univ, ← hs.closure_eq], exact image_closure_subset_closure_image hf } /-- The image of a dense set under a continuous map with dense range is a dense set. -/ lemma dense_range.dense_image {f : α → β} (hf' : dense_range f) (hf : continuous f) {s : set α} (hs : dense s) : dense (f '' s) := (hf'.mono $ hf.range_subset_closure_image_dense hs).of_closure /-- If a continuous map with dense range maps a dense set to a subset of `t`, then `t` is a dense set. -/ lemma dense_range.dense_of_maps_to {f : α → β} (hf' : dense_range f) (hf : continuous f) {s : set α} (hs : dense s) {t : set β} (ht : maps_to f s t) : dense t := (hf'.dense_image hf hs).mono ht.image_subset /-- Composition of a continuous map with dense range and a function with dense range has dense range. -/ lemma dense_range.comp {g : β → γ} {f : κ → β} (hg : dense_range g) (hf : dense_range f) (cg : continuous g) : dense_range (g ∘ f) := by { rw [dense_range, range_comp], exact hg.dense_image cg hf } lemma dense_range.nonempty_iff (hf : dense_range f) : nonempty κ ↔ nonempty β := range_nonempty_iff_nonempty.symm.trans hf.nonempty_iff lemma dense_range.nonempty [h : nonempty β] (hf : dense_range f) : nonempty κ := hf.nonempty_iff.mpr h /-- Given a function `f : α → β` with dense range and `b : β`, returns some `a : α`. -/ def dense_range.some (hf : dense_range f) (b : β) : κ := classical.choice $ hf.nonempty_iff.mpr ⟨b⟩ end dense_range end continuous
164131346a0c7d3a6b2a0972d2554d4f7a8b10e9
94637389e03c919023691dcd05bd4411b1034aa5
/src/inClassNotes/typeclasses/dihedral_4/d4.lean
ed9c7c4b1a20636c9acd1657b8833316b3846dba
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
478
lean
import ..algebra /- The group, D4. -/ inductive dihedral_4 : Type | r0 -- 0 quarter turns r: rotation | r1 -- 1 quarter turn | r2 -- 2 quarter turns | r3 -- 3 quarter turns | sr0 -- flip horizontal s: reflection | sr1 -- flip ne/sw | sr2 -- flip vertical | sr3 -- flip nw/se open dihedral_4 def e := r0 def mul : dihedral_4 → dihedral_4 → dihedral_4 -- closed | _ _ := r0 /- r^n is still a rotation sr^n and r^ns are reflections -/
5933af8ec1657de3fec2fa931f70bf9e53a0ba71
ca37452420f42eb9a19643a034c532fb39187bd0
/lemmas2.lean
a71b269baf9759c2b91666e489cd3930c4008ab1
[]
no_license
minchaowu/Kruskal.lean
0096fd12c6732dcb55214907e7241df27d22a51e
0ec4a724c18d8fa2bc1e81dfc026a045888526d5
refs/heads/master
1,589,975,750,330
1,481,928,508,000
1,481,928,508,000
70,121,484
0
0
null
null
null
null
UTF-8
Lean
false
false
33,631
lean
import data.nat data.set lemmas_from_ramsey lemmas1 open classical nat function prod set subtype noncomputable theory definition inj_from_to {A B: Type} (f : A → B) (S1 : set A) (S2 : set B) := maps_to f S1 S2 ∧ inj_on f S1 theorem inj_from_to_id {A : Type} (S1 : set A) : (∀ a, a ∈ S1 → id a ∈ S1) ∧ ∀ a₁ a₂, a₁ ∈ S1 → a₂ ∈ S1 → id a₁ = id a₂ → a₁ = a₂ := by split;intro;intro;simp;intros;intro;simp theorem inj_from_to_compose {A B C : Type} {g : B → C} {f : A → B} {S1 : set A} {S2 : set B} {S3 : set C} (Hg : inj_from_to g S2 S3) (Hf : inj_from_to f S1 S2) : inj_from_to (g ∘ f) S1 S3 := have Hl : ∀ a, a ∈ S1 → g (f a) ∈ S3, from take a, assume Ha, have f a ∈ S2, from (and.left Hf) a Ha, (and.left Hg) (f a) this, have ∀ a₁ a₂, a₁ ∈ S1 → a₂ ∈ S1 → g (f a₁) = g (f a₂) → a₁ = a₂, from take a₁ a₂, assume Ha₁, assume Ha₂, assume Heq, have in1 : f a₁ ∈ S2, from and.left Hf a₁ Ha₁, have in2 : f a₂ ∈ S2, from and.left Hf a₂ Ha₂, have f a₁ = f a₂, from and.right Hg (f a₁) (f a₂) in1 in2 Heq, and.right Hf a₁ a₂ Ha₁ Ha₂ this, and.intro Hl this theorem gt_of_gt_pred {a b : ℕ} (H : pred b < a) : b ≤ a := by_cases (suppose b = 0, by+ simp) (suppose b ≠ 0, have ∃ k, b = succ k, from exists_eq_succ_of_ne_zero this, obtain k hk, from this, have pred (succ k) < a, by+ rewrite hk at H;exact H, have k < a, by+ simp, have succ k ≤ a, from succ_le_of_lt this, by+ simp) theorem sub_gt_of_gt {a b c : ℕ} (H1 : a > b) (H2 : b > c) : a - c > b - c := have c ≤ a, from le_of_lt (gt.trans H1 H2), have a - c + c = a, from nat.sub_add_cancel this, have c ≤ b, from le_of_lt H2, have b - c + c = b, from nat.sub_add_cancel this, have b ≤ a, from le_of_lt H1, have b - c ≤ a - c, from nat.sub_le_sub_right this c, or.elim (nat.lt_or_eq_of_le this) (assume Hl, Hl) (assume Hr, have a - c + c = b - c + c, by+ simp, have refl : a > a, by+ simp, absurd refl (not_lt_self a)) theorem lt_pred_nonzero_self {n : ℕ} (H : n ≠ 0) : pred n < n := have ∃ k, n = succ k, from exists_eq_succ_of_ne_zero H, obtain k hk, from this, by+ simp theorem eq_values_of_eq_func {A B : Type} {f g : A → B} (H : f = g) (a : A) : f a = g a := have g a = g a, from rfl, by+ rewrite -H at this{1};exact this theorem ne_empty_of_mem {X : Type} {s : set X} {x : X} (H : x ∈ s) : s ≠ ∅ := begin intro Hs, rewrite Hs at H, apply not_mem_empty _ H end theorem image_nonempty {A B : Type} {f : A → B} {S : set A} (H : S ≠ ∅) : f ' S ≠ ∅ := have ∃ s, s ∈ S, from exists_mem_of_ne_empty H, obtain s h, from this, have f s ∈ f ' S, from exists.intro s (and.intro h rfl), ne_empty_of_mem this theorem not_mem_singleton {A : Type} (x a : A) (H : x ≠ a) : x ∉ '{a} := suppose x ∈ '{a}, H (eq_of_mem_singleton this) theorem refl_of_diff_of_ins_singleton {A : Type} {a : A} {S : set A} (H : a ∉ S) : S = (insert a S) \ '{a} := begin apply subset.antisymm, intro,intro,split,apply or.inr, assumption, intro,have x = a, by apply eq_of_mem_singleton, assumption, have a ∈ S, by simp, contradiction, intro,intro H2,apply or.elim (and.left H2),intro, have x ∈ '{a}, by rewrite a_1; apply mem_singleton, apply absurd this (and.right H2), intro, assumption end namespace kruskal check good_pairs section -- Given a countable set of objects A (which is ordered by f), and assuming that there exists a bad sequence (i.e., f ∘ g) of these objects, we can find a (sub)sequence (f ∘ h) which is bad and ∀ i, h 0 ≤ h i. parameter {A : Type} parameter f : ℕ → A parameter g : ℕ → ℕ parameter o : A → A → Prop parameter H : ¬ is_good (f ∘ g) o definition ran_g : set ℕ := {x : ℕ | ∃ i, g i = x} theorem ne_empty_ran : ran_g ≠ ∅ := have g 0 ∈ ran_g, from exists.intro 0 rfl, ne_empty_of_mem this private definition min : ℕ := chooseleast ran_g ne_empty_ran definition index_of_min : ℕ := have min ∈ ran_g, from least_is_mem ran_g ne_empty_ran, some this theorem minimality_of_min (n : ℕ) : g index_of_min ≤ g n := have H1 : g index_of_min = min, from some_spec (least_is_mem ran_g ne_empty_ran), have g n ∈ ran_g, from exists.intro n rfl, minimality H1 this private definition h (n : ℕ) : ℕ := g (index_of_min + n) theorem exists_sub_bad : ∃ h : ℕ → ℕ, ¬ is_good (f ∘ h) o ∧ ∀ i : ℕ, h 0 ≤ h i := have badness : ¬ is_good (f ∘ h) o, from suppose is_good (f ∘ h) o, obtain (i j) hij, from this, have Hr : o (f (g (index_of_min + i))) (f (g (index_of_min + j))), from and.right hij, have index_of_min + i < index_of_min + j, from add_lt_add_left (and.left hij) _, have is_good (f ∘ g) o, from exists.intro (index_of_min + i) (exists.intro (index_of_min + j) (and.intro this Hr)), H this, have ∀ i : ℕ, h 0 ≤ h i, by+ intro; apply minimality_of_min (index_of_min + i), exists.intro h (and.intro badness this) end definition finite_subsets (Q : Type) : Type := {x : set Q | finite x} definition non_descending {Q : Type} (A B : finite_subsets Q) (o : Q → Q → Prop) (f : Q → Q) := ∀ a : Q, a ∈ elt_of A → o a (f a) ∧ f a ∈ elt_of B definition order_on_finite_subsets {Q : Type} (o : Q → Q → Prop) (A B : finite_subsets Q) := ∃ f, inj_from_to f (elt_of A) (elt_of B) ∧ non_descending A B o f definition extends_at {A : Type} (n : ℕ) (f : ℕ → A) (g : ℕ → A) : Prop := ∀ m, m ≤ n → g m = f m theorem extends_at.refl {A : Type} {n : ℕ} {f : ℕ → A} : extends_at n f f := λ m H, rfl theorem extends_at.trans {A : Type} {n m : ℕ} {f g h: ℕ → A} (H1 : extends_at n f g) (H2 : extends_at m g h) (H3 : n ≤ m) : extends_at n f h := take k, assume H, have g k = f k, from H1 k H, have k ≤ m, from le.trans H H3, have h k = g k, from H2 k this, by+ simp definition induced_set_of_exists {A : Type} {P : A → Prop} (H : ∃ x, P x) : set A := {x | P x} theorem nonempty_induced_set {A : Type} {P : A → Prop} (H : ∃ x, P x) : induced_set_of_exists H ≠ ∅ := obtain a h, from H, ne_empty_of_mem h theorem property_of_induced_set {A : Type} {P : A → Prop} (H : ∃ x, P x) : ∀₀ s ∈ induced_set_of_exists H, P s := take s, assume h, h theorem least_seq_at_n {S : set (ℕ → ℕ)} (H : S ≠ ∅) (n : ℕ) : ∃₀ f ∈ S, ∀₀ g ∈ S, f n ≤ g n := let T : set ℕ := {x | ∃₀ f ∈ S, f n = x} in have ∃ f, f ∈ S, from exists_mem_of_ne_empty H, obtain f h, from this, have f n ∈ T, from exists.intro f (and.intro h rfl), have nemp : T ≠ ∅, from ne_empty_of_mem this, let a := chooseleast T nemp in have a ∈ T, from least_is_mem T nemp, obtain f' h, from this, have f' n = a, from and.right h, have ∀₀ g ∈ S, f' n ≤ g n, from take g, assume Hg, have g n ∈ T, from exists.intro g (and.intro Hg rfl), have a ≤ g n, from minimality rfl this, by+ simp, exists.intro f' (and.intro (and.left h) this) section -- given an n, take an f from {f | P f} such that |f n| is as small as possible. parameter {A : Type} parameter {P : (ℕ → A) → Prop} parameter g : A → ℕ -- a function which calculates the cardinality of a : A in some sense. parameter H : ∃ f : ℕ → A, P f definition card_of_f (f : ℕ → A) (n : ℕ) := g (f n) definition set_of_f := induced_set_of_exists H lemma nonempty_set_of_f : set_of_f ≠ ∅ := nonempty_induced_set H definition S : set (ℕ → ℕ) := card_of_f ' set_of_f lemma nonempty_S : S ≠ ∅ := image_nonempty nonempty_set_of_f theorem exists_min_f (n : ℕ) : ∃₀ f ∈ S, ∀₀ g ∈ S, f n ≤ g n := least_seq_at_n nonempty_S n definition minf_at_n (n : ℕ) : ℕ → A := let fc := some (exists_min_f n) in have fc ∈ S, from and.left (some_spec (exists_min_f n)), some this theorem property_of_minf (n : ℕ) : P (minf_at_n n) := let fc := some (exists_min_f n) in have fc ∈ S, from and.left (some_spec (exists_min_f n)), have minf_at_n n ∈ set_of_f ∧ card_of_f (minf_at_n n) = fc, from some_spec this, have minf_at_n n ∈ set_of_f, from and.left this, property_of_induced_set H this -- For every f satisfying P, we have the inequality. Intuitively, it says that |(minf_at_n n) n| is always less than or equal to |f n|. theorem minimality_of_minf (f : ℕ → A) (Hp : P f) (n : ℕ) : g (minf_at_n n n) ≤ g (f n) := let fc := some (exists_min_f n) in have fc ∈ S, from and.left (some_spec (exists_min_f n)), have minf_at_n n ∈ set_of_f ∧ card_of_f (minf_at_n n) = fc, from some_spec this, have card_of_f (minf_at_n n) = fc, from and.right this, have eq2 : card_of_f (minf_at_n n) n = fc n, from eq_values_of_eq_func this n, have Hr : ∀₀ g ∈ S, fc n ≤ g n, from and.right (some_spec (exists_min_f n)), have card_of_f f ∈ S, from exists.intro f (and.intro Hp rfl), have le : fc n ≤ card_of_f f n, from Hr this, have card_of_f (minf_at_n n) n = g (minf_at_n n n), from rfl, have card_of_f f n = g (f n), from rfl, have card_of_f (minf_at_n n) n ≤ card_of_f f n, by+ rewrite -eq2 at le;exact le, by+ simp end section parameter {A : Type} parameter {P : (ℕ → A) → Prop} -- some property about f parameter g : A → ℕ -- a measure of cardinality of A parameter H : ∃ f, P f -- construct a sequence of functions with property P such that each one extends its predecessor and is the minimal one at n. noncomputable definition mbs_helper (n : ℕ) : {f : ℕ → A | P f} := nat.rec_on n (let f₀ := minf_at_n g H 0 in have P f₀, from property_of_minf g H 0, tag f₀ this) (λ pred h', let f' := elt_of h' in have H1 : extends_at pred f' f', from extends_at.refl, have H2 : P f', from has_property h', have HP : ∃ f, extends_at pred f' f ∧ P f, from exists.intro f' (and.intro H1 H2), let fn := minf_at_n g HP (succ pred) in have extends_at pred f' fn ∧ P fn, from property_of_minf g HP (succ pred), have P fn, from proof and.right this qed, tag fn this) section parameter n : ℕ definition helper_elt := elt_of (mbs_helper n) definition helper_succ := elt_of (mbs_helper (succ n)) lemma helper_ext_refl : extends_at n helper_elt helper_elt := extends_at.refl lemma helper_has_property : P helper_elt := has_property (mbs_helper n) lemma helper_inner_hyp : ∃ g, extends_at n helper_elt g ∧ P g := exists.intro helper_elt (and.intro helper_ext_refl helper_has_property) theorem succ_ext_of_mbs_helper : extends_at n helper_elt helper_succ := and.left (property_of_minf g helper_inner_hyp (succ n)) end theorem ext_of_mbs_helper (n : ℕ) : ∀ m, m ≤ n → extends_at m (elt_of (mbs_helper m)) (elt_of (mbs_helper n)) := nat.induction_on n (take m, assume H, have m = 0, from eq_zero_of_le_zero H, have extends_at 0 (elt_of (mbs_helper 0)) (elt_of (mbs_helper 0)), from extends_at.refl, by+ simp) (take a, assume IH, take m, assume H, by_cases (suppose m = succ a, have extends_at m (elt_of (mbs_helper (succ a))) (elt_of (mbs_helper (succ a))), from extends_at.refl, by+ simp) (suppose m ≠ succ a, have m < succ a, from lt_of_le_of_ne H this, have Hle : m ≤ a, from (and.left (lt_succ_iff_le m a)) this, have H1 : extends_at m (elt_of (mbs_helper m)) (elt_of (mbs_helper a)), from IH m Hle, have extends_at a (elt_of (mbs_helper a)) (elt_of (mbs_helper (succ a))), from succ_ext_of_mbs_helper a, extends_at.trans H1 this Hle)) theorem congruence_of_mbs_helper {n m : ℕ} (H : m ≤ n) : (elt_of (mbs_helper n)) m = (elt_of (mbs_helper m)) m := have extends_at m (elt_of (mbs_helper m)) (elt_of (mbs_helper n)), from ext_of_mbs_helper n m H, this m (le.refl m) end section -- construction and properties of mbs. parameter {A : Type} parameter {o : A → A → Prop} parameter g : A → ℕ parameter H : ∃ f : ℕ → A, ¬ is_good f o noncomputable definition seq_of_bad_seq (n : ℕ) : {f : ℕ → A | ¬ is_good f o} := mbs_helper g H n definition minimal_bad_seq (n : ℕ) : A := (elt_of (seq_of_bad_seq n)) n definition ext_of_seq_of_bad_seq := ext_of_mbs_helper g H definition congruence_of_seq_of_bad_seq {n m : ℕ} (Hnm : m ≤ n) := congruence_of_mbs_helper g H Hnm definition bad_seq_elt := helper_elt g H definition bad_seq_inner_hyp := helper_inner_hyp g H theorem badness_of_mbs : ¬ is_good minimal_bad_seq o := suppose is_good minimal_bad_seq o, obtain (i j : ℕ) h, from this, have le : i < j, from and.left h, have i ≤ j, from le_of_lt_or_eq (or.intro_left (i = j) le), have ext : extends_at i (elt_of (seq_of_bad_seq i)) (elt_of (seq_of_bad_seq j)), from ext_of_seq_of_bad_seq j i this, have i ≤ i, from le.refl i, have elt_of (seq_of_bad_seq j) i = (minimal_bad_seq i), from ext i this, have o (elt_of (seq_of_bad_seq j) i) (minimal_bad_seq j), by+ simp, have i < j ∧ o (elt_of (seq_of_bad_seq j) i) (elt_of (seq_of_bad_seq j) j), from and.intro le this, have good : is_good (elt_of (seq_of_bad_seq j)) o, from exists.intro i (exists.intro j this), have ¬ is_good (elt_of (seq_of_bad_seq j)) o, from has_property (seq_of_bad_seq j), this good theorem minimality_of_mbs_0 (f : ℕ → A) (Hf : ¬ is_good f o) : g (minimal_bad_seq 0) ≤ g (f 0) := minimality_of_minf g H f Hf 0 theorem minimality_of_mbs (n : ℕ) (f : ℕ → A) (H1 : extends_at n minimal_bad_seq f ∧ ¬ is_good f o) : g (minimal_bad_seq (succ n)) ≤ g (f (succ n)) := have Hl : ∀ m, m ≤ n → f m = (bad_seq_elt n) m, from take m, assume Hle, have f m = minimal_bad_seq m, from and.left H1 m Hle, have bad_seq_elt n m = minimal_bad_seq m, from congruence_of_seq_of_bad_seq Hle, by+ simp, have ins_P : extends_at n (bad_seq_elt n) f ∧ ¬ is_good f o, from and.intro Hl (and.right H1), have ineq : g (minf_at_n g (bad_seq_inner_hyp n) (succ n) (succ n)) ≤ g (f (succ n)), from minimality_of_minf g (bad_seq_inner_hyp n) f ins_P (succ n), have minimal_bad_seq (succ n) = minf_at_n g (bad_seq_inner_hyp n) (succ n) (succ n), from rfl, by+ rewrite (eq.symm this) at ineq; exact ineq end check seq_of_bad_seq section -- Given two sequences f and g, a function h which modifies indices so that h 0 is the break point, construct a new sequence 'combined_seq' by concatenating f and g at (h 0). parameter {Q :Type} parameter {o : Q → Q → Prop} parameters f g : ℕ → Q parameter h : ℕ → ℕ parameter Hh : ∀ i, h 0 ≤ h i parameter Hf : ¬ is_good f o parameter Hg : ¬ is_good g o -- in Higman's lemma in Williams 1963, h is f, g is the bad sequence B ∘ f parameter H : ∀ i j, o (f i) (g (j - h 0)) → o (f i) (f (h (j - h 0))) definition combined_seq (n : ℕ) : Q := if h 0 ≠ 0 ∧ n ≤ pred (h 0) then f n else g (n - (h 0)) theorem g_part_of_combined_seq (H : (h 0) = 0) : ∀ x, combined_seq x = g x := take n, have ¬ (h 0) ≠ 0, from not_not_intro H, have ¬ ((h 0) ≠ 0 ∧ n ≤ pred (h 0)), from not_and_of_not_left (n ≤ pred (h 0)) this, have combined_seq n = g (n - (h 0)), from if_neg this, by+ simp theorem badness_of_combined_seq : ¬ is_good combined_seq o := assume good : is_good combined_seq o, obtain (i j) hw, from good, by_cases (suppose (h 0) = 0, have combined_seq = g, from funext (g_part_of_combined_seq this), have is_good g o, by+ rewrite this at good;exact good, Hg this) (assume ne, by_cases (assume Hposi : i ≤ pred (h 0), have eq1i : combined_seq i = f i, from if_pos (and.intro ne Hposi), by_cases (suppose j ≤ pred (h 0), have eq1j : combined_seq j = f j, from if_pos (and.intro ne this), have o (combined_seq i) (combined_seq j), from and.right hw, have o (combined_seq i) (f j), by+ rewrite eq1j at this; exact this, have o (f i) (f j), by+ simp, have is_good f o, from exists.intro i (exists.intro j (and.intro (and.left hw) this)), Hf this) (suppose ¬ j ≤ pred (h 0), have ¬ ((h 0) ≠ 0 ∧ j ≤ pred (h 0)), from not_and_of_not_right ((h 0) ≠ 0) this, have eq2j : combined_seq j = g (j - (h 0)), from if_neg this, have o (f i) (g (j - (h 0))), by+ simp, have Hr : o (f i) (f (h (j - (h 0)))), from !H this, have i < h (j - (h 0)), from have ilth0 : i < h 0, from lt_of_le_of_lt Hposi (lt_pred_nonzero_self ne), have h 0 ≤ h (j - h 0), from Hh (j - h 0), lt_of_lt_of_le ilth0 this, have is_good f o, from exists.intro i (exists.intro (h (j - h 0)) (and.intro this Hr)), Hf this)) (assume Hnegi : ¬ i ≤ pred (h 0), have iht : pred (h 0) < i, from lt_of_not_ge Hnegi, have ¬ (h 0 ≠ 0 ∧ i ≤ pred (h 0)), from not_and_of_not_right (h 0 ≠ 0) Hnegi, have eq2i : combined_seq i = g (i - h 0), from if_neg this, by_cases (assume Hposj : j ≤ pred (h 0), have j < i, from lt_of_le_of_lt Hposj iht, (not_lt_of_gt (and.left hw)) this) (assume Hnegj : ¬ j ≤ pred (h 0), have pred (h 0) < j, from lt_of_not_ge Hnegj, have ¬ (h 0 ≠ 0 ∧ j ≤ pred (h 0)), from not_and_of_not_right (h 0 ≠ 0) Hnegj, have eq2j : combined_seq j = g (j - h 0), from if_neg this, have o (combined_seq i) (combined_seq j), from and.right hw, have o (combined_seq i) (g (j - h 0)), by+ simp, have Hr2 : o (g (i - h 0)) (g (j - h 0)), by+ simp, have ige : h 0 ≤ i, from gt_of_gt_pred iht, have jgt : h 0 < j, from lt_of_le_of_lt ige (and.left hw), have i - h 0 < j - h 0, from or.elim (lt_or_eq_of_le ige) (assume hl, sub_gt_of_gt (and.left hw) hl) (assume hr, have 0 < j - h 0, from nat.sub_pos_of_lt jgt, by+ simp), have is_good g o, from exists.intro (i - h 0) (exists.intro (j - h 0) (and.intro this Hr2)), Hg this))) end section -- further assume that f is a minimal bad sequence and card (g 0) < card (f (h 0)) -- In other words, this section says, assuming that there is a bad sequence of Q, if g is a bad sequence such that H holds, then there is a contradiction. parameter {Q :Type} parameter {o : Q → Q → Prop} parameters {g : ℕ → Q} parameter h : ℕ → ℕ parameter m : Q → ℕ -- a measure of cardinality parameter Hh : ∀ i, h 0 ≤ h i parameter Hex : ∃ f, ¬ is_good f o parameter Hg : ¬ is_good g o parameter H : ∀ i j, o (minimal_bad_seq m Hex i) (g (j - h 0)) → o (minimal_bad_seq m Hex i) ((minimal_bad_seq m Hex) (h (j - h 0))) parameter Hbp : m (g 0) < m (minimal_bad_seq m Hex (h 0)) definition comb_seq_with_mbs := combined_seq (minimal_bad_seq m Hex) g h theorem g_part_of_comb_seq_with_mbs (H1 : (h 0) = 0) : ∀ x, comb_seq_with_mbs x = g x := g_part_of_combined_seq (minimal_bad_seq m Hex) g h H1 theorem badness_of_comb_seq_with_mbs : ¬ is_good comb_seq_with_mbs o := badness_of_combined_seq (minimal_bad_seq m Hex) g h Hh (badness_of_mbs m Hex) Hg H theorem comb_seq_extends_mbs_at_pred_bp (H : h 0 ≠ 0): extends_at (pred (h 0)) (minimal_bad_seq m Hex) comb_seq_with_mbs := λ m, λ Hm, if_pos (and.intro H Hm) lemma comb_seq_h0 : comb_seq_with_mbs (h 0) = g 0 := by_cases (suppose h 0 = 0, have comb_seq_with_mbs (h 0) = g (h 0), from g_part_of_comb_seq_with_mbs this (h 0), by+ simp) (suppose h 0 ≠ 0, have pred (h 0) < h 0, from lt_pred_nonzero_self this, have ¬ h 0 ≤ pred (h 0), from not_le_of_gt this, have ¬ ((h 0) ≠ 0 ∧ h 0 ≤ pred (h 0)), from not_and_of_not_right ((h 0) ≠ 0) this, have comb_seq_with_mbs (h 0) = g (h 0 - h 0), from if_neg this, by+ simp) theorem local_contra_of_comb_seq_with_mbs : false := by_cases (suppose h 0 = 0, have eq : comb_seq_with_mbs 0 = g 0, from g_part_of_comb_seq_with_mbs this 0, have m (comb_seq_with_mbs 0) < m (minimal_bad_seq m Hex (h 0)), by+ rewrite -eq at Hbp;exact Hbp, have le : m (comb_seq_with_mbs 0) < m (minimal_bad_seq m Hex 0), by+ simp, have m (minimal_bad_seq m Hex 0) ≤ m (comb_seq_with_mbs 0), from minimality_of_mbs_0 m Hex comb_seq_with_mbs badness_of_comb_seq_with_mbs, (not_le_of_gt le) this) (assume Hneg, have le : m (minimal_bad_seq m Hex (succ (pred (h 0)))) ≤ m (comb_seq_with_mbs (succ (pred (h 0)))), from minimality_of_mbs m Hex (pred (h 0)) comb_seq_with_mbs (and.intro (comb_seq_extends_mbs_at_pred_bp Hneg) badness_of_comb_seq_with_mbs), have h 0 > 0, from pos_of_ne_zero Hneg, have succ (pred (h 0)) = h 0, from succ_pred_of_pos this, have m (minimal_bad_seq m Hex (h 0)) ≤ m (comb_seq_with_mbs (h 0)), by+ rewrite this at le;exact le, have m (minimal_bad_seq m Hex (h 0)) ≤ m (g 0), by+ rewrite comb_seq_h0 at this;exact this, have ¬ m (g 0) < m (minimal_bad_seq m Hex (h 0)), from not_lt_of_ge this, this Hbp) end check local_contra_of_comb_seq_with_mbs section parameter {Q : Type} parameter [wqo Q] definition ofs := @order_on_finite_subsets Q wqo.le theorem ofs_refl (q : finite_subsets Q) : ofs q q := have ∀ a : Q, a ∈ elt_of q → wqo.le a (id a) ∧ id a ∈ elt_of q, by intros;split;apply wqo.refl;simp, exists.intro id (and.intro (inj_from_to_id (elt_of q)) this) theorem ofs_trans (a b c : finite_subsets Q) (H1 : ofs a b) (H2 : ofs b c) : ofs a c := obtain f hf, from H1, obtain g hg, from H2, have inj : inj_from_to (g ∘ f) (elt_of a) (elt_of c), from inj_from_to_compose (and.left hg) (and.left hf), have ∀ q : Q, q ∈ elt_of a → wqo.le q ((g ∘ f) q) ∧ (g ∘ f) q ∈ elt_of c, from take q, assume Hq, have le1 : wqo.le q (f q), from and.left ((and.right hf) q Hq), have fqin : f q ∈ elt_of b, from and.right ((and.right hf) q Hq), have le2 : wqo.le (f q) ((g ∘ f) q), from and.left ((and.right hg) (f q) fqin), have qle : wqo.le q ((g ∘ f) q), from !wqo.trans le1 le2, have (g ∘ f) q ∈ elt_of c, from and.right ((and.right hg) (f q) fqin), and.intro qle this, exists.intro (g ∘ f) (and.intro inj this) parameter H : ∃ f : ℕ → finite_subsets Q, ¬ is_good f ofs definition card_of_finite_subsets {A : Type} (s : finite_subsets A) := card (elt_of s) definition Higman's_mbs (n : ℕ) : finite_subsets Q := minimal_bad_seq card_of_finite_subsets H n theorem badness_of_Higman's_mbs : ¬ is_good Higman's_mbs ofs := badness_of_mbs card_of_finite_subsets H theorem nonempty_mem_of_mbs (n : ℕ) : elt_of (Higman's_mbs n) ≠ ∅ := suppose elt_of (Higman's_mbs n) = ∅, have lt : n < succ n, from lt_succ_self n, have nondescending : ∀ a : Q, a ∈ elt_of (Higman's_mbs n) → wqo.le a (id a) ∧ id a ∈ elt_of (Higman's_mbs (succ n)), from λ a, λ H, have a ∉ ∅, from not_mem_empty a, by+ simp, have ofs (Higman's_mbs n) (Higman's_mbs (succ n)), begin+ fapply exists.intro,exact id,repeat split, intros a Ha,apply and.right (nondescending a Ha), intros,simp,apply nondescending end, have is_good Higman's_mbs ofs, from exists.intro n (exists.intro (succ n) (and.intro lt this)), badness_of_Higman's_mbs this definition B_pairs (n : ℕ) : Q × finite_subsets Q := have ∃ a : Q, a ∈ elt_of (Higman's_mbs n), from exists_mem_of_ne_empty (nonempty_mem_of_mbs n), let q := some this in let b := elt_of (Higman's_mbs n) \ '{q} in have finite (elt_of (Higman's_mbs n)), from has_property (Higman's_mbs n), have finite b, from proof @finite_diff _ _ _ this qed, (q, tag b this) private definition B (n : ℕ) : finite_subsets Q := pr2 (B_pairs n) definition qn (n : ℕ) : Q := pr1 (B_pairs n) theorem qn_in_mbs (n : ℕ) : qn n ∈ elt_of (Higman's_mbs n) := some_spec (exists_mem_of_ne_empty (nonempty_mem_of_mbs n)) theorem qn_not_in_Bn (n : ℕ) : qn n ∉ elt_of (B n) := suppose qn n ∈ elt_of (B n), (and.right this) (mem_singleton (qn n)) theorem ins_B_pairs (n : ℕ) : insert (qn n) (elt_of (B n)) = elt_of (Higman's_mbs n) := have ∃ a : Q, a ∈ elt_of (Higman's_mbs n), from exists_mem_of_ne_empty (nonempty_mem_of_mbs n), have qnin : qn n ∈ elt_of (Higman's_mbs n), from some_spec this, have elt_of (B n) = elt_of (Higman's_mbs n) \ '{qn n}, from rfl, begin+ apply subset.antisymm, intros x H1, apply or.elim H1, intro, simp, intro, have x ∈ elt_of (Higman's_mbs n) \ '{qn n}, by simp, apply and.left this, intros x H2, cases (decidable.em (x = qn n)) with [H3, H4], apply or.inl, exact H3, apply or.inr, rewrite this, apply and.intro, exact H2, apply not_mem_singleton, exact H4 end theorem sub_B_mbs (n : ℕ) : elt_of (B n) ⊆ elt_of (Higman's_mbs n) := by intros; intro; rewrite -ins_B_pairs; apply or.inr; assumption theorem trans_of_B (i j : ℕ) (H1 : ofs (Higman's_mbs i) (B j)) : ofs (Higman's_mbs i) (Higman's_mbs j) := obtain f hf, from H1, have inj_from_to f (elt_of (Higman's_mbs i)) (elt_of (B j)), from and.left hf, have Hl : ∀ a, a ∈ elt_of (Higman's_mbs i) → f a ∈ elt_of (Higman's_mbs j), from take a, assume Ha, have f a ∈ elt_of (B j), from and.left this a Ha, (sub_B_mbs j) this, have inj : inj_from_to f (elt_of (Higman's_mbs i)) (elt_of (Higman's_mbs j)), from and.intro Hl (and.right (and.left hf)), have non_descending (Higman's_mbs i) (Higman's_mbs j) wqo.le f, from take a, assume Ha, have Hl : wqo.le a (f a), from and.left ((and.right hf) a Ha), have f a ∈ elt_of (B j), from and.right ((and.right hf) a Ha), have fain : f a ∈ insert (qn j) (elt_of (B j)), from or.intro_right (f a = qn j) this, have insert (qn j) (elt_of (B j)) = elt_of (Higman's_mbs j), from ins_B_pairs j, have f a ∈ elt_of (Higman's_mbs j), by+ rewrite this at fain;exact fain, and.intro Hl this, exists.intro f (and.intro inj this) section parameter Hg : ∃ g : ℕ → ℕ, ¬ is_good (B ∘ g) ofs ∧ ∀ i : ℕ, g 0 ≤ g i private definition g := some Hg theorem Higman's_Hg : ¬ is_good (B ∘ g) ofs := and.left (some_spec Hg) theorem Higman's_Hex : ∃ f, ¬ is_good f ofs := exists.intro (B ∘ g) Higman's_Hg theorem Higman's_Hh : ∀ i : ℕ, g 0 ≤ g i := and.right (some_spec Hg) theorem Higman's_H : ∀ i j, ofs (Higman's_mbs i) ((B ∘ g) (j - g 0)) → ofs (Higman's_mbs i) (Higman's_mbs (g (j - g 0))) := λ i j, λ H1, trans_of_B i (g (j - g 0)) H1 definition Higman's_comb_seq (n : ℕ) : finite_subsets Q := @comb_seq_with_mbs _ ofs (B ∘ g) g card_of_finite_subsets Higman's_Hex n theorem card_B_lt_mbs (n : ℕ) : card (elt_of (B n)) < card (elt_of (Higman's_mbs n)) := have finite (elt_of (B n)), from has_property (B n), have card (insert (qn n) (elt_of (B n))) = card (elt_of (B n)) + 1, from @card_insert_of_not_mem _ _ _ this (qn_not_in_Bn n), have card (elt_of (B n)) < card (elt_of (B n)) + 1, from lt_succ_self (card (elt_of (B n))), have card (elt_of (B n)) < card (insert (qn n) (elt_of (B n))), by+ simp, have insert (qn n) (elt_of (B n)) = elt_of (Higman's_mbs n), from ins_B_pairs n, by+ simp theorem Higman's_Hbp : card_of_finite_subsets (B (g 0)) < card_of_finite_subsets (Higman's_mbs (g 0)) := card_B_lt_mbs (g 0) theorem Higman's_local_contradition : false := local_contra_of_comb_seq_with_mbs g card_of_finite_subsets Higman's_Hh Higman's_Hex Higman's_Hg Higman's_H Higman's_Hbp end check Higman's_local_contradition definition ClassB : Type := {x : finite_subsets Q | ∃ i, B i = x} definition oB (b1 : ClassB) (b2 : ClassB) : Prop := ofs (elt_of b1) (elt_of b2) theorem oB_refl (q : ClassB) : oB q q := ofs_refl (elt_of q) theorem oB_trans (a b c : ClassB) (H1 : oB a b) (H2 : oB b c) : oB a c := !ofs_trans H1 H2 section -- Suppose there exists a bad sequence of objects in ClassB. We show that we can construct a g : ℕ → ℕ such that ¬ is_good (B ∘ g) o. Then we can apply 'exists_sub_bad'. We cannot directly apply this theorem because ClassB is a type distinct from finite_subsets Q. parameter HfB : ∃ f, ¬ is_good f oB private definition f' : ℕ → ClassB := some HfB private theorem bad_f' : ¬ is_good f' oB := some_spec HfB private definition g' (n : ℕ) := elt_of (f' n) theorem exists_bad_B_seq : ¬ is_good g' ofs := suppose is_good g' ofs, obtain (i j) hg', from this, have ofs (elt_of (f' i)) (elt_of (f' j)), from and.right hg', have is_good f' oB, from exists.intro i (exists.intro j (and.intro (and.left hg') this)), bad_f' this private definition g (n : ℕ) : ℕ := have ∃ i, B i = g' n, from has_property (f' n), some this private theorem comp_eq_g' : B ∘ g = g' := have ∀ x, B (g x) = g' x, from take x, some_spec (has_property (f' x)), funext this private theorem bad_comp : ¬ is_good (B ∘ g) ofs := have ¬ is_good g' ofs, from exists_bad_B_seq, by+ rewrite -comp_eq_g' at this;exact this theorem exists_sub_bad_B_seq : ∃ h : ℕ → ℕ, ¬ is_good (B ∘ h) ofs ∧ ∀ i : ℕ, h 0 ≤ h i := exists_sub_bad B g ofs bad_comp end theorem oB_is_good : ∀ f, is_good f oB := by_contradiction (suppose ¬ ∀ f, is_good f oB, have ∃ f, ¬ is_good f oB, from exists_not_of_not_forall this, have ∃ h : ℕ → ℕ, ¬ is_good (B ∘ h) ofs ∧ ∀ i : ℕ, h 0 ≤ h i, from exists_sub_bad_B_seq this, Higman's_local_contradition this) definition wqo_ClassB [instance] : wqo ClassB := wqo.mk oB oB_refl oB_trans oB_is_good definition wqo_prod_Q_ClassB [instance] : wqo (Q × ClassB) := wqo_prod theorem good_prod_Q_ClassB : ∀ f : ℕ → Q × ClassB, is_good f (o_for_pairs wqo.le oB) := wqo.is_good lemma B_refl (n : ℕ) : ∃ i, B i = B n := exists.intro n rfl definition fB (n : ℕ) : ClassB := tag (B n) (B_refl n) private definition p (n : ℕ) : Q × ClassB := (qn n, fB n) theorem good_p : is_good p (o_for_pairs wqo.le oB) := good_prod_Q_ClassB p theorem Hij : ∃ i j, i < j ∧ (wqo.le (qn i) (qn j) ∧ oB (fB i) (fB j)) := good_p theorem exists_embeds : ∃ i j, i < j ∧ ofs (Higman's_mbs i) (Higman's_mbs j) := obtain (i j) hij, from good_p, have oB (fB i) (fB j), from and.right (and.right hij), obtain f₁ hf1, from this, have injf₁ : inj_from_to f₁ (elt_of (B i)) (elt_of (B j)), from and.left hf1, have ∀ a : Q, a ∈ elt_of (B i) → wqo.le a (f₁ a) ∧ f₁ a ∈ elt_of (B j), from and.right hf1, let f₂ (q : Q) : Q := if q = qn i then qn j else f₁ q in have nondescending : ∀ a : Q, a ∈ elt_of (Higman's_mbs i) → wqo.le a (f₂ a) ∧ f₂ a ∈ elt_of (Higman's_mbs j), from take a, assume Ha, have Hor : a = qn i ∨ a ∈ elt_of (B i), by+ rewrite -(ins_B_pairs i) at Ha;exact Ha, begin+ cases (decidable.em (a = qn i)) with [H1, H2], split, rewrite (if_pos H1), rewrite H1, exact and.left (and.right hij),rewrite (if_pos H1), apply qn_in_mbs, split, have conj : wqo.le a (f₂ a) ∧ f₂ a ∈ elt_of (B j), by rewrite (if_neg H2), apply and.right hf1, apply or_resolve_right Hor H2, exact and.left conj, have conj : wqo.le a (f₂ a) ∧ f₂ a ∈ elt_of (B j), by rewrite (if_neg H2), apply and.right hf1, apply or_resolve_right Hor H2, exact (sub_B_mbs j) (and.right conj) end, have Hmapsto : ∀ a, a ∈ elt_of (Higman's_mbs i) → f₂ a ∈ elt_of (Higman's_mbs j), from take a, assume Ha, and.right (nondescending a Ha), have ∀ a₁ a₂, a₁ ∈ elt_of (Higman's_mbs i) → a₂ ∈ elt_of (Higman's_mbs i) → f₂ a₁ = f₂ a₂ → a₁ = a₂, from take a₁ a₂, assume Ha₁, assume Ha₂, assume Heq, have Hora₁ : a₁ = qn i ∨ a₁ ∈ elt_of (B i), by+ rewrite -(ins_B_pairs i) at Ha₁;exact Ha₁, have Hora₂ : a₂ = qn i ∨ a₂ ∈ elt_of (B i), by+ rewrite -(ins_B_pairs i) at Ha₂;exact Ha₂, by_cases (assume Hpos : a₁ = qn i, -- level-1 subcase // pos have eq21j : f₂ a₁ = qn j, from if_pos Hpos, by_contradiction (suppose a₁ ≠ a₂, have neq : qn i ≠ a₂, by+ rewrite Hpos at this;exact this, have eq2212 : f₂ a₂ = f₁ a₂, from if_neg (ne.symm neq), have qn j ∈ elt_of (B j), begin+ rewrite [-eq21j, Heq, eq2212], apply and.left injf₁, exact or_resolve_right Hora₂ (ne.symm neq) end, (qn_not_in_Bn j) this)) (assume Hneg, -- level-1 subcase // neg have eq2111 : f₂ a₁ = f₁ a₁, from if_neg Hneg, have a1inBi : a₁ ∈ elt_of (B i), from or_resolve_right Hora₁ Hneg, by_cases (assume Hposa₂ : a₂ = qn i, -- level-2 subcase // pos have eq21j : f₂ a₂ = qn j, from if_pos Hposa₂, by_contradiction (suppose a₁ ≠ a₂, have neq2 : a₁ ≠ qn i, by+ rewrite Hposa₂ at this;exact this, have eq2111 : f₂ a₁ = f₁ a₁, from if_neg neq2, have qn j ∈ elt_of (B j), begin+ rewrite [-eq21j, -Heq, eq2111], apply and.left injf₁, exact or_resolve_right Hora₁ neq2 end, (qn_not_in_Bn j) this)) (assume Hnega₂, -- level-2 subcase // neg have eq2212 : f₂ a₂ = f₁ a₂, from if_neg Hnega₂, have f₁ a₁ = f₂ a₂, by+ rewrite eq2111 at Heq;exact Heq, have eq1112 : f₁ a₁ = f₁ a₂, from eq.trans this eq2212, have a₂ ∈ elt_of (B i), from or_resolve_right Hora₂ Hnega₂, (and.right injf₁) a₁ a₂ a1inBi this eq1112)), have inj_from_to f₂ (elt_of (Higman's_mbs i)) (elt_of (Higman's_mbs j)), from and.intro Hmapsto this, have ofs (Higman's_mbs i) (Higman's_mbs j), from exists.intro f₂ (and.intro this nondescending), exists.intro i (exists.intro j (and.intro (and.left hij) this)) theorem goodness_of_Higman's_mbs : is_good Higman's_mbs ofs := exists_embeds theorem Higman's_contradiction : false := badness_of_Higman's_mbs goodness_of_Higman's_mbs end check Higman's_contradiction variable {Q : Type} variable [wqo Q] theorem ofs_is_good : ∀ f : ℕ → finite_subsets Q , is_good f ofs := by_contradiction (suppose ¬ ∀ f, is_good f ofs, have ∃ f, ¬ is_good f ofs, from exists_not_of_not_forall this, Higman's_contradiction this) definition wqo_finite_subsets [instance] : wqo (finite_subsets Q) := wqo.mk ofs ofs_refl ofs_trans ofs_is_good example : @wqo.le (finite_subsets Q) _ = ofs := rfl check wqo_finite_subsets end kruskal
e6d6b399a54ffbd787b2f794bd8c64057261c637
94e33a31faa76775069b071adea97e86e218a8ee
/src/linear_algebra/quadratic_form/isometry.lean
f51eef6dfcb0e339881e471efe1eb31332202d3f
[ "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,537
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying, Eric Wieser -/ import linear_algebra.quadratic_form.basic /-! # Isometries with respect to quadratic forms ## Main definitions * `quadratic_form.isometry`: `linear_equiv`s which map between two different quadratic forms * `quadratic_form.equvialent`: propositional version of the above ## Main results * `equivalent_weighted_sum_squares`: in finite dimensions, any quadratic form is equivalent to a parametrization of `quadratic_form.weighted_sum_squares`. -/ variables {ι R K M M₁ M₂ M₃ V : Type*} namespace quadratic_form variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₁] [module R M₂] [module R M₃] /-- An isometry between two quadratic spaces `M₁, Q₁` and `M₂, Q₂` over a ring `R`, is a linear equivalence between `M₁` and `M₂` that commutes with the quadratic forms. -/ @[nolint has_inhabited_instance] structure isometry (Q₁ : quadratic_form R M₁) (Q₂ : quadratic_form R M₂) extends M₁ ≃ₗ[R] M₂ := (map_app' : ∀ m, Q₂ (to_fun m) = Q₁ m) /-- Two quadratic forms over a ring `R` are equivalent if there exists an isometry between them: a linear equivalence that transforms one quadratic form into the other. -/ def equivalent (Q₁ : quadratic_form R M₁) (Q₂ : quadratic_form R M₂) := nonempty (Q₁.isometry Q₂) namespace isometry variables {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₃ : quadratic_form R M₃} instance : has_coe (Q₁.isometry Q₂) (M₁ ≃ₗ[R] M₂) := ⟨isometry.to_linear_equiv⟩ @[simp] lemma to_linear_equiv_eq_coe (f : Q₁.isometry Q₂) : f.to_linear_equiv = f := rfl instance : has_coe_to_fun (Q₁.isometry Q₂) (λ _, M₁ → M₂) := ⟨λ f, ⇑(f : M₁ ≃ₗ[R] M₂)⟩ @[simp] lemma coe_to_linear_equiv (f : Q₁.isometry Q₂) : ⇑(f : M₁ ≃ₗ[R] M₂) = f := rfl @[simp] lemma map_app (f : Q₁.isometry Q₂) (m : M₁) : Q₂ (f m) = Q₁ m := f.map_app' m /-- The identity isometry from a quadratic form to itself. -/ @[refl] def refl (Q : quadratic_form R M) : Q.isometry Q := { map_app' := λ m, rfl, .. linear_equiv.refl R M } /-- The inverse isometry of an isometry between two quadratic forms. -/ @[symm] def symm (f : Q₁.isometry Q₂) : Q₂.isometry Q₁ := { map_app' := by { intro m, rw ← f.map_app, congr, exact f.to_linear_equiv.apply_symm_apply m }, .. (f : M₁ ≃ₗ[R] M₂).symm } /-- The composition of two isometries between quadratic forms. -/ @[trans] def trans (f : Q₁.isometry Q₂) (g : Q₂.isometry Q₃) : Q₁.isometry Q₃ := { map_app' := by { intro m, rw [← f.map_app, ← g.map_app], refl }, .. (f : M₁ ≃ₗ[R] M₂).trans (g : M₂ ≃ₗ[R] M₃) } end isometry namespace equivalent variables {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₃ : quadratic_form R M₃} @[refl] lemma refl (Q : quadratic_form R M) : Q.equivalent Q := ⟨isometry.refl Q⟩ @[symm] lemma symm (h : Q₁.equivalent Q₂) : Q₂.equivalent Q₁ := h.elim $ λ f, ⟨f.symm⟩ @[trans] lemma trans (h : Q₁.equivalent Q₂) (h' : Q₂.equivalent Q₃) : Q₁.equivalent Q₃ := h'.elim $ h.elim $ λ f g, ⟨f.trans g⟩ end equivalent variables [fintype ι] {v : basis ι R M} /-- A quadratic form composed with a `linear_equiv` is isometric to itself. -/ def isometry_of_comp_linear_equiv (Q : quadratic_form R M) (f : M₁ ≃ₗ[R] M) : Q.isometry (Q.comp (f : M₁ →ₗ[R] M)) := { map_app' := begin intro, simp only [comp_apply, linear_equiv.coe_coe, linear_equiv.to_fun_eq_coe, linear_equiv.apply_symm_apply, f.apply_symm_apply], end, .. f.symm } /-- A quadratic form is isometric to its bases representations. -/ noncomputable def isometry_basis_repr (Q : quadratic_form R M) (v : basis ι R M) : isometry Q (Q.basis_repr v) := isometry_of_comp_linear_equiv Q v.equiv_fun.symm variables [field K] [invertible (2 : K)] [add_comm_group V] [module K V] /-- Given an orthogonal basis, a quadratic form is isometric with a weighted sum of squares. -/ noncomputable def isometry_weighted_sum_squares (Q : quadratic_form K V) (v : basis (fin (finite_dimensional.finrank K V)) K V) (hv₁ : (associated Q).is_Ortho v) : Q.isometry (weighted_sum_squares K (λ i, Q (v i))) := begin let iso := Q.isometry_basis_repr v, refine ⟨iso, λ m, _⟩, convert iso.map_app m, rw basis_repr_eq_of_is_Ortho _ _ hv₁, end variables [finite_dimensional K V] open bilin_form lemma equivalent_weighted_sum_squares (Q : quadratic_form K V) : ∃ w : fin (finite_dimensional.finrank K V) → K, equivalent Q (weighted_sum_squares K w) := let ⟨v, hv₁⟩ := exists_orthogonal_basis (associated_is_symm _ Q) in ⟨_, ⟨Q.isometry_weighted_sum_squares v hv₁⟩⟩ lemma equivalent_weighted_sum_squares_units_of_nondegenerate' (Q : quadratic_form K V) (hQ : (associated Q).nondegenerate) : ∃ w : fin (finite_dimensional.finrank K V) → Kˣ, equivalent Q (weighted_sum_squares K w) := begin obtain ⟨v, hv₁⟩ := exists_orthogonal_basis (associated_is_symm _ Q), have hv₂ := hv₁.not_is_ortho_basis_self_of_nondegenerate hQ, simp_rw [is_ortho, associated_eq_self_apply] at hv₂, exact ⟨λ i, units.mk0 _ (hv₂ i), ⟨Q.isometry_weighted_sum_squares v hv₁⟩⟩, end end quadratic_form
c2212bb0257a452390529c15b6ebf114a907ead7
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/analysis/normed_space/is_R_or_C.lean
bad1305f97dd8268f066b8430fb06fd0648a110b
[ "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
4,124
lean
/- Copyright (c) 2021 Kalle Kytölä. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kalle Kytölä -/ import data.complex.is_R_or_C import analysis.normed_space.operator_norm import analysis.normed_space.pointwise /-! # Normed spaces over R or C This file is about results on normed spaces over the fields `ℝ` and `ℂ`. ## Main definitions None. ## Main theorems * `continuous_linear_map.op_norm_bound_of_ball_bound`: A bound on the norms of values of a linear map in a ball yields a bound on the operator norm. ## Notes This file exists mainly to avoid importing `is_R_or_C` in the main normed space theory files. -/ open metric @[simp, is_R_or_C_simps] lemma is_R_or_C.norm_coe_norm {𝕜 : Type*} [is_R_or_C 𝕜] {E : Type*} [normed_add_comm_group E] {z : E} : ∥(∥z∥ : 𝕜)∥ = ∥z∥ := by { unfold_coes, simp only [norm_algebra_map', ring_hom.to_fun_eq_coe, norm_norm], } variables {𝕜 : Type*} [is_R_or_C 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] /-- Lemma to normalize a vector in a normed space `E` over either `ℂ` or `ℝ` to unit length. -/ @[simp] lemma norm_smul_inv_norm {x : E} (hx : x ≠ 0) : ∥(∥x∥⁻¹ : 𝕜) • x∥ = 1 := begin have : ∥x∥ ≠ 0 := by simp [hx], field_simp [norm_smul] end /-- Lemma to normalize a vector in a normed space `E` over either `ℂ` or `ℝ` to length `r`. -/ lemma norm_smul_inv_norm' {r : ℝ} (r_nonneg : 0 ≤ r) {x : E} (hx : x ≠ 0) : ∥(r * ∥x∥⁻¹ : 𝕜) • x∥ = r := begin have : ∥x∥ ≠ 0 := by simp [hx], field_simp [norm_smul, is_R_or_C.norm_eq_abs, r_nonneg] with is_R_or_C_simps end lemma linear_map.bound_of_sphere_bound {r : ℝ} (r_pos : 0 < r) (c : ℝ) (f : E →ₗ[𝕜] 𝕜) (h : ∀ z ∈ sphere (0 : E) r, ∥f z∥ ≤ c) (z : E) : ∥f z∥ ≤ c / r * ∥z∥ := begin by_cases z_zero : z = 0, { rw z_zero, simp only [linear_map.map_zero, norm_zero, mul_zero], }, set z₁ := (r * ∥z∥⁻¹ : 𝕜) • z with hz₁, have norm_f_z₁ : ∥f z₁∥ ≤ c, { apply h, rw mem_sphere_zero_iff_norm, exact norm_smul_inv_norm' r_pos.le z_zero }, have r_ne_zero : (r : 𝕜) ≠ 0 := (algebra_map ℝ 𝕜).map_ne_zero.mpr r_pos.ne.symm, have eq : f z = ∥z∥ / r * (f z₁), { rw [hz₁, linear_map.map_smul, smul_eq_mul], rw [← mul_assoc, ← mul_assoc, div_mul_cancel _ r_ne_zero, mul_inv_cancel, one_mul], simp only [z_zero, is_R_or_C.of_real_eq_zero, norm_eq_zero, ne.def, not_false_iff], }, rw [eq, norm_mul, norm_div, is_R_or_C.norm_coe_norm, is_R_or_C.norm_of_nonneg r_pos.le, div_mul_eq_mul_div, div_mul_eq_mul_div, mul_comm], apply div_le_div _ _ r_pos rfl.ge, { exact mul_nonneg ((norm_nonneg _).trans norm_f_z₁) (norm_nonneg z), }, apply mul_le_mul norm_f_z₁ rfl.le (norm_nonneg z) ((norm_nonneg _).trans norm_f_z₁), end /-- `linear_map.bound_of_ball_bound` is a version of this over arbitrary nontrivially normed fields. It produces a less precise bound so we keep both versions. -/ lemma linear_map.bound_of_ball_bound' {r : ℝ} (r_pos : 0 < r) (c : ℝ) (f : E →ₗ[𝕜] 𝕜) (h : ∀ z ∈ closed_ball (0 : E) r, ∥f z∥ ≤ c) (z : E) : ∥f z∥ ≤ c / r * ∥z∥ := f.bound_of_sphere_bound r_pos c (λ z hz, h z hz.le) z lemma continuous_linear_map.op_norm_bound_of_ball_bound {r : ℝ} (r_pos : 0 < r) (c : ℝ) (f : E →L[𝕜] 𝕜) (h : ∀ z ∈ closed_ball (0 : E) r, ∥f z∥ ≤ c) : ∥f∥ ≤ c / r := begin apply continuous_linear_map.op_norm_le_bound, { apply div_nonneg _ r_pos.le, exact (norm_nonneg _).trans (h 0 (by simp only [norm_zero, mem_closed_ball, dist_zero_left, r_pos.le])), }, apply linear_map.bound_of_ball_bound' r_pos, exact λ z hz, h z hz, end variables (𝕜) include 𝕜 lemma normed_space.sphere_nonempty_is_R_or_C [nontrivial E] {r : ℝ} (hr : 0 ≤ r) : nonempty (sphere (0:E) r) := begin letI : normed_space ℝ E := normed_space.restrict_scalars ℝ 𝕜 E, exact set.nonempty_coe_sort.mpr (normed_space.sphere_nonempty.mpr hr), end
7783ac55615a56f880bc7e9a9415e27ede7460ab
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/tests/lean/run/algebra1.lean
0ecdef98a2dda008bbd3677717f9adaae8dc131f
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,213
lean
import logic namespace experiment definition Type1 := Type.{1} context variable {A : Type} variable f : A → A → A variable one : A variable inv : A → A infixl `*` := f postfix `^-1`:100 := inv definition is_assoc := ∀ a b c, (a*b)*c = a*b*c definition is_id := ∀ a, a*one = a definition is_inv := ∀ a, a*a^-1 = one end namespace algebra inductive mul_struct [class] (A : Type) : Type := mk : (A → A → A) → mul_struct A inductive add_struct [class] (A : Type) : Type := mk : (A → A → A) → add_struct A definition mul {A : Type} [s : mul_struct A] (a b : A) := mul_struct.rec (fun f, f) s a b infixl `*` := mul definition add {A : Type} [s : add_struct A] (a b : A) := add_struct.rec (fun f, f) s a b infixl `+` := add end algebra open algebra inductive nat : Type := | zero : nat | succ : nat → nat namespace nat constant add : nat → nat → nat constant mul : nat → nat → nat definition is_mul_struct [instance] : algebra.mul_struct nat := algebra.mul_struct.mk mul definition is_add_struct [instance] : algebra.add_struct nat := algebra.add_struct.mk add definition to_nat (n : num) : nat := #experiment.algebra num.rec nat.zero (λ n, pos_num.rec (succ zero) (λ n r, r + r) (λ n r, r + r + succ zero) n) n end nat namespace algebra namespace semigroup inductive semigroup_struct [class] (A : Type) : Type := mk : Π (mul : A → A → A), is_assoc mul → semigroup_struct A definition mul {A : Type} (s : semigroup_struct A) (a b : A) := semigroup_struct.rec (fun f h, f) s a b definition assoc {A : Type} (s : semigroup_struct A) : is_assoc (mul s) := semigroup_struct.rec (fun f h, h) s definition is_mul_struct [instance] (A : Type) [s : semigroup_struct A] : mul_struct A := mul_struct.mk (mul s) inductive semigroup : Type := mk : Π (A : Type), semigroup_struct A → semigroup definition carrier [coercion] (g : semigroup) := semigroup.rec (fun c s, c) g definition is_semigroup [instance] [g : semigroup] : semigroup_struct (carrier g) := semigroup.rec (fun c s, s) g end semigroup namespace monoid check semigroup.mul inductive monoid_struct [class] (A : Type) : Type := mk_monoid_struct : Π (mul : A → A → A) (id : A), is_assoc mul → is_id mul id → monoid_struct A definition mul {A : Type} (s : monoid_struct A) (a b : A) := monoid_struct.rec (fun mul id a i, mul) s a b definition assoc {A : Type} (s : monoid_struct A) : is_assoc (mul s) := monoid_struct.rec (fun mul id a i, a) s open semigroup definition is_semigroup_struct [instance] (A : Type) [s : monoid_struct A] : semigroup_struct A := semigroup_struct.mk (mul s) (assoc s) inductive monoid : Type := mk_monoid : Π (A : Type), monoid_struct A → monoid definition carrier [coercion] (m : monoid) := monoid.rec (fun c s, c) m definition is_monoid [instance] (m : monoid) : monoid_struct (carrier m) := monoid.rec (fun c s, s) m end monoid end algebra section open algebra algebra.semigroup algebra.monoid variable M : monoid variables a b c : M check a*b*c*a*b*c*a*b*a*b*c*a check a*b end end experiment
e0a2bdd42e592b0e7b5897dc42d18372d3db906c
57c233acf9386e610d99ed20ef139c5f97504ba3
/test/differentiable.lean
bf9199386df9f574e58e17e0b49d83d204d93cf8
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
2,467
lean
import analysis.special_functions.trigonometric.deriv import analysis.special_functions.log_deriv namespace real example : differentiable ℝ (λ (x : ℝ), exp x) := by simp example : differentiable ℝ (λ (x : ℝ), exp ((sin x)^2) - exp (exp (cos (x - 3)))) := by simp example (x : ℝ) : deriv (λ (x : ℝ), (cos x)^2 + 1 + (sin x)^2) x = 0 := by { simp, ring } example (x : ℝ) : deriv (λ (x : ℝ), (1+x)^3 - x^3 - 3 * x^2 - 3 * x - 4) x = 0 := by { simp, ring } example (x : ℝ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) := by { simp, ring } example (x : ℝ) : differentiable_at ℝ (λ x, (cos x, x)) x := by simp example (x : ℝ) (h : 1 + sin x ≠ 0) : deriv (λ x, exp (cos x) / (1 + sin x)) x = (-(exp (cos x) * sin x * (1 + sin x)) - exp (cos x) * cos x) / (1 + sin x) ^ 2 := by simp [h] example (x : ℝ) : differentiable_at ℝ (λ x, (sin x) / (exp x)) x := by simp [exp_ne_zero] example : differentiable ℝ (λ x, (sin x) / (exp x)) := by simp [exp_ne_zero] example (x : ℝ) (h : x ≠ 0) : deriv (λ x, x * (log x - 1)) x = log x := by simp [h] end real namespace complex example : differentiable ℂ (λ (x : ℂ), exp x) := by simp example : differentiable ℂ (λ (x : ℂ), exp ((sin x)^2) - exp (exp (cos (x - 3)))) := by simp example (x : ℂ) : deriv (λ (x : ℂ), (cos x)^2 + I + (sin x)^2) x = 0 := by { simp, ring } example (x : ℂ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) := by { simp, ring } example (x : ℂ) : differentiable_at ℂ (λ x, (cos x, x)) x := by simp example (x : ℂ) (h : 1 + sin x ≠ 0) : deriv (λ x, exp (cos x) / (1 + sin x)) x = (-(exp (cos x) * sin x * (1 + sin x)) - exp (cos x) * cos x) / (1 + sin x) ^ 2 := by simp [h] example (x : ℂ) : differentiable_at ℂ (λ x, (sin x) / (exp x)) x := by simp [exp_ne_zero] example : differentiable ℂ (λ x, (sin x) / (exp x)) := by simp [exp_ne_zero] end complex namespace polynomial variables {R : Type*} [comm_semiring R] example : (2 : polynomial R).derivative = 0 := by conv_lhs { simp } example : (3 + X : polynomial R).derivative = 1 := by conv_lhs { simp } example : (2 * X ^ 2 : polynomial R).derivative = 4 * X := by conv_lhs { simp, ring_nf, } example : (X ^ 2 : polynomial R).derivative = 2 * X := by conv_lhs { simp } example : ((C 2 * X ^ 3).derivative : polynomial R) = 6 * X ^ 2 := by conv_lhs { simp, ring_nf, } end polynomial
1bf691c8d132f841fab8f0588476703b97765d4c
35b83be3126daae10419b573c55e1fed009d3ae8
/src/Amy_Lean_Try/_del.lean
4f545b8b8f8471d975597eed679c91cd276ce4e0
[]
no_license
AHassan1024/Lean_Playground
ccb25b72029d199c0d23d002db2d32a9f2689ebc
a00b004c3a2eb9e3e863c361aa2b115260472414
refs/heads/master
1,586,221,905,125
1,544,951,310,000
1,544,951,310,000
157,934,290
0
0
null
null
null
null
UTF-8
Lean
false
false
7,695
lean
--import tactic.finish -- This is an example as per the instructions -- in the introduction. The follwing means: let -- there be an example such that P, Q, and R are -- Prop(ositions), where there is a hypothesis HP -- that refers to the proposition P, and there is -- a hypothesis HQ that refers to the proposition -- Q, and P is the variable to find the truth value -- of. As such, we begin the proof, give a valid -- proof of HP, which means that P has a truth value. -- Then end not being underlined in red or green -- shows that the proof is a valid one to be able to -- arrive at the conclusion that P is defined. example (P Q R : Prop) (HP : P) (HQ : Q) : P := begin exact HP, end -- proof of P → Q, and then proving P, to prove Q theorem easy (P Q : Prop) (HP :P) (HPQ : P → Q) : Q := begin exact HPQ HP, end -- proving P → q is the idea that we should assume we -- already have a proof of P, and then somehow deduce -- a proof of Q. This can be done in Lean by the -- intro tactic. theorem Q_implies_P_impliesQ (P Q : Prop) (HQ : Q) : P → Q := -- propositions p and q given such that hq is a proof of q, -- and hence define p → q. begin intro HP, exact HQ, end -- the intro tactic is a cons for p → q -- if the goal is p → q then we can type intro hp and then lean proves our goal, modulo some other simpler things (proof of q) theorem P_implies_P (P : Prop) : P → P := begin intro HP, exact HP, end example (P Q : Prop) : P ∧ (P → Q) → Q := begin intro HPnPQ, cases HPnPQ with HP HPQ, exact HPQ HP, end theorem and_comm1 (P Q : Prop) : P ∧ Q → Q ∧ P := begin assume HPQ : P ∧ Q, have HP : P, from and.left HPQ, have HQ : Q, from and.right HPQ, show Q ∧ P, from and.intro HQ HP, end constant m : nat constant n : nat constants b1 b2 : bool #check m #check n #check n + 0 #check m * (n + 0) #check b1 #check b1 && b2 #check b1 || b2 #check tt /-Text inbetween these symbols is ignored. aka. Mass commentating tool!!-/ -- theorem comm_1 (A B C : Prop) : (A ∧ B) ∧ C ↔ A ∧ (B ∧ C) := -- begin -- split, -- { -- intro HAnBnC, -- cases HAnBnC with HAnB HC, -- cases HAnB with HA HB, -- split, -- { -- exact HA, -- }, -- { -- split, -- { -- exact HB, -- }, -- { -- exact HC, -- }, -- }, -- }, -- end theorem needs_intros (P Q R :Prop) (HR : R) : P → (Q → R) := begin intro HP, intro HQ, exact HR, end theorem very_easy : true := begin exact trivial, end theorem very_hard: false := begin sorry, end theorem false_implies_false : false → false := begin intro Hfalse, exact Hfalse, end theorem not_not (P : Prop) : P → ¬ (¬ P) := begin intro HP, intro HnP, apply HnP, -- to reduce goal from false to P. exact HP, end theorem contrapos (P Q : Prop) (HPQ : P → Q) : ¬ Q → ¬ P := begin intro HnQ, intro HP, apply HnQ, apply HPQ, apply HP, end theorem P_implies_P_or_Q (P Q :Prop) (HP : P) : P ∨ Q := begin left, exact HP, end theorem Q_implies_P_or_Q (P Q : Prop) (HQ : Q) : P ∨ Q := begin right, exact HQ, end theorem dont_get_lost (P Q : Prop) (HQ : Q) : P ∨ Q := begin left, -- goal no longer provable; as there is nothing left to deduce to be able to prove P. sorry, end theorem or_symmetry (P Q :Prop) : P ∨ Q → Q ∨ P := begin intro HPQ, cases HPQ with HP HQ, { right, exact HP, }, { left, exact HQ, }, end theorem or_experiment (P Q R :Prop) (HPQR : P ∨ Q ∨ R) : true := begin cases HPQR with HP HQR, sorry, sorry, end theorem or_associativity (P Q R : Prop) : P ∨ (Q ∨ R) → (P ∨ Q) ∨ R := begin intro HPQR, cases HPQR with HP HQR, { left, left, exact HP, }, { cases HQR with HQ HR, { left, right, exact HQ, }, { right, exact HR, }, }, end theorem and_definition (P Q : Prop) (HP : P) (HQ : Q) : P ∧ Q := begin split, {exact HP,}, {exact HQ,}, end theorem and_symmetry (P Q : Prop) (HP :P) (HQ : Q) : P ∧ Q → Q ∧ P := begin intro HPQ, split, cases HPQ with HP HQ, {exact HQ,}, {exact HP,}, end theorem and_transitivity (P Q R : Prop) : (P ∧ Q) ∧ (Q ∧ R) → (P ∧ R) := begin intro HPQR, cases HPQR with HPQ HQR, split, cases HPQ with HP HQ, exact HP, cases HQR with HQ HR, exact HR, end theorem iff_symmetric (P Q : Prop) : (P ↔ Q) ↔ (Q ↔ P) := begin split, intro HPiffQ, cases HPiffQ with HPtoQ HQtoP, split, exact HQtoP, exact HPtoQ, intro HQiffP, cases HQiffP with HQtoP HPtoQ, split, exact HPtoQ, exact HQtoP, end theorem iff_transitive (P Q R : Prop) : (P ↔ Q) ∧ (Q ↔ R) → (P ↔ R) := begin intro H, cases H with HPiffQ HQiffR, rw HPiffQ, exact HQiffR, end theorem not_not_1 (P : Prop) : ¬ (¬ P) → P := begin cases (classical.em P) with HP HnP, { intro HnnP, exact HP, }, { intro HnnP, exfalso, apply HnnP, exact HnP, }, end theorem contra (P Q : Prop) : (¬ Q → ¬ P) → (P → Q) := begin intro HnQnP, intro HP, cases (classical.em Q) with HQ HnQ, { exact HQ, }, { exfalso, apply HnQnP, exact HnQ, exact HP, }, end theorem name1 (A B : Prop) : (¬ (A ∧ B)) ↔ (¬ A ∨ ¬ B) := begin cases classical.em A with HA HnA, { cases classical.em B with HB HnB, { have HAB := and_definition A B HA HB, split, { intro H, exfalso, exact H HAB, }, { intro H, cases H with H1 H2, { exfalso, contradiction, }, { exfalso, contradiction, } } }, { split, { intro H, right, exact HnB, }, { intro H, cases H with H1 H2, { exfalso, exact H1 HA, }, { intro HAB, cases HAB with _ HB, exact HnB HB, }, }, }, }, { cases classical.em B with HB HnB, { split, intro _, left, exact HnA, intro _, intro H, cases H with HA _, exact HnA HA, }, { split, intro _, left, exact HnA, intro _, intro H, cases H with HA _, exact HnA HA, } } -- intro HnAaB, -- right, -- intro HB, -- apply HnAaB, -- split, -- sorry, -- sorry, -- intro HnAnB, -- cases HnAnB with HnA HnB, -- { -- intro HAaB, -- sorry, -- } -- sorry, end theorem name2 (P Q : Prop) (HP : P) (HQ : Q) : P ∧ Q := begin split, exact HP, exact HQ, end
16e0bc6217ede1d04ee90e59c43f3f563778a0d2
137c667471a40116a7afd7261f030b30180468c2
/src/analysis/convex/caratheodory.lean
f2a33b0cf63e1558af2efd896ea9644d17bc8e5d
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,913
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison -/ import analysis.convex.basic import linear_algebra.finite_dimensional /-! # Carathéodory's convexity theorem This file is devoted to proving Carathéodory's convexity theorem: The convex hull of a set `s` in ℝᵈ is the union of the convex hulls of the (d+1)-tuples in `s`. ## Main results: * `convex_hull_eq_union`: Carathéodory's convexity theorem ## Implementation details This theorem was formalized as part of the Sphere Eversion project. ## Tags convex hull, caratheodory -/ universes u open set finset finite_dimensional open_locale big_operators variables {E : Type u} [add_comm_group E] [module ℝ E] [finite_dimensional ℝ E] namespace caratheodory /-- If `x` is in the convex hull of some finset `t` with strictly more than `finrank + 1` elements, then it is in the union of the convex hulls of the finsets `t.erase y` for `y ∈ t`. -/ lemma mem_convex_hull_erase [decidable_eq E] {t : finset E} (h : finrank ℝ E + 1 < t.card) {x : E} (m : x ∈ convex_hull (↑t : set E)) : ∃ (y : (↑t : set E)), x ∈ convex_hull (↑(t.erase y) : set E) := begin simp only [finset.convex_hull_eq, mem_set_of_eq] at m ⊢, obtain ⟨f, fpos, fsum, rfl⟩ := m, obtain ⟨g, gcombo, gsum, gpos⟩ := exists_relation_sum_zero_pos_coefficient_of_dim_succ_lt_card h, clear h, let s := t.filter (λ z : E, 0 < g z), obtain ⟨i₀, mem, w⟩ : ∃ i₀ ∈ s, ∀ i ∈ s, f i₀ / g i₀ ≤ f i / g i, { apply s.exists_min_image (λ z, f z / g z), obtain ⟨x, hx, hgx⟩ : ∃ x ∈ t, 0 < g x := gpos, exact ⟨x, mem_filter.mpr ⟨hx, hgx⟩⟩, }, have hg : 0 < g i₀ := by { rw mem_filter at mem, exact mem.2 }, have hi₀ : i₀ ∈ t := filter_subset _ _ mem, let k : E → ℝ := λ z, f z - (f i₀ / g i₀) * g z, have hk : k i₀ = 0 := by field_simp [k, ne_of_gt hg], have ksum : ∑ e in t.erase i₀, k e = 1, { calc ∑ e in t.erase i₀, k e = ∑ e in t, k e : by conv_rhs { rw [← insert_erase hi₀, sum_insert (not_mem_erase i₀ t), hk, zero_add], } ... = ∑ e in t, (f e - f i₀ / g i₀ * g e) : rfl ... = 1 : by rw [sum_sub_distrib, fsum, ← mul_sum, gsum, mul_zero, sub_zero] }, refine ⟨⟨i₀, hi₀⟩, k, _, ksum, _⟩, { simp only [and_imp, sub_nonneg, mem_erase, ne.def, subtype.coe_mk], intros e hei₀ het, by_cases hes : e ∈ s, { have hge : 0 < g e := by { rw mem_filter at hes, exact hes.2 }, rw ← le_div_iff hge, exact w _ hes, }, { calc _ ≤ 0 : mul_nonpos_of_nonneg_of_nonpos _ _ -- prove two goals below ... ≤ f e : fpos e het, { apply div_nonneg (fpos i₀ (mem_of_subset (filter_subset _ t) mem)) (le_of_lt hg) }, { simpa only [mem_filter, het, true_and, not_lt] using hes }, } }, { simp only [subtype.coe_mk, center_mass_eq_of_sum_1 _ id ksum, id], calc ∑ e in t.erase i₀, k e • e = ∑ e in t, k e • e : sum_erase _ (by rw [hk, zero_smul]) ... = ∑ e in t, (f e - f i₀ / g i₀ * g e) • e : rfl ... = t.center_mass f id : _, simp only [sub_smul, mul_smul, sum_sub_distrib, ← smul_sum, gcombo, smul_zero, sub_zero, center_mass, fsum, inv_one, one_smul, id.def], }, end /-- The convex hull of a finset `t` with `finrank ℝ E + 1 < t.card` is equal to the union of the convex hulls of the finsets `t.erase x` for `x ∈ t`. -/ lemma step [decidable_eq E] (t : finset E) (h : finrank ℝ E + 1 < t.card) : convex_hull (↑t : set E) = ⋃ (x : (↑t : set E)), convex_hull ↑(t.erase x) := begin apply set.subset.antisymm, { intros x m', obtain ⟨y, m⟩ := mem_convex_hull_erase h m', exact mem_Union.2 ⟨y, m⟩, }, { refine Union_subset _, intro x, apply convex_hull_mono, apply erase_subset, } end /-- The convex hull of a finset `t` with `finrank ℝ E + 1 < t.card` is contained in the union of the convex hulls of the finsets `t' ⊆ t` with `t'.card ≤ finrank ℝ E + 1`. -/ lemma shrink' (t : finset E) (k : ℕ) (h : t.card = finrank ℝ E + 1 + k) : convex_hull (↑t : set E) ⊆ ⋃ (t' : finset E) (w : t' ⊆ t) (b : t'.card ≤ finrank ℝ E + 1), convex_hull ↑t' := begin induction k with k ih generalizing t, { apply subset_subset_Union t, apply subset_subset_Union (set.subset.refl _), exact subset_subset_Union (le_of_eq h) (subset.refl _), }, { classical, rw step _ (by { rw h, simp, } : finrank ℝ E + 1 < t.card), apply Union_subset, intro i, transitivity, { apply ih, rw [card_erase_of_mem, h, nat.pred_succ], exact i.2, }, { apply Union_subset_Union, intro t', apply Union_subset_Union_const, exact λ h, set.subset.trans h (erase_subset _ _), } } end /-- The convex hull of any finset `t` is contained in the union of the convex hulls of the finsets `t' ⊆ t` with `t'.card ≤ finrank ℝ E + 1`. -/ lemma shrink (t : finset E) : convex_hull (↑t : set E) ⊆ ⋃ (t' : finset E) (w : t' ⊆ t) (b : t'.card ≤ finrank ℝ E + 1), convex_hull ↑t' := begin by_cases h : t.card ≤ finrank ℝ E + 1, { apply subset_subset_Union t, apply subset_subset_Union (set.subset.refl _), exact subset_subset_Union h (set.subset.refl _), }, push_neg at h, obtain ⟨k, w⟩ := le_iff_exists_add.mp (le_of_lt h), clear h, exact shrink' _ _ w, end end caratheodory /-- One inclusion of **Carathéodory's convexity theorem**. The convex hull of a set `s` in ℝᵈ is contained in the union of the convex hulls of the (d+1)-tuples in `s`. -/ lemma convex_hull_subset_union (s : set E) : convex_hull s ⊆ ⋃ (t : finset E) (w : ↑t ⊆ s) (b : t.card ≤ finrank ℝ E + 1), convex_hull ↑t := begin -- First we replace `convex_hull s` with the union of the convex hulls of finite subsets, rw convex_hull_eq_union_convex_hull_finite_subsets, -- and prove the inclusion for each of those. apply Union_subset, intro r, apply Union_subset, intro h, -- Second, for each convex hull of a finite subset, we shrink it. refine subset.trans (caratheodory.shrink _) _, -- After that it's just shuffling unions around. refine Union_subset_Union (λ t, _), exact Union_subset_Union2 (λ htr, ⟨subset.trans htr h, subset.refl _⟩) end /-- **Carathéodory's convexity theorem**. The convex hull of a set `s` in ℝᵈ is the union of the convex hulls of the (d+1)-tuples in `s`. -/ theorem convex_hull_eq_union (s : set E) : convex_hull s = ⋃ (t : finset E) (w : ↑t ⊆ s) (b : t.card ≤ finrank ℝ E + 1), convex_hull ↑t := begin apply set.subset.antisymm, { apply convex_hull_subset_union, }, iterate 3 { convert Union_subset _, intro, }, exact convex_hull_mono ‹_›, end /-- A more explicit formulation of **Carathéodory's convexity theorem**, writing an element of a convex hull as the center of mass of an explicit `finset` with cardinality at most `dim + 1`. -/ theorem eq_center_mass_card_le_dim_succ_of_mem_convex_hull {s : set E} {x : E} (h : x ∈ convex_hull s) : ∃ (t : finset E) (w : ↑t ⊆ s) (b : t.card ≤ finrank ℝ E + 1) (f : E → ℝ), (∀ y ∈ t, 0 ≤ f y) ∧ t.sum f = 1 ∧ t.center_mass f id = x := begin rw convex_hull_eq_union at h, simp only [exists_prop, mem_Union] at h, obtain ⟨t, w, b, m⟩ := h, refine ⟨t, w, b, _⟩, rw finset.convex_hull_eq at m, simpa only [exists_prop] using m, end /-- A variation on **Carathéodory's convexity theorem**, writing an element of a convex hull as a center of mass of an explicit `finset` with cardinality at most `dim + 1`, where all coefficients in the center of mass formula are strictly positive. (This is proved using `eq_center_mass_card_le_dim_succ_of_mem_convex_hull`, and discarding any elements of the set with coefficient zero.) -/ theorem eq_pos_center_mass_card_le_dim_succ_of_mem_convex_hull {s : set E} {x : E} (h : x ∈ convex_hull s) : ∃ (t : finset E) (w : ↑t ⊆ s) (b : t.card ≤ finrank ℝ E + 1) (f : E → ℝ), (∀ y ∈ t, 0 < f y) ∧ t.sum f = 1 ∧ t.center_mass f id = x := begin obtain ⟨t, w, b, f, ⟨pos, sum, center⟩⟩ := eq_center_mass_card_le_dim_succ_of_mem_convex_hull h, let t' := t.filter (λ z, 0 < f z), have t'sum : t'.sum f = 1, { rw ← sum, exact sum_filter_of_ne (λ x hxt hfx, (pos x hxt).lt_of_ne hfx.symm) }, refine ⟨t', _, _, f, ⟨_, t'sum, _⟩⟩, { exact subset.trans (filter_subset _ t) w, }, { exact (card_filter_le _ _).trans b, }, { exact λ y H, (mem_filter.mp H).right, }, { rw ← center, simp only [center_mass, t'sum, sum, inv_one, one_smul, id.def], refine sum_filter_of_ne (λ x hxt hfx, (pos x hxt).lt_of_ne $ λ hf₀, _), rw [← hf₀, zero_smul] at hfx, exact hfx rfl }, end
3c00e26919f3df4f2ebddccb95a75208bb50c6ab
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/set_theory/surreal/basic.lean
fe2df6135ac01106128d06422234591b5340bd6f
[ "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
15,489
lean
/- Copyright (c) 2019 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Scott Morrison -/ import algebra.order.hom.monoid import set_theory.game.ordinal /-! # Surreal numbers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The basic theory of surreal numbers, built on top of the theory of combinatorial (pre-)games. A pregame is `numeric` if all the Left options are strictly smaller than all the Right options, and all those options are themselves numeric. In terms of combinatorial games, the numeric games have "frozen"; you can only make your position worse by playing, and Left is some definite "number" of moves ahead (or behind) Right. A surreal number is an equivalence class of numeric pregames. In fact, the surreals form a complete ordered field, containing a copy of the reals (and much else besides!) but we do not yet have a complete development. ## Order properties Surreal numbers inherit the relations `≤` and `<` from games (`surreal.has_le` and `surreal.has_lt`), and these relations satisfy the axioms of a partial order. ## Algebraic operations We show that the surreals form a linear ordered commutative group. One can also map all the ordinals into the surreals! ### Multiplication of surreal numbers The proof that multiplication lifts to surreal numbers is surprisingly difficult and is currently missing in the library. A sample proof can be found in Theorem 3.8 in the second reference below. The difficulty lies in the length of the proof and the number of theorems that need to proven simultaneously. This will make for a fun and challenging project. The branch `surreal_mul` contains some progress on this proof. ### Todo - Define the field structure on the surreals. ## References * [Conway, *On numbers and games*][conway2001] * [Schleicher, Stoll, *An introduction to Conway's games and numbers*][schleicher_stoll] -/ universes u open_locale pgame namespace pgame /-- A pre-game is numeric if everything in the L set is less than everything in the R set, and all the elements of L and R are also numeric. -/ def numeric : pgame → Prop | ⟨l, r, L, R⟩ := (∀ i j, L i < R j) ∧ (∀ i, numeric (L i)) ∧ (∀ j, numeric (R j)) lemma numeric_def {x : pgame} : numeric x ↔ (∀ i j, x.move_left i < x.move_right j) ∧ (∀ i, numeric (x.move_left i)) ∧ (∀ j, numeric (x.move_right j)) := by { cases x, refl } namespace numeric lemma mk {x : pgame} (h₁ : ∀ i j, x.move_left i < x.move_right j) (h₂ : ∀ i, numeric (x.move_left i)) (h₃ : ∀ j, numeric (x.move_right j)) : numeric x := numeric_def.2 ⟨h₁, h₂, h₃⟩ lemma left_lt_right {x : pgame} (o : numeric x) (i : x.left_moves) (j : x.right_moves) : x.move_left i < x.move_right j := by { cases x, exact o.1 i j } lemma move_left {x : pgame} (o : numeric x) (i : x.left_moves) : numeric (x.move_left i) := by { cases x, exact o.2.1 i } lemma move_right {x : pgame} (o : numeric x) (j : x.right_moves) : numeric (x.move_right j) := by { cases x, exact o.2.2 j } end numeric @[elab_as_eliminator] theorem numeric_rec {C : pgame → Prop} (H : ∀ l r (L : l → pgame) (R : r → pgame), (∀ i j, L i < R j) → (∀ i, numeric (L i)) → (∀ i, numeric (R i)) → (∀ i, C (L i)) → (∀ i, C (R i)) → C ⟨l, r, L, R⟩) : ∀ x, numeric x → C x | ⟨l, r, L, R⟩ ⟨h, hl, hr⟩ := H _ _ _ _ h hl hr (λ i, numeric_rec _ (hl i)) (λ i, numeric_rec _ (hr i)) theorem relabelling.numeric_imp {x y : pgame} (r : x ≡r y) (ox : numeric x) : numeric y := begin induction x using pgame.move_rec_on with x IHl IHr generalizing y, apply numeric.mk (λ i j, _) (λ i, _) (λ j, _), { rw ←lt_congr (r.move_left_symm i).equiv (r.move_right_symm j).equiv, apply ox.left_lt_right }, { exact IHl _ (ox.move_left _) (r.move_left_symm i) }, { exact IHr _ (ox.move_right _) (r.move_right_symm j) } end /-- Relabellings preserve being numeric. -/ theorem relabelling.numeric_congr {x y : pgame} (r : x ≡r y) : numeric x ↔ numeric y := ⟨r.numeric_imp, r.symm.numeric_imp⟩ theorem lf_asymm {x y : pgame} (ox : numeric x) (oy : numeric y) : x ⧏ y → ¬ y ⧏ x := begin refine numeric_rec (λ xl xr xL xR hx oxl oxr IHxl IHxr, _) x ox y oy, refine numeric_rec (λ yl yr yL yR hy oyl oyr IHyl IHyr, _), rw [mk_lf_mk, mk_lf_mk], rintro (⟨i, h₁⟩ | ⟨j, h₁⟩) (⟨i, h₂⟩ | ⟨j, h₂⟩), { exact IHxl _ _ (oyl _) (h₁.move_left_lf _) (h₂.move_left_lf _) }, { exact (le_trans h₂ h₁).not_gf (lf_of_lt (hy _ _)) }, { exact (le_trans h₁ h₂).not_gf (lf_of_lt (hx _ _)) }, { exact IHxr _ _ (oyr _) (h₁.lf_move_right _) (h₂.lf_move_right _) }, end theorem le_of_lf {x y : pgame} (h : x ⧏ y) (ox : numeric x) (oy : numeric y) : x ≤ y := not_lf.1 (lf_asymm ox oy h) alias le_of_lf ← lf.le theorem lt_of_lf {x y : pgame} (h : x ⧏ y) (ox : numeric x) (oy : numeric y) : x < y := (lt_or_fuzzy_of_lf h).resolve_right (not_fuzzy_of_le (h.le ox oy)) alias lt_of_lf ← lf.lt theorem lf_iff_lt {x y : pgame} (ox : numeric x) (oy : numeric y) : x ⧏ y ↔ x < y := ⟨λ h, h.lt ox oy, lf_of_lt⟩ /-- Definition of `x ≤ y` on numeric pre-games, in terms of `<` -/ theorem le_iff_forall_lt {x y : pgame} (ox : x.numeric) (oy : y.numeric) : x ≤ y ↔ (∀ i, x.move_left i < y) ∧ ∀ j, x < y.move_right j := begin refine le_iff_forall_lf.trans (and_congr _ _); refine forall_congr (λ i, lf_iff_lt _ _); apply_rules [numeric.move_left, numeric.move_right] end /-- Definition of `x < y` on numeric pre-games, in terms of `≤` -/ theorem lt_iff_exists_le {x y : pgame} (ox : x.numeric) (oy : y.numeric) : x < y ↔ (∃ i, x ≤ y.move_left i) ∨ ∃ j, x.move_right j ≤ y := by rw [←lf_iff_lt ox oy, lf_iff_exists_le] theorem lt_of_exists_le {x y : pgame} (ox : x.numeric) (oy : y.numeric) : ((∃ i, x ≤ y.move_left i) ∨ ∃ j, x.move_right j ≤ y) → x < y := (lt_iff_exists_le ox oy).2 /-- The definition of `x < y` on numeric pre-games, in terms of `<` two moves later. -/ theorem lt_def {x y : pgame} (ox : x.numeric) (oy : y.numeric) : x < y ↔ (∃ i, (∀ i', x.move_left i' < y.move_left i) ∧ ∀ j, x < (y.move_left i).move_right j) ∨ ∃ j, (∀ i, (x.move_right j).move_left i < y) ∧ ∀ j', x.move_right j < y.move_right j' := begin rw [←lf_iff_lt ox oy, lf_def], refine or_congr _ _; refine exists_congr (λ x_1, _); refine and_congr _ _; refine (forall_congr $ λ i, lf_iff_lt _ _); apply_rules [numeric.move_left, numeric.move_right] end theorem not_fuzzy {x y : pgame} (ox : numeric x) (oy : numeric y) : ¬ fuzzy x y := λ h, not_lf.2 ((lf_of_fuzzy h).le ox oy) h.2 theorem lt_or_equiv_or_gt {x y : pgame} (ox : numeric x) (oy : numeric y) : x < y ∨ x ≈ y ∨ y < x := (lf_or_equiv_or_gf x y).imp (λ h, h.lt ox oy) $ or.imp_right $ λ h, h.lt oy ox theorem numeric_of_is_empty (x : pgame) [is_empty x.left_moves] [is_empty x.right_moves] : numeric x := numeric.mk is_empty_elim is_empty_elim is_empty_elim theorem numeric_of_is_empty_left_moves (x : pgame) [is_empty x.left_moves] : (∀ j, numeric (x.move_right j)) → numeric x := numeric.mk is_empty_elim is_empty_elim theorem numeric_of_is_empty_right_moves (x : pgame) [is_empty x.right_moves] (H : ∀ i, numeric (x.move_left i)) : numeric x := numeric.mk (λ _, is_empty_elim) H is_empty_elim theorem numeric_zero : numeric 0 := numeric_of_is_empty 0 theorem numeric_one : numeric 1 := numeric_of_is_empty_right_moves 1 $ λ _, numeric_zero theorem numeric.neg : Π {x : pgame} (o : numeric x), numeric (-x) | ⟨l, r, L, R⟩ o := ⟨λ j i, neg_lt_neg_iff.2 (o.1 i j), λ j, (o.2.2 j).neg, λ i, (o.2.1 i).neg⟩ namespace numeric theorem move_left_lt {x : pgame} (o : numeric x) (i) : x.move_left i < x := (move_left_lf i).lt (o.move_left i) o theorem move_left_le {x : pgame} (o : numeric x) (i) : x.move_left i ≤ x := (o.move_left_lt i).le theorem lt_move_right {x : pgame} (o : numeric x) (j) : x < x.move_right j := (lf_move_right j).lt o (o.move_right j) theorem le_move_right {x : pgame} (o : numeric x) (j) : x ≤ x.move_right j := (o.lt_move_right j).le theorem add : Π {x y : pgame} (ox : numeric x) (oy : numeric y), numeric (x + y) | ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ox oy := ⟨begin rintros (ix|iy) (jx|jy), { exact add_lt_add_right (ox.1 ix jx) _ }, { exact (add_lf_add_of_lf_of_le (lf_mk _ _ ix) (oy.le_move_right jy)).lt ((ox.move_left ix).add oy) (ox.add (oy.move_right jy)) }, { exact (add_lf_add_of_lf_of_le (mk_lf _ _ jx) (oy.move_left_le iy)).lt (ox.add (oy.move_left iy)) ((ox.move_right jx).add oy) }, { exact add_lt_add_left (oy.1 iy jy) ⟨xl, xr, xL, xR⟩ } end, begin split, { rintros (ix|iy), { exact (ox.move_left ix).add oy }, { exact ox.add (oy.move_left iy) } }, { rintros (jx|jy), { apply (ox.move_right jx).add oy }, { apply ox.add (oy.move_right jy) } } end⟩ using_well_founded { dec_tac := pgame_wf_tac } lemma sub {x y : pgame} (ox : numeric x) (oy : numeric y) : numeric (x - y) := ox.add oy.neg end numeric /-- Pre-games defined by natural numbers are numeric. -/ theorem numeric_nat : Π (n : ℕ), numeric n | 0 := numeric_zero | (n + 1) := (numeric_nat n).add numeric_one /-- Ordinal games are numeric. -/ theorem numeric_to_pgame (o : ordinal) : o.to_pgame.numeric := begin induction o using ordinal.induction with o IH, apply numeric_of_is_empty_right_moves, simpa using λ i, IH _ (ordinal.to_left_moves_to_pgame_symm_lt i) end end pgame open pgame /-- The type of surreal numbers. These are the numeric pre-games quotiented by the equivalence relation `x ≈ y ↔ x ≤ y ∧ y ≤ x`. In the quotient, the order becomes a total order. -/ def surreal := quotient (subtype.setoid numeric) namespace surreal /-- Construct a surreal number from a numeric pre-game. -/ def mk (x : pgame) (h : x.numeric) : surreal := ⟦⟨x, h⟩⟧ instance : has_zero surreal := ⟨mk 0 numeric_zero⟩ instance : has_one surreal := ⟨mk 1 numeric_one⟩ instance : inhabited surreal := ⟨0⟩ /-- Lift an equivalence-respecting function on pre-games to surreals. -/ def lift {α} (f : ∀ x, numeric x → α) (H : ∀ {x y} (hx : numeric x) (hy : numeric y), x.equiv y → f x hx = f y hy) : surreal → α := quotient.lift (λ x : {x // numeric x}, f x.1 x.2) (λ x y, H x.2 y.2) /-- Lift a binary equivalence-respecting function on pre-games to surreals. -/ def lift₂ {α} (f : ∀ x y, numeric x → numeric y → α) (H : ∀ {x₁ y₁ x₂ y₂} (ox₁ : numeric x₁) (oy₁ : numeric y₁) (ox₂ : numeric x₂) (oy₂ : numeric y₂), x₁.equiv x₂ → y₁.equiv y₂ → f x₁ y₁ ox₁ oy₁ = f x₂ y₂ ox₂ oy₂) : surreal → surreal → α := lift (λ x ox, lift (λ y oy, f x y ox oy) (λ y₁ y₂ oy₁ oy₂, H _ _ _ _ equiv_rfl)) (λ x₁ x₂ ox₁ ox₂ h, funext $ quotient.ind $ by exact λ ⟨y, oy⟩, H _ _ _ _ h equiv_rfl) instance : has_le surreal := ⟨lift₂ (λ x y _ _, x ≤ y) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, propext (le_congr hx hy))⟩ instance : has_lt surreal := ⟨lift₂ (λ x y _ _, x < y) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, propext (lt_congr hx hy))⟩ /-- Addition on surreals is inherited from pre-game addition: the sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/ instance : has_add surreal := ⟨surreal.lift₂ (λ (x y : pgame) (ox) (oy), ⟦⟨x + y, ox.add oy⟩⟧) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, quotient.sound (add_congr hx hy))⟩ /-- Negation for surreal numbers is inherited from pre-game negation: the negation of `{L | R}` is `{-R | -L}`. -/ instance : has_neg surreal := ⟨surreal.lift (λ x ox, ⟦⟨-x, ox.neg⟩⟧) (λ _ _ _ _ a, quotient.sound (neg_equiv_neg_iff.2 a))⟩ instance : ordered_add_comm_group surreal := { add := (+), add_assoc := by { rintros ⟨_⟩ ⟨_⟩ ⟨_⟩, exact quotient.sound add_assoc_equiv }, zero := 0, zero_add := by { rintros ⟨_⟩, exact quotient.sound (zero_add_equiv a) }, add_zero := by { rintros ⟨_⟩, exact quotient.sound (add_zero_equiv a) }, neg := has_neg.neg, add_left_neg := by { rintros ⟨_⟩, exact quotient.sound (add_left_neg_equiv a) }, add_comm := by { rintros ⟨_⟩ ⟨_⟩, exact quotient.sound add_comm_equiv }, le := (≤), lt := (<), le_refl := by { rintros ⟨_⟩, apply @le_rfl pgame }, le_trans := by { rintros ⟨_⟩ ⟨_⟩ ⟨_⟩, apply @le_trans pgame }, lt_iff_le_not_le := by { rintros ⟨_, ox⟩ ⟨_, oy⟩, apply @lt_iff_le_not_le pgame }, le_antisymm := by { rintros ⟨_⟩ ⟨_⟩ h₁ h₂, exact quotient.sound ⟨h₁, h₂⟩ }, add_le_add_left := by { rintros ⟨_⟩ ⟨_⟩ hx ⟨_⟩, exact @add_le_add_left pgame _ _ _ _ _ hx _ } } noncomputable instance : linear_ordered_add_comm_group surreal := { le_total := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩; classical; exact or_iff_not_imp_left.2 (λ h, (pgame.not_le.1 h).le oy ox), decidable_le := classical.dec_rel _, ..surreal.ordered_add_comm_group } instance : add_monoid_with_one surreal := add_monoid_with_one.unary /-- Casts a `surreal` number into a `game`. -/ def to_game : surreal →+o game := { to_fun := lift (λ x _, ⟦x⟧) (λ x y ox oy, quot.sound), map_zero' := rfl, map_add' := by { rintros ⟨_, _⟩ ⟨_, _⟩, refl }, monotone' := by { rintros ⟨_, _⟩ ⟨_, _⟩, exact id } } theorem zero_to_game : to_game 0 = 0 := rfl @[simp] theorem one_to_game : to_game 1 = 1 := rfl @[simp] theorem nat_to_game : ∀ n : ℕ, to_game n = n := map_nat_cast' _ one_to_game theorem upper_bound_numeric {ι : Type u} {f : ι → pgame.{u}} (H : ∀ i, (f i).numeric) : (upper_bound f).numeric := numeric_of_is_empty_right_moves _ $ λ i, (H _).move_left _ theorem lower_bound_numeric {ι : Type u} {f : ι → pgame.{u}} (H : ∀ i, (f i).numeric) : (lower_bound f).numeric := numeric_of_is_empty_left_moves _ $ λ i, (H _).move_right _ /-- A small set `s` of surreals is bounded above. -/ lemma bdd_above_of_small (s : set surreal.{u}) [small.{u} s] : bdd_above s := begin let g := subtype.val ∘ quotient.out ∘ subtype.val ∘ (equiv_shrink s).symm, refine ⟨mk (upper_bound g) (upper_bound_numeric $ λ i, subtype.prop _), λ i hi, _⟩, rw ←quotient.out_eq i, show i.out.1 ≤ _, simpa [g] using le_upper_bound g (equiv_shrink s ⟨i, hi⟩) end /-- A small set `s` of surreals is bounded below. -/ lemma bdd_below_of_small (s : set surreal.{u}) [small.{u} s] : bdd_below s := begin let g := subtype.val ∘ quotient.out ∘ subtype.val ∘ (equiv_shrink s).symm, refine ⟨mk (lower_bound g) (lower_bound_numeric $ λ i, subtype.prop _), λ i hi, _⟩, rw ←quotient.out_eq i, show _ ≤ i.out.1, simpa [g] using lower_bound_le g (equiv_shrink s ⟨i, hi⟩) end end surreal open surreal namespace ordinal /-- Converts an ordinal into the corresponding surreal. -/ noncomputable def to_surreal : ordinal ↪o surreal := { to_fun := λ o, mk _ (numeric_to_pgame o), inj' := λ a b h, to_pgame_equiv_iff.1 (quotient.exact h), map_rel_iff' := @to_pgame_le_iff } end ordinal
d8b8e7bc63bb2146f36f90d9e846c557666a9cc2
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Elab/Log.lean
4f55d463f80a590346a1ddfa87f773d2da7d1154
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,842
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Util import Lean.Elab.Exception namespace Lean namespace Elab class MonadLog (m : Type → Type) := (getRef : m Syntax) (getFileMap : m FileMap) (getFileName : m String) (logMessage : Message → m Unit) instance monadLogTrans (m n) [MonadLog m] [MonadLift m n] : MonadLog n := { getRef := liftM (MonadLog.getRef : m _), getFileMap := liftM (MonadLog.getFileMap : m _), getFileName := liftM (MonadLog.getFileName : m _), logMessage := fun msg => liftM (MonadLog.logMessage msg : m _ ) } export MonadLog (getFileMap getFileName logMessage) open MonadLog (getRef) variables {m : Type → Type} [Monad m] [MonadLog m] [AddMessageContext m] def getRefPos : m String.Pos := do ref ← getRef; pure $ ref.getPos.getD 0 def getRefPosition : m Position := do pos ← getRefPos; fileMap ← getFileMap; pure $ fileMap.toPosition pos def logAt (ref : Syntax) (msgData : MessageData) (severity : MessageSeverity := MessageSeverity.error): m Unit := do currRef ← getRef; let ref := replaceRef ref currRef; let pos := ref.getPos.getD 0; fileMap ← getFileMap; fileName ← getFileName; msgData ← addMessageContext msgData; logMessage { fileName := fileName, pos := fileMap.toPosition pos, data := msgData, severity := severity } def logErrorAt (ref : Syntax) (msgData : MessageData) : m Unit := logAt ref msgData MessageSeverity.error def logWarningAt (ref : Syntax) (msgData : MessageData) : m Unit := logAt ref msgData MessageSeverity.warning def logInfoAt (ref : Syntax) (msgData : MessageData) : m Unit := logAt ref msgData MessageSeverity.information def log (msgData : MessageData) (severity : MessageSeverity := MessageSeverity.error): m Unit := do ref ← getRef; logAt ref msgData severity def logError (msgData : MessageData) : m Unit := log msgData MessageSeverity.error def logWarning (msgData : MessageData) : m Unit := log msgData MessageSeverity.warning def logInfo (msgData : MessageData) : m Unit := log msgData MessageSeverity.information def logException [MonadIO m] (ex : Exception) : m Unit := do match ex with | Exception.error ref msg => logErrorAt ref msg | Exception.internal id => unless (id == abortExceptionId) do name ← liftIO $ id.getName; logError ("internal exception: " ++ name) def logTrace (cls : Name) (msgData : MessageData) : m Unit := do logInfo (MessageData.tagged cls msgData) @[inline] def trace [MonadOptions m] (cls : Name) (msg : Unit → MessageData) : m Unit := do opts ← getOptions; when (checkTraceOption opts cls) $ logTrace cls (msg ()) def logDbgTrace [MonadOptions m] (msg : MessageData) : m Unit := do trace `Elab.debug fun _ => msg end Elab end Lean
871d6c835f135544e5d6c63ed2d7869145d851b6
43390109ab88557e6090f3245c47479c123ee500
/src/M1P2/sheet_5.lean
bb1de138dee4ec560ab5ace956f4bd5c232a3255
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,914
lean
import group_theory.subgroup data.set.basic algebra.group data.equiv import xenalib.Ellen_Arlt_matrix_rings -- sheet 5 variables {G : Type*} [group G] variables (H K : set G) variables [is_subgroup H] [is_subgroup K] -- 1. Recall that for a matrix A = (aij), the transpose of A is the matrix AT = (bij), where bij = aji. Let G = GL(2,R), and let H ⊆ G be the subset -- H ={A∈G|ATA=I}. -- (a) Show that H is a subgroup of G. -- (b) What are the possible determinants for an element of H? -- (c) Show that the elements of H with determinant 1 form a subgroup K of -- G. -- (d) Prove that, with K as in (c): -- 􏰄􏰂cosθ −sinθ􏰃 􏰅 K = sin θ cos θ : θ ∈ R -- . -- (e) Find an element of H of order 3, and another with infinite order. -- (f) Show that K is abelian. Is H abelian? -- (g) Generalize parts (a), (b), (c). -- 2∗. Which of the following subsets H are subgroups of the given group G? -- (a) G=(Z,+),H={n∈Z|n≡0mod37}. -- (b) G=GL(2,C),H={A∈G|A2 =I}. -- (c) G=GL(2,R),H={A∈G|det(A)=1}. -- (d) G=Sn,H={g∈G|g(1)=1}(forn∈N). -- (e) G=Sn,H={g∈G|g(1)=2}. -- (f) G=Sn,H isthesetofallpermutationsg∈Gsuchthat g(i) − g(j) ≡ i − j mod n for all i, j ∈ {1, . . . , n}. -- 3. Let G be a group with subgroups H and K. -- (a) Prove that H ∩ K is a subgroup of G. theorem sheet05_q3a: is_subgroup(H ∩ K) := sorry -- (b) Show that H ∪ K is not a subgroup, unless either H ⊆ K or K ⊆ H. theorem sheet05_q3b (hp:¬(H ⊆ K ∨ K ⊆ H)): ¬is_subgroup(H ∪ K) := sorry -- 4. Prove the following statements. definition is_cyclic (G : Type*) [group G] := ∃ x : G, gpowers x = set.univ -- (a) Every cyclic group is abelian. theorem sheet05_q4a : is_cyclic G → comm_group G := sorry --{ ..is_subgrou } definition gsymmetric (n : ℕ) := equiv.perm (fin n) -- (b) The symmetric group is not abelian, unless n < 3. theorem sheet05_q4b (n : ℕ) (n < 3) : comm_group (gsymmetric n) → gsymmetric n := sorry -- 5. Find an example of each of the following: -- (a) an element of order 3 in the group GL(2, C). -- (b) an element of order 3 in the group GL(2, R). -- (c) an element of infinite order in the group GL(2, R). (d) an element of order 12 in the group S7. -- 6. Let G=S₅. -- (a) Show that any element of G which fixes exactly two points in {1, 2, 3, 4, 5} -- must have order 3. -- (b) What are the possible orders of a cyclic subgroup of G? -- (c) Find a proper subgroup of G which is not cyclic. -- 7. Which of the following groups are cyclic? Prove one statement, delete the other. -- (a) theorem sheet05_q7a_is_T : gsymmetric 2 → is_cyclic G := sorry theorem sheet05_q7a_is_F : ¬ (gsymmetric 2 → is_cyclic G) := sorry -- (b) theorem sheet05_q7b_is_T : group (GL 2 R) → is_cyclic G := sorry theorem sheet05_q7b_is_F : group (GL 2 R) → ¬ (is_cyclic G) := sorry􏰃 -- (c) 0 b | -- (d) (Q,+). a, b ∈ {1, −1} -- under matrix multiplication.
36cae47f1ee1546c71854457ff61a5f90219285c
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/struct_infer.lean
d4f3dae89057fd9bd37b23da1dfb92dffe345f00
[ "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
665
lean
import data.nat.basic open nat namespace foo definition associative {A : Type} (op : A → A → A) := ∀a b c, op (op a b) c = op a (op b c) structure semigroup [class] (A : Type) := mk {} :: (mul: A → A → A) (mul_assoc : associative mul) definition nat_semigroup [instance] : semigroup nat := semigroup.mk nat.mul nat.mul_assoc example (a b c : nat) : (a * b) * c = a * (b * c) := semigroup.mul_assoc a b c structure semigroup2 (A : Type) := mk () :: (mul: A → A → A) (mul_assoc : associative mul) definition s := semigroup2.mk nat nat.mul nat.mul_assoc example (a b c : nat) : (a * b) * c = a * (b * c) := semigroup2.mul_assoc nat s a b c end foo
86f49f927278817e2181cdc674329cc97b3e8b71
675b8263050a5d74b89ceab381ac81ce70535688
/src/measure_theory/integration.lean
ebd82baeb8a408e9b02716793a00842bac6109fe
[ "Apache-2.0" ]
permissive
vozor/mathlib
5921f55235ff60c05f4a48a90d616ea167068adf
f7e728ad8a6ebf90291df2a4d2f9255a6576b529
refs/heads/master
1,675,607,702,231
1,609,023,279,000
1,609,023,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
72,073
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl -/ import measure_theory.measure_space import measure_theory.borel_space import data.indicator_function import data.support /-! # Lebesgue integral for `ennreal`-valued functions We define simple functions and show that each Borel measurable function on `ennreal` can be approximated by a sequence of simple functions. To prove something for an arbitrary measurable function into `ennreal`, the theorem `measurable.ennreal_induction` shows that is it sufficient to show that the property holds for (multiples of) characteristic functions and is closed under addition and supremum of increasing sequences of functions. ## Notation We introduce the following notation for the lower Lebesgue integral of a function `f : α → ennreal`. * `∫⁻ x, f x ∂μ`: integral of a function `f : α → ennreal` with respect to a measure `μ`; * `∫⁻ x, f x`: integral of a function `f : α → ennreal` with respect to the canonical measure `volume` on `α`; * `∫⁻ x in s, f x ∂μ`: integral of a function `f : α → ennreal` over a set `s` with respect to a measure `μ`, defined as `∫⁻ x, f x ∂(μ.restrict s)`; * `∫⁻ x in s, f x`: integral of a function `f : α → ennreal` over a set `s` with respect to the canonical measure `volume`, defined as `∫⁻ x, f x ∂(volume.restrict s)`. -/ noncomputable theory open set (hiding restrict restrict_apply) filter ennreal open_locale classical topological_space big_operators nnreal namespace measure_theory variables {α β γ δ : Type*} /-- A function `f` from a measurable space to any type is called *simple*, if every preimage `f ⁻¹' {x}` is measurable, and the range is finite. This structure bundles a function with these properties. -/ structure {u v} simple_func (α : Type u) [measurable_space α] (β : Type v) := (to_fun : α → β) (is_measurable_fiber' : ∀ x, is_measurable (to_fun ⁻¹' {x})) (finite_range' : (set.range to_fun).finite) local infixr ` →ₛ `:25 := simple_func namespace simple_func section measurable variables [measurable_space α] instance has_coe_to_fun : has_coe_to_fun (α →ₛ β) := ⟨_, to_fun⟩ lemma coe_injective ⦃f g : α →ₛ β⦄ (H : ⇑f = g) : f = g := by cases f; cases g; congr; exact H @[ext] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g := coe_injective $ funext H lemma finite_range (f : α →ₛ β) : (set.range f).finite := f.finite_range' lemma is_measurable_fiber (f : α →ₛ β) (x : β) : is_measurable (f ⁻¹' {x}) := f.is_measurable_fiber' x /-- Range of a simple function `α →ₛ β` as a `finset β`. -/ protected def range (f : α →ₛ β) : finset β := f.finite_range.to_finset @[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ b ∈ range f := finite.mem_to_finset theorem mem_range_self (f : α →ₛ β) (x : α) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩ @[simp] lemma coe_range (f : α →ₛ β) : (↑f.range : set β) = set.range f := f.finite_range.coe_to_finset theorem mem_range_of_measure_ne_zero {f : α →ₛ β} {x : β} {μ : measure α} (H : μ (f ⁻¹' {x}) ≠ 0) : x ∈ f.range := let ⟨a, ha⟩ := nonempty_of_measure_ne_zero H in mem_range.2 ⟨a, ha⟩ lemma forall_range_iff {f : α →ₛ β} {p : β → Prop} : (∀ y ∈ f.range, p y) ↔ ∀ x, p (f x) := by simp only [mem_range, set.forall_range_iff] lemma exists_range_iff {f : α →ₛ β} {p : β → Prop} : (∃ y ∈ f.range, p y) ↔ ∃ x, p (f x) := by simpa only [mem_range, exists_prop] using set.exists_range_iff lemma preimage_eq_empty_iff (f : α →ₛ β) (b : β) : f ⁻¹' {b} = ∅ ↔ b ∉ f.range := preimage_singleton_eq_empty.trans $ not_congr mem_range.symm /-- Constant function as a `simple_func`. -/ def const (α) {β} [measurable_space α] (b : β) : α →ₛ β := ⟨λ a, b, λ x, is_measurable.const _, finite_range_const⟩ instance [inhabited β] : inhabited (α →ₛ β) := ⟨const _ (default _)⟩ theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl @[simp] theorem coe_const (b : β) : ⇑(const α b) = function.const α b := rfl @[simp] lemma range_const (α) [measurable_space α] [nonempty α] (b : β) : (const α b).range = {b} := finset.coe_injective $ by simp lemma is_measurable_cut (r : α → β → Prop) (f : α →ₛ β) (h : ∀b, is_measurable {a | r a b}) : is_measurable {a | r a (f a)} := begin have : {a | r a (f a)} = ⋃ b ∈ range f, {a | r a b} ∩ f ⁻¹' {b}, { ext a, suffices : r a (f a) ↔ ∃ i, r a (f i) ∧ f a = f i, by simpa, exact ⟨λ h, ⟨a, ⟨h, rfl⟩⟩, λ ⟨a', ⟨h', e⟩⟩, e.symm ▸ h'⟩ }, rw this, exact is_measurable.bUnion f.finite_range.countable (λ b _, is_measurable.inter (h b) (f.is_measurable_fiber _)) end theorem is_measurable_preimage (f : α →ₛ β) (s) : is_measurable (f ⁻¹' s) := is_measurable_cut (λ _ b, b ∈ s) f (λ b, is_measurable.const (b ∈ s)) /-- A simple function is measurable -/ protected theorem measurable [measurable_space β] (f : α →ₛ β) : measurable f := λ s _, is_measurable_preimage f s protected lemma sum_measure_preimage_singleton (f : α →ₛ β) {μ : measure α} (s : finset β) : ∑ y in s, μ (f ⁻¹' {y}) = μ (f ⁻¹' ↑s) := sum_measure_preimage_singleton _ (λ _ _, f.is_measurable_fiber _) lemma sum_range_measure_preimage_singleton (f : α →ₛ β) (μ : measure α) : ∑ y in f.range, μ (f ⁻¹' {y}) = μ univ := by rw [f.sum_measure_preimage_singleton, coe_range, preimage_range] /-- If-then-else as a `simple_func`. -/ def piecewise (s : set α) (hs : is_measurable s) (f g : α →ₛ β) : α →ₛ β := ⟨s.piecewise f g, λ x, by letI : measurable_space β := ⊤; exact f.measurable.piecewise hs g.measurable trivial, (f.finite_range.union g.finite_range).subset range_ite_subset⟩ @[simp] theorem coe_piecewise {s : set α} (hs : is_measurable s) (f g : α →ₛ β) : ⇑(piecewise s hs f g) = s.piecewise f g := rfl theorem piecewise_apply {s : set α} (hs : is_measurable s) (f g : α →ₛ β) (a) : piecewise s hs f g a = if a ∈ s then f a else g a := rfl @[simp] lemma piecewise_compl {s : set α} (hs : is_measurable sᶜ) (f g : α →ₛ β) : piecewise sᶜ hs f g = piecewise s hs.of_compl g f := coe_injective $ by simp [hs] @[simp] lemma piecewise_univ (f g : α →ₛ β) : piecewise univ is_measurable.univ f g = f := coe_injective $ by simp @[simp] lemma piecewise_empty (f g : α →ₛ β) : piecewise ∅ is_measurable.empty f g = g := coe_injective $ by simp lemma measurable_bind [measurable_space γ] (f : α →ₛ β) (g : β → α → γ) (hg : ∀ b, measurable (g b)) : measurable (λ a, g (f a) a) := λ s hs, f.is_measurable_cut (λ a b, g b a ∈ s) $ λ b, hg b hs /-- If `f : α →ₛ β` is a simple function and `g : β → α →ₛ γ` is a family of simple functions, then `f.bind g` binds the first argument of `g` to `f`. In other words, `f.bind g a = g (f a) a`. -/ def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ := ⟨λa, g (f a) a, λ c, f.is_measurable_cut (λ a b, g b a = c) $ λ b, (g b).is_measurable_preimage {c}, (f.finite_range.bUnion (λ b _, (g b).finite_range)).subset $ by rintro _ ⟨a, rfl⟩; simp; exact ⟨a, a, rfl⟩⟩ @[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) : f.bind g a = g (f a) a := rfl /-- Given a function `g : β → γ` and a simple function `f : α →ₛ β`, `f.map g` return the simple function `g ∘ f : α →ₛ γ` -/ def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g) theorem map_apply (g : β → γ) (f : α →ₛ β) (a) : f.map g a = g (f a) := rfl theorem map_map (g : β → γ) (h: γ → δ) (f : α →ₛ β) : (f.map g).map h = f.map (h ∘ g) := rfl @[simp] theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl @[simp] theorem range_map [decidable_eq γ] (g : β → γ) (f : α →ₛ β) : (f.map g).range = f.range.image g := finset.coe_injective $ by simp [range_comp] @[simp] theorem map_const (g : β → γ) (b : β) : (const α b).map g = const α (g b) := rfl lemma map_preimage (f : α →ₛ β) (g : β → γ) (s : set γ) : (f.map g) ⁻¹' s = f ⁻¹' ↑(f.range.filter (λb, g b ∈ s)) := by { simp only [coe_range, sep_mem_eq, set.mem_range, function.comp_app, coe_map, finset.coe_filter, ← mem_preimage, inter_comm, preimage_inter_range], apply preimage_comp } lemma map_preimage_singleton (f : α →ₛ β) (g : β → γ) (c : γ) : (f.map g) ⁻¹' {c} = f ⁻¹' ↑(f.range.filter (λ b, g b = c)) := map_preimage _ _ _ /-- Composition of a `simple_fun` and a measurable function is a `simple_func`. -/ def comp [measurable_space β] (f : β →ₛ γ) (g : α → β) (hgm : measurable g) : α →ₛ γ := { to_fun := f ∘ g, finite_range' := f.finite_range.subset $ set.range_comp_subset_range _ _, is_measurable_fiber' := λ z, hgm (f.is_measurable_fiber z) } @[simp] lemma coe_comp [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) : ⇑(f.comp g hgm) = f ∘ g := rfl lemma range_comp_subset_range [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) : (f.comp g hgm).range ⊆ f.range := finset.coe_subset.1 $ by simp only [coe_range, coe_comp, set.range_comp_subset_range] /-- If `f` is a simple function taking values in `β → γ` and `g` is another simple function with the same domain and codomain `β`, then `f.seq g = f a (g a)`. -/ def seq (f : α →ₛ (β → γ)) (g : α →ₛ β) : α →ₛ γ := f.bind (λf, g.map f) @[simp] lemma seq_apply (f : α →ₛ (β → γ)) (g : α →ₛ β) (a : α) : f.seq g a = f a (g a) := rfl /-- Combine two simple functions `f : α →ₛ β` and `g : α →ₛ β` into `λ a, (f a, g a)`. -/ def pair (f : α →ₛ β) (g : α →ₛ γ) : α →ₛ (β × γ) := (f.map prod.mk).seq g @[simp] lemma pair_apply (f : α →ₛ β) (g : α →ₛ γ) (a) : pair f g a = (f a, g a) := rfl lemma pair_preimage (f : α →ₛ β) (g : α →ₛ γ) (s : set β) (t : set γ) : (pair f g) ⁻¹' (set.prod s t) = (f ⁻¹' s) ∩ (g ⁻¹' t) := rfl /- A special form of `pair_preimage` -/ lemma pair_preimage_singleton (f : α →ₛ β) (g : α →ₛ γ) (b : β) (c : γ) : (pair f g) ⁻¹' {(b, c)} = (f ⁻¹' {b}) ∩ (g ⁻¹' {c}) := by { rw ← singleton_prod_singleton, exact pair_preimage _ _ _ _ } theorem bind_const (f : α →ₛ β) : f.bind (const α) = f := by ext; simp instance [has_zero β] : has_zero (α →ₛ β) := ⟨const α 0⟩ instance [has_add β] : has_add (α →ₛ β) := ⟨λf g, (f.map (+)).seq g⟩ instance [has_mul β] : has_mul (α →ₛ β) := ⟨λf g, (f.map (*)).seq g⟩ instance [has_sup β] : has_sup (α →ₛ β) := ⟨λf g, (f.map (⊔)).seq g⟩ instance [has_inf β] : has_inf (α →ₛ β) := ⟨λf g, (f.map (⊓)).seq g⟩ instance [has_le β] : has_le (α →ₛ β) := ⟨λf g, ∀a, f a ≤ g a⟩ @[simp, norm_cast] lemma coe_zero [has_zero β] : ⇑(0 : α →ₛ β) = 0 := rfl @[simp] lemma const_zero [has_zero β] : const α (0:β) = 0 := rfl @[simp, norm_cast] lemma coe_add [has_add β] (f g : α →ₛ β) : ⇑(f + g) = f + g := rfl @[simp, norm_cast] lemma coe_mul [has_mul β] (f g : α →ₛ β) : ⇑(f * g) = f * g := rfl @[simp, norm_cast] lemma coe_le [preorder β] {f g : α →ₛ β} : (f : α → β) ≤ g ↔ f ≤ g := iff.rfl @[simp] lemma range_zero [nonempty α] [has_zero β] : (0 : α →ₛ β).range = {0} := finset.ext $ λ x, by simp [eq_comm] lemma eq_zero_of_mem_range_zero [has_zero β] : ∀ {y : β}, y ∈ (0 : α →ₛ β).range → y = 0 := forall_range_iff.2 $ λ x, rfl lemma sup_apply [has_sup β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl lemma mul_apply [has_mul β] (f g : α →ₛ β) (a : α) : (f * g) a = f a * g a := rfl lemma add_apply [has_add β] (f g : α →ₛ β) (a : α) : (f + g) a = f a + g a := rfl lemma add_eq_map₂ [has_add β] (f g : α →ₛ β) : f + g = (pair f g).map (λp:β×β, p.1 + p.2) := rfl lemma mul_eq_map₂ [has_mul β] (f g : α →ₛ β) : f * g = (pair f g).map (λp:β×β, p.1 * p.2) := rfl lemma sup_eq_map₂ [has_sup β] (f g : α →ₛ β) : f ⊔ g = (pair f g).map (λp:β×β, p.1 ⊔ p.2) := rfl lemma const_mul_eq_map [has_mul β] (f : α →ₛ β) (b : β) : const α b * f = f.map (λa, b * a) := rfl instance [add_monoid β] : add_monoid (α →ₛ β) := function.injective.add_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add instance add_comm_monoid [add_comm_monoid β] : add_comm_monoid (α →ₛ β) := function.injective.add_comm_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add instance [has_neg β] : has_neg (α →ₛ β) := ⟨λf, f.map (has_neg.neg)⟩ @[simp, norm_cast] lemma coe_neg [has_neg β] (f : α →ₛ β) : ⇑(-f) = -f := rfl instance [has_sub β] : has_sub (α →ₛ β) := ⟨λf g, (f.map (has_sub.sub)).seq g⟩ @[simp, norm_cast] lemma coe_sub [add_group β] (f g : α →ₛ β) : ⇑(f - g) = f - g := rfl instance [add_group β] : add_group (α →ₛ β) := function.injective.add_group_sub (λ f, show α → β, from f) coe_injective coe_zero coe_add coe_neg coe_sub instance [add_comm_group β] : add_comm_group (α →ₛ β) := function.injective.add_comm_group_sub (λ f, show α → β, from f) coe_injective coe_zero coe_add coe_neg coe_sub variables {K : Type*} instance [has_scalar K β] : has_scalar K (α →ₛ β) := ⟨λk f, f.map ((•) k)⟩ @[simp] lemma coe_smul [has_scalar K β] (c : K) (f : α →ₛ β) : ⇑(c • f) = c • f := rfl lemma smul_apply [has_scalar K β] (k : K) (f : α →ₛ β) (a : α) : (k • f) a = k • f a := rfl instance [semiring K] [add_comm_monoid β] [semimodule K β] : semimodule K (α →ₛ β) := function.injective.semimodule K ⟨λ f, show α → β, from f, coe_zero, coe_add⟩ coe_injective coe_smul lemma smul_eq_map [has_scalar K β] (k : K) (f : α →ₛ β) : k • f = f.map ((•) k) := rfl instance [preorder β] : preorder (α →ₛ β) := { le_refl := λf a, le_refl _, le_trans := λf g h hfg hgh a, le_trans (hfg _) (hgh a), .. simple_func.has_le } instance [partial_order β] : partial_order (α →ₛ β) := { le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a), .. simple_func.preorder } instance [order_bot β] : order_bot (α →ₛ β) := { bot := const α ⊥, bot_le := λf a, bot_le, .. simple_func.partial_order } instance [order_top β] : order_top (α →ₛ β) := { top := const α ⊤, le_top := λf a, le_top, .. simple_func.partial_order } instance [semilattice_inf β] : semilattice_inf (α →ₛ β) := { inf := (⊓), inf_le_left := assume f g a, inf_le_left, inf_le_right := assume f g a, inf_le_right, le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup β] : semilattice_sup (α →ₛ β) := { sup := (⊔), le_sup_left := assume f g a, le_sup_left, le_sup_right := assume f g a, le_sup_right, sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup_bot β] : semilattice_sup_bot (α →ₛ β) := { .. simple_func.semilattice_sup,.. simple_func.order_bot } instance [lattice β] : lattice (α →ₛ β) := { .. simple_func.semilattice_sup,.. simple_func.semilattice_inf } instance [bounded_lattice β] : bounded_lattice (α →ₛ β) := { .. simple_func.lattice, .. simple_func.order_bot, .. simple_func.order_top } lemma finset_sup_apply [semilattice_sup_bot β] {f : γ → α →ₛ β} (s : finset γ) (a : α) : s.sup f a = s.sup (λc, f c a) := begin refine finset.induction_on s rfl _, assume a s hs ih, rw [finset.sup_insert, finset.sup_insert, sup_apply, ih] end section restrict variables [has_zero β] /-- Restrict a simple function `f : α →ₛ β` to a set `s`. If `s` is measurable, then `f.restrict s a = if a ∈ s then f a else 0`, otherwise `f.restrict s = const α 0`. -/ def restrict (f : α →ₛ β) (s : set α) : α →ₛ β := if hs : is_measurable s then piecewise s hs f 0 else 0 theorem restrict_of_not_measurable {f : α →ₛ β} {s : set α} (hs : ¬is_measurable s) : restrict f s = 0 := dif_neg hs @[simp] theorem coe_restrict (f : α →ₛ β) {s : set α} (hs : is_measurable s) : ⇑(restrict f s) = indicator s f := by { rw [restrict, dif_pos hs], refl } @[simp] theorem restrict_univ (f : α →ₛ β) : restrict f univ = f := by simp [restrict] @[simp] theorem restrict_empty (f : α →ₛ β) : restrict f ∅ = 0 := by simp [restrict] theorem map_restrict_of_zero [has_zero γ] {g : β → γ} (hg : g 0 = 0) (f : α →ₛ β) (s : set α) : (f.restrict s).map g = (f.map g).restrict s := ext $ λ x, if hs : is_measurable s then by simp [hs, set.indicator_comp_of_zero hg] else by simp [restrict_of_not_measurable hs, hg] theorem map_coe_ennreal_restrict (f : α →ₛ ℝ≥0) (s : set α) : (f.restrict s).map (coe : ℝ≥0 → ennreal) = (f.map coe).restrict s := map_restrict_of_zero ennreal.coe_zero _ _ theorem map_coe_nnreal_restrict (f : α →ₛ ℝ≥0) (s : set α) : (f.restrict s).map (coe : ℝ≥0 → ℝ) = (f.map coe).restrict s := map_restrict_of_zero nnreal.coe_zero _ _ theorem restrict_apply (f : α →ₛ β) {s : set α} (hs : is_measurable s) (a) : restrict f s a = if a ∈ s then f a else 0 := by simp only [hs, coe_restrict] theorem restrict_preimage (f : α →ₛ β) {s : set α} (hs : is_measurable s) {t : set β} (ht : (0:β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t := by simp [hs, indicator_preimage_of_not_mem _ _ ht] theorem restrict_preimage_singleton (f : α →ₛ β) {s : set α} (hs : is_measurable s) {r : β} (hr : r ≠ 0) : restrict f s ⁻¹' {r} = s ∩ f ⁻¹' {r} := f.restrict_preimage hs hr.symm lemma mem_restrict_range {r : β} {s : set α} {f : α →ₛ β} (hs : is_measurable s) : r ∈ (restrict f s).range ↔ (r = 0 ∧ s ≠ univ) ∨ (r ∈ f '' s) := by rw [← finset.mem_coe, coe_range, coe_restrict _ hs, mem_range_indicator] lemma mem_image_of_mem_range_restrict {r : β} {s : set α} {f : α →ₛ β} (hr : r ∈ (restrict f s).range) (h0 : r ≠ 0) : r ∈ f '' s := if hs : is_measurable s then by simpa [mem_restrict_range hs, h0] using hr else by { rw [restrict_of_not_measurable hs] at hr, exact (h0 $ eq_zero_of_mem_range_zero hr).elim } @[mono] lemma restrict_mono [preorder β] (s : set α) {f g : α →ₛ β} (H : f ≤ g) : f.restrict s ≤ g.restrict s := if hs : is_measurable s then λ x, by simp only [coe_restrict _ hs, indicator_le_indicator (H x)] else by simp only [restrict_of_not_measurable hs, le_refl] end restrict section approx section variables [semilattice_sup_bot β] [has_zero β] /-- Fix a sequence `i : ℕ → β`. Given a function `α → β`, its `n`-th approximation by simple functions is defined so that in case `β = ennreal` it sends each `a` to the supremum of the set `{i k | k ≤ n ∧ i k ≤ f a}`, see `approx_apply` and `supr_approx_apply` for details. -/ def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β := (finset.range n).sup (λk, restrict (const α (i k)) {a:α | i k ≤ f a}) lemma approx_apply [topological_space β] [order_closed_topology β] [measurable_space β] [opens_measurable_space β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : measurable f) : (approx i f n : α →ₛ β) a = (finset.range n).sup (λk, if i k ≤ f a then i k else 0) := begin dsimp only [approx], rw [finset_sup_apply], congr, funext k, rw [restrict_apply], refl, exact (hf is_measurable_Ici) end lemma monotone_approx (i : ℕ → β) (f : α → β) : monotone (approx i f) := assume n m h, finset.sup_mono $ finset.range_subset.2 h lemma approx_comp [topological_space β] [order_closed_topology β] [measurable_space β] [opens_measurable_space β] [measurable_space γ] {i : ℕ → β} {f : γ → β} {g : α → γ} {n : ℕ} (a : α) (hf : measurable f) (hg : measurable g) : (approx i (f ∘ g) n : α →ₛ β) a = (approx i f n : γ →ₛ β) (g a) := by rw [approx_apply _ hf, approx_apply _ (hf.comp hg)] end lemma supr_approx_apply [topological_space β] [complete_lattice β] [order_closed_topology β] [has_zero β] [measurable_space β] [opens_measurable_space β] (i : ℕ → β) (f : α → β) (a : α) (hf : measurable f) (h_zero : (0 : β) = ⊥) : (⨆n, (approx i f n : α →ₛ β) a) = (⨆k (h : i k ≤ f a), i k) := begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _), { rw [approx_apply a hf, h_zero], refine finset.sup_le (assume k hk, _), split_ifs, exact le_supr_of_le k (le_supr _ h), exact bot_le }, { refine le_supr_of_le (k+1) _, rw [approx_apply a hf], have : k ∈ finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _), refine le_trans (le_of_eq _) (finset.le_sup this), rw [if_pos hk] } end end approx section eapprox /-- A sequence of `ennreal`s such that its range is the set of non-negative rational numbers. -/ def ennreal_rat_embed (n : ℕ) : ennreal := ennreal.of_real ((encodable.decode ℚ n).get_or_else (0 : ℚ)) lemma ennreal_rat_embed_encode (q : ℚ) : ennreal_rat_embed (encodable.encode q) = nnreal.of_real q := by rw [ennreal_rat_embed, encodable.encodek]; refl /-- Approximate a function `α → ennreal` by a sequence of simple functions. -/ def eapprox : (α → ennreal) → ℕ → α →ₛ ennreal := approx ennreal_rat_embed lemma monotone_eapprox (f : α → ennreal) : monotone (eapprox f) := monotone_approx _ f lemma supr_eapprox_apply (f : α → ennreal) (hf : measurable f) (a : α) : (⨆n, (eapprox f n : α →ₛ ennreal) a) = f a := begin rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl], refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _), assume h, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨q, hq, lt_q, q_lt⟩, have : (nnreal.of_real q : ennreal) ≤ (⨆ (k : ℕ) (h : ennreal_rat_embed k ≤ f a), ennreal_rat_embed k), { refine le_supr_of_le (encodable.encode q) _, rw [ennreal_rat_embed_encode q], refine le_supr_of_le (le_of_lt q_lt) _, exact le_refl _ }, exact lt_irrefl _ (lt_of_le_of_lt this lt_q) end lemma eapprox_comp [measurable_space γ] {f : γ → ennreal} {g : α → γ} {n : ℕ} (hf : measurable f) (hg : measurable g) : (eapprox (f ∘ g) n : α → ennreal) = (eapprox f n : γ →ₛ ennreal) ∘ g := funext $ assume a, approx_comp a hf hg end eapprox end measurable section measure variables [measurable_space α] {μ : measure α} /-- Integral of a simple function whose codomain is `ennreal`. -/ def lintegral (f : α →ₛ ennreal) (μ : measure α) : ennreal := ∑ x in f.range, x * μ (f ⁻¹' {x}) lemma lintegral_eq_of_subset (f : α →ₛ ennreal) {s : finset ennreal} (hs : ∀ x, f x ≠ 0 → μ (f ⁻¹' {f x}) ≠ 0 → f x ∈ s) : f.lintegral μ = ∑ x in s, x * μ (f ⁻¹' {x}) := begin refine finset.sum_bij_ne_zero (λr _ _, r) _ _ _ _, { simpa only [forall_range_iff, mul_ne_zero_iff, and_imp] }, { intros, assumption }, { intros b _ hb, refine ⟨b, _, hb, rfl⟩, rw [mem_range, ← preimage_singleton_nonempty], exact nonempty_of_measure_ne_zero (mul_ne_zero_iff.1 hb).2 }, { intros, refl } end /-- Calculate the integral of `(g ∘ f)`, where `g : β → ennreal` and `f : α →ₛ β`. -/ lemma map_lintegral (g : β → ennreal) (f : α →ₛ β) : (f.map g).lintegral μ = ∑ x in f.range, g x * μ (f ⁻¹' {x}) := begin simp only [lintegral, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, rw [map_preimage_singleton, ← f.sum_measure_preimage_singleton, finset.mul_sum], refine finset.sum_congr _ _, { congr }, { assume x, simp only [finset.mem_filter], rintro ⟨_, h⟩, rw h }, end lemma add_lintegral (f g : α →ₛ ennreal) : (f + g).lintegral μ = f.lintegral μ + g.lintegral μ := calc (f + g).lintegral μ = ∑ x in (pair f g).range, (x.1 * μ (pair f g ⁻¹' {x}) + x.2 * μ (pair f g ⁻¹' {x})) : by rw [add_eq_map₂, map_lintegral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _) ... = ∑ x in (pair f g).range, x.1 * μ (pair f g ⁻¹' {x}) + ∑ x in (pair f g).range, x.2 * μ (pair f g ⁻¹' {x}) : by rw [finset.sum_add_distrib] ... = ((pair f g).map prod.fst).lintegral μ + ((pair f g).map prod.snd).lintegral μ : by rw [map_lintegral, map_lintegral] ... = lintegral f μ + lintegral g μ : rfl lemma const_mul_lintegral (f : α →ₛ ennreal) (x : ennreal) : (const α x * f).lintegral μ = x * f.lintegral μ := calc (f.map (λa, x * a)).lintegral μ = ∑ r in f.range, x * r * μ (f ⁻¹' {r}) : map_lintegral _ _ ... = ∑ r in f.range, x * (r * μ (f ⁻¹' {r})) : finset.sum_congr rfl (assume a ha, mul_assoc _ _ _) ... = x * f.lintegral μ : finset.mul_sum.symm /-- Integral of a simple function `α →ₛ ennreal` as a bilinear map. -/ def lintegralₗ : (α →ₛ ennreal) →ₗ[ennreal] measure α →ₗ[ennreal] ennreal := { to_fun := λ f, { to_fun := lintegral f, map_add' := by simp [lintegral, mul_add, finset.sum_add_distrib], map_smul' := λ c μ, by simp [lintegral, mul_left_comm _ c, finset.mul_sum] }, map_add' := λ f g, linear_map.ext (λ μ, add_lintegral f g), map_smul' := λ c f, linear_map.ext (λ μ, const_mul_lintegral f c) } @[simp] lemma zero_lintegral : (0 : α →ₛ ennreal).lintegral μ = 0 := linear_map.ext_iff.1 lintegralₗ.map_zero μ lemma lintegral_add {ν} (f : α →ₛ ennreal) : f.lintegral (μ + ν) = f.lintegral μ + f.lintegral ν := (lintegralₗ f).map_add μ ν lemma lintegral_smul (f : α →ₛ ennreal) (c : ennreal) : f.lintegral (c • μ) = c • f.lintegral μ := (lintegralₗ f).map_smul c μ @[simp] lemma lintegral_zero (f : α →ₛ ennreal) : f.lintegral 0 = 0 := (lintegralₗ f).map_zero lemma lintegral_sum {ι} (f : α →ₛ ennreal) (μ : ι → measure α) : f.lintegral (measure.sum μ) = ∑' i, f.lintegral (μ i) := begin simp only [lintegral, measure.sum_apply, f.is_measurable_preimage, ← finset.tsum_subtype, ← ennreal.tsum_mul_left], apply ennreal.tsum_comm end lemma restrict_lintegral (f : α →ₛ ennreal) {s : set α} (hs : is_measurable s) : (restrict f s).lintegral μ = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) := calc (restrict f s).lintegral μ = ∑ r in f.range, r * μ (restrict f s ⁻¹' {r}) : lintegral_eq_of_subset _ $ λ x hx, if hxs : x ∈ s then by simp [f.restrict_apply hs, if_pos hxs, mem_range_self] else false.elim $ hx $ by simp [*] ... = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) : finset.sum_congr rfl $ forall_range_iff.2 $ λ b, if hb : f b = 0 then by simp only [hb, zero_mul] else by rw [restrict_preimage_singleton _ hs hb, inter_comm] lemma lintegral_restrict (f : α →ₛ ennreal) (s : set α) (μ : measure α) : f.lintegral (μ.restrict s) = ∑ y in f.range, y * μ (f ⁻¹' {y} ∩ s) := by simp only [lintegral, measure.restrict_apply, f.is_measurable_preimage] lemma restrict_lintegral_eq_lintegral_restrict (f : α →ₛ ennreal) {s : set α} (hs : is_measurable s) : (restrict f s).lintegral μ = f.lintegral (μ.restrict s) := by rw [f.restrict_lintegral hs, lintegral_restrict] lemma const_lintegral (c : ennreal) : (const α c).lintegral μ = c * μ univ := begin rw [lintegral], by_cases ha : nonempty α, { resetI, simp [preimage_const_of_mem] }, { simp [μ.eq_zero_of_not_nonempty ha] } end lemma const_lintegral_restrict (c : ennreal) (s : set α) : (const α c).lintegral (μ.restrict s) = c * μ s := by rw [const_lintegral, measure.restrict_apply is_measurable.univ, univ_inter] lemma restrict_const_lintegral (c : ennreal) {s : set α} (hs : is_measurable s) : ((const α c).restrict s).lintegral μ = c * μ s := by rw [restrict_lintegral_eq_lintegral_restrict _ hs, const_lintegral_restrict] lemma le_sup_lintegral (f g : α →ₛ ennreal) : f.lintegral μ ⊔ g.lintegral μ ≤ (f ⊔ g).lintegral μ := calc f.lintegral μ ⊔ g.lintegral μ = ((pair f g).map prod.fst).lintegral μ ⊔ ((pair f g).map prod.snd).lintegral μ : rfl ... ≤ ∑ x in (pair f g).range, (x.1 ⊔ x.2) * μ (pair f g ⁻¹' {x}) : begin rw [map_lintegral, map_lintegral], refine sup_le _ _; refine finset.sum_le_sum (λ a _, canonically_ordered_semiring.mul_le_mul _ (le_refl _)), exact le_sup_left, exact le_sup_right end ... = (f ⊔ g).lintegral μ : by rw [sup_eq_map₂, map_lintegral] /-- `simple_func.lintegral` is monotone both in function and in measure. -/ @[mono] lemma lintegral_mono {f g : α →ₛ ennreal} (hfg : f ≤ g) {μ ν : measure α} (hμν : μ ≤ ν) : f.lintegral μ ≤ g.lintegral ν := calc f.lintegral μ ≤ f.lintegral μ ⊔ g.lintegral μ : le_sup_left ... ≤ (f ⊔ g).lintegral μ : le_sup_lintegral _ _ ... = g.lintegral μ : by rw [sup_of_le_right hfg] ... ≤ g.lintegral ν : finset.sum_le_sum $ λ y hy, ennreal.mul_left_mono $ hμν _ (g.is_measurable_preimage _) /-- `simple_func.lintegral` depends only on the measures of `f ⁻¹' {y}`. -/ lemma lintegral_eq_of_measure_preimage [measurable_space β] {f : α →ₛ ennreal} {g : β →ₛ ennreal} {ν : measure β} (H : ∀ y, μ (f ⁻¹' {y}) = ν (g ⁻¹' {y})) : f.lintegral μ = g.lintegral ν := begin simp only [lintegral, ← H], apply lintegral_eq_of_subset, simp only [H], intros, exact mem_range_of_measure_ne_zero ‹_› end /-- If two simple functions are equal a.e., then their `lintegral`s are equal. -/ lemma lintegral_congr {f g : α →ₛ ennreal} (h : f =ᵐ[μ] g) : f.lintegral μ = g.lintegral μ := lintegral_eq_of_measure_preimage $ λ y, measure_congr $ eventually.set_eq $ h.mono $ λ x hx, by simp [hx] lemma lintegral_map {β} [measurable_space β] {μ' : measure β} (f : α →ₛ ennreal) (g : β →ₛ ennreal) (m : α → β) (eq : ∀a:α, f a = g (m a)) (h : ∀s:set β, is_measurable s → μ' s = μ (m ⁻¹' s)) : f.lintegral μ = g.lintegral μ' := lintegral_eq_of_measure_preimage $ λ y, by { simp only [preimage, eq], exact (h (g ⁻¹' {y}) (g.is_measurable_preimage _)).symm } end measure section fin_meas_supp variables [measurable_space α] [has_zero β] [has_zero γ] {μ : measure α} open finset ennreal function lemma support_eq (f : α →ₛ β) : support f = ⋃ y ∈ f.range.filter (λ y, y ≠ 0), f ⁻¹' {y} := set.ext $ λ x, by simp only [finset.bUnion_preimage_singleton, mem_support, set.mem_preimage, finset.mem_coe, mem_filter, mem_range_self, true_and] /-- A `simple_func` has finite measure support if it is equal to `0` outside of a set of finite measure. -/ protected def fin_meas_supp (f : α →ₛ β) (μ : measure α) : Prop := f =ᶠ[μ.cofinite] 0 lemma fin_meas_supp_iff_support {f : α →ₛ β} {μ : measure α} : f.fin_meas_supp μ ↔ μ (support f) < ⊤ := iff.rfl lemma fin_meas_supp_iff {f : α →ₛ β} {μ : measure α} : f.fin_meas_supp μ ↔ ∀ y ≠ 0, μ (f ⁻¹' {y}) < ⊤ := begin split, { refine λ h y hy, lt_of_le_of_lt (measure_mono _) h, exact λ x hx (H : f x = 0), hy $ H ▸ eq.symm hx }, { intro H, rw [fin_meas_supp_iff_support, support_eq], refine lt_of_le_of_lt (measure_bUnion_finset_le _ _) (sum_lt_top _), exact λ y hy, H y (finset.mem_filter.1 hy).2 } end namespace fin_meas_supp lemma meas_preimage_singleton_ne_zero {f : α →ₛ β} (h : f.fin_meas_supp μ) {y : β} (hy : y ≠ 0) : μ (f ⁻¹' {y}) < ⊤ := fin_meas_supp_iff.1 h y hy protected lemma map {f : α →ₛ β} {g : β → γ} (hf : f.fin_meas_supp μ) (hg : g 0 = 0) : (f.map g).fin_meas_supp μ := flip lt_of_le_of_lt hf (measure_mono $ support_comp_subset hg f) lemma of_map {f : α →ₛ β} {g : β → γ} (h : (f.map g).fin_meas_supp μ) (hg : ∀b, g b = 0 → b = 0) : f.fin_meas_supp μ := flip lt_of_le_of_lt h $ measure_mono $ support_subset_comp hg _ lemma map_iff {f : α →ₛ β} {g : β → γ} (hg : ∀ {b}, g b = 0 ↔ b = 0) : (f.map g).fin_meas_supp μ ↔ f.fin_meas_supp μ := ⟨λ h, h.of_map $ λ b, hg.1, λ h, h.map $ hg.2 rfl⟩ protected lemma pair {f : α →ₛ β} {g : α →ₛ γ} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (pair f g).fin_meas_supp μ := calc μ (support $ pair f g) = μ (support f ∪ support g) : congr_arg μ $ support_prod_mk f g ... ≤ μ (support f) + μ (support g) : measure_union_le _ _ ... < _ : add_lt_top.2 ⟨hf, hg⟩ protected lemma map₂ [has_zero δ] {μ : measure α} {f : α →ₛ β} (hf : f.fin_meas_supp μ) {g : α →ₛ γ} (hg : g.fin_meas_supp μ) {op : β → γ → δ} (H : op 0 0 = 0) : ((pair f g).map (function.uncurry op)).fin_meas_supp μ := (hf.pair hg).map H protected lemma add {β} [add_monoid β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (f + g).fin_meas_supp μ := by { rw [add_eq_map₂], exact hf.map₂ hg (zero_add 0) } protected lemma mul {β} [monoid_with_zero β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (f * g).fin_meas_supp μ := by { rw [mul_eq_map₂], exact hf.map₂ hg (zero_mul 0) } lemma lintegral_lt_top {f : α →ₛ ennreal} (hm : f.fin_meas_supp μ) (hf : ∀ᵐ a ∂μ, f a < ⊤) : f.lintegral μ < ⊤ := begin refine sum_lt_top (λ a ha, _), rcases eq_or_lt_of_le (le_top : a ≤ ⊤) with rfl|ha, { simp only [ae_iff, lt_top_iff_ne_top, ne.def, not_not] at hf, simp [set.preimage, hf] }, { by_cases ha0 : a = 0, { subst a, rwa [zero_mul] }, { exact mul_lt_top ha (fin_meas_supp_iff.1 hm _ ha0) } } end lemma of_lintegral_lt_top {f : α →ₛ ennreal} (h : f.lintegral μ < ⊤) : f.fin_meas_supp μ := begin refine fin_meas_supp_iff.2 (λ b hb, _), rw [lintegral, sum_lt_top_iff] at h, by_cases b_mem : b ∈ f.range, { rw ennreal.lt_top_iff_ne_top, have h : ¬ _ = ⊤ := ennreal.lt_top_iff_ne_top.1 (h b b_mem), simp only [mul_eq_top, not_or_distrib, not_and_distrib] at h, rcases h with ⟨h, h'⟩, refine or.elim h (λh, by contradiction) (λh, h) }, { rw ← preimage_eq_empty_iff at b_mem, rw [b_mem, measure_empty], exact with_top.zero_lt_top } end lemma iff_lintegral_lt_top {f : α →ₛ ennreal} (hf : ∀ᵐ a ∂μ, f a < ⊤) : f.fin_meas_supp μ ↔ f.lintegral μ < ⊤ := ⟨λ h, h.lintegral_lt_top hf, λ h, of_lintegral_lt_top h⟩ end fin_meas_supp end fin_meas_supp /-- To prove something for an arbitrary simple function, it suffices to show that the property holds for (multiples of) characteristic functions and is closed under addition (of functions with disjoint support). It is possible to make the hypotheses in `h_sum` a bit stronger, and such conditions can be added once we need them (for example it is only necessary to consider the case where `g` is a multiple of a characteristic function, and that this multiple doesn't appear in the image of `f`) -/ @[elab_as_eliminator] protected lemma induction {α γ} [measurable_space α] [add_monoid γ] {P : simple_func α γ → Prop} (h_ind : ∀ c {s} (hs : is_measurable s), P (simple_func.piecewise s hs (simple_func.const _ c) (simple_func.const _ 0))) (h_sum : ∀ ⦃f g : simple_func α γ⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → P f → P g → P (f + g)) (f : simple_func α γ) : P f := begin generalize' h : f.range \ {0} = s, rw [← finset.coe_inj, finset.coe_sdiff, finset.coe_singleton, simple_func.coe_range] at h, revert s f h, refine finset.induction _ _, { intros f hf, rw [finset.coe_empty, diff_eq_empty, range_subset_singleton] at hf, convert h_ind 0 is_measurable.univ, ext x, simp [hf] }, { intros x s hxs ih f hf, have mx := f.is_measurable_preimage {x}, let g := simple_func.piecewise (f ⁻¹' {x}) mx 0 f, have Pg : P g, { apply ih, simp only [g, simple_func.coe_piecewise, range_piecewise], rw [image_compl_preimage, union_diff_distrib, diff_diff_comm, hf, finset.coe_insert, insert_diff_self_of_not_mem, diff_eq_empty.mpr, set.empty_union], { rw [set.image_subset_iff], convert set.subset_univ _, exact preimage_const_of_mem (mem_singleton _) }, { rwa [finset.mem_coe] }}, convert h_sum _ Pg (h_ind x mx), { ext1 y, by_cases hy : y ∈ f ⁻¹' {x}; [simpa [hy], simp [hy]] }, { rintro y -, by_cases hy : y ∈ f ⁻¹' {x}; simp [hy] } } end end simple_func section lintegral open simple_func variables [measurable_space α] {μ : measure α} /-- The lower Lebesgue integral of a function `f` with respect to a measure `μ`. -/ def lintegral (μ : measure α) (f : α → ennreal) : ennreal := ⨆ (g : α →ₛ ennreal) (hf : ⇑g ≤ f), g.lintegral μ /-! In the notation for integrals, an expression like `∫⁻ x, g ∥x∥ ∂μ` will not be parsed correctly, and needs parentheses. We do not set the binding power of `r` to `0`, because then `∫⁻ x, f x = 0` will be parsed incorrectly. -/ notation `∫⁻` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := lintegral μ r notation `∫⁻` binders `, ` r:(scoped:60 f, lintegral volume f) := r notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 := lintegral (measure.restrict μ s) r notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, lintegral (measure.restrict volume s) f) := r theorem simple_func.lintegral_eq_lintegral (f : α →ₛ ennreal) (μ : measure α) : ∫⁻ a, f a ∂ μ = f.lintegral μ := le_antisymm (bsupr_le $ λ g hg, lintegral_mono hg $ le_refl _) (le_supr_of_le f $ le_supr_of_le (le_refl _) (le_refl _)) @[mono] lemma lintegral_mono' ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) ⦃f g : α → ennreal⦄ (hfg : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂ν := supr_le_supr $ λ φ, supr_le_supr2 $ λ hφ, ⟨le_trans hφ hfg, lintegral_mono (le_refl φ) hμν⟩ lemma lintegral_mono ⦃f g : α → ennreal⦄ (hfg : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ := lintegral_mono' (le_refl μ) hfg lemma lintegral_mono_nnreal {f g : α → ℝ≥0} (h : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ := begin refine lintegral_mono _, intro a, rw ennreal.coe_le_coe, exact h a, end lemma monotone_lintegral (μ : measure α) : monotone (lintegral μ) := lintegral_mono @[simp] lemma lintegral_const (c : ennreal) : ∫⁻ a, c ∂μ = c * μ univ := by rw [← simple_func.const_lintegral, ← simple_func.lintegral_eq_lintegral, simple_func.coe_const] lemma set_lintegral_one (s) : ∫⁻ a in s, 1 ∂μ = μ s := by rw [lintegral_const, one_mul, measure.restrict_apply_univ] /-- `∫⁻ a in s, f a ∂μ` is defined as the supremum of integrals of simple functions `φ : α →ₛ ennreal` such that `φ ≤ f`. This lemma says that it suffices to take functions `φ : α →ₛ ℝ≥0`. -/ lemma lintegral_eq_nnreal (f : α → ennreal) (μ : measure α) : (∫⁻ a, f a ∂μ) = (⨆ (φ : α →ₛ ℝ≥0) (hf : ∀ x, ↑(φ x) ≤ f x), (φ.map (coe : ℝ≥0 → ennreal)).lintegral μ) := begin refine le_antisymm (bsupr_le $ assume φ hφ, _) (supr_le_supr2 $ λ φ, ⟨φ.map (coe : ℝ≥0 → ennreal), le_refl _⟩), by_cases h : ∀ᵐ a ∂μ, φ a ≠ ⊤, { let ψ := φ.map ennreal.to_nnreal, replace h : ψ.map (coe : ℝ≥0 → ennreal) =ᵐ[μ] φ := h.mono (λ a, ennreal.coe_to_nnreal), have : ∀ x, ↑(ψ x) ≤ f x := λ x, le_trans ennreal.coe_to_nnreal_le_self (hφ x), exact le_supr_of_le (φ.map ennreal.to_nnreal) (le_supr_of_le this (ge_of_eq $ lintegral_congr h)) }, { have h_meas : μ (φ ⁻¹' {⊤}) ≠ 0, from mt measure_zero_iff_ae_nmem.1 h, refine le_trans le_top (ge_of_eq $ (supr_eq_top _).2 $ λ b hb, _), obtain ⟨n, hn⟩ : ∃ n : ℕ, b < n * μ (φ ⁻¹' {⊤}), from exists_nat_mul_gt h_meas (ne_of_lt hb), use (const α (n : ℝ≥0)).restrict (φ ⁻¹' {⊤}), simp only [lt_supr_iff, exists_prop, coe_restrict, φ.is_measurable_preimage, coe_const, ennreal.coe_indicator, map_coe_ennreal_restrict, map_const, ennreal.coe_nat, restrict_const_lintegral], refine ⟨indicator_le (λ x hx, le_trans _ (hφ _)), hn⟩, simp only [mem_preimage, mem_singleton_iff] at hx, simp only [hx, le_top] } end theorem supr_lintegral_le {ι : Sort*} (f : ι → α → ennreal) : (⨆i, ∫⁻ a, f i a ∂μ) ≤ (∫⁻ a, ⨆i, f i a ∂μ) := begin simp only [← supr_apply], exact (monotone_lintegral μ).le_map_supr end theorem supr2_lintegral_le {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ennreal) : (⨆i (h : ι' i), ∫⁻ a, f i h a ∂μ) ≤ (∫⁻ a, ⨆i (h : ι' i), f i h a ∂μ) := by { convert (monotone_lintegral μ).le_map_supr2 f, ext1 a, simp only [supr_apply] } theorem le_infi_lintegral {ι : Sort*} (f : ι → α → ennreal) : (∫⁻ a, ⨅i, f i a ∂μ) ≤ (⨅i, ∫⁻ a, f i a ∂μ) := by { simp only [← infi_apply], exact (monotone_lintegral μ).map_infi_le } theorem le_infi2_lintegral {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ennreal) : (∫⁻ a, ⨅ i (h : ι' i), f i h a ∂μ) ≤ (⨅ i (h : ι' i), ∫⁻ a, f i h a ∂μ) := by { convert (monotone_lintegral μ).map_infi2_le f, ext1 a, simp only [infi_apply] } /-- Monotone convergence theorem -- sometimes called Beppo-Levi convergence. See `lintegral_supr_directed` for a more general form. -/ theorem lintegral_supr {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : monotone f) : (∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) := begin set c : ℝ≥0 → ennreal := coe, set F := λ a:α, ⨆n, f n a, have hF : measurable F := measurable_supr hf, refine le_antisymm _ (supr_lintegral_le _), rw [lintegral_eq_nnreal], refine supr_le (assume s, supr_le (assume hsf, _)), refine ennreal.le_of_forall_lt_one_mul_lt (assume a ha, _), rcases ennreal.lt_iff_exists_coe.1 ha with ⟨r, rfl, ha⟩, have ha : r < 1 := ennreal.coe_lt_coe.1 ha, let rs := s.map (λa, r * a), have eq_rs : (const α r : α →ₛ ennreal) * map c s = rs.map c, { ext1 a, exact ennreal.coe_mul.symm }, have eq : ∀p, (rs.map c) ⁻¹' {p} = (⋃n, (rs.map c) ⁻¹' {p} ∩ {a | p ≤ f n a}), { assume p, rw [← inter_Union, ← inter_univ ((map c rs) ⁻¹' {p})] {occs := occurrences.pos [1]}, refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _), by_cases p_eq : p = 0, { simp [p_eq] }, simp at hx, subst hx, have : r * s x ≠ 0, { rwa [(≠), ← ennreal.coe_eq_zero] }, have : s x ≠ 0, { refine mt _ this, assume h, rw [h, mul_zero] }, have : (rs.map c) x < ⨆ (n : ℕ), f n x, { refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x), suffices : r * s x < 1 * s x, simpa [rs], exact mul_lt_mul_of_pos_right ha (zero_lt_iff_ne_zero.2 this) }, rcases lt_supr_iff.1 this with ⟨i, hi⟩, exact mem_Union.2 ⟨i, le_of_lt hi⟩ }, have mono : ∀r:ennreal, monotone (λn, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}), { assume r i j h, refine inter_subset_inter (subset.refl _) _, assume x hx, exact le_trans hx (h_mono h x) }, have h_meas : ∀n, is_measurable {a : α | ⇑(map c rs) a ≤ f n a} := assume n, is_measurable_le (simple_func.measurable _) (hf n), calc (r:ennreal) * (s.map c).lintegral μ = ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r}) : by rw [← const_mul_lintegral, eq_rs, simple_func.lintegral] ... ≤ ∑ r in (rs.map c).range, r * μ (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) : le_of_eq (finset.sum_congr rfl $ assume x hx, by rw ← eq) ... ≤ ∑ r in (rs.map c).range, (⨆n, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : le_of_eq (finset.sum_congr rfl $ assume x hx, begin rw [measure_Union_eq_supr _ (directed_of_sup $ mono x), ennreal.mul_supr], { assume i, refine ((rs.map c).is_measurable_preimage _).inter _, exact hf i is_measurable_Ici } end) ... ≤ ⨆n, ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) : begin refine le_of_eq _, rw [ennreal.finset_sum_supr_nat], assume p i j h, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (measure_mono $ mono p h) end ... ≤ (⨆n:ℕ, ((rs.map c).restrict {a | (rs.map c) a ≤ f n a}).lintegral μ) : begin refine supr_le_supr (assume n, _), rw [restrict_lintegral _ (h_meas n)], { refine le_of_eq (finset.sum_congr rfl $ assume r hr, _), congr' 2 with a, refine and_congr_right _, simp {contextual := tt} } end ... ≤ (⨆n, ∫⁻ a, f n a ∂μ) : begin refine supr_le_supr (assume n, _), rw [← simple_func.lintegral_eq_lintegral], refine lintegral_mono (assume a, _), dsimp, rw [restrict_apply], split_ifs; simp, simpa using h, exact h_meas n end end lemma lintegral_eq_supr_eapprox_lintegral {f : α → ennreal} (hf : measurable f) : (∫⁻ a, f a ∂μ) = (⨆n, (eapprox f n).lintegral μ) := calc (∫⁻ a, f a ∂μ) = (∫⁻ a, ⨆n, (eapprox f n : α → ennreal) a ∂μ) : by congr; ext a; rw [supr_eapprox_apply f hf] ... = (⨆n, ∫⁻ a, (eapprox f n : α → ennreal) a ∂μ) : begin rw [lintegral_supr], { assume n, exact (eapprox f n).measurable }, { assume i j h, exact (monotone_eapprox f h) } end ... = (⨆n, (eapprox f n).lintegral μ) : by congr; ext n; rw [(eapprox f n).lintegral_eq_lintegral] @[simp] lemma lintegral_add {f g : α → ennreal} (hf : measurable f) (hg : measurable g) : (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) := calc (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, (⨆n, (eapprox f n : α → ennreal) a) + (⨆n, (eapprox g n : α → ennreal) a) ∂μ) : by congr; funext a; rw [supr_eapprox_apply f hf, supr_eapprox_apply g hg] ... = (∫⁻ a, (⨆n, (eapprox f n + eapprox g n : α → ennreal) a) ∂μ) : begin congr, funext a, rw [ennreal.supr_add_supr_of_monotone], { refl }, { assume i j h, exact monotone_eapprox _ h a }, { assume i j h, exact monotone_eapprox _ h a }, end ... = (⨆n, (eapprox f n).lintegral μ + (eapprox g n).lintegral μ) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.add_lintegral, ← simple_func.lintegral_eq_lintegral], refl }, { assume n, exact measurable.add (eapprox f n).measurable (eapprox g n).measurable }, { assume i j h a, exact add_le_add (monotone_eapprox _ h _) (monotone_eapprox _ h _) } end ... = (⨆n, (eapprox f n).lintegral μ) + (⨆n, (eapprox g n).lintegral μ) : by refine (ennreal.supr_add_supr_of_monotone _ _).symm; { assume i j h, exact simple_func.lintegral_mono (monotone_eapprox _ h) (le_refl μ) } ... = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) : by rw [lintegral_eq_supr_eapprox_lintegral hf, lintegral_eq_supr_eapprox_lintegral hg] lemma lintegral_zero : (∫⁻ a:α, 0 ∂μ) = 0 := by simp lemma lintegral_zero_fun : (∫⁻ a:α, (0 : α → ennreal) a ∂μ) = 0 := by simp @[simp] lemma lintegral_smul_measure (c : ennreal) (f : α → ennreal) : ∫⁻ a, f a ∂ (c • μ) = c * ∫⁻ a, f a ∂μ := by simp only [lintegral, supr_subtype', simple_func.lintegral_smul, ennreal.mul_supr, smul_eq_mul] @[simp] lemma lintegral_sum_measure {ι} (f : α → ennreal) (μ : ι → measure α) : ∫⁻ a, f a ∂(measure.sum μ) = ∑' i, ∫⁻ a, f a ∂(μ i) := begin simp only [lintegral, supr_subtype', simple_func.lintegral_sum, ennreal.tsum_eq_supr_sum], rw [supr_comm], congr, funext s, induction s using finset.induction_on with i s hi hs, { apply bot_unique, simp }, simp only [finset.sum_insert hi, ← hs], refine (ennreal.supr_add_supr _).symm, intros φ ψ, exact ⟨⟨φ ⊔ ψ, λ x, sup_le (φ.2 x) (ψ.2 x)⟩, add_le_add (simple_func.lintegral_mono le_sup_left (le_refl _)) (finset.sum_le_sum $ λ j hj, simple_func.lintegral_mono le_sup_right (le_refl _))⟩ end @[simp] lemma lintegral_add_measure (f : α → ennreal) (μ ν : measure α) : ∫⁻ a, f a ∂ (μ + ν) = ∫⁻ a, f a ∂μ + ∫⁻ a, f a ∂ν := by simpa [tsum_fintype] using lintegral_sum_measure f (λ b, cond b μ ν) @[simp] lemma lintegral_zero_measure (f : α → ennreal) : ∫⁻ a, f a ∂0 = 0 := bot_unique $ by simp [lintegral] lemma lintegral_finset_sum (s : finset β) {f : β → α → ennreal} (hf : ∀b, measurable (f b)) : (∫⁻ a, ∑ b in s, f b a ∂μ) = ∑ b in s, ∫⁻ a, f b a ∂μ := begin refine finset.induction_on s _ _, { simp }, { assume a s has ih, simp only [finset.sum_insert has], rw [lintegral_add (hf _) (s.measurable_sum hf), ih] } end @[simp] lemma lintegral_const_mul (r : ennreal) {f : α → ennreal} (hf : measurable f) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := calc (∫⁻ a, r * f a ∂μ) = (∫⁻ a, (⨆n, (const α r * eapprox f n) a) ∂μ) : by { congr, funext a, rw [← supr_eapprox_apply f hf, ennreal.mul_supr], refl } ... = (⨆n, r * (eapprox f n).lintegral μ) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.const_mul_lintegral, ← simple_func.lintegral_eq_lintegral] }, { assume n, exact simple_func.measurable _ }, { assume i j h a, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (monotone_eapprox _ h _) } end ... = r * (∫⁻ a, f a ∂μ) : by rw [← ennreal.mul_supr, lintegral_eq_supr_eapprox_lintegral hf] lemma lintegral_const_mul_le (r : ennreal) (f : α → ennreal) : r * (∫⁻ a, f a ∂μ) ≤ (∫⁻ a, r * f a ∂μ) := begin rw [lintegral, ennreal.mul_supr], refine supr_le (λs, _), rw [ennreal.mul_supr], simp only [supr_le_iff, ge_iff_le], assume hs, rw ← simple_func.const_mul_lintegral, refine le_supr_of_le (const α r * s) (le_supr_of_le (λx, _) (le_refl _)), exact canonically_ordered_semiring.mul_le_mul (le_refl _) (hs x) end lemma lintegral_const_mul' (r : ennreal) (f : α → ennreal) (hr : r ≠ ⊤) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := begin by_cases h : r = 0, { simp [h] }, apply le_antisymm _ (lintegral_const_mul_le r f), have rinv : r * r⁻¹ = 1 := ennreal.mul_inv_cancel h hr, have rinv' : r ⁻¹ * r = 1, by { rw mul_comm, exact rinv }, have := lintegral_const_mul_le (r⁻¹) (λx, r * f x), simp [(mul_assoc _ _ _).symm, rinv'] at this, simpa [(mul_assoc _ _ _).symm, rinv] using canonically_ordered_semiring.mul_le_mul (le_refl r) this end lemma lintegral_mul_const (r : ennreal) {f : α → ennreal} (hf : measurable f) : ∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r := by simp_rw [mul_comm, lintegral_const_mul r hf] lemma lintegral_mul_const_le (r : ennreal) (f : α → ennreal) : ∫⁻ a, f a ∂μ * r ≤ ∫⁻ a, f a * r ∂μ := by simp_rw [mul_comm, lintegral_const_mul_le r f] lemma lintegral_mul_const' (r : ennreal) (f : α → ennreal) (hr : r ≠ ⊤): ∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r := by simp_rw [mul_comm, lintegral_const_mul' r f hr] lemma lintegral_mono_ae {f g : α → ennreal} (h : ∀ᵐ a ∂μ, f a ≤ g a) : (∫⁻ a, f a ∂μ) ≤ (∫⁻ a, g a ∂μ) := begin rcases exists_is_measurable_superset_of_measure_eq_zero h with ⟨t, hts, ht, ht0⟩, have : ∀ᵐ x ∂μ, x ∉ t := measure_zero_iff_ae_nmem.1 ht0, refine (supr_le $ assume s, supr_le $ assume hfs, le_supr_of_le (s.restrict tᶜ) $ le_supr_of_le _ _), { assume a, by_cases a ∈ t; simp [h, restrict_apply, ht.compl], exact le_trans (hfs a) (by_contradiction $ assume hnfg, h (hts hnfg)) }, { refine le_of_eq (simple_func.lintegral_congr $ this.mono $ λ a hnt, _), by_cases hat : a ∈ t; simp [hat, ht.compl], exact (hnt hat).elim } end lemma lintegral_congr_ae {f g : α → ennreal} (h : f =ᵐ[μ] g) : (∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) := le_antisymm (lintegral_mono_ae $ h.le) (lintegral_mono_ae $ h.symm.le) lemma lintegral_congr {f g : α → ennreal} (h : ∀ a, f a = g a) : (∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) := by simp only [h] lemma set_lintegral_congr {f : α → ennreal} {s t : set α} (h : s =ᵐ[μ] t) : ∫⁻ x in s, f x ∂μ = ∫⁻ x in t, f x ∂μ := by rw [restrict_congr_set h] -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₁ {f f' : α → β} (h : f =ᵐ[μ] f') (g : β → ennreal) : (∫⁻ a, g (f a) ∂μ) = (∫⁻ a, g (f' a) ∂μ) := lintegral_congr_ae $ h.mono $ λ a h, by rw h -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₂ {f₁ f₁' : α → β} {f₂ f₂' : α → γ} (h₁ : f₁ =ᵐ[μ] f₁') (h₂ : f₂ =ᵐ[μ] f₂') (g : β → γ → ennreal) : (∫⁻ a, g (f₁ a) (f₂ a) ∂μ) = (∫⁻ a, g (f₁' a) (f₂' a) ∂μ) := lintegral_congr_ae $ h₁.mp $ h₂.mono $ λ _ h₂ h₁, by rw [h₁, h₂] @[simp] lemma lintegral_indicator (f : α → ennreal) {s : set α} (hs : is_measurable s) : ∫⁻ a, s.indicator f a ∂μ = ∫⁻ a in s, f a ∂μ := begin simp only [lintegral, ← restrict_lintegral_eq_lintegral_restrict _ hs, supr_subtype'], apply le_antisymm; refine supr_le_supr2 (subtype.forall.2 $ λ φ hφ, _), { refine ⟨⟨φ, le_trans hφ (indicator_le_self _ _)⟩, _⟩, refine simple_func.lintegral_mono (λ x, _) (le_refl _), by_cases hx : x ∈ s, { simp [hx, hs, le_refl] }, { apply le_trans (hφ x), simp [hx, hs, le_refl] } }, { refine ⟨⟨φ.restrict s, λ x, _⟩, le_refl _⟩, simp [hφ x, hs, indicator_le_indicator] } end /-- Chebyshev's inequality -/ lemma mul_meas_ge_le_lintegral {f : α → ennreal} (hf : measurable f) (ε : ennreal) : ε * μ {x | ε ≤ f x} ≤ ∫⁻ a, f a ∂μ := begin have : is_measurable {a : α | ε ≤ f a }, from hf is_measurable_Ici, rw [← simple_func.restrict_const_lintegral _ this, ← simple_func.lintegral_eq_lintegral], refine lintegral_mono (λ a, _), simp only [restrict_apply _ this], split_ifs; [assumption, exact zero_le _] end lemma meas_ge_le_lintegral_div {f : α → ennreal} (hf : measurable f) {ε : ennreal} (hε : ε ≠ 0) (hε' : ε ≠ ⊤) : μ {x | ε ≤ f x} ≤ (∫⁻ a, f a ∂μ) / ε := (ennreal.le_div_iff_mul_le (or.inl hε) (or.inl hε')).2 $ by { rw [mul_comm], exact mul_meas_ge_le_lintegral hf ε } @[simp] lemma lintegral_eq_zero_iff {f : α → ennreal} (hf : measurable f) : ∫⁻ a, f a ∂μ = 0 ↔ (f =ᵐ[μ] 0) := begin refine iff.intro (assume h, _) (assume h, _), { have : ∀n:ℕ, ∀ᵐ a ∂μ, f a < n⁻¹, { assume n, rw [ae_iff, ← le_zero_iff_eq, ← @ennreal.zero_div n⁻¹, ennreal.le_div_iff_mul_le, mul_comm], simp only [not_lt], -- TODO: why `rw ← h` fails with "not an equality or an iff"? exacts [h ▸ mul_meas_ge_le_lintegral hf n⁻¹, or.inl (ennreal.inv_ne_zero.2 ennreal.coe_nat_ne_top), or.inr ennreal.zero_ne_top] }, refine (ae_all_iff.2 this).mono (λ a ha, _), by_contradiction h, rcases ennreal.exists_inv_nat_lt h with ⟨n, hn⟩, exact (lt_irrefl _ $ lt_trans hn $ ha n).elim }, { calc ∫⁻ a, f a ∂μ = ∫⁻ a, 0 ∂μ : lintegral_congr_ae h ... = 0 : lintegral_zero } end lemma lintegral_pos_iff_support {f : α → ennreal} (hf : measurable f) : 0 < ∫⁻ a, f a ∂μ ↔ 0 < μ (function.support f) := by simp [zero_lt_iff_ne_zero, hf, filter.eventually_eq, ae_iff, function.support] /-- Weaker version of the monotone convergence theorem-/ lemma lintegral_supr_ae {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f n.succ a) : (∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) := let ⟨s, hs⟩ := exists_is_measurable_superset_of_measure_eq_zero (ae_iff.1 (ae_all_iff.2 h_mono)) in let g := λ n a, if a ∈ s then 0 else f n a in have g_eq_f : ∀ᵐ a ∂μ, ∀n, g n a = f n a, from (measure_zero_iff_ae_nmem.1 hs.2.2).mono (assume a ha n, if_neg ha), calc ∫⁻ a, ⨆n, f n a ∂μ = ∫⁻ a, ⨆n, g n a ∂μ : lintegral_congr_ae $ g_eq_f.mono $ λ a ha, by simp only [ha] ... = ⨆n, (∫⁻ a, g n a ∂μ) : lintegral_supr (assume n, measurable_const.piecewise hs.2.1 (hf n)) (monotone_of_monotone_nat $ assume n a, classical.by_cases (assume h : a ∈ s, by simp [g, if_pos h]) (assume h : a ∉ s, begin simp only [g, if_neg h], have := hs.1, rw subset_def at this, have := mt (this a) h, simp only [not_not, mem_set_of_eq] at this, exact this n end)) ... = ⨆n, (∫⁻ a, f n a ∂μ) : by simp only [lintegral_congr_ae (g_eq_f.mono $ λ a ha, ha _)] lemma lintegral_sub {f g : α → ennreal} (hf : measurable f) (hg : measurable g) (hg_fin : ∫⁻ a, g a ∂μ < ⊤) (h_le : g ≤ᵐ[μ] f) : ∫⁻ a, f a - g a ∂μ = ∫⁻ a, f a ∂μ - ∫⁻ a, g a ∂μ := begin rw [← ennreal.add_left_inj hg_fin, ennreal.sub_add_cancel_of_le (lintegral_mono_ae h_le), ← lintegral_add (hf.ennreal_sub hg) hg], refine lintegral_congr_ae (h_le.mono $ λ x hx, _), exact ennreal.sub_add_cancel_of_le hx end /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi_ae {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) (h_mono : ∀n:ℕ, f n.succ ≤ᵐ[μ] f n) (h_fin : ∫⁻ a, f 0 a ∂μ < ⊤) : ∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ := have fn_le_f0 : ∫⁻ a, ⨅n, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ, from lintegral_mono (assume a, infi_le_of_le 0 (le_refl _)), have fn_le_f0' : (⨅n, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, f 0 a ∂μ, from infi_le_of_le 0 (le_refl _), (ennreal.sub_right_inj h_fin fn_le_f0 fn_le_f0').1 $ show ∫⁻ a, f 0 a ∂μ - ∫⁻ a, ⨅n, f n a ∂μ = ∫⁻ a, f 0 a ∂μ - (⨅n, ∫⁻ a, f n a ∂μ), from calc ∫⁻ a, f 0 a ∂μ - (∫⁻ a, ⨅n, f n a ∂μ) = ∫⁻ a, f 0 a - ⨅n, f n a ∂μ: (lintegral_sub (h_meas 0) (measurable_infi h_meas) (calc (∫⁻ a, ⨅n, f n a ∂μ) ≤ ∫⁻ a, f 0 a ∂μ : lintegral_mono (assume a, infi_le _ _) ... < ⊤ : h_fin ) (ae_of_all _ $ assume a, infi_le _ _)).symm ... = ∫⁻ a, ⨆n, f 0 a - f n a ∂μ : congr rfl (funext (assume a, ennreal.sub_infi)) ... = ⨆n, ∫⁻ a, f 0 a - f n a ∂μ : lintegral_supr_ae (assume n, (h_meas 0).ennreal_sub (h_meas n)) (assume n, (h_mono n).mono $ assume a ha, ennreal.sub_le_sub (le_refl _) ha) ... = ⨆n, ∫⁻ a, f 0 a ∂μ - ∫⁻ a, f n a ∂μ : have h_mono : ∀ᵐ a ∂μ, ∀n:ℕ, f n.succ a ≤ f n a := ae_all_iff.2 h_mono, have h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f 0 a := assume n, h_mono.mono $ assume a h, begin induction n with n ih, {exact le_refl _}, {exact le_trans (h n) ih} end, congr rfl (funext $ assume n, lintegral_sub (h_meas _) (h_meas _) (calc ∫⁻ a, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ : lintegral_mono_ae $ h_mono n ... < ⊤ : h_fin) (h_mono n)) ... = ∫⁻ a, f 0 a ∂μ - ⨅n, ∫⁻ a, f n a ∂μ : ennreal.sub_infi.symm /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) (h_mono : ∀ ⦃m n⦄, m ≤ n → f n ≤ f m) (h_fin : ∫⁻ a, f 0 a ∂μ < ⊤) : ∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ := lintegral_infi_ae h_meas (λ n, ae_of_all _ $ h_mono $ le_of_lt n.lt_succ_self) h_fin /-- Known as Fatou's lemma -/ lemma lintegral_liminf_le {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) : ∫⁻ a, liminf at_top (λ n, f n a) ∂μ ≤ liminf at_top (λ n, ∫⁻ a, f n a ∂μ) := calc ∫⁻ a, liminf at_top (λ n, f n a) ∂μ = ∫⁻ a, ⨆n:ℕ, ⨅i≥n, f i a ∂μ : by simp only [liminf_eq_supr_infi_of_nat] ... = ⨆n:ℕ, ∫⁻ a, ⨅i≥n, f i a ∂μ : lintegral_supr (assume n, measurable_binfi _ (countable_encodable _) h_meas) (assume n m hnm a, infi_le_infi_of_subset $ λ i hi, le_trans hnm hi) ... ≤ ⨆n:ℕ, ⨅i≥n, ∫⁻ a, f i a ∂μ : supr_le_supr $ λ n, le_infi2_lintegral _ ... = liminf at_top (λ n, ∫⁻ a, f n a ∂μ) : liminf_eq_supr_infi_of_nat.symm lemma limsup_lintegral_le {f : ℕ → α → ennreal} {g : α → ennreal} (hf_meas : ∀ n, measurable (f n)) (h_bound : ∀n, f n ≤ᵐ[μ] g) (h_fin : ∫⁻ a, g a ∂μ < ⊤) : limsup at_top (λn, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, f n a) ∂μ := calc limsup at_top (λn, ∫⁻ a, f n a ∂μ) = ⨅n:ℕ, ⨆i≥n, ∫⁻ a, f i a ∂μ : limsup_eq_infi_supr_of_nat ... ≤ ⨅n:ℕ, ∫⁻ a, ⨆i≥n, f i a ∂μ : infi_le_infi $ assume n, supr2_lintegral_le _ ... = ∫⁻ a, ⨅n:ℕ, ⨆i≥n, f i a ∂μ : begin refine (lintegral_infi _ _ _).symm, { assume n, exact measurable_bsupr _ (countable_encodable _) hf_meas }, { assume n m hnm a, exact (supr_le_supr_of_subset $ λ i hi, le_trans hnm hi) }, { refine lt_of_le_of_lt (lintegral_mono_ae _) h_fin, refine (ae_all_iff.2 h_bound).mono (λ n hn, _), exact supr_le (λ i, supr_le $ λ hi, hn i) } end ... = ∫⁻ a, limsup at_top (λn, f n a) ∂μ : by simp only [limsup_eq_infi_supr_of_nat] /-- Dominated convergence theorem for nonnegative functions -/ lemma tendsto_lintegral_of_dominated_convergence {F : ℕ → α → ennreal} {f : α → ennreal} (bound : α → ennreal) (hF_meas : ∀n, measurable (F n)) (h_bound : ∀n, F n ≤ᵐ[μ] bound) (h_fin : ∫⁻ a, bound a ∂μ < ⊤) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) at_top (𝓝 (∫⁻ a, f a ∂μ)) := tendsto_of_le_liminf_of_limsup_le (calc ∫⁻ a, f a ∂μ = ∫⁻ a, liminf at_top (λ (n : ℕ), F n a) ∂μ : lintegral_congr_ae $ h_lim.mono $ assume a h, h.liminf_eq.symm ... ≤ liminf at_top (λ n, ∫⁻ a, F n a ∂μ) : lintegral_liminf_le hF_meas) (calc limsup at_top (λ (n : ℕ), ∫⁻ a, F n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, F n a) ∂μ : limsup_lintegral_le hF_meas h_bound h_fin ... = ∫⁻ a, f a ∂μ : lintegral_congr_ae $ h_lim.mono $ λ a h, h.limsup_eq) /-- Dominated convergence theorem for filters with a countable basis -/ lemma tendsto_lintegral_filter_of_dominated_convergence {ι} {l : filter ι} {F : ι → α → ennreal} {f : α → ennreal} (bound : α → ennreal) (hl_cb : l.is_countably_generated) (hF_meas : ∀ᶠ n in l, measurable (F n)) (h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, F n a ≤ bound a) (h_fin : ∫⁻ a, bound a ∂μ < ⊤) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) l (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) l (𝓝 $ ∫⁻ a, f a ∂μ) := begin rw hl_cb.tendsto_iff_seq_tendsto, { intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem_sets hF_meas h_bound, replace h := hxl _ h, rcases h with ⟨k, h⟩, rw ← tendsto_add_at_top_iff_nat k, refine tendsto_lintegral_of_dominated_convergence _ _ _ _ _, { exact bound }, { intro, refine (h _ _).1, exact nat.le_add_left _ _ }, { intro, refine (h _ _).2, exact nat.le_add_left _ _ }, { assumption }, { refine h_lim.mono (λ a h_lim, _), apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a), { assumption }, rw tendsto_add_at_top_iff_nat, assumption } }, end section open encodable /-- Monotone convergence for a suprema over a directed family and indexed by an encodable type -/ theorem lintegral_supr_directed [encodable β] {f : β → α → ennreal} (hf : ∀b, measurable (f b)) (h_directed : directed (≤) f) : ∫⁻ a, ⨆b, f b a ∂μ = ⨆b, ∫⁻ a, f b a ∂μ := begin by_cases hβ : nonempty β, swap, { simp [supr_of_empty hβ] }, resetI, inhabit β, have : ∀a, (⨆ b, f b a) = (⨆ n, f (h_directed.sequence f n) a), { assume a, refine le_antisymm (supr_le $ assume b, _) (supr_le $ assume n, le_supr (λn, f n a) _), exact le_supr_of_le (encode b + 1) (h_directed.le_sequence b a) }, calc ∫⁻ a, ⨆ b, f b a ∂μ = ∫⁻ a, ⨆ n, f (h_directed.sequence f n) a ∂μ : by simp only [this] ... = ⨆ n, ∫⁻ a, f (h_directed.sequence f n) a ∂μ : lintegral_supr (assume n, hf _) h_directed.sequence_mono ... = ⨆ b, ∫⁻ a, f b a ∂μ : begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume b, _), { exact le_supr (λb, ∫⁻ a, f b a ∂μ) _ }, { exact le_supr_of_le (encode b + 1) (lintegral_mono $ h_directed.le_sequence b) } end end end lemma lintegral_tsum [encodable β] {f : β → α → ennreal} (hf : ∀i, measurable (f i)) : ∫⁻ a, ∑' i, f i a ∂μ = ∑' i, ∫⁻ a, f i a ∂μ := begin simp only [ennreal.tsum_eq_supr_sum], rw [lintegral_supr_directed], { simp [lintegral_finset_sum _ hf] }, { assume b, exact finset.measurable_sum _ hf }, { assume s t, use [s ∪ t], split, exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_left _ _), exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_right _ _) } end open measure lemma lintegral_Union [encodable β] {s : β → set α} (hm : ∀ i, is_measurable (s i)) (hd : pairwise (disjoint on s)) (f : α → ennreal) : ∫⁻ a in ⋃ i, s i, f a ∂μ = ∑' i, ∫⁻ a in s i, f a ∂μ := by simp only [measure.restrict_Union hd hm, lintegral_sum_measure] lemma lintegral_Union_le [encodable β] (s : β → set α) (f : α → ennreal) : ∫⁻ a in ⋃ i, s i, f a ∂μ ≤ ∑' i, ∫⁻ a in s i, f a ∂μ := begin rw [← lintegral_sum_measure], exact lintegral_mono' restrict_Union_le (le_refl _) end lemma lintegral_map [measurable_space β] {f : β → ennreal} {g : α → β} (hf : measurable f) (hg : measurable g) : ∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ := begin simp only [lintegral_eq_supr_eapprox_lintegral, hf, hf.comp hg], { congr, funext n, symmetry, apply simple_func.lintegral_map, { assume a, exact congr_fun (simple_func.eapprox_comp hf hg) a }, { assume s hs, exact map_apply hg hs } }, end lemma lintegral_comp [measurable_space β] {f : β → ennreal} {g : α → β} (hf : measurable f) (hg : measurable g) : lintegral μ (f ∘ g) = ∫⁻ a, f a ∂(map g μ) := (lintegral_map hf hg).symm lemma set_lintegral_map [measurable_space β] {f : β → ennreal} {g : α → β} {s : set β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) : ∫⁻ y in s, f y ∂(map g μ) = ∫⁻ x in g ⁻¹' s, f (g x) ∂μ := by rw [restrict_map hg hs, lintegral_map hf hg] lemma lintegral_dirac (a : α) {f : α → ennreal} (hf : measurable f) : ∫⁻ a, f a ∂(dirac a) = f a := by simp [lintegral_congr_ae (eventually_eq_dirac hf)] lemma ae_lt_top {f : α → ennreal} (hf : measurable f) (h2f : ∫⁻ x, f x ∂μ < ⊤) : ∀ᵐ x ∂μ, f x < ⊤ := begin simp_rw [ae_iff, ennreal.not_lt_top], by_contra h, rw [← not_le] at h2f, apply h2f, have : (f ⁻¹' {⊤}).indicator ⊤ ≤ f, { intro x, by_cases hx : x ∈ f ⁻¹' {⊤}; [simpa [hx], simp [hx]] }, convert lintegral_mono this, rw [lintegral_indicator _ (hf (is_measurable_singleton ⊤))], simp [ennreal.top_mul, preimage, h] end /-- Given a measure `μ : measure α` and a function `f : α → ennreal`, `μ.with_density f` is the measure such that for a measurable set `s` we have `μ.with_density f s = ∫⁻ a in s, f a ∂μ`. -/ def measure.with_density (μ : measure α) (f : α → ennreal) : measure α := measure.of_measurable (λs hs, ∫⁻ a in s, f a ∂μ) (by simp) (λ s hs hd, lintegral_Union hs hd _) @[simp] lemma with_density_apply (f : α → ennreal) {s : set α} (hs : is_measurable s) : μ.with_density f s = ∫⁻ a in s, f a ∂μ := measure.of_measurable_apply s hs end lintegral end measure_theory open measure_theory measure_theory.simple_func /-- To prove something for an arbitrary measurable function into `ennreal`, it suffices to show that the property holds for (multiples of) characteristic functions and is closed under addition and supremum of increasing sequences of functions. It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions can be added once we need them (for example in `h_sum` it is only necessary to consider the sum of a simple function with a multiple of a characteristic function and that the intersection of their images is a subset of `{0}`. -/ @[elab_as_eliminator] theorem measurable.ennreal_induction {α} [measurable_space α] {P : (α → ennreal) → Prop} (h_ind : ∀ (c : ennreal) ⦃s⦄, is_measurable s → P (indicator s (λ _, c))) (h_sum : ∀ ⦃f g : α → ennreal⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → measurable f → measurable g → P f → P g → P (f + g)) (h_supr : ∀ ⦃f : ℕ → α → ennreal⦄ (hf : ∀n, measurable (f n)) (h_mono : monotone f) (hP : ∀ n, P (f n)), P (λ x, ⨆ n, f n x)) ⦃f : α → ennreal⦄ (hf : measurable f) : P f := begin convert h_supr (λ n, (eapprox f n).measurable) (monotone_eapprox f) _, { ext1 x, rw [supr_eapprox_apply f hf] }, { exact λ n, simple_func.induction (λ c s hs, h_ind c hs) (λ f g hfg hf hg, h_sum hfg f.measurable g.measurable hf hg) (eapprox f n) } end namespace measure_theory /-- This is Exercise 1.2.1 from [tao2010]. It allows you to express integration of a measurable function with respect to `(μ.with_density f)` as an integral with respect to `μ`, called the base measure. `μ` is often the Lebesgue measure, and in this circumstance `f` is the probability density function, and `(μ.with_density f)` represents any continuous random variable as a probability measure, such as the uniform distribution between 0 and 1, the Gaussian distribution, the exponential distribution, the Beta distribution, or the Cauchy distribution (see Section 2.4 of [wasserman2004]). Thus, this method shows how to one can calculate expectations, variances, and other moments as a function of the probability density function. -/ lemma lintegral_with_density_eq_lintegral_mul {α} [measurable_space α] (μ : measure α) {f : α → ennreal} (h_mf : measurable f) : ∀ {g : α → ennreal}, measurable g → ∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ := begin apply measurable.ennreal_induction, { intros c s h_ms, simp [*, mul_comm _ c] }, { intros g h h_univ h_mea_g h_mea_h h_ind_g h_ind_h, simp [mul_add, *, measurable.ennreal_mul] }, { intros g h_mea_g h_mono_g h_ind, have : monotone (λ n a, f a * g n a) := λ m n hmn x, ennreal.mul_le_mul le_rfl (h_mono_g hmn x), simp [lintegral_supr, ennreal.mul_supr, h_mf.ennreal_mul (h_mea_g _), *] } end end measure_theory
765310869439ae2f81ce94f3609e167159208197
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/topology/metric_space/emetric_space.lean
c8e126652ed16d4bfe70bd8f7042dc3e863466f0
[ "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
40,288
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import data.real.nnreal data.real.ennreal import topology.uniform_space.separation topology.uniform_space.uniform_embedding import topology.uniform_space.pi topology.bases topology.uniform_space.uniform_convergence /-! # Extended metric spaces This file is devoted to the definition and study of `emetric_spaces`, i.e., metric spaces in which the distance is allowed to take the value ∞. This extended distance is called `edist`, and takes values in `ennreal`. Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity The class `emetric_space` therefore extends `uniform_space` (and `topological_space`). -/ open set filter classical noncomputable theory open_locale uniformity topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Characterizing uniformities associated to a (generalized) distance function `D` in terms of the elements of the uniformity. -/ theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>z, principal {p:α×α | D p.1 p.2 < ε} := le_antisymm (le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩) (λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in mem_infi_sets ε $ mem_infi_sets ε0 $ mem_principal_sets.2 $ λ ⟨a, b⟩, h) class has_edist (α : Type*) := (edist : α → α → ennreal) export has_edist (edist) /- Design note: one could define an `emetric_space` just by giving `edist`, and then derive an instance of `uniform_space` by taking the natural uniform structure associated to the distance. This creates diamonds problem for products, as the uniform structure on the product of two emetric spaces could be obtained first by obtaining two uniform spaces and then taking their products, or by taking the product of the emetric spaces and then the associated uniform structure. The two uniform structure we have just described are equal, but not defeq, which creates a lot of problem. The idea is to add, in the very definition of an `emetric_space`, a uniform structure with a uniformity which equal to the one given by the distance, but maybe not defeq. And the instance from `emetric_space` to `uniform_space` uses this uniformity. In this way, when we create the product of emetric spaces, we put in the product the uniformity corresponding to the product of the uniformities. There is one more proof obligation, that this product uniformity is equal to the uniformity corresponding to the product metric. But the diamond problem disappears. The same trick is used in the definition of a metric space, where one stores as well a uniform structure and an edistance. -/ /-- Creating a uniform space from an extended distance. -/ def uniform_space_of_edist (edist : α → α → ennreal) (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, have (2 : ennreal) = (2 : ℕ) := by simp, have A : 0 < ε / 2 := ennreal.div_pos_iff.2 ⟨ne_of_gt h, this ▸ ennreal.nat_ne_top 2⟩, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets A (subset.refl _)) $ have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε, from assume a b c hac hcb, calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _ ... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb ... = ε : by rw [ennreal.add_halves], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [edist_comm] } section prio set_option default_priority 100 -- see Note [default priority] /-- Extended metric spaces, with an extended distance `edist` possibly taking the value ∞ Each emetric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating an `emetric_space` structure, the uniformity fields are not necessary, they will be filled in by default. There is a default value for the uniformity, that can be substituted in cases of interest, for instance when instantiating an `emetric_space` structure on a product. Continuity of `edist` is finally proving in `topology.instances.ennreal` -/ class emetric_space (α : Type u) extends has_edist α : Type u := (edist_self : ∀ x : α, edist x x = 0) (eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) (to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle) (uniformity_edist : 𝓤 α = ⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε} . control_laws_tac) end prio /- emetric spaces are less common than metric spaces. Therefore, we work in a dedicated namespace, while notions associated to metric spaces are mostly in the root namespace. -/ variables [emetric_space α] @[priority 100] -- see Note [lower instance priority] instance emetric_space.to_uniform_space' : uniform_space α := emetric_space.to_uniform_space export emetric_space (edist_self eq_of_edist_eq_zero edist_comm edist_triangle) attribute [simp] edist_self /-- Characterize the equality of points by the vanishing of their extended distance -/ @[simp] theorem edist_eq_zero {x y : α} : edist x y = 0 ↔ x = y := iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _) @[simp] theorem zero_eq_edist {x y : α} : 0 = edist x y ↔ x = y := iff.intro (assume h, eq_of_edist_eq_zero (h.symm)) (assume : x = y, this ▸ (edist_self _).symm) theorem edist_le_zero {x y : α} : (edist x y ≤ 0) ↔ x = y := le_zero_iff_eq.trans edist_eq_zero /-- Triangle inequality for the extended distance -/ theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y := by rw edist_comm z; apply edist_triangle theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z := by rw edist_comm y; apply edist_triangle lemma edist_triangle4 (x y z t : α) : edist x t ≤ edist x y + edist y z + edist z t := calc edist x t ≤ edist x z + edist z t : edist_triangle x z t ... ≤ (edist x y + edist y z) + edist z t : add_le_add_right' (edist_triangle x y z) /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) : edist (f m) (f n) ≤ (finset.Ico m n).sum (λ i, edist (f i) (f (i + 1))) := begin revert n, refine nat.le_induction _ _, { simp only [finset.sum_empty, finset.Ico.self_eq_empty, edist_self], -- TODO: Why doesn't Lean close this goal automatically? `apply le_refl` fails too. exact le_refl (0:ennreal) }, { assume n hn hrec, calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _ ... ≤ (finset.Ico m n).sum _ + _ : add_le_add' hrec (le_refl _) ... = (finset.Ico m (n+1)).sum _ : by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) : edist (f 0) (f n) ≤ (finset.range n).sum (λ i, edist (f i) (f (i + 1))) := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_edist f (nat.zero_le n) /-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ennreal} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f m) (f n) ≤ (finset.Ico m n).sum d := le_trans (edist_le_Ico_sum_edist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2 /-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ennreal} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f 0) (f n) ≤ (finset.range n).sum d := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd) /-- Two points coincide if their distance is `< ε` for all positive ε -/ theorem eq_of_forall_edist_le {x y : α} (h : ∀ε, ε > 0 → edist x y ≤ ε) : x = y := eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h) /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist : 𝓤 α = ⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε} := emetric_space.uniformity_edist theorem uniformity_basis_edist : (𝓤 α).has_basis (λ ε : ennreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := (@uniformity_edist α _).symm ▸ has_basis_binfi_principal (λ r hr p hp, ⟨min r p, lt_min hr hp, λ x hx, lt_of_lt_of_le hx (min_le_left _ _), λ x hx, lt_of_lt_of_le hx (min_le_right _ _)⟩) ⟨1, ennreal.zero_lt_one⟩ /-- Characterization of the elements of the uniformity in terms of the extended distance -/ theorem mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := uniformity_basis_edist.mem_uniformity_iff /-- Given `f : β → ennreal`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist`, `uniformity_basis_edist'`, `uniformity_basis_edist_nnreal`, and `uniformity_basis_edist_inv_nat`. -/ protected theorem emetric.mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ennreal} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 < f x}) := begin refine λ s, uniformity_basis_edist.mem_iff.trans _, split, { rintros ⟨ε, ε₀, hε⟩, rcases hf ε ε₀ with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end /-- Given `f : β → ennreal`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist_le` and `uniformity_basis_edist_le'`. -/ protected theorem emetric.mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ennreal} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 ≤ f x}) := begin refine λ s, uniformity_basis_edist.mem_iff.trans _, split, { rintros ⟨ε, ε₀, hε⟩, rcases dense ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x hx, H (le_of_lt hx)⟩ } end theorem uniformity_basis_edist_le : (𝓤 α).has_basis (λ ε : ennreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_edist' (ε' : ennreal) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ennreal, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := dense hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_le' (ε' : ennreal) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ennreal, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := dense hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_nnreal : (𝓤 α).has_basis (λ ε : nnreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, ennreal.coe_pos.2) (λ ε ε₀, let ⟨δ, hδ⟩ := ennreal.lt_iff_exists_nnreal_btwn.1 ε₀ in ⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩) theorem uniformity_basis_edist_inv_nat : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < (↑n)⁻¹}) := emetric.mk_uniformity_basis (λ n _, ennreal.inv_pos.2 $ ennreal.nat_ne_top n) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_nat_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) /-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/ theorem edist_mem_uniformity {ε:ennreal} (ε0 : 0 < ε) : {p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩ namespace emetric theorem uniformity_has_countable_basis : has_countable_basis (𝓤 α) := has_countable_basis_of_seq _ _ uniformity_basis_edist_inv_nat.eq_infi /-- ε-δ characterization of uniform continuity on emetric spaces -/ theorem uniform_continuous_iff [emetric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_iff uniformity_basis_edist /-- ε-δ characterization of uniform embeddings on emetric spaces -/ theorem uniform_embedding_iff [emetric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [emetric_space β] {f : α → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ) := begin split, { assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : edist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : edist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end /-- ε-δ characterization of Cauchy sequences on emetric spaces -/ protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε := uniformity_basis_edist.cauchy_iff /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem complete_of_convergent_controlled_sequences (B : ℕ → ennreal) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := uniform_space.complete_of_convergent_controlled_sequences uniformity_has_countable_basis (λ n, {p:α×α | edist p.1 p.2 < B n}) (λ n, edist_mem_uniformity $ hB n) H /-- A sequentially complete emetric space is complete. -/ theorem complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := uniform_space.complete_of_cauchy_seq_tendsto uniformity_has_countable_basis /-- Expressing locally uniform convergence on a set using `edist`. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ nhds_within x s, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `edist`. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, edist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `edist`. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := by simp [← nhds_within_univ, ← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff] /-- Expressing uniform convergence using `edist`. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, edist (f x) (F n x) < ε := by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp } end emetric open emetric /-- An emetric space is separated -/ @[priority 100] -- see Note [lower instance priority] instance to_separated : separated α := separated_def.2 $ λ x y h, eq_of_forall_edist_le $ λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0)) /-- Auxiliary function to replace the uniformity on an emetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct an emetric space with a specified uniformity. -/ def emetric_space.replace_uniformity {α} [U : uniform_space α] (m : emetric_space α) (H : @uniformity _ U = @uniformity _ emetric_space.to_uniform_space) : emetric_space α := { edist := @edist _ m.to_has_edist, edist_self := edist_self, eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@emetric_space.uniformity_edist α _) } /-- The extended metric induced by an injective function taking values in an emetric space. -/ def emetric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : emetric_space β) : emetric_space α := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h), edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Emetric space instance on subsets of emetric spaces -/ instance {α : Type*} {p : α → Prop} [t : emetric_space α] : emetric_space (subtype p) := t.induced coe (λ x y, subtype.coe_ext.2) /-- The extended distance on a subset of an emetric space is the restriction of the original distance, by definition -/ theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist (x : α) y := rfl /-- The product of two emetric spaces, with the max distance, is an extended metric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.emetric_space_max [emetric_space β] : emetric_space (α × β) := { edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_self := λ x, by simp, eq_of_edist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, have A : x.fst = y.fst := edist_le_zero.1 h₁, have B : x.snd = y.snd := edist_le_zero.1 h₂, exact prod.ext_iff.2 ⟨A, B⟩ end, edist_comm := λ x y, by simp [edist_comm], edist_triangle := λ x y z, max_le (le_trans (edist_triangle _ _ _) (add_le_add' (le_max_left _ _) (le_max_left _ _))) (le_trans (edist_triangle _ _ _) (add_le_add' (le_max_right _ _) (le_max_right _ _))), uniformity_edist := begin refine uniformity_prod.trans _, simp [emetric_space.uniformity_edist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.edist_eq [emetric_space β] (x y : α × β) : edist x y = max (edist x.1 y.1) (edist x.2 y.2) := rfl section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of emetric spaces, with the max distance, is still an emetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) := { edist := λ f g, finset.sup univ (λb, edist (f b) (g b)), edist_self := assume f, bot_unique $ finset.sup_le $ by simp, edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _, edist_triangle := assume f g h, begin simp only [finset.sup_le_iff], assume b hb, exact le_trans (edist_triangle _ (g b) _) (add_le_add' (le_sup hb) (le_sup hb)) end, eq_of_edist_eq_zero := assume f g eq0, begin have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0, simp only [finset.sup_le_iff] at eq1, exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b), end, to_uniform_space := Pi.uniform_space _, uniformity_edist := begin simp only [Pi.uniformity, emetric_space.uniformity_edist, comap_infi, gt_iff_lt, preimage_set_of_eq, comap_principal], rw infi_comm, congr, funext ε, rw infi_comm, congr, funext εpos, change 0 < ε at εpos, simp [ext_iff, εpos] end } end pi namespace emetric variables {x y z : α} {ε ε₁ ε₂ : ennreal} {s : set α} /-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/ def ball (x : α) (ε : ennreal) : set α := {y | edist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw edist_comm; refl /-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/ def closed_ball (x : α) (ε : ennreal) := {y | edist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y, by simp; intros h; apply le_of_lt h theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := lt_of_le_of_lt (zero_le _) hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show edist x x < ε, by rw edist_self; assumption theorem mem_closed_ball_self : x ∈ closed_ball x ε := show edist x x ≤ ε, by rw edist_self; exact bot_le theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [edist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (edist_triangle_left x y z) (lt_of_lt_of_le (ennreal.add_lt_add h₁ h₂) h) theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y < ⊤) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, calc edist z y ≤ edist z x + edist x y : edist_triangle _ _ _ ... = edist x y + edist z x : add_comm _ _ ... < edist x y + ε₁ : (ennreal.add_lt_add_iff_left h').2 zx ... ≤ ε₂ : h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := begin have : 0 < ε - edist y x := by simpa using h, refine ⟨ε - edist y x, this, ball_subset _ _⟩, { rw ennreal.add_sub_cancel_of_le (le_of_lt h), apply le_refl _}, { have : edist y x ≠ ⊤ := ne_top_of_lt h, apply lt_top_iff_ne_top.2 this } end theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 := eq_empty_iff_forall_not_mem.trans ⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))), λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩ /-- Relation “two points are at a finite edistance” is an equivalence relation. -/ def edist_lt_top_setoid : setoid α := { r := λ x y, edist x y < ⊤, iseqv := ⟨λ x, by { rw edist_self, exact ennreal.coe_lt_top }, λ x y h, by rwa edist_comm, λ x y z hxy hyz, lt_of_le_of_lt (edist_triangle x y z) (ennreal.add_lt_top.2 ⟨hxy, hyz⟩)⟩ } @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [emetric.ball_eq_empty_iff] theorem nhds_basis_eball : (𝓝 x).has_basis (λ ε:ennreal, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_edist theorem nhds_eq : 𝓝 x = (⨅ε>0, principal (ball x ε)) := nhds_basis_eball.eq_binfi theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_eball s theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem is_closed_ball_top : is_closed (ball x ⊤) := is_open_iff.2 $ λ y hy, ⟨⊤, ennreal.coe_lt_top, subset_compl_iff_disjoint.2 $ ball_disjoint $ by { rw ennreal.top_add, exact le_of_not_lt hy }⟩ theorem ball_mem_nhds (x : α) {ε : ennreal} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := mem_nhds_sets is_open_ball (mem_ball_self ε0) /-- ε-characterization of the closure in emetric spaces -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem mem_closure_iff : x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε := (mem_closure_iff_nhds_basis nhds_basis_eball).trans $ by simp only [mem_ball, edist_comm x] theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, edist (u x) a < ε := nhds_basis_eball.tendsto_right_iff theorem tendsto_at_top [nonempty β] [semilattice_sup β] (u : β → α) {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_eball).trans $ by simp only [exists_prop, true_and, mem_Ici, mem_ball] /-- In an emetric space, Cauchy sequences are characterized by the fact that, eventually, the edistance between its elements is arbitrarily small -/ theorem cauchy_seq_iff [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u m) (u n) < ε := uniformity_basis_edist.cauchy_seq_iff /-- A variation around the emetric characterization of Cauchy sequences -/ theorem cauchy_seq_iff' [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>(0 : ennreal), ∃N, ∀n≥N, edist (u n) (u N) < ε := uniformity_basis_edist.cauchy_seq_iff' /-- A variation of the emetric characterization of Cauchy sequences that deals with `nnreal` upper bounds. -/ theorem cauchy_seq_iff_nnreal [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ ε : nnreal, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u n) (u N) < ε := uniformity_basis_edist_nnreal.cauchy_seq_iff' theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ theorem totally_bounded_iff' {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, _, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ section compact /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set -/ lemma countable_closure_of_compact {α : Type u} [emetric_space α] {s : set α} (hs : compact s) : ∃ t ⊆ s, (countable t ∧ s = closure t) := begin have A : ∀ (e:ennreal), e > 0 → ∃ t ⊆ s, (finite t ∧ s ⊆ (⋃x∈t, ball x e)) := totally_bounded_iff'.1 (compact_iff_totally_bounded_complete.1 hs).1, -- assume e, finite_cover_balls_of_compact hs, have B : ∀ (e:ennreal), ∃ t ⊆ s, finite t ∧ (e > 0 → s ⊆ (⋃x∈t, ball x e)), { intro e, cases le_or_gt e 0 with h, { exact ⟨∅, by finish⟩ }, { rcases A e h with ⟨s, ⟨finite_s, closure_s⟩⟩, existsi s, finish }}, /-The desired countable set is obtained by taking for each `n` the centers of a finite cover by balls of radius `1/n`, and then the union over `n`. -/ choose T T_in_s finite_T using B, let t := ⋃n:ℕ, T n⁻¹, have T₁ : t ⊆ s := begin apply Union_subset, assume n, apply T_in_s end, have T₂ : countable t := by finish [countable_Union, countable_finite], have T₃ : s ⊆ closure t, { intros x x_in_s, apply mem_closure_iff.2, intros ε εpos, rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 εpos) with ⟨n, hn⟩, have inv_n_pos : (0 : ennreal) < (n : ℕ)⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have C : x ∈ (⋃y∈ T (n : ℕ)⁻¹, ball y (n : ℕ)⁻¹) := mem_of_mem_of_subset x_in_s ((finite_T (n : ℕ)⁻¹).2 inv_n_pos), rcases mem_Union.1 C with ⟨y, _, ⟨y_in_T, rfl⟩, Dxy⟩, simp at Dxy, -- Dxy : edist x y < 1 / ↑n have : y ∈ t := mem_of_mem_of_subset y_in_T (by apply subset_Union (λ (n:ℕ), T (n : ℕ)⁻¹)), have : edist x y < ε := lt_trans Dxy hn, exact ⟨y, ‹y ∈ t›, ‹edist x y < ε›⟩ }, have T₄ : closure t ⊆ s := calc closure t ⊆ closure s : closure_mono T₁ ... = s : closure_eq_of_is_closed (closed_of_compact _ hs), exact ⟨t, ⟨T₁, T₂, subset.antisymm T₃ T₄⟩⟩ end end compact section first_countable @[priority 100] -- see Note [lower instance priority] instance (α : Type u) [emetric_space α] : topological_space.first_countable_topology α := uniform_space.first_countable_topology uniformity_has_countable_basis end first_countable section second_countable open topological_space /-- A separable emetric space is second countable: one obtains a countable basis by taking the balls centered at points in a dense subset, and with rational radii. We do not register this as an instance, as there is already an instance going in the other direction from second countable spaces to separable spaces, and we want to avoid loops. -/ lemma second_countable_of_separable (α : Type u) [emetric_space α] [separable_space α] : second_countable_topology α := let ⟨S, ⟨S_countable, S_dense⟩⟩ := separable_space.exists_countable_closure_eq_univ in ⟨⟨⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, ⟨show countable ⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, { apply countable_bUnion S_countable, intros a aS, apply countable_Union, simp }, show uniform_space.to_topological_space = generate_from (⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}), { have A : ∀ (u : set α), (u ∈ ⋃x ∈ S, ⋃ (n : nat), ({ball x ((n : ennreal)⁻¹)} : set (set α))) → is_open u, { simp only [and_imp, exists_prop, set.mem_Union, set.mem_singleton_iff, exists_imp_distrib], intros u x hx i u_ball, rw [u_ball], exact is_open_ball }, have B : is_topological_basis (⋃x ∈ S, ⋃ (n : nat), ({ball x (n⁻¹)} : set (set α))), { refine is_topological_basis_of_open_of_nhds A (λa u au open_u, _), rcases is_open_iff.1 open_u a au with ⟨ε, εpos, εball⟩, have : ε / 2 > 0 := ennreal.half_pos εpos, /- The ball `ball a ε` is included in `u`. We need to find one of our balls `ball x (n⁻¹)` containing `a` and contained in `ball a ε`. For this, we take `n` larger than `2/ε`, and then `x` in `S` at distance at most `n⁻¹` of `a` -/ rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 (ennreal.half_pos εpos)) with ⟨n, εn⟩, have : (0 : ennreal) < n⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have : (a : α) ∈ closure (S : set α) := by rw [S_dense]; simp, rcases mem_closure_iff.1 this _ ‹(0 : ennreal) < n⁻¹› with ⟨x, xS, xdist⟩, existsi ball x (↑n)⁻¹, have I : ball x (n⁻¹) ⊆ ball a ε := λy ydist, calc edist y a = edist a y : edist_comm _ _ ... ≤ edist a x + edist y x : edist_triangle_right _ _ _ ... < n⁻¹ + n⁻¹ : ennreal.add_lt_add xdist ydist ... < ε/2 + ε/2 : ennreal.add_lt_add εn εn ... = ε : ennreal.add_halves _, simp only [emetric.mem_ball, exists_prop, set.mem_Union, set.mem_singleton_iff], exact ⟨⟨x, ⟨xS, ⟨n, rfl⟩⟩⟩, ⟨by simpa, subset.trans I εball⟩⟩ }, exact B.2.2 }⟩⟩⟩ end second_countable section diam /-- The diameter of a set in an emetric space, named `emetric.diam` -/ def diam (s : set α) := ⨆ (x ∈ s) (y ∈ s), edist x y lemma diam_le_iff_forall_edist_le {d : ennreal} : diam s ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist x y ≤ d := by simp only [diam, supr_le_iff] /-- If two points belong to some set, their edistance is bounded by the diameter of the set -/ lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s := diam_le_iff_forall_edist_le.1 (le_refl _) x hx y hy /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_edist_le {d : ennreal} (h : ∀ (x ∈ s) (y ∈ s), edist x y ≤ d) : diam s ≤ d := diam_le_iff_forall_edist_le.2 h /-- The diameter of a subsingleton vanishes. -/ lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := le_zero_iff_eq.1 $ diam_le_of_forall_edist_le $ λ x hx y hy, (hs hx hy).symm ▸ edist_self y ▸ le_refl _ /-- The diameter of the empty set vanishes -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- The diameter of a singleton vanishes -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton lemma diam_eq_zero_iff : diam s = 0 ↔ s.subsingleton := ⟨λ h x hx y hy, edist_le_zero.1 $ h ▸ edist_le_diam_of_mem hx hy, diam_subsingleton⟩ lemma diam_pos_iff : 0 < diam s ↔ ∃ (x ∈ s) (y ∈ s), x ≠ y := begin have := not_congr (@diam_eq_zero_iff _ _ s), dunfold set.subsingleton at this, push_neg at this, simpa only [zero_lt_iff_ne_zero, exists_prop] using this end lemma diam_insert : diam (insert x s) = max (diam s) (⨆ y ∈ s, edist y x) := eq_of_forall_ge_iff $ λ d, by simp only [diam_le_iff_forall_edist_le, ball_insert_iff, max_le_iff, edist_self, zero_le, true_and, supr_le_iff, forall_and_distrib, edist_comm x, and_self, (and_assoc _ _).symm, max_comm (diam s)] lemma diam_pair : diam ({x, y} : set α) = edist x y := by simp only [supr_singleton, diam_insert, diam_singleton, ennreal.max_zero_left] lemma diam_triple : diam ({x, y, z} : set α) = max (edist x y) (max (edist y z) (edist x z)) := by simp only [diam_insert, supr_insert, supr_singleton, diam_singleton, ennreal.max_zero_left, ennreal.sup_eq_max] /-- The diameter is monotonous with respect to inclusion -/ lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t := diam_le_of_forall_edist_le $ λ x hx y hy, edist_le_diam_of_mem (h hx) (h hy) /-- The diameter of a union is controlled by the diameter of the sets, and the edistance between two points in the sets. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t := begin have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _ ... ≤ diam s + edist x y + diam t : add_le_add' (add_le_add' (edist_le_diam_of_mem ha xs) (le_refl _)) (edist_le_diam_of_mem yt hb), refine diam_le_of_forall_edist_le (λa ha b hb, _), cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b ... ≤ diam s + (edist x y + diam t) : le_add_right (le_refl _) ... = diam s + edist x y + diam t : by simp only [add_comm, eq_self_iff_true, add_left_comm] }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [edist_comm] at Z }, { calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b ... ≤ (diam s + edist x y) + diam t : le_add_left (le_refl _) } end lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := let ⟨x, ⟨xs, xt⟩⟩ := h in by simpa using diam_union xs xt lemma diam_closed_ball {r : ennreal} : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_edist_le $ λa ha b hb, calc edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add' ha hb ... = 2 * r : by simp [mul_two, mul_comm] lemma diam_ball {r : ennreal} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball end diam end emetric --namespace
1f927d8fd0d402a66257974f8b13bf9b07a87a28
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/data/vector2.lean
5e8209af795023781a61fa67c007fd9b9c470ac2
[ "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
8,333
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Additional theorems about the `vector` type. -/ import data.vector data.list.basic data.sigma data.equiv.basic category.traversable universes u variables {n : ℕ} namespace vector variables {α : Type*} attribute [simp] head_cons tail_cons instance [inhabited α] : inhabited (vector α n) := ⟨of_fn (λ _, default α)⟩ theorem to_list_injective : function.injective (@to_list α n) := subtype.val_injective @[simp] theorem to_list_of_fn : ∀ {n} (f : fin n → α), to_list (of_fn f) = list.of_fn f | 0 f := rfl | (n+1) f := by rw [of_fn, list.of_fn_succ, to_list_cons, to_list_of_fn] @[simp] theorem mk_to_list : ∀ (v : vector α n) h, (⟨to_list v, h⟩ : vector α n) = v | ⟨l, h₁⟩ h₂ := rfl theorem nth_eq_nth_le : ∀ (v : vector α n) (i), nth v i = v.to_list.nth_le i.1 (by rw to_list_length; exact i.2) | ⟨l, h⟩ i := rfl @[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = f i := by rw [nth_eq_nth_le, ← list.nth_le_of_fn f]; congr; apply to_list_of_fn @[simp] theorem of_fn_nth (v : vector α n) : of_fn (nth v) = v := begin rcases v with ⟨l, rfl⟩, apply to_list_injective, change nth ⟨l, eq.refl _⟩ with λ i, nth ⟨l, rfl⟩ i, simp [nth, list.of_fn_nth_le] end @[simp] theorem nth_tail : ∀ (v : vector α n.succ) (i : fin n), nth (tail v) i = nth v i.succ | ⟨a::l, e⟩ ⟨i, h⟩ := by simp [nth_eq_nth_le]; refl @[simp] theorem tail_of_fn {n : ℕ} (f : fin n.succ → α) : tail (of_fn f) = of_fn (λ i, f i.succ) := (of_fn_nth _).symm.trans $ by congr; funext i; simp theorem head'_to_list : ∀ (v : vector α n.succ), (to_list v).head' = some (head v) | ⟨a::l, e⟩ := rfl def reverse (v : vector α n) : vector α n := ⟨v.to_list.reverse, by simp⟩ @[simp] theorem nth_zero : ∀ (v : vector α n.succ), nth v 0 = head v | ⟨a::l, e⟩ := rfl @[simp] theorem head_of_fn {n : ℕ} (f : fin n.succ → α) : head (of_fn f) = f 0 := by rw [← nth_zero, nth_of_fn] @[simp] theorem nth_cons_zero (a : α) (v : vector α n) : nth (a :: v) 0 = a := by simp [nth_zero] @[simp] theorem nth_cons_succ (a : α) (v : vector α n) (i : fin n) : nth (a :: v) i.succ = nth v i := by rw [← nth_tail, tail_cons] def m_of_fn {m} [monad m] {α : Type u} : ∀ {n}, (fin n → m α) → m (vector α n) | 0 f := pure nil | (n+1) f := do a ← f 0, v ← m_of_fn (λi, f i.succ), pure (a :: v) theorem m_of_fn_pure {m} [monad m] [is_lawful_monad m] {α} : ∀ {n} (f : fin n → α), @m_of_fn m _ _ _ (λ i, pure (f i)) = pure (of_fn f) | 0 f := rfl | (n+1) f := by simp [m_of_fn, @m_of_fn_pure n, of_fn] def mmap {m} [monad m] {α} {β : Type u} (f : α → m β) : ∀ {n}, vector α n → m (vector β n) | _ ⟨[], rfl⟩ := pure nil | _ ⟨a::l, rfl⟩ := do h' ← f a, t' ← mmap ⟨l, rfl⟩, pure (h' :: t') @[simp] theorem mmap_nil {m} [monad m] {α β} (f : α → m β) : mmap f nil = pure nil := rfl @[simp] theorem mmap_cons {m} [monad m] {α β} (f : α → m β) (a) : ∀ {n} (v : vector α n), mmap f (a::v) = do h' ← f a, t' ← mmap f v, pure (h' :: t') | _ ⟨l, rfl⟩ := rfl @[extensionality] theorem ext : ∀ {v w : vector α n} (h : ∀ m : fin n, vector.nth v m = vector.nth w m), v = w | ⟨v, hv⟩ ⟨w, hw⟩ h := subtype.eq (list.ext_le (by rw [hv, hw]) (λ m hm hn, h ⟨m, hv ▸ hm⟩)) instance zero_subsingleton : subsingleton (vector α 0) := ⟨λ _ _, vector.ext (λ m, fin.elim0 m)⟩ def to_array : vector α n → array n α | ⟨xs, h⟩ := cast (by rw h) xs.to_array section insert_nth variable {a : α} def insert_nth (a : α) (i : fin (n+1)) (v : vector α n) : vector α (n+1) := ⟨v.1.insert_nth i.1 a, begin rw [list.length_insert_nth, v.2], rw [v.2, ← nat.succ_le_succ_iff], exact i.2 end⟩ lemma insert_nth_val {i : fin (n+1)} {v : vector α n} : (v.insert_nth a i).val = v.val.insert_nth i.1 a := rfl @[simp] lemma remove_nth_val {i : fin n} : ∀{v : vector α n}, (remove_nth i v).val = v.val.remove_nth i.1 | ⟨l, hl⟩ := rfl lemma remove_nth_insert_nth {v : vector α n} {i : fin (n+1)} : remove_nth i (insert_nth a i v) = v := subtype.eq $ list.remove_nth_insert_nth i.1 v.1 lemma remove_nth_insert_nth_ne {v : vector α (n+1)} : ∀{i j : fin (n+2)} (h : i ≠ j), remove_nth i (insert_nth a j v) = insert_nth a (i.pred_above j h.symm) (remove_nth (j.pred_above i h) v) | ⟨i, hi⟩ ⟨j, hj⟩ ne := begin have : i ≠ j := fin.vne_of_ne ne, refine subtype.eq _, dsimp [insert_nth, remove_nth, fin.pred_above, fin.cast_lt], rcases lt_trichotomy i j with h | h | h, { have h_nji : ¬ j < i := lt_asymm h, have j_pos : 0 < j := lt_of_le_of_lt (zero_le i) h, simp [h, h_nji, fin.lt_iff_val_lt_val], rw [show j.pred = j - 1, from rfl, list.insert_nth_remove_nth_of_ge, nat.sub_add_cancel j_pos], { rw [v.2], exact lt_of_lt_of_le h (nat.le_of_succ_le_succ hj) }, { exact nat.le_sub_right_of_add_le h } }, { exact (this h).elim }, { have h_nij : ¬ i < j := lt_asymm h, have i_pos : 0 < i := lt_of_le_of_lt (zero_le j) h, simp [h, h_nij, fin.lt_iff_val_lt_val], rw [show i.pred = i - 1, from rfl, list.insert_nth_remove_nth_of_le, nat.sub_add_cancel i_pos], { show i - 1 + 1 ≤ v.val.length, rw [v.2, nat.sub_add_cancel i_pos], exact nat.le_of_lt_succ hi }, { exact nat.le_sub_right_of_add_le h } } end lemma insert_nth_comm (a b : α) (i j : fin (n+1)) (h : i ≤ j) : ∀(v : vector α n), (v.insert_nth a i).insert_nth b j.succ = (v.insert_nth b j).insert_nth a i.cast_succ | ⟨l, hl⟩ := begin refine subtype.eq _, simp [insert_nth_val, fin.succ_val, fin.cast_succ], apply list.insert_nth_comm, { assumption }, { rw hl, exact nat.le_of_succ_le_succ j.2 } end end insert_nth end vector namespace vector section traverse variables {F G : Type u → Type u} variables [applicative F] [applicative G] open applicative functor open list (cons) nat private def traverse_aux {α β : Type u} (f : α → F β) : Π (x : list α), F (vector β x.length) | [] := pure vector.nil | (x::xs) := vector.cons <$> f x <*> traverse_aux xs protected def traverse {α β : Type u} (f : α → F β) : vector α n → F (vector β n) | ⟨v, Hv⟩ := cast (by rw Hv) $ traverse_aux f v variables [is_lawful_applicative F] [is_lawful_applicative G] variables {α β γ : Type u} @[simp] protected lemma traverse_def (f : α → F β) (x : α) : ∀ (xs : vector α n), (x :: xs).traverse f = cons <$> f x <*> xs.traverse f := by rintro ⟨xs, rfl⟩; refl protected lemma id_traverse : ∀ (x : vector α n), x.traverse id.mk = x := begin rintro ⟨x, rfl⟩, dsimp [vector.traverse, cast], induction x with x xs IH, {refl}, simp! [IH], refl end open function protected lemma comp_traverse (f : β → F γ) (g : α → G β) : ∀ (x : vector α n), vector.traverse (comp.mk ∘ functor.map f ∘ g) x = comp.mk (vector.traverse f <$> vector.traverse g x) := by rintro ⟨x, rfl⟩; dsimp [vector.traverse, cast]; induction x with x xs; simp! [cast, *] with functor_norm; [refl, simp [(∘)]] protected lemma traverse_eq_map_id {α β} (f : α → β) : ∀ (x : vector α n), x.traverse (id.mk ∘ f) = id.mk (map f x) := by rintro ⟨x, rfl⟩; simp!; induction x; simp! * with functor_norm; refl variable (η : applicative_transformation F G) protected lemma naturality {α β : Type*} (f : α → F β) : ∀ (x : vector α n), η (x.traverse f) = x.traverse (@η _ ∘ f) := by rintro ⟨x, rfl⟩; simp! [cast]; induction x with x xs IH; simp! * with functor_norm end traverse instance : traversable.{u} (flip vector n) := { traverse := @vector.traverse n, map := λ α β, @vector.map.{u u} α β n } instance : is_lawful_traversable.{u} (flip vector n) := { id_traverse := @vector.id_traverse n, comp_traverse := @vector.comp_traverse n, traverse_eq_map_id := @vector.traverse_eq_map_id n, naturality := @vector.naturality n, id_map := by intros; cases x; simp! [(<$>)], comp_map := by intros; cases x; simp! [(<$>)] } end vector
aa837637f5f28568491112f5fe7d144907d1c4d3
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/finsupp/basic.lean
ed72c257151c0d916542a6323e2a4b522750aebe
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
108,483
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Scott Morrison -/ import data.finset.preimage import algebra.indicator_function import algebra.group_action_hom /-! # Type of functions with finite support For any type `α` and a type `M` with zero, we define the type `finsupp α M` (notation: `α →₀ M`) of finitely supported functions from `α` to `M`, i.e. the functions which are zero everywhere on `α` except on a finite set. Functions with finite support are used (at least) in the following parts of the library: * `monoid_algebra R M` and `add_monoid_algebra R M` are defined as `M →₀ R`; * polynomials and multivariate polynomials are defined as `add_monoid_algebra`s, hence they use `finsupp` under the hood; * the linear combination of a family of vectors `v i` with coefficients `f i` (as used, e.g., to define linearly independent family `linear_independent`) is defined as a map `finsupp.total : (ι → M) → (ι →₀ R) →ₗ[R] M`. Some other constructions are naturally equivalent to `α →₀ M` with some `α` and `M` but are defined in a different way in the library: * `multiset α ≃+ α →₀ ℕ`; * `free_abelian_group α ≃+ α →₀ ℤ`. Most of the theory assumes that the range is a commutative additive monoid. This gives us the big sum operator as a powerful way to construct `finsupp` elements. Many constructions based on `α →₀ M` use `semireducible` type tags to avoid reusing unwanted type instances. E.g., `monoid_algebra`, `add_monoid_algebra`, and types based on these two have non-pointwise multiplication. ## Notations This file adds `α →₀ M` as a global notation for `finsupp α M`. We also use the following convention for `Type*` variables in this file * `α`, `β`, `γ`: types with no additional structure that appear as the first argument to `finsupp` somewhere in the statement; * `ι` : an auxiliary index type; * `M`, `M'`, `N`, `P`: types with `has_zero` or `(add_)(comm_)monoid` structure; `M` is also used for a (semi)module over a (semi)ring. * `G`, `H`: groups (commutative or not, multiplicative or additive); * `R`, `S`: (semi)rings. ## TODO * This file is currently ~2K lines long, so possibly it should be splitted into smaller chunks; * Add the list of definitions and important lemmas to the module docstring. ## Implementation notes This file is a `noncomputable theory` and uses classical logic throughout. ## Notation This file defines `α →₀ β` as notation for `finsupp α β`. -/ noncomputable theory open_locale classical big_operators open finset variables {α β γ ι M M' N P G H R S : Type*} /-- `finsupp α M`, denoted `α →₀ M`, is the type of functions `f : α → M` such that `f x = 0` for all but finitely many `x`. -/ structure finsupp (α : Type*) (M : Type*) [has_zero M] := (support : finset α) (to_fun : α → M) (mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0) infixr ` →₀ `:25 := finsupp namespace finsupp /-! ### Basic declarations about `finsupp` -/ section basic variable [has_zero M] instance : has_coe_to_fun (α →₀ M) := ⟨λ _, α → M, to_fun⟩ @[simp] lemma coe_mk (f : α → M) (s : finset α) (h : ∀ a, a ∈ s ↔ f a ≠ 0) : ⇑(⟨s, f, h⟩ : α →₀ M) = f := rfl instance : has_zero (α →₀ M) := ⟨⟨∅, 0, λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩ @[simp] lemma coe_zero : ⇑(0 : α →₀ M) = 0 := rfl lemma zero_apply {a : α} : (0 : α →₀ M) a = 0 := rfl @[simp] lemma support_zero : (0 : α →₀ M).support = ∅ := rfl instance : inhabited (α →₀ M) := ⟨0⟩ @[simp] lemma mem_support_iff {f : α →₀ M} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 := f.mem_support_to_fun @[simp, norm_cast] lemma fun_support_eq (f : α →₀ M) : function.support f = f.support := set.ext $ λ x, mem_support_iff.symm lemma not_mem_support_iff {f : α →₀ M} {a} : a ∉ f.support ↔ f a = 0 := not_iff_comm.1 mem_support_iff.symm lemma coe_fn_injective : @function.injective (α →₀ M) (α → M) coe_fn | ⟨s, f, hf⟩ ⟨t, g, hg⟩ h := begin change f = g at h, subst h, have : s = t, { ext a, exact (hf a).trans (hg a).symm }, subst this end @[simp, norm_cast] lemma coe_fn_inj {f g : α →₀ M} : (f : α → M) = g ↔ f = g := coe_fn_injective.eq_iff @[simp, norm_cast] lemma coe_eq_zero {f : α →₀ M} : (f : α → M) = 0 ↔ f = 0 := by rw [← coe_zero, coe_fn_inj] @[ext] lemma ext {f g : α →₀ M} (h : ∀a, f a = g a) : f = g := coe_fn_injective (funext h) lemma ext_iff {f g : α →₀ M} : f = g ↔ (∀a:α, f a = g a) := ⟨by rintros rfl a; refl, ext⟩ lemma ext_iff' {f g : α →₀ M} : f = g ↔ f.support = g.support ∧ ∀ x ∈ f.support, f x = g x := ⟨λ h, h ▸ ⟨rfl, λ _ _, rfl⟩, λ ⟨h₁, h₂⟩, ext $ λ a, if h : a ∈ f.support then h₂ a h else have hf : f a = 0, from not_mem_support_iff.1 h, have hg : g a = 0, by rwa [h₁, not_mem_support_iff] at h, by rw [hf, hg]⟩ lemma congr_fun {f g : α →₀ M} (h : f = g) (a : α) : f a = g a := congr_fun (congr_arg finsupp.to_fun h) a @[simp] lemma support_eq_empty {f : α →₀ M} : f.support = ∅ ↔ f = 0 := by exact_mod_cast @function.support_eq_empty_iff _ _ _ f lemma support_nonempty_iff {f : α →₀ M} : f.support.nonempty ↔ f ≠ 0 := by simp only [finsupp.support_eq_empty, finset.nonempty_iff_ne_empty, ne.def] lemma nonzero_iff_exists {f : α →₀ M} : f ≠ 0 ↔ ∃ a : α, f a ≠ 0 := by simp [← finsupp.support_eq_empty, finset.eq_empty_iff_forall_not_mem] lemma card_support_eq_zero {f : α →₀ M} : card f.support = 0 ↔ f = 0 := by simp instance [decidable_eq α] [decidable_eq M] : decidable_eq (α →₀ M) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a)) ext_iff'.symm lemma finite_support (f : α →₀ M) : set.finite (function.support f) := f.fun_support_eq.symm ▸ f.support.finite_to_set lemma support_subset_iff {s : set α} {f : α →₀ M} : ↑f.support ⊆ s ↔ (∀a∉s, f a = 0) := by simp only [set.subset_def, mem_coe, mem_support_iff]; exact forall_congr (assume a, not_imp_comm) /-- Given `fintype α`, `equiv_fun_on_fintype` is the `equiv` between `α →₀ β` and `α → β`. (All functions on a finite type are finitely supported.) -/ @[simps] def equiv_fun_on_fintype [fintype α] : (α →₀ M) ≃ (α → M) := ⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp only [true_and, finset.mem_univ, iff_self, finset.mem_filter, finset.filter_congr_decidable, forall_true_iff]), begin intro f, ext a, refl end, begin intro f, ext a, refl end⟩ @[simp] lemma equiv_fun_on_fintype_symm_coe {α} [fintype α] (f : α →₀ M) : equiv_fun_on_fintype.symm f = f := by { ext, simp [equiv_fun_on_fintype], } end basic /-! ### Declarations about `single` -/ section single variables [has_zero M] {a a' : α} {b : M} /-- `single a b` is the finitely supported function which has value `b` at `a` and zero otherwise. -/ def single (a : α) (b : M) : α →₀ M := ⟨if b = 0 then ∅ else {a}, λ a', if a = a' then b else 0, λ a', begin by_cases hb : b = 0; by_cases a = a'; simp only [hb, h, if_pos, if_false, mem_singleton], { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨λ _, hb, λ _, rfl⟩ }, { exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ } end⟩ lemma single_apply [decidable (a = a')] : single a b a' = if a = a' then b else 0 := by convert rfl lemma single_eq_indicator : ⇑(single a b) = set.indicator {a} (λ _, b) := by { ext, simp [single_apply, set.indicator, @eq_comm _ a] } @[simp] lemma single_eq_same : (single a b : α →₀ M) a = b := if_pos rfl @[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ M) a' = 0 := if_neg h lemma single_eq_update : ⇑(single a b) = function.update 0 a b := by rw [single_eq_indicator, ← set.piecewise_eq_indicator, set.piecewise_singleton] lemma single_eq_pi_single : ⇑(single a b) = pi.single a b := single_eq_update @[simp] lemma single_zero : (single a 0 : α →₀ M) = 0 := coe_fn_injective $ by simpa only [single_eq_update, coe_zero] using function.update_eq_self a (0 : α → M) lemma single_of_single_apply (a a' : α) (b : M) : single a ((single a' b) a) = single a' (single a' b) a := begin rw [single_apply, single_apply], ext, split_ifs, { rw h, }, { rw [zero_apply, single_apply, if_t_t], }, end lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} := if_neg hb lemma support_single_subset : (single a b).support ⊆ {a} := show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _] lemma single_apply_mem (x) : single a b x ∈ ({0, b} : set M) := by rcases em (a = x) with (rfl|hx); [simp, simp [single_eq_of_ne hx]] lemma range_single_subset : set.range (single a b) ⊆ {0, b} := set.range_subset_iff.2 single_apply_mem /-- `finsupp.single a b` is injective in `b`. For the statement that it is injective in `a`, see `finsupp.single_left_injective` -/ lemma single_injective (a : α) : function.injective (single a : M → α →₀ M) := assume b₁ b₂ eq, have (single a b₁ : α →₀ M) a = (single a b₂ : α →₀ M) a, by rw eq, by rwa [single_eq_same, single_eq_same] at this lemma single_apply_eq_zero {a x : α} {b : M} : single a b x = 0 ↔ (x = a → b = 0) := by simp [single_eq_indicator] lemma mem_support_single (a a' : α) (b : M) : a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 := by simp [single_apply_eq_zero, not_or_distrib] lemma eq_single_iff {f : α →₀ M} {a b} : f = single a b ↔ f.support ⊆ {a} ∧ f a = b := begin refine ⟨λ h, h.symm ▸ ⟨support_single_subset, single_eq_same⟩, _⟩, rintro ⟨h, rfl⟩, ext x, by_cases hx : a = x; simp only [hx, single_eq_same, single_eq_of_ne, ne.def, not_false_iff], exact not_mem_support_iff.1 (mt (λ hx, (mem_singleton.1 (h hx)).symm) hx) end lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : M) : single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) := begin split, { assume eq, by_cases a₁ = a₂, { refine or.inl ⟨h, _⟩, rwa [h, (single_injective a₂).eq_iff] at eq }, { rw [ext_iff] at eq, have h₁ := eq a₁, have h₂ := eq a₂, simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂, exact or.inr ⟨h₁, h₂.symm⟩ } }, { rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩), { refl }, { rw [single_zero, single_zero] } } end /-- `finsupp.single a b` is injective in `a`. For the statement that it is injective in `b`, see `finsupp.single_injective` -/ lemma single_left_injective (h : b ≠ 0) : function.injective (λ a : α, single a b) := λ a a' H, (((single_eq_single_iff _ _ _ _).mp H).resolve_right $ λ hb, h hb.1).left lemma single_left_inj (h : b ≠ 0) : single a b = single a' b ↔ a = a' := (single_left_injective h).eq_iff lemma support_single_ne_bot (i : α) (h : b ≠ 0) : (single i b).support ≠ ⊥ := begin have : i ∈ (single i b).support := by simpa using h, intro H, simpa [H] end lemma support_single_disjoint {b' : M} (hb : b ≠ 0) (hb' : b' ≠ 0) {i j : α} : disjoint (single i b).support (single j b').support ↔ i ≠ j := by rw [support_single_ne_zero hb, support_single_ne_zero hb', disjoint_singleton] @[simp] lemma single_eq_zero : single a b = 0 ↔ b = 0 := by simp [ext_iff, single_eq_indicator] lemma single_swap (a₁ a₂ : α) (b : M) : single a₁ b a₂ = single a₂ b a₁ := by simp only [single_apply]; ac_refl instance [nonempty α] [nontrivial M] : nontrivial (α →₀ M) := begin inhabit α, rcases exists_ne (0 : M) with ⟨x, hx⟩, exact nontrivial_of_ne (single (default α) x) 0 (mt single_eq_zero.1 hx) end lemma unique_single [unique α] (x : α →₀ M) : x = single (default α) (x (default α)) := ext $ unique.forall_iff.2 single_eq_same.symm lemma unique_ext [unique α] {f g : α →₀ M} (h : f (default α) = g (default α)) : f = g := ext $ λ a, by rwa [unique.eq_default a] lemma unique_ext_iff [unique α] {f g : α →₀ M} : f = g ↔ f (default α) = g (default α) := ⟨λ h, h ▸ rfl, unique_ext⟩ @[simp] lemma unique_single_eq_iff [unique α] {b' : M} : single a b = single a' b' ↔ b = b' := by rw [unique_ext_iff, unique.eq_default a, unique.eq_default a', single_eq_same, single_eq_same] lemma support_eq_singleton {f : α →₀ M} {a : α} : f.support = {a} ↔ f a ≠ 0 ∧ f = single a (f a) := ⟨λ h, ⟨mem_support_iff.1 $ h.symm ▸ finset.mem_singleton_self a, eq_single_iff.2 ⟨subset_of_eq h, rfl⟩⟩, λ h, h.2.symm ▸ support_single_ne_zero h.1⟩ lemma support_eq_singleton' {f : α →₀ M} {a : α} : f.support = {a} ↔ ∃ b ≠ 0, f = single a b := ⟨λ h, let h := support_eq_singleton.1 h in ⟨_, h.1, h.2⟩, λ ⟨b, hb, hf⟩, hf.symm ▸ support_single_ne_zero hb⟩ lemma card_support_eq_one {f : α →₀ M} : card f.support = 1 ↔ ∃ a, f a ≠ 0 ∧ f = single a (f a) := by simp only [card_eq_one, support_eq_singleton] lemma card_support_eq_one' {f : α →₀ M} : card f.support = 1 ↔ ∃ a (b ≠ 0), f = single a b := by simp only [card_eq_one, support_eq_singleton'] @[simp] lemma equiv_fun_on_fintype_single [fintype α] (x : α) (m : M) : (@finsupp.equiv_fun_on_fintype α M _ _) (finsupp.single x m) = pi.single x m := by { ext, simp [finsupp.single_eq_pi_single, finsupp.equiv_fun_on_fintype], } @[simp] lemma equiv_fun_on_fintype_symm_single [fintype α] (x : α) (m : M) : (@finsupp.equiv_fun_on_fintype α M _ _).symm (pi.single x m) = finsupp.single x m := by { ext, simp [finsupp.single_eq_pi_single, finsupp.equiv_fun_on_fintype], } end single /-! ### Declarations about `update` -/ section update variables [has_zero M] (f : α →₀ M) (a : α) (b : M) (i : α) /-- Replace the value of a `α →₀ M` at a given point `a : α` by a given value `b : M`. If `b = 0`, this amounts to removing `a` from the `finsupp.support`. Otherwise, if `a` was not in the `finsupp.support`, it is added to it. This is the finitely-supported version of `function.update`. -/ def update : α →₀ M := ⟨if b = 0 then f.support.erase a else insert a f.support, function.update f a b, λ i, begin simp only [function.update_apply, ne.def], split_ifs with hb ha ha hb; simp [ha, hb] end⟩ @[simp] lemma coe_update : (f.update a b : α → M) = function.update f a b := rfl @[simp] lemma update_self : f.update a (f a) = f := by { ext, simp } lemma support_update : support (f.update a b) = if b = 0 then f.support.erase a else insert a f.support := rfl @[simp] lemma support_update_zero : support (f.update a 0) = f.support.erase a := if_pos rfl variables {b} lemma support_update_ne_zero (h : b ≠ 0) : support (f.update a b) = insert a f.support := if_neg h end update /-! ### Declarations about `on_finset` -/ section on_finset variables [has_zero M] /-- `on_finset s f hf` is the finsupp function representing `f` restricted to the finset `s`. The function needs to be `0` outside of `s`. Use this when the set needs to be filtered anyways, otherwise a better set representation is often available. -/ def on_finset (s : finset α) (f : α → M) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ M := ⟨s.filter (λa, f a ≠ 0), f, by simpa⟩ @[simp] lemma on_finset_apply {s : finset α} {f : α → M} {hf a} : (on_finset s f hf : α →₀ M) a = f a := rfl @[simp] lemma support_on_finset_subset {s : finset α} {f : α → M} {hf} : (on_finset s f hf).support ⊆ s := filter_subset _ _ @[simp] lemma mem_support_on_finset {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) {a : α} : a ∈ (finsupp.on_finset s f hf).support ↔ f a ≠ 0 := by rw [finsupp.mem_support_iff, finsupp.on_finset_apply] lemma support_on_finset {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) : (finsupp.on_finset s f hf).support = s.filter (λ a, f a ≠ 0) := rfl end on_finset section of_support_finite variables [has_zero M] /-- The natural `finsupp` induced by the function `f` given that it has finite support. -/ noncomputable def of_support_finite (f : α → M) (hf : (function.support f).finite) : α →₀ M := { support := hf.to_finset, to_fun := f, mem_support_to_fun := λ _, hf.mem_to_finset } lemma of_support_finite_coe {f : α → M} {hf : (function.support f).finite} : (of_support_finite f hf : α → M) = f := rfl instance : can_lift (α → M) (α →₀ M) := { coe := coe_fn, cond := λ f, (function.support f).finite, prf := λ f hf, ⟨of_support_finite f hf, rfl⟩ } end of_support_finite /-! ### Declarations about `map_range` -/ section map_range variables [has_zero M] [has_zero N] [has_zero P] /-- The composition of `f : M → N` and `g : α →₀ M` is `map_range f hf g : α →₀ N`, well-defined when `f 0 = 0`. This preserves the structure on `f`, and exists in various bundled forms for when `f` is itself bundled: * `finsupp.map_range.equiv` * `finsupp.map_range.zero_hom` * `finsupp.map_range.add_monoid_hom` * `finsupp.map_range.add_equiv` * `finsupp.map_range.linear_map` * `finsupp.map_range.linear_equiv` -/ def map_range (f : M → N) (hf : f 0 = 0) (g : α →₀ M) : α →₀ N := on_finset g.support (f ∘ g) $ assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf @[simp] lemma map_range_apply {f : M → N} {hf : f 0 = 0} {g : α →₀ M} {a : α} : map_range f hf g a = f (g a) := rfl @[simp] lemma map_range_zero {f : M → N} {hf : f 0 = 0} : map_range f hf (0 : α →₀ M) = 0 := ext $ λ a, by simp only [hf, zero_apply, map_range_apply] @[simp] lemma map_range_id (g : α →₀ M) : map_range id rfl g = g := ext $ λ _, rfl lemma map_range_comp (f : N → P) (hf : f 0 = 0) (f₂ : M → N) (hf₂ : f₂ 0 = 0) (h : (f ∘ f₂) 0 = 0) (g : α →₀ M) : map_range (f ∘ f₂) h g = map_range f hf (map_range f₂ hf₂ g) := ext $ λ _, rfl lemma support_map_range {f : M → N} {hf : f 0 = 0} {g : α →₀ M} : (map_range f hf g).support ⊆ g.support := support_on_finset_subset @[simp] lemma map_range_single {f : M → N} {hf : f 0 = 0} {a : α} {b : M} : map_range f hf (single a b) = single a (f b) := ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf] end map_range /-! ### Declarations about `emb_domain` -/ section emb_domain variables [has_zero M] [has_zero N] /-- Given `f : α ↪ β` and `v : α →₀ M`, `emb_domain f v : β →₀ M` is the finitely supported function whose value at `f a : β` is `v a`. For a `b : β` outside the range of `f`, it is zero. -/ def emb_domain (f : α ↪ β) (v : α →₀ M) : β →₀ M := begin refine ⟨v.support.map f, λa₂, if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩, { rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩, exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.injective hb) }, { assume a₂, split_ifs, { simp only [h, true_iff, ne.def], rw [← not_mem_support_iff, not_not], apply finset.choose_mem }, { simp only [h, ne.def, ne_self_iff_false] } } end @[simp] lemma support_emb_domain (f : α ↪ β) (v : α →₀ M) : (emb_domain f v).support = v.support.map f := rfl @[simp] lemma emb_domain_zero (f : α ↪ β) : (emb_domain f 0 : β →₀ M) = 0 := rfl @[simp] lemma emb_domain_apply (f : α ↪ β) (v : α →₀ M) (a : α) : emb_domain f v (f a) = v a := begin change dite _ _ _ = _, split_ifs; rw [finset.mem_map' f] at h, { refine congr_arg (v : α → M) (f.inj' _), exact finset.choose_property (λa₁, f a₁ = f a) _ _ }, { exact (not_mem_support_iff.1 h).symm } end lemma emb_domain_notin_range (f : α ↪ β) (v : α →₀ M) (a : β) (h : a ∉ set.range f) : emb_domain f v a = 0 := begin refine dif_neg (mt (assume h, _) h), rcases finset.mem_map.1 h with ⟨a, h, rfl⟩, exact set.mem_range_self a end lemma emb_domain_injective (f : α ↪ β) : function.injective (emb_domain f : (α →₀ M) → (β →₀ M)) := λ l₁ l₂ h, ext $ λ a, by simpa only [emb_domain_apply] using ext_iff.1 h (f a) @[simp] lemma emb_domain_inj {f : α ↪ β} {l₁ l₂ : α →₀ M} : emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ := (emb_domain_injective f).eq_iff @[simp] lemma emb_domain_eq_zero {f : α ↪ β} {l : α →₀ M} : emb_domain f l = 0 ↔ l = 0 := (emb_domain_injective f).eq_iff' $ emb_domain_zero f lemma emb_domain_map_range (f : α ↪ β) (g : M → N) (p : α →₀ M) (hg : g 0 = 0) : emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a', rfl⟩, rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] }, { rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption } end lemma single_of_emb_domain_single (l : α →₀ M) (f : α ↪ β) (a : β) (b : M) (hb : b ≠ 0) (h : l.emb_domain f = single a b) : ∃ x, l = single x b ∧ f x = a := begin have h_map_support : finset.map f (l.support) = {a}, by rw [←support_emb_domain, h, support_single_ne_zero hb]; refl, have ha : a ∈ finset.map f (l.support), by simp only [h_map_support, finset.mem_singleton], rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩, use c, split, { ext d, rw [← emb_domain_apply f l, h], by_cases h_cases : c = d, { simp only [eq.symm h_cases, hc₂, single_eq_same] }, { rw [single_apply, single_apply, if_neg, if_neg h_cases], by_contra hfd, exact h_cases (f.injective (hc₂.trans hfd)) } }, { exact hc₂ } end @[simp] lemma emb_domain_single (f : α ↪ β) (a : α) (m : M) : emb_domain f (single a m) = single (f a) m := begin ext b, by_cases h : b ∈ set.range f, { rcases h with ⟨a', rfl⟩, simp [single_apply], }, { simp only [emb_domain_notin_range, h, single_apply, not_false_iff], rw if_neg, rintro rfl, simpa using h, }, end end emb_domain /-! ### Declarations about `zip_with` -/ section zip_with variables [has_zero M] [has_zero N] [has_zero P] /-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying `zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and it is well-defined when `f 0 0 = 0`. -/ def zip_with (f : M → N → P) (hf : f 0 0 = 0) (g₁ : α →₀ M) (g₂ : α →₀ N) : (α →₀ P) := on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib], rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf end @[simp] lemma zip_with_apply {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} {a : α} : zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl lemma support_zip_with [D : decidable_eq α] {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by rw subsingleton.elim D; exact support_on_finset_subset end zip_with /-! ### Declarations about `erase` -/ section erase variables [has_zero M] /-- `erase a f` is the finitely supported function equal to `f` except at `a` where it is equal to `0`. -/ def erase (a : α) (f : α →₀ M) : α →₀ M := ⟨f.support.erase a, (λa', if a' = a then 0 else f a'), assume a', by rw [mem_erase, mem_support_iff]; split_ifs; [exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩, exact and_iff_right h]⟩ @[simp] lemma support_erase {a : α} {f : α →₀ M} : (f.erase a).support = f.support.erase a := rfl @[simp] lemma erase_same {a : α} {f : α →₀ M} : (f.erase a) a = 0 := if_pos rfl @[simp] lemma erase_ne {a a' : α} {f : α →₀ M} (h : a' ≠ a) : (f.erase a) a' = f a' := if_neg h @[simp] lemma erase_single {a : α} {b : M} : (erase a (single a b)) = 0 := begin ext s, by_cases hs : s = a, { rw [hs, erase_same], refl }, { rw [erase_ne hs], exact single_eq_of_ne (ne.symm hs) } end lemma erase_single_ne {a a' : α} {b : M} (h : a ≠ a') : (erase a (single a' b)) = single a' b := begin ext s, by_cases hs : s = a, { rw [hs, erase_same, single_eq_of_ne (h.symm)] }, { rw [erase_ne hs] } end @[simp] lemma erase_zero (a : α) : erase a (0 : α →₀ M) = 0 := by rw [← support_eq_empty, support_erase, support_zero, erase_empty] end erase /-! ### Declarations about `sum` and `prod` In most of this section, the domain `β` is assumed to be an `add_monoid`. -/ section sum_prod /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ @[to_additive "`sum f g` is the sum of `g a (f a)` over the support of `f`. "] def prod [has_zero M] [comm_monoid N] (f : α →₀ M) (g : α → M → N) : N := ∏ a in f.support, g a (f a) variables [has_zero M] [has_zero M'] [comm_monoid N] @[to_additive] lemma prod_of_support_subset (f : α →₀ M) {s : finset α} (hs : f.support ⊆ s) (g : α → M → N) (h : ∀ i ∈ s, g i 0 = 1) : f.prod g = ∏ x in s, g x (f x) := finset.prod_subset hs $ λ x hxs hx, h x hxs ▸ congr_arg (g x) $ not_mem_support_iff.1 hx @[to_additive] lemma prod_fintype [fintype α] (f : α →₀ M) (g : α → M → N) (h : ∀ i, g i 0 = 1) : f.prod g = ∏ i, g i (f i) := f.prod_of_support_subset (subset_univ _) g (λ x _, h x) @[simp, to_additive] lemma prod_single_index {a : α} {b : M} {h : α → M → N} (h_zero : h a 0 = 1) : (single a b).prod h = h a b := calc (single a b).prod h = ∏ x in {a}, h x (single a b x) : prod_of_support_subset _ support_single_subset h $ λ x hx, (mem_singleton.1 hx).symm ▸ h_zero ... = h a b : by simp @[to_additive] lemma prod_map_range_index {f : M → M'} {hf : f 0 = 0} {g : α →₀ M} {h : α → M' → N} (h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) := finset.prod_subset support_map_range $ λ _ _ H, by rw [not_mem_support_iff.1 H, h0] @[simp, to_additive] lemma prod_zero_index {h : α → M → N} : (0 : α →₀ M).prod h = 1 := rfl @[to_additive] lemma prod_comm (f : α →₀ M) (g : β →₀ M') (h : α → M → β → M' → N) : f.prod (λ x v, g.prod (λ x' v', h x v x' v')) = g.prod (λ x' v', f.prod (λ x v, h x v x' v')) := finset.prod_comm @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (a = x) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq, } @[simp] lemma sum_ite_self_eq [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (a = x) v 0) = f a := by { convert f.sum_ite_eq a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] } /-- A restatement of `prod_ite_eq` with the equality test reversed. -/ @[simp, to_additive "A restatement of `sum_ite_eq` with the equality test reversed."] lemma prod_ite_eq' [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (x = a) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq', } @[simp] lemma sum_ite_self_eq' [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (x = a) v 0) = f a := by { convert f.sum_ite_eq' a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] } @[simp] lemma prod_pow [fintype α] (f : α →₀ ℕ) (g : α → N) : f.prod (λ a b, g a ^ b) = ∏ a, g a ^ (f a) := f.prod_fintype _ $ λ a, pow_zero _ /-- If `g` maps a second argument of 0 to 1, then multiplying it over the result of `on_finset` is the same as multiplying it over the original `finset`. -/ @[to_additive "If `g` maps a second argument of 0 to 0, summing it over the result of `on_finset` is the same as summing it over the original `finset`."] lemma on_finset_prod {s : finset α} {f : α → M} {g : α → M → N} (hf : ∀a, f a ≠ 0 → a ∈ s) (hg : ∀ a, g a 0 = 1) : (on_finset s f hf).prod g = ∏ a in s, g a (f a) := finset.prod_subset support_on_finset_subset $ by simp [*] { contextual := tt } @[to_additive] lemma _root_.submonoid.finsupp_prod_mem (S : submonoid N) (f : α →₀ M) (g : α → M → N) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ S) : f.prod g ∈ S := S.prod_mem $ λ i hi, h _ (finsupp.mem_support_iff.mp hi) end sum_prod /-! ### Additive monoid structure on `α →₀ M` -/ section add_zero_class variables [add_zero_class M] instance : has_add (α →₀ M) := ⟨zip_with (+) (add_zero 0)⟩ @[simp] lemma coe_add (f g : α →₀ M) : ⇑(f + g) = f + g := rfl lemma add_apply (g₁ g₂ : α →₀ M) (a : α) : (g₁ + g₂) a = g₁ a + g₂ a := rfl lemma support_add [decidable_eq α] {g₁ g₂ : α →₀ M} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with lemma support_add_eq [decidable_eq α] {g₁ g₂ : α →₀ M} (h : disjoint g₁.support g₂.support) : (g₁ + g₂).support = g₁.support ∪ g₂.support := le_antisymm support_zip_with $ assume a ha, (finset.mem_union.1 ha).elim (assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, add_zero]) (assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, zero_add]) @[simp] lemma single_add {a : α} {b₁ b₂ : M} : single a (b₁ + b₂) = single a b₁ + single a b₂ := ext $ assume a', begin by_cases h : a = a', { rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] } end instance : add_zero_class (α →₀ M) := { zero := 0, add := (+), zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _, add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ } /-- `finsupp.single` as an `add_monoid_hom`. See `finsupp.lsingle` for the stronger version as a linear map. -/ @[simps] def single_add_hom (a : α) : M →+ α →₀ M := ⟨single a, single_zero, λ _ _, single_add⟩ /-- Evaluation of a function `f : α →₀ M` at a point as an additive monoid homomorphism. See `finsupp.lapply` for the stronger version as a linear map. -/ @[simps apply] def apply_add_hom (a : α) : (α →₀ M) →+ M := ⟨λ g, g a, zero_apply, λ _ _, add_apply _ _ _⟩ lemma update_eq_single_add_erase (f : α →₀ M) (a : α) (b : M) : f.update a b = single a b + f.erase a := begin ext j, rcases eq_or_ne a j with rfl|h, { simp }, { simp [function.update_noteq h.symm, single_apply, h, erase_ne, h.symm] } end lemma update_eq_erase_add_single (f : α →₀ M) (a : α) (b : M) : f.update a b = f.erase a + single a b := begin ext j, rcases eq_or_ne a j with rfl|h, { simp }, { simp [function.update_noteq h.symm, single_apply, h, erase_ne, h.symm] } end lemma single_add_erase (a : α) (f : α →₀ M) : single a (f a) + f.erase a = f := by rw [←update_eq_single_add_erase, update_self] lemma erase_add_single (a : α) (f : α →₀ M) : f.erase a + single a (f a) = f := by rw [←update_eq_erase_add_single, update_self] @[simp] lemma erase_add (a : α) (f f' : α →₀ M) : erase a (f + f') = erase a f + erase a f' := begin ext s, by_cases hs : s = a, { rw [hs, add_apply, erase_same, erase_same, erase_same, add_zero] }, rw [add_apply, erase_ne hs, erase_ne hs, erase_ne hs, add_apply], end /-- `finsupp.erase` as an `add_monoid_hom`. -/ @[simps] def erase_add_hom (a : α) : (α →₀ M) →+ (α →₀ M) := { to_fun := erase a, map_zero' := erase_zero a, map_add' := erase_add a } @[elab_as_eliminator] protected theorem induction {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) : p f := suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction₂ {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) : p f := suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction_linear {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (hadd : ∀ f g : α →₀ M, p f → p g → p (f + g)) (hsingle : ∀ a b, p (single a b)) : p f := induction₂ f h0 (λ a b f _ _ w, hadd _ _ w (hsingle _ _)) @[simp] lemma add_closure_Union_range_single : add_submonoid.closure (⋃ a : α, set.range (single a : M → α →₀ M)) = ⊤ := top_unique $ λ x hx, finsupp.induction x (add_submonoid.zero_mem _) $ λ a b f ha hb hf, add_submonoid.add_mem _ (add_submonoid.subset_closure $ set.mem_Union.2 ⟨a, set.mem_range_self _⟩) hf /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. -/ lemma add_hom_ext [add_zero_class N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x y, f (single x y) = g (single x y)) : f = g := begin refine add_monoid_hom.eq_of_eq_on_mdense add_closure_Union_range_single (λ f hf, _), simp only [set.mem_Union, set.mem_range] at hf, rcases hf with ⟨x, y, rfl⟩, apply H end /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. We formulate this using equality of `add_monoid_hom`s so that `ext` tactic can apply a type-specific extensionality lemma after this one. E.g., if the fiber `M` is `ℕ` or `ℤ`, then it suffices to verify `f (single a 1) = g (single a 1)`. -/ @[ext] lemma add_hom_ext' [add_zero_class N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x, f.comp (single_add_hom x) = g.comp (single_add_hom x)) : f = g := add_hom_ext $ λ x, add_monoid_hom.congr_fun (H x) lemma mul_hom_ext [mul_one_class N] ⦃f g : multiplicative (α →₀ M) →* N⦄ (H : ∀ x y, f (multiplicative.of_add $ single x y) = g (multiplicative.of_add $ single x y)) : f = g := monoid_hom.ext $ add_monoid_hom.congr_fun $ @add_hom_ext α M (additive N) _ _ f.to_additive'' g.to_additive'' H @[ext] lemma mul_hom_ext' [mul_one_class N] {f g : multiplicative (α →₀ M) →* N} (H : ∀ x, f.comp (single_add_hom x).to_multiplicative = g.comp (single_add_hom x).to_multiplicative) : f = g := mul_hom_ext $ λ x, monoid_hom.congr_fun (H x) lemma map_range_add [add_zero_class N] {f : M → N} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ M) : map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ := ext $ λ a, by simp only [hf', add_apply, map_range_apply] /-- Bundle `emb_domain f` as an additive map from `α →₀ M` to `β →₀ M`. -/ @[simps] def emb_domain.add_monoid_hom (f : α ↪ β) : (α →₀ M) →+ (β →₀ M) := { to_fun := λ v, emb_domain f v, map_zero' := by simp, map_add' := λ v w, begin ext b, by_cases h : b ∈ set.range f, { rcases h with ⟨a, rfl⟩, simp, }, { simp [emb_domain_notin_range, h], }, end, } @[simp] lemma emb_domain_add (f : α ↪ β) (v w : α →₀ M) : emb_domain f (v + w) = emb_domain f v + emb_domain f w := (emb_domain.add_monoid_hom f).map_add v w end add_zero_class section add_monoid variables [add_monoid M] instance : add_monoid (α →₀ M) := { add_monoid . zero := 0, add := (+), add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _, nsmul := λ n v, v.map_range ((•) n) (nsmul_zero _), nsmul_zero' := λ v, by { ext i, simp }, nsmul_succ' := λ n v, by { ext i, simp [nat.succ_eq_one_add, add_nsmul] }, .. finsupp.add_zero_class } end add_monoid end finsupp @[to_additive] lemma mul_equiv.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N ≃* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ @[to_additive] lemma monoid_hom.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N →* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ lemma ring_hom.map_finsupp_sum [has_zero M] [semiring R] [semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.sum g) = f.sum (λ a b, h (g a b)) := h.map_sum _ _ lemma ring_hom.map_finsupp_prod [has_zero M] [comm_semiring R] [comm_semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ @[to_additive] lemma monoid_hom.coe_finsupp_prod [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) : ⇑(f.prod g) = f.prod (λ i fi, g i fi) := monoid_hom.coe_prod _ _ @[simp, to_additive] lemma monoid_hom.finsupp_prod_apply [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) (x : N) : f.prod g x = f.prod (λ i fi, g i fi x) := monoid_hom.finset_prod_apply _ _ _ namespace finsupp instance [add_comm_monoid M] : add_comm_monoid (α →₀ M) := { add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _, .. finsupp.add_monoid } instance [add_group G] : has_sub (α →₀ G) := ⟨zip_with has_sub.sub (sub_zero _)⟩ instance [add_group G] : add_group (α →₀ G) := { neg := map_range (has_neg.neg) neg_zero, sub := has_sub.sub, sub_eq_add_neg := λ x y, ext (λ i, sub_eq_add_neg _ _), add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _, gsmul := λ n v, v.map_range ((•) n) (gsmul_zero _), gsmul_zero' := λ v, by { ext i, simp }, gsmul_succ' := λ n v, by { ext i, simp [nat.succ_eq_one_add, add_gsmul] }, gsmul_neg' := λ n v, by { ext i, simp only [nat.succ_eq_add_one, map_range_apply, gsmul_neg_succ_of_nat, int.coe_nat_succ, neg_inj, add_gsmul, add_nsmul, one_gsmul, gsmul_coe_nat, one_nsmul] }, .. finsupp.add_monoid } instance [add_comm_group G] : add_comm_group (α →₀ G) := { add_comm := add_comm, ..finsupp.add_group } lemma single_multiset_sum [add_comm_monoid M] (s : multiset M) (a : α) : single a s.sum = (s.map (single a)).sum := multiset.induction_on s single_zero $ λ a s ih, by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons] lemma single_finset_sum [add_comm_monoid M] (s : finset ι) (f : ι → M) (a : α) : single a (∑ b in s, f b) = ∑ b in s, single a (f b) := begin transitivity, apply single_multiset_sum, rw [multiset.map_map], refl end lemma single_sum [has_zero M] [add_comm_monoid N] (s : ι →₀ M) (f : ι → M → N) (a : α) : single a (s.sum f) = s.sum (λd c, single a (f d c)) := single_finset_sum _ _ _ @[to_additive] lemma prod_neg_index [add_group G] [comm_monoid M] {g : α →₀ G} {h : α → G → M} (h0 : ∀a, h a 0 = 1) : (-g).prod h = g.prod (λa b, h a (- b)) := prod_map_range_index h0 @[simp] lemma coe_neg [add_group G] (g : α →₀ G) : ⇑(-g) = -g := rfl lemma neg_apply [add_group G] (g : α →₀ G) (a : α) : (- g) a = - g a := rfl @[simp] lemma coe_sub [add_group G] (g₁ g₂ : α →₀ G) : ⇑(g₁ - g₂) = g₁ - g₂ := rfl lemma sub_apply [add_group G] (g₁ g₂ : α →₀ G) (a : α) : (g₁ - g₂) a = g₁ a - g₂ a := rfl @[simp] lemma support_neg [add_group G] {f : α →₀ G} : support (-f) = support f := finset.subset.antisymm support_map_range (calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm ... ⊆ support (- f) : support_map_range) lemma erase_eq_sub_single [add_group G] (f : α →₀ G) (a : α) : f.erase a = f - single a (f a) := begin ext a', rcases eq_or_ne a a' with rfl|h, { simp }, { simp [erase_ne h.symm, single_eq_of_ne h] } end lemma update_eq_sub_add_single [add_group G] (f : α →₀ G) (a : α) (b : G) : f.update a b = f - single a (f a) + single a b := by rw [update_eq_erase_add_single, erase_eq_sub_single] @[simp] lemma sum_apply [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → β →₀ N} {a₂ : β} : (f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) := (apply_add_hom a₂ : (β →₀ N) →+ _).map_sum _ _ lemma support_sum [decidable_eq β] [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → (β →₀ N)} : (f.sum g).support ⊆ f.support.bUnion (λa, (g a (f a)).support) := have ∀ c, f.sum (λ a b, g a b c) ≠ 0 → (∃ a, f a ≠ 0 ∧ ¬ (g a (f a)) c = 0), from assume a₁ h, let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨a, mem_support_iff.mp ha, ne⟩, by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bUnion, sum_apply, exists_prop] @[simp] lemma sum_zero [has_zero M] [add_comm_monoid N] {f : α →₀ M} : f.sum (λa b, (0 : N)) = 0 := finset.sum_const_zero @[simp, to_additive] lemma prod_mul [has_zero M] [comm_monoid N] {f : α →₀ M} {h₁ h₂ : α → M → N} : f.prod (λa b, h₁ a b * h₂ a b) = f.prod h₁ * f.prod h₂ := finset.prod_mul_distrib @[simp, to_additive] lemma prod_inv [has_zero M] [comm_group G] {f : α →₀ M} {h : α → M → G} : f.prod (λa b, (h a b)⁻¹) = (f.prod h)⁻¹ := (((monoid_hom.id G)⁻¹).map_prod _ _).symm @[simp] lemma sum_sub [has_zero M] [add_comm_group G] {f : α →₀ M} {h₁ h₂ : α → M → G} : f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ := finset.sum_sub_distrib @[to_additive] lemma prod_add_index [add_comm_monoid M] [comm_monoid N] {f g : α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := have hf : f.prod h = ∏ a in f.support ∪ g.support, h a (f a), from f.prod_of_support_subset (subset_union_left _ _) _ $ λ a ha, h_zero a, have hg : g.prod h = ∏ a in f.support ∪ g.support, h a (g a), from g.prod_of_support_subset (subset_union_right _ _) _ $ λ a ha, h_zero a, have hfg : (f + g).prod h = ∏ a in f.support ∪ g.support, h a ((f + g) a), from (f + g).prod_of_support_subset support_add _ $ λ a ha, h_zero a, by simp only [*, add_apply, prod_mul_distrib] @[simp] lemma sum_add_index' [add_comm_monoid M] [add_comm_monoid N] {f g : α →₀ M} (h : α → M →+ N) : (f + g).sum (λ x, h x) = f.sum (λ x, h x) + g.sum (λ x, h x) := sum_add_index (λ a, (h a).map_zero) (λ a, (h a).map_add) @[simp] lemma prod_add_index' [add_comm_monoid M] [comm_monoid N] {f g : α →₀ M} (h : α → multiplicative M →* N) : (f + g).prod (λ a b, h a (multiplicative.of_add b)) = f.prod (λ a b, h a (multiplicative.of_add b)) * g.prod (λ a b, h a (multiplicative.of_add b)) := prod_add_index (λ a, (h a).map_one) (λ a, (h a).map_mul) /-- The canonical isomorphism between families of additive monoid homomorphisms `α → (M →+ N)` and monoid homomorphisms `(α →₀ M) →+ N`. -/ def lift_add_hom [add_comm_monoid M] [add_comm_monoid N] : (α → M →+ N) ≃+ ((α →₀ M) →+ N) := { to_fun := λ F, { to_fun := λ f, f.sum (λ x, F x), map_zero' := finset.sum_empty, map_add' := λ _ _, sum_add_index (λ x, (F x).map_zero) (λ x, (F x).map_add) }, inv_fun := λ F x, F.comp $ single_add_hom x, left_inv := λ F, by { ext, simp }, right_inv := λ F, by { ext, simp }, map_add' := λ F G, by { ext, simp } } @[simp] lemma lift_add_hom_apply [add_comm_monoid M] [add_comm_monoid N] (F : α → M →+ N) (f : α →₀ M) : lift_add_hom F f = f.sum (λ x, F x) := rfl @[simp] lemma lift_add_hom_symm_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) : lift_add_hom.symm F x = F.comp (single_add_hom x) := rfl lemma lift_add_hom_symm_apply_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) (y : M) : lift_add_hom.symm F x y = F (single x y) := rfl @[simp] lemma lift_add_hom_single_add_hom [add_comm_monoid M] : lift_add_hom (single_add_hom : α → M →+ α →₀ M) = add_monoid_hom.id _ := lift_add_hom.to_equiv.apply_eq_iff_eq_symm_apply.2 rfl @[simp] lemma sum_single [add_comm_monoid M] (f : α →₀ M) : f.sum single = f := add_monoid_hom.congr_fun lift_add_hom_single_add_hom f @[simp] lemma lift_add_hom_apply_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) (b : M) : lift_add_hom f (single a b) = f a b := sum_single_index (f a).map_zero @[simp] lemma lift_add_hom_comp_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) : (lift_add_hom f).comp (single_add_hom a) = f a := add_monoid_hom.ext $ λ b, lift_add_hom_apply_single f a b lemma comp_lift_add_hom [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] (g : N →+ P) (f : α → M →+ N) : g.comp (lift_add_hom f) = lift_add_hom (λ a, g.comp (f a)) := lift_add_hom.symm_apply_eq.1 $ funext $ λ a, by rw [lift_add_hom_symm_apply, add_monoid_hom.comp_assoc, lift_add_hom_comp_single] lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β} {h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) : (f - g).sum h = f.sum h - g.sum h := (lift_add_hom (λ a, add_monoid_hom.of_map_sub (h a) (h_sub a))).map_sub f g @[to_additive] lemma prod_emb_domain [has_zero M] [comm_monoid N] {v : α →₀ M} {f : α ↪ β} {g : β → M → N} : (v.emb_domain f).prod g = v.prod (λ a b, g (f a) b) := begin rw [prod, prod, support_emb_domain, finset.prod_map], simp_rw emb_domain_apply, end @[to_additive] lemma prod_finset_sum_index [add_comm_monoid M] [comm_monoid N] {s : finset ι} {g : ι → α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : ∏ i in s, (g i).prod h = (∑ i in s, g i).prod h := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add] @[to_additive] lemma prod_sum_index [add_comm_monoid M] [add_comm_monoid N] [comm_monoid P] {f : α →₀ M} {g : α → M → β →₀ N} {h : β → N → P} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f.sum g).prod h = f.prod (λa b, (g a b).prod h) := (prod_finset_sum_index h_zero h_add).symm lemma multiset_sum_sum_index [add_comm_monoid M] [add_comm_monoid N] (f : multiset (α →₀ M)) (h : α → M → N) (h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : M), h a (b₁ + b₂) = h a b₁ + h a b₂) : (f.sum.sum h) = (f.map $ λg:α →₀ M, g.sum h).sum := multiset.induction_on f rfl $ assume a s ih, by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih] lemma support_sum_eq_bUnion {α : Type*} {ι : Type*} {M : Type*} [add_comm_monoid M] {g : ι → α →₀ M} (s : finset ι) (h : ∀ i₁ i₂, i₁ ≠ i₂ → disjoint (g i₁).support (g i₂).support) : (∑ i in s, g i).support = s.bUnion (λ i, (g i).support) := begin apply finset.induction_on s, { simp }, { intros i s hi, simp only [hi, sum_insert, not_false_iff, bUnion_insert], intro hs, rw [finsupp.support_add_eq, hs], rw [hs], intros x hx, simp only [mem_bUnion, exists_prop, inf_eq_inter, ne.def, mem_inter] at hx, obtain ⟨hxi, j, hj, hxj⟩ := hx, have hn : i ≠ j := λ H, hi (H.symm ▸ hj), apply h _ _ hn, simp [hxi, hxj] } end lemma multiset_map_sum [has_zero M] {f : α →₀ M} {m : β → γ} {h : α → M → multiset β} : multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) := (multiset.map_add_monoid_hom m).map_sum _ f.support lemma multiset_sum_sum [has_zero M] [add_comm_monoid N] {f : α →₀ M} {h : α → M → multiset N} : multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) := (multiset.sum_add_monoid_hom : multiset N →+ N).map_sum _ f.support section map_range section equiv variables [has_zero M] [has_zero N] [has_zero P] /-- `finsupp.map_range` as an equiv. -/ @[simps apply] def map_range.equiv (f : M ≃ N) (hf : f 0 = 0) (hf' : f.symm 0 = 0) : (α →₀ M) ≃ (α →₀ N) := { to_fun := (map_range f hf : (α →₀ M) → (α →₀ N)), inv_fun := (map_range f.symm hf' : (α →₀ N) → (α →₀ M)), left_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw equiv.symm_comp_self, { exact map_range_id _ }, { refl }, end, right_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw equiv.self_comp_symm, { exact map_range_id _ }, { refl }, end } @[simp] lemma map_range.equiv_refl : map_range.equiv (equiv.refl M) rfl rfl = equiv.refl (α →₀ M) := equiv.ext map_range_id lemma map_range.equiv_trans (f : M ≃ N) (hf : f 0 = 0) (hf') (f₂ : N ≃ P) (hf₂ : f₂ 0 = 0) (hf₂') : (map_range.equiv (f.trans f₂) (by rw [equiv.trans_apply, hf, hf₂]) (by rw [equiv.symm_trans_apply, hf₂', hf']) : (α →₀ _) ≃ _) = (map_range.equiv f hf hf').trans (map_range.equiv f₂ hf₂ hf₂') := equiv.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.equiv_symm (f : M ≃ N) (hf hf') : ((map_range.equiv f hf hf').symm : (α →₀ _) ≃ _) = map_range.equiv f.symm hf' hf := equiv.ext $ λ x, rfl end equiv section zero_hom variables [has_zero M] [has_zero N] [has_zero P] /-- Composition with a fixed zero-preserving homomorphism is itself an zero-preserving homomorphism on functions. -/ @[simps] def map_range.zero_hom (f : zero_hom M N) : zero_hom (α →₀ M) (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), map_zero' := map_range_zero } @[simp] lemma map_range.zero_hom_id : map_range.zero_hom (zero_hom.id M) = zero_hom.id (α →₀ M) := zero_hom.ext map_range_id lemma map_range.zero_hom_comp (f : zero_hom N P) (f₂ : zero_hom M N) : (map_range.zero_hom (f.comp f₂) : zero_hom (α →₀ _) _) = (map_range.zero_hom f).comp (map_range.zero_hom f₂) := zero_hom.ext $ map_range_comp _ _ _ _ _ end zero_hom section add_monoid_hom variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] /-- Composition with a fixed additive homomorphism is itself an additive homomorphism on functions. -/ @[simps] def map_range.add_monoid_hom (f : M →+ N) : (α →₀ M) →+ (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), map_zero' := map_range_zero, map_add' := λ a b, map_range_add f.map_add _ _ } @[simp] lemma map_range.add_monoid_hom_id : map_range.add_monoid_hom (add_monoid_hom.id M) = add_monoid_hom.id (α →₀ M) := add_monoid_hom.ext map_range_id lemma map_range.add_monoid_hom_comp (f : N →+ P) (f₂ : M →+ N) : (map_range.add_monoid_hom (f.comp f₂) : (α →₀ _) →+ _) = (map_range.add_monoid_hom f).comp (map_range.add_monoid_hom f₂) := add_monoid_hom.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.add_monoid_hom_to_zero_hom (f : M →+ N) : (map_range.add_monoid_hom f).to_zero_hom = (map_range.zero_hom f.to_zero_hom : zero_hom (α →₀ _) _) := zero_hom.ext $ λ _, rfl lemma map_range_multiset_sum (f : M →+ N) (m : multiset (α →₀ M)) : map_range f f.map_zero m.sum = (m.map $ λx, map_range f f.map_zero x).sum := (map_range.add_monoid_hom f : (α →₀ _) →+ _).map_multiset_sum _ lemma map_range_finset_sum (f : M →+ N) (s : finset ι) (g : ι → (α →₀ M)) : map_range f f.map_zero (∑ x in s, g x) = ∑ x in s, map_range f f.map_zero (g x) := (map_range.add_monoid_hom f : (α →₀ _) →+ _).map_sum _ _ /-- `finsupp.map_range.add_monoid_hom` as an equiv. -/ @[simps apply] def map_range.add_equiv (f : M ≃+ N) : (α →₀ M) ≃+ (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), inv_fun := (map_range f.symm f.symm.map_zero : (α →₀ N) → (α →₀ M)), left_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw add_equiv.symm_comp_self, { exact map_range_id _ }, { refl }, end, right_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw add_equiv.self_comp_symm, { exact map_range_id _ }, { refl }, end, ..(map_range.add_monoid_hom f.to_add_monoid_hom) } @[simp] lemma map_range.add_equiv_refl : map_range.add_equiv (add_equiv.refl M) = add_equiv.refl (α →₀ M) := add_equiv.ext map_range_id lemma map_range.add_equiv_trans (f : M ≃+ N) (f₂ : N ≃+ P) : (map_range.add_equiv (f.trans f₂) : (α →₀ _) ≃+ _) = (map_range.add_equiv f).trans (map_range.add_equiv f₂) := add_equiv.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.add_equiv_symm (f : M ≃+ N) : ((map_range.add_equiv f).symm : (α →₀ _) ≃+ _) = map_range.add_equiv f.symm := add_equiv.ext $ λ x, rfl @[simp] lemma map_range.add_equiv_to_add_monoid_hom (f : M ≃+ N) : (map_range.add_equiv f : (α →₀ _) ≃+ _).to_add_monoid_hom = (map_range.add_monoid_hom f.to_add_monoid_hom : (α →₀ _) →+ _) := add_monoid_hom.ext $ λ _, rfl @[simp] lemma map_range.add_equiv_to_equiv (f : M ≃+ N) : (map_range.add_equiv f).to_equiv = (map_range.equiv f.to_equiv f.map_zero f.symm.map_zero : (α →₀ _) ≃ _) := equiv.ext $ λ _, rfl end add_monoid_hom end map_range /-! ### Declarations about `map_domain` -/ section map_domain variables [add_comm_monoid M] {v v₁ v₂ : α →₀ M} /-- Given `f : α → β` and `v : α →₀ M`, `map_domain f v : β →₀ M` is the finitely supported function whose value at `a : β` is the sum of `v x` over all `x` such that `f x = a`. -/ def map_domain (f : α → β) (v : α →₀ M) : β →₀ M := v.sum $ λa, single (f a) lemma map_domain_apply {f : α → β} (hf : function.injective f) (x : α →₀ M) (a : α) : map_domain f x (f a) = x a := begin rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same], { assume b _ hba, exact single_eq_of_ne (hf.ne hba) }, { assume h, rw [not_mem_support_iff.1 h, single_zero, zero_apply] } end lemma map_domain_notin_range {f : α → β} (x : α →₀ M) (a : β) (h : a ∉ set.range f) : map_domain f x a = 0 := begin rw [map_domain, sum_apply, sum], exact finset.sum_eq_zero (assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _) end @[simp] lemma map_domain_id : map_domain id v = v := sum_single _ lemma map_domain_comp {f : α → β} {g : β → γ} : map_domain (g ∘ f) v = map_domain g (map_domain f v) := begin refine ((sum_sum_index _ _).trans _).symm, { intros, exact single_zero }, { intros, exact single_add }, refine sum_congr rfl (λ _ _, sum_single_index _), { exact single_zero } end @[simp] lemma map_domain_single {f : α → β} {a : α} {b : M} : map_domain f (single a b) = single (f a) b := sum_single_index single_zero @[simp] lemma map_domain_zero {f : α → β} : map_domain f (0 : α →₀ M) = (0 : β →₀ M) := sum_zero_index lemma map_domain_congr {f g : α → β} (h : ∀x∈v.support, f x = g x) : v.map_domain f = v.map_domain g := finset.sum_congr rfl $ λ _ H, by simp only [h _ H] lemma map_domain_add {f : α → β} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ := sum_add_index (λ _, single_zero) (λ _ _ _, single_add) @[simp] lemma map_domain_equiv_apply {f : α ≃ β} (x : α →₀ M) (a : β) : map_domain f x a = x (f.symm a) := begin conv_lhs { rw ←f.apply_symm_apply a }, exact map_domain_apply f.injective _ _, end /-- `finsupp.map_domain` is an `add_monoid_hom`. -/ @[simps] def map_domain.add_monoid_hom (f : α → β) : (α →₀ M) →+ (β →₀ M) := { to_fun := map_domain f, map_zero' := map_domain_zero, map_add' := λ _ _, map_domain_add} @[simp] lemma map_domain.add_monoid_hom_id : map_domain.add_monoid_hom id = add_monoid_hom.id (α →₀ M) := add_monoid_hom.ext $ λ _, map_domain_id lemma map_domain.add_monoid_hom_comp (f : β → γ) (g : α → β) : (map_domain.add_monoid_hom (f ∘ g) : (α →₀ M) →+ (γ →₀ M)) = (map_domain.add_monoid_hom f).comp (map_domain.add_monoid_hom g) := add_monoid_hom.ext $ λ _, map_domain_comp lemma map_domain_finset_sum {f : α → β} {s : finset ι} {v : ι → α →₀ M} : map_domain f (∑ i in s, v i) = ∑ i in s, map_domain f (v i) := (map_domain.add_monoid_hom f : (α →₀ M) →+ β →₀ M).map_sum _ _ lemma map_domain_sum [has_zero N] {f : α → β} {s : α →₀ N} {v : α → N → α →₀ M} : map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) := (map_domain.add_monoid_hom f : (α →₀ M) →+ β →₀ M).map_finsupp_sum _ _ lemma map_domain_support [decidable_eq β] {f : α → β} {s : α →₀ M} : (s.map_domain f).support ⊆ s.support.image f := finset.subset.trans support_sum $ finset.subset.trans (finset.bUnion_mono $ assume a ha, support_single_subset) $ by rw [finset.bUnion_singleton]; exact subset.refl _ @[to_additive] lemma prod_map_domain_index [comm_monoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (h_zero : ∀b, h b 0 = 1) (h_add : ∀b m₁ m₂, h b (m₁ + m₂) = h b m₁ * h b m₂) : (map_domain f s).prod h = s.prod (λa m, h (f a) m) := (prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _) /-- A version of `sum_map_domain_index` that takes a bundled `add_monoid_hom`, rather than separate linearity hypotheses. -/ -- Note that in `prod_map_domain_index`, `M` is still an additive monoid, -- so there is no analogous version in terms of `monoid_hom`. @[simp] lemma sum_map_domain_index_add_monoid_hom [add_comm_monoid N] {f : α → β} {s : α →₀ M} (h : β → M →+ N) : (map_domain f s).sum (λ b m, h b m) = s.sum (λ a m, h (f a) m) := @sum_map_domain_index _ _ _ _ _ _ _ _ (λ b m, h b m) (λ b, (h b).map_zero) (λ b m₁ m₂, (h b).map_add _ _) lemma emb_domain_eq_map_domain (f : α ↪ β) (v : α →₀ M) : emb_domain f v = map_domain f v := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a, rfl⟩, rw [map_domain_apply f.injective, emb_domain_apply] }, { rw [map_domain_notin_range, emb_domain_notin_range]; assumption } end @[to_additive] lemma prod_map_domain_index_inj [comm_monoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (hf : function.injective f) : (s.map_domain f).prod h = s.prod (λa b, h (f a) b) := by rw [←function.embedding.coe_fn_mk f hf, ←emb_domain_eq_map_domain, prod_emb_domain] lemma map_domain_injective {f : α → β} (hf : function.injective f) : function.injective (map_domain f : (α →₀ M) → (β →₀ M)) := begin assume v₁ v₂ eq, ext a, have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq }, rwa [map_domain_apply hf, map_domain_apply hf] at this, end lemma map_domain.add_monoid_hom_comp_map_range [add_comm_monoid N] (f : α → β) (g : M →+ N) : (map_domain.add_monoid_hom f).comp (map_range.add_monoid_hom g) = (map_range.add_monoid_hom g).comp (map_domain.add_monoid_hom f) := by { ext, simp } /-- When `g` preserves addition, `map_range` and `map_domain` commute. -/ lemma map_domain_map_range [add_comm_monoid N] (f : α → β) (v : α →₀ M) (g : M → N) (h0 : g 0 = 0) (hadd : ∀ x y, g (x + y) = g x + g y) : map_domain f (map_range g h0 v) = map_range g h0 (map_domain f v) := let g' : M →+ N := { to_fun := g, map_zero' := h0, map_add' := hadd} in add_monoid_hom.congr_fun (map_domain.add_monoid_hom_comp_map_range f g') v end map_domain /-! ### Declarations about `comap_domain` -/ section comap_domain /-- Given `f : α → β`, `l : β →₀ M` and a proof `hf` that `f` is injective on the preimage of `l.support`, `comap_domain f l hf` is the finitely supported function from `α` to `M` given by composing `l` with `f`. -/ def comap_domain [has_zero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑l.support)) : α →₀ M := { support := l.support.preimage f hf, to_fun := (λ a, l (f a)), mem_support_to_fun := begin intros a, simp only [finset.mem_def.symm, finset.mem_preimage], exact l.mem_support_to_fun (f a), end } @[simp] lemma comap_domain_apply [has_zero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑l.support)) (a : α) : comap_domain f l hf a = l (f a) := rfl lemma sum_comap_domain [has_zero M] [add_comm_monoid N] (f : α → β) (l : β →₀ M) (g : β → M → N) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) : (comap_domain f l hf.inj_on).sum (g ∘ f) = l.sum g := begin simp only [sum, comap_domain_apply, (∘)], simp [comap_domain, finset.sum_preimage_of_bij f _ _ (λ x, g x (l x))], end lemma eq_zero_of_comap_domain_eq_zero [add_comm_monoid M] (f : α → β) (l : β →₀ M) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) : comap_domain f l hf.inj_on = 0 → l = 0 := begin rw [← support_eq_empty, ← support_eq_empty, comap_domain], simp only [finset.ext_iff, finset.not_mem_empty, iff_false, mem_preimage], assume h a ha, cases hf.2.2 ha with b hb, exact h b (hb.2.symm ▸ ha) end lemma map_domain_comap_domain [add_comm_monoid M] (f : α → β) (l : β →₀ M) (hf : function.injective f) (hl : ↑l.support ⊆ set.range f): map_domain f (comap_domain f l (hf.inj_on _)) = l := begin ext a, by_cases h_cases: a ∈ set.range f, { rcases set.mem_range.1 h_cases with ⟨b, hb⟩, rw [hb.symm, map_domain_apply hf, comap_domain_apply] }, { rw map_domain_notin_range _ _ h_cases, by_contra h_contr, apply h_cases (hl $ finset.mem_coe.2 $ mem_support_iff.2 $ λ h, h_contr h.symm) } end end comap_domain section option /-- Restrict a finitely supported function on `option α` to a finitely supported function on `α`. -/ def some [has_zero M] (f : option α →₀ M) : α →₀ M := f.comap_domain option.some (λ _, by simp) @[simp] lemma some_apply [has_zero M] (f : option α →₀ M) (a : α) : f.some a = f (option.some a) := rfl @[simp] lemma some_zero [has_zero M] : (0 : option α →₀ M).some = 0 := by { ext, simp, } @[simp] lemma some_add [add_comm_monoid M] (f g : option α →₀ M) : (f + g).some = f.some + g.some := by { ext, simp, } @[simp] lemma some_single_none [has_zero M] (m : M) : (single none m : option α →₀ M).some = 0 := by { ext, simp, } @[simp] lemma some_single_some [has_zero M] (a : α) (m : M) : (single (option.some a) m : option α →₀ M).some = single a m := by { ext b, simp [single_apply], } @[to_additive] lemma prod_option_index [add_comm_monoid M] [comm_monoid N] (f : option α →₀ M) (b : option α → M → N) (h_zero : ∀ o, b o 0 = 1) (h_add : ∀ o m₁ m₂, b o (m₁ + m₂) = b o m₁ * b o m₂) : f.prod b = b none (f none) * f.some.prod (λ a, b (option.some a)) := begin apply induction_linear f, { simp [h_zero], }, { intros f₁ f₂ h₁ h₂, rw [finsupp.prod_add_index, h₁, h₂, some_add, finsupp.prod_add_index], simp only [h_add, pi.add_apply, finsupp.coe_add], rw mul_mul_mul_comm, all_goals { simp [h_zero, h_add], }, }, { rintros (_|a) m; simp [h_zero, h_add], } end lemma sum_option_index_smul [semiring R] [add_comm_monoid M] [module R M] (f : option α →₀ R) (b : option α → M) : f.sum (λ o r, r • b o) = f none • b none + f.some.sum (λ a r, r • b (option.some a)) := f.sum_option_index _ (λ _, zero_smul _ _) (λ _ _ _, add_smul _ _ _) end option /-! ### Declarations about `equiv_congr_left` -/ section equiv_congr_left variable [has_zero M] /-- Given `f : α ≃ β`, we can map `l : α →₀ M` to `equiv_map_domain f l : β →₀ M` (computably) by mapping the support forwards and the function backwards. -/ def equiv_map_domain (f : α ≃ β) (l : α →₀ M) : β →₀ M := { support := l.support.map f.to_embedding, to_fun := λ a, l (f.symm a), mem_support_to_fun := λ a, by simp only [finset.mem_map_equiv, mem_support_to_fun]; refl } @[simp] lemma equiv_map_domain_apply (f : α ≃ β) (l : α →₀ M) (b : β) : equiv_map_domain f l b = l (f.symm b) := rfl lemma equiv_map_domain_symm_apply (f : α ≃ β) (l : β →₀ M) (a : α) : equiv_map_domain f.symm l a = l (f a) := rfl @[simp] lemma equiv_map_domain_refl (l : α →₀ M) : equiv_map_domain (equiv.refl _) l = l := by ext x; refl lemma equiv_map_domain_refl' : equiv_map_domain (equiv.refl _) = @id (α →₀ M) := by ext x; refl lemma equiv_map_domain_trans (f : α ≃ β) (g : β ≃ γ) (l : α →₀ M) : equiv_map_domain (f.trans g) l = equiv_map_domain g (equiv_map_domain f l) := by ext x; refl lemma equiv_map_domain_trans' (f : α ≃ β) (g : β ≃ γ) : @equiv_map_domain _ _ M _ (f.trans g) = equiv_map_domain g ∘ equiv_map_domain f := by ext x; refl @[simp] lemma equiv_map_domain_single (f : α ≃ β) (a : α) (b : M) : equiv_map_domain f (single a b) = single (f a) b := by ext x; simp only [single_apply, equiv.apply_eq_iff_eq_symm_apply, equiv_map_domain_apply]; congr @[simp] lemma equiv_map_domain_zero {f : α ≃ β} : equiv_map_domain f (0 : α →₀ M) = (0 : β →₀ M) := by ext x; simp only [equiv_map_domain_apply, coe_zero, pi.zero_apply] lemma equiv_map_domain_eq_map_domain {M} [add_comm_monoid M] (f : α ≃ β) (l : α →₀ M) : equiv_map_domain f l = map_domain f l := by ext x; simp [map_domain_equiv_apply] /-- Given `f : α ≃ β`, the finitely supported function spaces are also in bijection: `(α →₀ M) ≃ (β →₀ M)`. This is the finitely-supported version of `equiv.Pi_congr_left`. -/ def equiv_congr_left (f : α ≃ β) : (α →₀ M) ≃ (β →₀ M) := by refine ⟨equiv_map_domain f, equiv_map_domain f.symm, λ f, _, λ f, _⟩; ext x; simp only [equiv_map_domain_apply, equiv.symm_symm, equiv.symm_apply_apply, equiv.apply_symm_apply] @[simp] lemma equiv_congr_left_apply (f : α ≃ β) (l : α →₀ M) : equiv_congr_left f l = equiv_map_domain f l := rfl @[simp] lemma equiv_congr_left_symm (f : α ≃ β) : (@equiv_congr_left _ _ M _ f).symm = equiv_congr_left f.symm := rfl end equiv_congr_left /-! ### Declarations about `filter` -/ section filter section has_zero variables [has_zero M] (p : α → Prop) (f : α →₀ M) /-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/ def filter (p : α → Prop) (f : α →₀ M) : α →₀ M := { to_fun := λ a, if p a then f a else 0, support := f.support.filter (λ a, p a), mem_support_to_fun := λ a, by split_ifs; { simp only [h, mem_filter, mem_support_iff], tauto } } lemma filter_apply (a : α) [D : decidable (p a)] : f.filter p a = if p a then f a else 0 := by rw subsingleton.elim D; refl lemma filter_eq_indicator : ⇑(f.filter p) = set.indicator {x | p x} f := rfl @[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a := if_pos h @[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 := if_neg h @[simp] lemma support_filter [D : decidable_pred p] : (f.filter p).support = f.support.filter p := by rw subsingleton.elim D; refl lemma filter_zero : (0 : α →₀ M).filter p = 0 := by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty] @[simp] lemma filter_single_of_pos {a : α} {b : M} (h : p a) : (single a b).filter p = single a b := coe_fn_injective $ by simp [filter_eq_indicator, set.subset_def, mem_support_single, h] @[simp] lemma filter_single_of_neg {a : α} {b : M} (h : ¬ p a) : (single a b).filter p = 0 := ext $ by simp [filter_eq_indicator, single_apply_eq_zero, @imp.swap (p _), h] end has_zero lemma filter_pos_add_filter_neg [add_zero_class M] (f : α →₀ M) (p : α → Prop) : f.filter p + f.filter (λa, ¬ p a) = f := coe_fn_injective $ set.indicator_self_add_compl {x | p x} f end filter /-! ### Declarations about `frange` -/ section frange variables [has_zero M] /-- `frange f` is the image of `f` on the support of `f`. -/ def frange (f : α →₀ M) : finset M := finset.image f f.support theorem mem_frange {f : α →₀ M} {y : M} : y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y := finset.mem_image.trans ⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩, λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩ theorem zero_not_mem_frange {f : α →₀ M} : (0:M) ∉ f.frange := λ H, (mem_frange.1 H).1 rfl theorem frange_single {x : α} {y : M} : frange (single x y) ⊆ {y} := λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸ (by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc]) end frange /-! ### Declarations about `subtype_domain` -/ section subtype_domain section zero variables [has_zero M] {p : α → Prop} /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain (p : α → Prop) (f : α →₀ M) : (subtype p →₀ M) := ⟨f.support.subtype p, f ∘ coe, λ a, by simp only [mem_subtype, mem_support_iff]⟩ @[simp] lemma support_subtype_domain [D : decidable_pred p] {f : α →₀ M} : (subtype_domain p f).support = f.support.subtype p := by rw subsingleton.elim D; refl @[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ M} : (subtype_domain p v) a = v (a.val) := rfl @[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ M) = 0 := rfl lemma subtype_domain_eq_zero_iff' {f : α →₀ M} : f.subtype_domain p = 0 ↔ ∀ x, p x → f x = 0 := by simp_rw [← support_eq_empty, support_subtype_domain, subtype_eq_empty, not_mem_support_iff] lemma subtype_domain_eq_zero_iff {f : α →₀ M} (hf : ∀ x ∈ f.support , p x) : f.subtype_domain p = 0 ↔ f = 0 := subtype_domain_eq_zero_iff'.trans ⟨λ H, ext $ λ x, if hx : p x then H x hx else not_mem_support_iff.1 $ mt (hf x) hx, λ H x _, by simp [H]⟩ @[to_additive] lemma prod_subtype_domain_index [comm_monoid N] {v : α →₀ M} {h : α → M → N} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λa b, h a b) = v.prod h := prod_bij (λp _, p.val) (λ _, mem_subtype.1) (λ _ _, rfl) (λ _ _ _ _, subtype.eq) (λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩) end zero section add_zero_class variables [add_zero_class M] {p : α → Prop} {v v' : α →₀ M} @[simp] lemma subtype_domain_add {v v' : α →₀ M} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ _, rfl /-- `subtype_domain` but as an `add_monoid_hom`. -/ def subtype_domain_add_monoid_hom : (α →₀ M) →+ subtype p →₀ M := { to_fun := subtype_domain p, map_zero' := subtype_domain_zero, map_add' := λ _ _, subtype_domain_add } /-- `finsupp.filter` as an `add_monoid_hom`. -/ def filter_add_hom (p : α → Prop) : (α →₀ M) →+ (α →₀ M) := { to_fun := filter p, map_zero' := filter_zero p, map_add' := λ f g, coe_fn_injective $ set.indicator_add {x | p x} f g } @[simp] lemma filter_add {v v' : α →₀ M} : (v + v').filter p = v.filter p + v'.filter p := (filter_add_hom p).map_add v v' end add_zero_class section comm_monoid variables [add_comm_monoid M] {p : α → Prop} lemma subtype_domain_sum {s : finset ι} {h : ι → α →₀ M} : (∑ c in s, h c).subtype_domain p = ∑ c in s, (h c).subtype_domain p := (subtype_domain_add_monoid_hom : _ →+ subtype p →₀ M).map_sum _ s lemma subtype_domain_finsupp_sum [has_zero N] {s : β →₀ N} {h : β → N → α →₀ M} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum lemma filter_sum (s : finset ι) (f : ι → α →₀ M) : (∑ a in s, f a).filter p = ∑ a in s, filter p (f a) := (filter_add_hom p : (α →₀ M) →+ _).map_sum f s lemma filter_eq_sum (p : α → Prop) [D : decidable_pred p] (f : α →₀ M) : f.filter p = ∑ i in f.support.filter p, single i (f i) := (f.filter p).sum_single.symm.trans $ finset.sum_congr (by rw subsingleton.elim D; refl) $ λ x hx, by rw [filter_apply_pos _ _ (mem_filter.1 hx).2] end comm_monoid section group variables [add_group G] {p : α → Prop} {v v' : α →₀ G} @[simp] lemma subtype_domain_neg : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ _, rfl @[simp] lemma subtype_domain_sub : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ _, rfl @[simp] lemma single_neg {a : α} {b : G} : single a (-b) = -single a b := (single_add_hom a : G →+ _).map_neg b @[simp] lemma single_sub {a : α} {b₁ b₂ : G} : single a (b₁ - b₂) = single a b₁ - single a b₂ := (single_add_hom a : G →+ _).map_sub b₁ b₂ @[simp] lemma erase_neg (a : α) (f : α →₀ G) : erase a (-f) = -erase a f := (erase_add_hom a : (_ →₀ G) →+ _).map_neg f @[simp] lemma erase_sub (a : α) (f₁ f₂ : α →₀ G) : erase a (f₁ - f₂) = erase a f₁ - erase a f₂ := (erase_add_hom a : (_ →₀ G) →+ _).map_sub f₁ f₂ @[simp] lemma filter_neg (p : α → Prop) (f : α →₀ G) : filter p (-f) = -filter p f := (filter_add_hom p : (_ →₀ G) →+ _).map_neg f @[simp] lemma filter_sub (p : α → Prop) (f₁ f₂ : α →₀ G) : filter p (f₁ - f₂) = filter p f₁ - filter p f₂ := (filter_add_hom p : (_ →₀ G) →+ _).map_sub f₁ f₂ end group end subtype_domain /-! ### Declarations relating `finsupp` to `multiset` -/ section multiset /-- Given `f : α →₀ ℕ`, `f.to_multiset` is the multiset with multiplicities given by the values of `f` on the elements of `α`. We define this function as an `add_equiv`. -/ def to_multiset : (α →₀ ℕ) ≃+ multiset α := { to_fun := λ f, f.sum (λa n, n • {a}), inv_fun := λ s, ⟨s.to_finset, λ a, s.count a, λ a, by simp⟩, left_inv := λ f, ext $ λ a, by { simp only [sum, multiset.count_sum', multiset.count_singleton, mul_boole, coe_mk, multiset.mem_to_finset, iff_self, not_not, mem_support_iff, ite_eq_left_iff, ne.def, multiset.count_eq_zero, multiset.count_nsmul, finset.sum_ite_eq, ite_not], exact eq.symm }, right_inv := λ s, by simp only [sum, coe_mk, multiset.to_finset_sum_count_nsmul_eq], map_add' := λ f g, sum_add_index (λ a, zero_nsmul _) (λ a, add_nsmul _) } lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 := rfl lemma to_multiset_add (m n : α →₀ ℕ) : (m + n).to_multiset = m.to_multiset + n.to_multiset := to_multiset.map_add m n lemma to_multiset_apply (f : α →₀ ℕ) : f.to_multiset = f.sum (λ a n, n • {a}) := rfl @[simp] lemma to_multiset_symm_apply (s : multiset α) (x : α) : finsupp.to_multiset.symm s x = s.count x := rfl @[simp] lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = n • {a} := by rw [to_multiset_apply, sum_single_index]; apply zero_nsmul lemma to_multiset_sum {ι : Type*} {f : ι → α →₀ ℕ} (s : finset ι) : finsupp.to_multiset (∑ i in s, f i) = ∑ i in s, finsupp.to_multiset (f i) := add_equiv.map_sum _ _ _ lemma to_multiset_sum_single {ι : Type*} (s : finset ι) (n : ℕ) : finsupp.to_multiset (∑ i in s, single i n) = n • s.val := by simp_rw [to_multiset_sum, finsupp.to_multiset_single, sum_nsmul, sum_multiset_singleton] lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λa, id) := by simp [to_multiset_apply, add_monoid_hom.map_finsupp_sum, function.id_def] lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) : f.to_multiset.map g = (f.map_domain g).to_multiset := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single, to_multiset_single, to_multiset_add, to_multiset_single, ← multiset.coe_map_add_monoid_hom, (multiset.map_add_monoid_hom g).map_nsmul], refl } end @[simp] lemma prod_to_multiset [comm_monoid M] (f : M →₀ ℕ) : f.to_multiset.prod = f.prod (λa n, a ^ n) := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, finsupp.prod_add_index, finsupp.prod_single_index, multiset.prod_nsmul, multiset.prod_singleton], { exact pow_zero a }, { exact pow_zero }, { exact pow_add } } end @[simp] lemma to_finset_to_multiset [decidable_eq α] (f : α →₀ ℕ) : f.to_multiset.to_finset = f.support := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.to_finset_zero, support_zero] }, { assume a n f ha hn ih, rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq, support_single_ne_zero hn, multiset.to_finset_nsmul _ _ hn, multiset.to_finset_singleton], refine disjoint.mono_left support_single_subset _, rwa [finset.disjoint_singleton_left] } end @[simp] lemma count_to_multiset [decidable_eq α] (f : α →₀ ℕ) (a : α) : f.to_multiset.count a = f a := calc f.to_multiset.count a = f.sum (λx n, (n • {x} : multiset α).count a) : (multiset.count_add_monoid_hom a).map_sum _ f.support ... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_nsmul] ... = f a * ({a} : multiset α).count a : sum_eq_single _ (λ a' _ H, by simp only [multiset.count_singleton, if_false, H.symm, mul_zero]) (λ H, by simp only [not_mem_support_iff.1 H, zero_mul]) ... = f a : by rw [multiset.count_singleton_self, mul_one] lemma mem_support_multiset_sum [add_comm_monoid M] {s : multiset (α →₀ M)} (a : α) : a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ M).support := multiset.induction_on s false.elim begin assume f s ih ha, by_cases a ∈ f.support, { exact ⟨f, multiset.mem_cons_self _ _, h⟩ }, { simp only [multiset.sum_cons, mem_support_iff, add_apply, not_mem_support_iff.1 h, zero_add] at ha, rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩, exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ } end lemma mem_support_finset_sum [add_comm_monoid M] {s : finset ι} {h : ι → α →₀ M} (a : α) (ha : a ∈ (∑ c in s, h c).support) : ∃ c ∈ s, a ∈ (h c).support := let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in ⟨c, hc, eq.symm ▸ hfa⟩ @[simp] lemma mem_to_multiset (f : α →₀ ℕ) (i : α) : i ∈ f.to_multiset ↔ i ∈ f.support := by rw [← multiset.count_ne_zero, finsupp.count_to_multiset, finsupp.mem_support_iff] end multiset /-! ### Declarations about `curry` and `uncurry` -/ section curry_uncurry variables [add_comm_monoid M] [add_comm_monoid N] /-- Given a finitely supported function `f` from a product type `α × β` to `γ`, `curry f` is the "curried" finitely supported function from `α` to the type of finitely supported functions from `β` to `γ`. -/ protected def curry (f : (α × β) →₀ M) : α →₀ (β →₀ M) := f.sum $ λp c, single p.1 (single p.2 c) @[simp] lemma curry_apply (f : (α × β) →₀ M) (x : α) (y : β) : f.curry x y = f (x, y) := begin have : ∀ (b : α × β), single b.fst (single b.snd (f b)) x y = if b = (x, y) then f b else 0, { rintros ⟨b₁, b₂⟩, simp [single_apply, ite_apply, prod.ext_iff, ite_and], split_ifs; simp [single_apply, *] }, rw [finsupp.curry, sum_apply, sum_apply, finsupp.sum, finset.sum_eq_single, this, if_pos rfl], { intros b hb b_ne, rw [this b, if_neg b_ne] }, { intros hxy, rw [this (x, y), if_pos rfl, not_mem_support_iff.mp hxy] } end lemma sum_curry_index (f : (α × β) →₀ M) (g : α → β → M → N) (hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) : f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) := begin rw [finsupp.curry], transitivity, { exact sum_sum_index (assume a, sum_zero_index) (assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) }, congr, funext p c, transitivity, { exact sum_single_index sum_zero_index }, exact sum_single_index (hg₀ _ _) end /-- Given a finitely supported function `f` from `α` to the type of finitely supported functions from `β` to `M`, `uncurry f` is the "uncurried" finitely supported function from `α × β` to `M`. -/ protected def uncurry (f : α →₀ (β →₀ M)) : (α × β) →₀ M := f.sum $ λa g, g.sum $ λb c, single (a, b) c /-- `finsupp_prod_equiv` defines the `equiv` between `((α × β) →₀ M)` and `(α →₀ (β →₀ M))` given by currying and uncurrying. -/ def finsupp_prod_equiv : ((α × β) →₀ M) ≃ (α →₀ (β →₀ M)) := by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [ finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single] lemma filter_curry (f : α × β →₀ M) (p : α → Prop) : (f.filter (λa:α×β, p a.1)).curry = f.curry.filter p := begin rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum, filter_sum, support_filter, sum_filter], refine finset.sum_congr rfl _, rintros ⟨a₁, a₂⟩ ha, dsimp only, split_ifs, { rw [filter_apply_pos, filter_single_of_pos]; exact h }, { rwa [filter_single_of_neg] } end lemma support_curry [decidable_eq α] (f : α × β →₀ M) : f.curry.support ⊆ f.support.image prod.fst := begin rw ← finset.bUnion_singleton, refine finset.subset.trans support_sum _, refine finset.bUnion_mono (assume a _, support_single_subset) end end curry_uncurry section sum /-- `finsupp.sum_elim f g` maps `inl x` to `f x` and `inr y` to `g y`. -/ def sum_elim {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) : α ⊕ β →₀ γ := on_finset ((f.support.map ⟨_, sum.inl_injective⟩) ∪ g.support.map ⟨_, sum.inr_injective⟩) (sum.elim f g) (λ ab h, by { cases ab with a b; simp only [sum.elim_inl, sum.elim_inr] at h; simpa }) @[simp] lemma coe_sum_elim {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) : ⇑(sum_elim f g) = sum.elim f g := rfl lemma sum_elim_apply {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : α ⊕ β) : sum_elim f g x = sum.elim f g x := rfl lemma sum_elim_inl {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : α) : sum_elim f g (sum.inl x) = f x := rfl lemma sum_elim_inr {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : β) : sum_elim f g (sum.inr x) = g x := rfl /-- The equivalence between `(α ⊕ β) →₀ γ` and `(α →₀ γ) × (β →₀ γ)`. This is the `finsupp` version of `equiv.sum_arrow_equiv_prod_arrow`. -/ @[simps apply symm_apply] def sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] : ((α ⊕ β) →₀ γ) ≃ (α →₀ γ) × (β →₀ γ) := { to_fun := λ f, ⟨f.comap_domain sum.inl (sum.inl_injective.inj_on _), f.comap_domain sum.inr (sum.inr_injective.inj_on _)⟩, inv_fun := λ fg, sum_elim fg.1 fg.2, left_inv := λ f, by { ext ab, cases ab with a b; simp }, right_inv := λ fg, by { ext; simp } } lemma fst_sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] (f : (α ⊕ β) →₀ γ) (x : α) : (sum_finsupp_equiv_prod_finsupp f).1 x = f (sum.inl x) := rfl lemma snd_sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] (f : (α ⊕ β) →₀ γ) (y : β) : (sum_finsupp_equiv_prod_finsupp f).2 y = f (sum.inr y) := rfl lemma sum_finsupp_equiv_prod_finsupp_symm_inl {α β γ : Type*} [has_zero γ] (fg : (α →₀ γ) × (β →₀ γ)) (x : α) : (sum_finsupp_equiv_prod_finsupp.symm fg) (sum.inl x) = fg.1 x := rfl lemma sum_finsupp_equiv_prod_finsupp_symm_inr {α β γ : Type*} [has_zero γ] (fg : (α →₀ γ) × (β →₀ γ)) (y : β) : (sum_finsupp_equiv_prod_finsupp.symm fg) (sum.inr y) = fg.2 y := rfl variables [add_monoid M] /-- The additive equivalence between `(α ⊕ β) →₀ M` and `(α →₀ M) × (β →₀ M)`. This is the `finsupp` version of `equiv.sum_arrow_equiv_prod_arrow`. -/ @[simps apply symm_apply] def sum_finsupp_add_equiv_prod_finsupp {α β : Type*} : ((α ⊕ β) →₀ M) ≃+ (α →₀ M) × (β →₀ M) := { map_add' := by { intros, ext; simp only [equiv.to_fun_as_coe, prod.fst_add, prod.snd_add, add_apply, snd_sum_finsupp_equiv_prod_finsupp, fst_sum_finsupp_equiv_prod_finsupp] }, .. sum_finsupp_equiv_prod_finsupp } lemma fst_sum_finsupp_add_equiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (x : α) : (sum_finsupp_add_equiv_prod_finsupp f).1 x = f (sum.inl x) := rfl lemma snd_sum_finsupp_add_equiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (y : β) : (sum_finsupp_add_equiv_prod_finsupp f).2 y = f (sum.inr y) := rfl lemma sum_finsupp_add_equiv_prod_finsupp_symm_inl {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (x : α) : (sum_finsupp_add_equiv_prod_finsupp.symm fg) (sum.inl x) = fg.1 x := rfl lemma sum_finsupp_add_equiv_prod_finsupp_symm_inr {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (y : β) : (sum_finsupp_add_equiv_prod_finsupp.symm fg) (sum.inr y) = fg.2 y := rfl end sum section variables [group G] [mul_action G α] [add_comm_monoid M] /-- Scalar multiplication by a group element g, given by precomposition with the action of g⁻¹ on the domain. -/ def comap_has_scalar : has_scalar G (α →₀ M) := { smul := λ g f, f.comap_domain (λ a, g⁻¹ • a) (λ a a' m m' h, by simpa [←mul_smul] using (congr_arg (λ a, g • a) h)) } local attribute [instance] comap_has_scalar /-- Scalar multiplication by a group element, given by precomposition with the action of g⁻¹ on the domain, is multiplicative in g. -/ def comap_mul_action : mul_action G (α →₀ M) := { one_smul := λ f, by { ext, dsimp [(•)], simp, }, mul_smul := λ g g' f, by { ext, dsimp [(•)], simp [mul_smul], }, } local attribute [instance] comap_mul_action /-- Scalar multiplication by a group element, given by precomposition with the action of g⁻¹ on the domain, is additive in the second argument. -/ def comap_distrib_mul_action : distrib_mul_action G (α →₀ M) := { smul_zero := λ g, by { ext, dsimp [(•)], simp, }, smul_add := λ g f f', by { ext, dsimp [(•)], simp, }, } /-- Scalar multiplication by a group element on finitely supported functions on a group, given by precomposition with the action of g⁻¹. -/ def comap_distrib_mul_action_self : distrib_mul_action G (G →₀ M) := @finsupp.comap_distrib_mul_action G M G _ (monoid.to_mul_action G) _ @[simp] lemma comap_smul_single (g : G) (a : α) (b : M) : g • single a b = single (g • a) b := begin ext a', dsimp [(•)], by_cases h : g • a = a', { subst h, simp [←mul_smul], }, { simp [single_eq_of_ne h], rw [single_eq_of_ne], rintro rfl, simpa [←mul_smul] using h, } end @[simp] lemma comap_smul_apply (g : G) (f : α →₀ M) (a : α) : (g • f) a = f (g⁻¹ • a) := rfl end section instance [monoid R] [add_monoid M] [distrib_mul_action R M] : has_scalar R (α →₀ M) := ⟨λa v, v.map_range ((•) a) (smul_zero _)⟩ /-! Throughout this section, some `monoid` and `semiring` arguments are specified with `{}` instead of `[]`. See note [implicit instance arguments]. -/ @[simp] lemma coe_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] (b : R) (v : α →₀ M) : ⇑(b • v) = b • v := rfl lemma smul_apply {_ : monoid R} [add_monoid M] [distrib_mul_action R M] (b : R) (v : α →₀ M) (a : α) : (b • v) a = b • (v a) := rfl lemma _root_.is_smul_regular.finsupp {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {k : R} (hk : is_smul_regular M k) : is_smul_regular (α →₀ M) k := λ _ _ h, ext $ λ i, hk (congr_fun h i) instance [monoid R] [nonempty α] [add_monoid M] [distrib_mul_action R M] [has_faithful_scalar R M] : has_faithful_scalar R (α →₀ M) := { eq_of_smul_eq_smul := λ r₁ r₂ h, let ⟨a⟩ := ‹nonempty α› in eq_of_smul_eq_smul $ λ m : M, by simpa using congr_fun (h (single a m)) a } variables (α M) instance [monoid R] [add_monoid M] [distrib_mul_action R M] : distrib_mul_action R (α →₀ M) := { smul := (•), smul_add := λ a x y, ext $ λ _, smul_add _ _ _, one_smul := λ x, ext $ λ _, one_smul _ _, mul_smul := λ r s x, ext $ λ _, mul_smul _ _ _, smul_zero := λ x, ext $ λ _, smul_zero _ } instance [monoid R] [monoid S] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action S M] [has_scalar R S] [is_scalar_tower R S M] : is_scalar_tower R S (α →₀ M) := { smul_assoc := λ r s a, ext $ λ _, smul_assoc _ _ _ } instance [monoid R] [monoid S] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action S M] [smul_comm_class R S M] : smul_comm_class R S (α →₀ M) := { smul_comm := λ r s a, ext $ λ _, smul_comm _ _ _ } instance [semiring R] [add_comm_monoid M] [module R M] : module R (α →₀ M) := { smul := (•), zero_smul := λ x, ext $ λ _, zero_smul _ _, add_smul := λ a x y, ext $ λ _, add_smul _ _ _, .. finsupp.distrib_mul_action α M } variables {α M} {R} lemma support_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {b : R} {g : α →₀ M} : (b • g).support ⊆ g.support := λ a, by { simp only [smul_apply, mem_support_iff, ne.def], exact mt (λ h, h.symm ▸ smul_zero _) } section variables {p : α → Prop} @[simp] lemma filter_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {b : R} {v : α →₀ M} : (b • v).filter p = b • v.filter p := coe_fn_injective $ set.indicator_smul {x | p x} b v end lemma map_domain_smul {_ : monoid R} [add_comm_monoid M] [distrib_mul_action R M] {f : α → β} (b : R) (v : α →₀ M) : map_domain f (b • v) = b • map_domain f v := begin change map_domain f (map_range _ _ _) = map_range _ _ _, apply finsupp.induction v, { simp only [map_domain_zero, map_range_zero] }, intros a b v' hv₁ hv₂ IH, rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add, map_range_single, map_domain_single, map_domain_single, map_range_single]; apply smul_add end @[simp] lemma smul_single {_ : monoid R} [add_monoid M] [distrib_mul_action R M] (c : R) (a : α) (b : M) : c • finsupp.single a b = finsupp.single a (c • b) := map_range_single @[simp] lemma smul_single' {_ : semiring R} (c : R) (a : α) (b : R) : c • finsupp.single a b = finsupp.single a (c * b) := smul_single _ _ _ lemma map_range_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] [add_monoid N] [distrib_mul_action R N] {f : M → N} {hf : f 0 = 0} (c : R) (v : α →₀ M) (hsmul : ∀ x, f (c • x) = c • f x) : map_range f hf (c • v) = c • map_range f hf v := begin erw ←map_range_comp, have : (f ∘ (•) c) = ((•) c ∘ f) := funext hsmul, simp_rw this, apply map_range_comp, rw [function.comp_apply, smul_zero, hf], end lemma smul_single_one [semiring R] (a : α) (b : R) : b • single a 1 = single a b := by rw [smul_single, smul_eq_mul, mul_one] end lemma sum_smul_index [semiring R] [add_comm_monoid M] {g : α →₀ R} {b : R} {h : α → R → M} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) := finsupp.sum_map_range_index h0 lemma sum_smul_index' [monoid R] [add_monoid M] [distrib_mul_action R M] [add_comm_monoid N] {g : α →₀ M} {b : R} {h : α → M → N} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi c, h i (b • c)) := finsupp.sum_map_range_index h0 /-- A version of `finsupp.sum_smul_index'` for bundled additive maps. -/ lemma sum_smul_index_add_monoid_hom [monoid R] [add_monoid M] [add_comm_monoid N] [distrib_mul_action R M] {g : α →₀ M} {b : R} {h : α → M →+ N} : (b • g).sum (λ a, h a) = g.sum (λ i c, h i (b • c)) := sum_map_range_index (λ i, (h i).map_zero) instance [semiring R] [add_comm_monoid M] [module R M] {ι : Type*} [no_zero_smul_divisors R M] : no_zero_smul_divisors R (ι →₀ M) := ⟨λ c f h, or_iff_not_imp_left.mpr (λ hc, finsupp.ext (λ i, (smul_eq_zero.mp (finsupp.ext_iff.mp h i)).resolve_left hc))⟩ section distrib_mul_action_hom variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid N] [distrib_mul_action R M] [distrib_mul_action R N] /-- `finsupp.single` as a `distrib_mul_action_hom`. See also `finsupp.lsingle` for the version as a linear map. -/ def distrib_mul_action_hom.single (a : α) : M →+[R] (α →₀ M) := { map_smul' := λ k m, by simp only [add_monoid_hom.to_fun_eq_coe, single_add_hom_apply, smul_single], .. single_add_hom a } lemma distrib_mul_action_hom_ext {f g : (α →₀ M) →+[R] N} (h : ∀ (a : α) (m : M), f (single a m) = g (single a m)) : f = g := distrib_mul_action_hom.to_add_monoid_hom_injective $ add_hom_ext h /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma distrib_mul_action_hom_ext' {f g : (α →₀ M) →+[R] N} (h : ∀ (a : α), f.comp (distrib_mul_action_hom.single a) = g.comp (distrib_mul_action_hom.single a)) : f = g := distrib_mul_action_hom_ext $ λ a, distrib_mul_action_hom.congr_fun (h a) end distrib_mul_action_hom section variables [has_zero R] /-- The `finsupp` version of `pi.unique`. -/ instance unique_of_right [subsingleton R] : unique (α →₀ R) := { uniq := λ l, ext $ λ i, subsingleton.elim _ _, .. finsupp.inhabited } /-- The `finsupp` version of `pi.unique_of_is_empty`. -/ instance unique_of_left [is_empty α] : unique (α →₀ R) := { uniq := λ l, ext is_empty_elim, .. finsupp.inhabited } end /-- Given an `add_comm_monoid M` and `s : set α`, `restrict_support_equiv s M` is the `equiv` between the subtype of finitely supported functions with support contained in `s` and the type of finitely supported functions from `s`. -/ def restrict_support_equiv (s : set α) (M : Type*) [add_comm_monoid M] : {f : α →₀ M // ↑f.support ⊆ s } ≃ (s →₀ M) := begin refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩, { refine set.subset.trans (finset.coe_subset.2 map_domain_support) _, rw [finset.coe_image, set.image_subset_iff], exact assume x hx, x.2 }, { rintros ⟨f, hf⟩, apply subtype.eq, ext a, dsimp only, refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _), { rcases h with ⟨x, rfl⟩, rw [map_domain_apply subtype.val_injective, subtype_domain_apply] }, { convert map_domain_notin_range _ _ h, rw [← not_mem_support_iff], refine mt _ h, exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } }, { assume f, ext ⟨a, ha⟩, dsimp only, rw [subtype_domain_apply, map_domain_apply subtype.val_injective] } end /-- Given `add_comm_monoid M` and `e : α ≃ β`, `dom_congr e` is the corresponding `equiv` between `α →₀ M` and `β →₀ M`. This is `finsupp.equiv_congr_left` as an `add_equiv`. -/ @[simps apply] protected def dom_congr [add_comm_monoid M] (e : α ≃ β) : (α →₀ M) ≃+ (β →₀ M) := { to_fun := equiv_map_domain e, inv_fun := equiv_map_domain e.symm, left_inv := λ v, begin simp only [← equiv_map_domain_trans, equiv.trans_symm], exact equiv_map_domain_refl _ end, right_inv := begin assume v, simp only [← equiv_map_domain_trans, equiv.symm_trans], exact equiv_map_domain_refl _ end, map_add' := λ a b, by simp only [equiv_map_domain_eq_map_domain]; exact map_domain_add } @[simp] lemma dom_congr_refl [add_comm_monoid M] : finsupp.dom_congr (equiv.refl α) = add_equiv.refl (α →₀ M) := add_equiv.ext $ λ _, equiv_map_domain_refl _ @[simp] lemma dom_congr_symm [add_comm_monoid M] (e : α ≃ β) : (finsupp.dom_congr e).symm = (finsupp.dom_congr e.symm : (β →₀ M) ≃+ (α →₀ M)):= add_equiv.ext $ λ _, rfl @[simp] lemma dom_congr_trans [add_comm_monoid M] (e : α ≃ β) (f : β ≃ γ) : (finsupp.dom_congr e).trans (finsupp.dom_congr f) = (finsupp.dom_congr (e.trans f) : (α →₀ M) ≃+ _) := add_equiv.ext $ λ _, (equiv_map_domain_trans _ _ _).symm end finsupp namespace finsupp /-! ### Declarations about sigma types -/ section sigma variables {αs : ι → Type*} [has_zero M] (l : (Σ i, αs i) →₀ M) /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `M` and an index element `i : ι`, `split l i` is the `i`th component of `l`, a finitely supported function from `as i` to `M`. This is the `finsupp` version of `sigma.curry`. -/ def split (i : ι) : αs i →₀ M := l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2) lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ := begin dunfold split, rw comap_domain_apply end /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β`, `split_support l` is the finset of indices in `ι` that appear in the support of `l`. -/ def split_support : finset ι := l.support.image sigma.fst lemma mem_split_support_iff_nonzero (i : ι) : i ∈ split_support l ↔ split l i ≠ 0 := begin rw [split_support, mem_image, ne.def, ← support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty, split, comap_domain, finset.nonempty], simp only [exists_prop, finset.mem_preimage, exists_and_distrib_right, exists_eq_right, mem_support_iff, sigma.exists, ne.def] end /-- Given `l`, a finitely supported function from the sigma type `Σ i, αs i` to `β` and an `ι`-indexed family `g` of functions from `(αs i →₀ β)` to `γ`, `split_comp` defines a finitely supported function from the index type `ι` to `γ` given by composing `g i` with `split l i`. -/ def split_comp [has_zero N] (g : Π i, (αs i →₀ M) → N) (hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ N := { support := split_support l, to_fun := λ i, g i (split l i), mem_support_to_fun := begin intros i, rw [mem_split_support_iff_nonzero, not_iff_not, hg], end } lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) := by simp only [finset.ext_iff, split_support, split, comap_domain, mem_image, mem_preimage, sigma.forall, mem_sigma]; tauto lemma sigma_sum [add_comm_monoid N] (f : (Σ (i : ι), αs i) → M → N) : l.sum f = ∑ i in split_support l, (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b) := by simp only [sum, sigma_support, sum_sigma, split_apply] variables {η : Type*} [fintype η] {ιs : η → Type*} [has_zero α] /-- On a `fintype η`, `finsupp.split` is an equivalence between `(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`. This is the `finsupp` version of `equiv.Pi_curry`. -/ noncomputable def sigma_finsupp_equiv_pi_finsupp : ((Σ j, ιs j) →₀ α) ≃ Π j, (ιs j →₀ α) := { to_fun := split, inv_fun := λ f, on_finset (finset.univ.sigma (λ j, (f j).support)) (λ ji, f ji.1 ji.2) (λ g hg, finset.mem_sigma.mpr ⟨finset.mem_univ _, mem_support_iff.mpr hg⟩), left_inv := λ f, by { ext, simp [split] }, right_inv := λ f, by { ext, simp [split] } } @[simp] lemma sigma_finsupp_equiv_pi_finsupp_apply (f : (Σ j, ιs j) →₀ α) (j i) : sigma_finsupp_equiv_pi_finsupp f j i = f ⟨j, i⟩ := rfl /-- On a `fintype η`, `finsupp.split` is an additive equivalence between `(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`. This is the `add_equiv` version of `finsupp.sigma_finsupp_equiv_pi_finsupp`. -/ noncomputable def sigma_finsupp_add_equiv_pi_finsupp {α : Type*} {ιs : η → Type*} [add_monoid α] : ((Σ j, ιs j) →₀ α) ≃+ Π j, (ιs j →₀ α) := { map_add' := λ f g, by { ext, simp }, .. sigma_finsupp_equiv_pi_finsupp } @[simp] lemma sigma_finsupp_add_equiv_pi_finsupp_apply {α : Type*} {ιs : η → Type*} [add_monoid α] (f : (Σ j, ιs j) →₀ α) (j i) : sigma_finsupp_add_equiv_pi_finsupp f j i = f ⟨j, i⟩ := rfl end sigma end finsupp /-! ### Declarations relating `multiset` to `finsupp` -/ namespace multiset /-- Given a multiset `s`, `s.to_finsupp` returns the finitely supported function on `ℕ` given by the multiplicities of the elements of `s`. -/ def to_finsupp : multiset α ≃+ (α →₀ ℕ) := finsupp.to_multiset.symm @[simp] lemma to_finsupp_support [D : decidable_eq α] (s : multiset α) : s.to_finsupp.support = s.to_finset := by rw subsingleton.elim D; refl @[simp] lemma to_finsupp_apply [D : decidable_eq α] (s : multiset α) (a : α) : to_finsupp s a = s.count a := by rw subsingleton.elim D; refl lemma to_finsupp_zero : to_finsupp (0 : multiset α) = 0 := add_equiv.map_zero _ lemma to_finsupp_add (s t : multiset α) : to_finsupp (s + t) = to_finsupp s + to_finsupp t := to_finsupp.map_add s t @[simp] lemma to_finsupp_singleton (a : α) : to_finsupp ({a} : multiset α) = finsupp.single a 1 := finsupp.to_multiset.symm_apply_eq.2 $ by simp @[simp] lemma to_finsupp_to_multiset (s : multiset α) : s.to_finsupp.to_multiset = s := finsupp.to_multiset.apply_symm_apply s lemma to_finsupp_eq_iff {s : multiset α} {f : α →₀ ℕ} : s.to_finsupp = f ↔ s = f.to_multiset := finsupp.to_multiset.symm_apply_eq end multiset @[simp] lemma finsupp.to_multiset_to_finsupp (f : α →₀ ℕ) : f.to_multiset.to_finsupp = f := finsupp.to_multiset.symm_apply_apply f /-! ### Declarations about order(ed) instances on `finsupp` -/ namespace finsupp instance [preorder M] [has_zero M] : preorder (α →₀ M) := { le := λ f g, ∀ s, f s ≤ g s, le_refl := λ f s, le_refl _, le_trans := λ f g h Hfg Hgh s, le_trans (Hfg s) (Hgh s) } instance [partial_order M] [has_zero M] : partial_order (α →₀ M) := { le_antisymm := λ f g hfg hgf, ext $ λ s, le_antisymm (hfg s) (hgf s), .. finsupp.preorder } instance [ordered_add_comm_monoid M] : ordered_add_comm_monoid (α →₀ M) := { add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s), .. finsupp.add_comm_monoid, .. finsupp.partial_order } instance [ordered_cancel_add_comm_monoid M] : ordered_cancel_add_comm_monoid (α →₀ M) := { add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s), le_of_add_le_add_left := λ a b c h s, le_of_add_le_add_left (h s), add_left_cancel := λ a b c h, ext $ λ s, add_left_cancel (ext_iff.1 h s), .. finsupp.add_comm_monoid, .. finsupp.partial_order } instance [ordered_add_comm_monoid M] [contravariant_class M M (+) (≤)] : contravariant_class (α →₀ M) (α →₀ M) (+) (≤) := ⟨λ f g h H x, le_of_add_le_add_left $ H x⟩ lemma le_def [preorder M] [has_zero M] {f g : α →₀ M} : f ≤ g ↔ ∀ x, f x ≤ g x := iff.rfl lemma le_iff' [canonically_ordered_add_monoid M] (f g : α →₀ M) {t : finset α} (hf : f.support ⊆ t) : f ≤ g ↔ ∀ s ∈ t, f s ≤ g s := ⟨λ h s hs, h s, λ h s, if H : s ∈ f.support then h s (hf H) else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩ lemma le_iff [canonically_ordered_add_monoid M] (f g : α →₀ M) : f ≤ g ↔ ∀ s ∈ f.support, f s ≤ g s := le_iff' f g (subset.refl _) instance decidable_le [canonically_ordered_add_monoid M] [decidable_rel (@has_le.le M _)] : decidable_rel (@has_le.le (α →₀ M) _) := λ f g, decidable_of_iff _ (le_iff f g).symm @[simp] lemma single_le_iff [canonically_ordered_add_monoid M] {i : α} {x : M} {f : α →₀ M} : single i x ≤ f ↔ x ≤ f i := (le_iff' _ _ support_single_subset).trans $ by simp @[simp] lemma add_eq_zero_iff [canonically_ordered_add_monoid M] (f g : α →₀ M) : f + g = 0 ↔ f = 0 ∧ g = 0 := by simp [ext_iff, forall_and_distrib] /-- `finsupp.to_multiset` as an order isomorphism. -/ def order_iso_multiset : (α →₀ ℕ) ≃o multiset α := { to_equiv := to_multiset.to_equiv, map_rel_iff' := λ f g, by simp [multiset.le_iff_count, le_def] } @[simp] lemma coe_order_iso_multiset : ⇑(@order_iso_multiset α) = to_multiset := rfl @[simp] lemma coe_order_iso_multiset_symm : ⇑(@order_iso_multiset α).symm = multiset.to_finsupp := rfl lemma to_multiset_strict_mono : strict_mono (@to_multiset α) := order_iso_multiset.strict_mono lemma sum_id_lt_of_lt (m n : α →₀ ℕ) (h : m < n) : m.sum (λ _, id) < n.sum (λ _, id) := begin rw [← card_to_multiset, ← card_to_multiset], apply multiset.card_lt_of_lt, exact to_multiset_strict_mono h end variable (α) /-- The order on `σ →₀ ℕ` is well-founded.-/ lemma lt_wf : well_founded (@has_lt.lt (α →₀ ℕ) _) := subrelation.wf (sum_id_lt_of_lt) $ inv_image.wf _ nat.lt_wf variable {α} /-! Declarations about subtraction on `finsupp` with codomain a `canonically_ordered_add_monoid`. Some of these lemmas are used to develop the partial derivative on `mv_polynomial`. -/ section nat_sub section canonically_ordered_monoid variables [canonically_ordered_add_monoid M] [has_sub M] [has_ordered_sub M] /-- This is called `tsub` for truncated subtraction, to distinguish it with subtraction in an additive group. -/ instance tsub : has_sub (α →₀ M) := ⟨zip_with (λ m n, m - n) (sub_self' 0)⟩ @[simp] lemma coe_tsub (g₁ g₂ : α →₀ M) : ⇑(g₁ - g₂) = g₁ - g₂ := rfl lemma tsub_apply (g₁ g₂ : α →₀ M) (a : α) : (g₁ - g₂) a = g₁ a - g₂ a := rfl instance : canonically_ordered_add_monoid (α →₀ M) := { bot := 0, bot_le := λ f s, zero_le (f s), le_iff_exists_add := begin intros f g, split, { intro H, use g - f, ext x, symmetry, exact add_sub_cancel_of_le (H x) }, { rintro ⟨g, rfl⟩ x, exact self_le_add_right (f x) (g x) } end, ..(by apply_instance : ordered_add_comm_monoid (α →₀ M)) } instance : has_ordered_sub (α →₀ M) := ⟨λ n m k, forall_congr $ λ x, sub_le_iff_right⟩ @[simp] lemma single_tsub {a : α} {n₁ n₂ : M} : single a (n₁ - n₂) = single a n₁ - single a n₂ := begin ext f, by_cases h : (a = f), { rw [h, tsub_apply, single_eq_same, single_eq_same, single_eq_same] }, rw [tsub_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, sub_self'] end end canonically_ordered_monoid /-! Some lemmas specifically about `ℕ`. -/ lemma sub_single_one_add {a : α} {u u' : α →₀ ℕ} (h : u a ≠ 0) : u - single a 1 + u' = u + u' - single a 1 := sub_add_eq_add_sub' $ single_le_iff.mpr $ nat.one_le_iff_ne_zero.mpr h lemma add_sub_single_one {a : α} {u u' : α →₀ ℕ} (h : u' a ≠ 0) : u + (u' - single a 1) = u + u' - single a 1 := (add_sub_assoc_of_le (single_le_iff.mpr $ nat.one_le_iff_ne_zero.mpr h) _).symm end nat_sub end finsupp namespace multiset lemma to_finsuppstrict_mono : strict_mono (@to_finsupp α) := finsupp.order_iso_multiset.symm.strict_mono end multiset
a4119329351251db045b550d127c0f309f710dd7
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/topology/algebra/group.lean
eaceb58e166a03b23d1c60b2719cf72db5f674c3
[ "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
28,399
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 _ _ _ }
4284314e0a94a8cd19c4d95dc2163665564c97c5
947b78d97130d56365ae2ec264df196ce769371a
/tests/playground/pldi/do2.lean
979622c9b79187dad3c0182a903270dbe72eef04
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
924
lean
open Lean /- inductive Syntax | missing : Syntax | node (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax | atom (info : SourceInfo) (val : String) : Syntax | ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Name × List String)) : Syntax -/ partial def expandHash : Syntax → StateT Bool MacroM Syntax | Syntax.node k args => if k == `doHash then do set true; `(←MonadState.get) else do args ← args.mapM expandHash; pure $ Syntax.node k args | stx => pure stx @[macro Lean.Parser.Term.do] def expandDo : Macro := fun stx => do (stx, expanded) ← expandHash stx false; if expanded then pure stx else Macro.throwUnsupported new_frontend syntax:max [doHash] "#" : term def tst : StateT (Nat × Nat) IO Unit := do if #.1 == 0 then IO.println "first field is zero" else IO.println "first field is not zero" #eval tst.run' (1, 1) #eval tst.run' (0, 1)
12e794136c7670a158141eb974e9707b7a12beaa
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/668.lean
77bdee3e44939448f7b46acaa128a2c4a62a2d4a
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
325
lean
set_option pp.coercions true namespace Nat constant Nat : Type₁ constant num2Nat : num → Nat attribute num2Nat [coercion] check (0 : Nat) end Nat constant Int : Type₁ namespace Int open Nat constant Nat2Int : Nat → Int attribute Nat2Int [coercion] check (0 : Int) end Int open Int check (0 : Int)
e04519a7b6c350b76017dd815c29f477852a573c
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/order/sub.lean
ddc86599a110df8c871c23a06335276ae52500d5
[ "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
30,546
lean
/- Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import algebra.order.monoid /-! # Ordered Subtraction This file proves lemmas relating (truncated) subtraction with an order. We provide a class `has_ordered_sub` stating that `a - b ≤ c ↔ a ≤ c + b`. The subtraction discussed here could both be normal subtraction in an additive group or truncated subtraction on a canonically ordered monoid (`ℕ`, `multiset`, `part_enat`, `ennreal`, ...) ## Implementation details `has_ordered_sub` is a mixin type-class, so that we can use the results in this file even in cases where we don't have a `canonically_ordered_add_monoid` instance (even though that is our main focus). Conversely, this means we can use `canonically_ordered_add_monoid` without necessarily having to define a subtraction. The results in this file are ordered by the type-class assumption needed to prove it. This means that similar results might not be close to each other. Furthermore, we don't prove implications if a bi-implication can be proven under the same assumptions. Lemmas using this class are named using `tsub` instead of `sub` (short for "truncated subtraction"). This is to avoid naming conflicts with similar lemmas about ordered groups. We provide a second version of most results that require `[contravariant_class α α (+) (≤)]`. In the second version we replace this type-class assumption by explicit `add_le_cancellable` assumptions. TODO: maybe we should make a multiplicative version of this, so that we can replace some identical lemmas about subtraction/division in `ordered_[add_]comm_group` with these. TODO: generalize `nat.le_of_le_of_sub_le_sub_right`, `nat.sub_le_sub_right_iff`, `nat.mul_self_sub_mul_self_eq` -/ variables {α β : Type*} /-- `has_ordered_sub α` means that `α` has a subtraction characterized by `a - b ≤ c ↔ a ≤ c + b`. In other words, `a - b` is the least `c` such that `a ≤ b + c`. This is satisfied both by the subtraction in additive ordered groups and by truncated subtraction in canonically ordered monoids on many specific types. -/ class has_ordered_sub (α : Type*) [has_le α] [has_add α] [has_sub α] := (tsub_le_iff_right : ∀ a b c : α, a - b ≤ c ↔ a ≤ c + b) section has_add variables [preorder α] [has_add α] [has_sub α] [has_ordered_sub α] {a b c d : α} @[simp] lemma tsub_le_iff_right : a - b ≤ c ↔ a ≤ c + b := has_ordered_sub.tsub_le_iff_right a b c /-- See `add_tsub_cancel_right` for the equality if `contravariant_class α α (+) (≤)`. -/ lemma add_tsub_le_right : a + b - b ≤ a := tsub_le_iff_right.mpr le_rfl lemma le_tsub_add : b ≤ (b - a) + a := tsub_le_iff_right.mp le_rfl lemma add_hom.le_map_tsub [preorder β] [has_add β] [has_sub β] [has_ordered_sub β] (f : add_hom α β) (hf : monotone f) (a b : α) : f a - f b ≤ f (a - b) := by { rw [tsub_le_iff_right, ← f.map_add], exact hf le_tsub_add } lemma le_mul_tsub {R : Type*} [distrib R] [preorder R] [has_sub R] [has_ordered_sub R] [covariant_class R R (*) (≤)] {a b c : R} : a * b - a * c ≤ a * (b - c) := (add_hom.mul_left a).le_map_tsub (monotone_id.const_mul' a) _ _ lemma le_tsub_mul {R : Type*} [comm_semiring R] [preorder R] [has_sub R] [has_ordered_sub R] [covariant_class R R (*) (≤)] {a b c : R} : a * c - b * c ≤ (a - b) * c := by simpa only [mul_comm _ c] using le_mul_tsub end has_add /-- An order isomorphism between types with ordered subtraction preserves subtraction provided that it preserves addition. -/ lemma order_iso.map_tsub {M N : Type*} [preorder M] [has_add M] [has_sub M] [has_ordered_sub M] [partial_order N] [has_add N] [has_sub N] [has_ordered_sub N] (e : M ≃o N) (h_add : ∀ a b, e (a + b) = e a + e b) (a b : M) : e (a - b) = e a - e b := begin set e_add : M ≃+ N := { map_add' := h_add, .. e }, refine le_antisymm _ (e_add.to_add_hom.le_map_tsub e.monotone a b), suffices : e (e.symm (e a) - e.symm (e b)) ≤ e (e.symm (e a - e b)), by simpa, exact e.monotone (e_add.symm.to_add_hom.le_map_tsub e.symm.monotone _ _) end /-! ### Preorder -/ section ordered_add_comm_monoid section preorder variables [preorder α] section add_comm_semigroup variables [add_comm_semigroup α] [has_sub α] [has_ordered_sub α] {a b c d : α} lemma tsub_le_iff_left : a - b ≤ c ↔ a ≤ b + c := by rw [tsub_le_iff_right, add_comm] lemma le_add_tsub : a ≤ b + (a - b) := tsub_le_iff_left.mp le_rfl /-- See `add_tsub_cancel_left` for the equality if `contravariant_class α α (+) (≤)`. -/ lemma add_tsub_le_left : a + b - a ≤ b := tsub_le_iff_left.mpr le_rfl lemma tsub_le_tsub_right (h : a ≤ b) (c : α) : a - c ≤ b - c := tsub_le_iff_left.mpr $ h.trans le_add_tsub lemma tsub_le_iff_tsub_le : a - b ≤ c ↔ a - c ≤ b := by rw [tsub_le_iff_left, tsub_le_iff_right] /-- See `tsub_tsub_cancel_of_le` for the equality. -/ lemma tsub_tsub_le : b - (b - a) ≤ a := tsub_le_iff_right.mpr le_add_tsub section cov variable [covariant_class α α (+) (≤)] lemma tsub_le_tsub_left (h : a ≤ b) (c : α) : c - b ≤ c - a := tsub_le_iff_left.mpr $ le_add_tsub.trans $ add_le_add_right h _ lemma tsub_le_tsub (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c := (tsub_le_tsub_right hab _).trans $ tsub_le_tsub_left hcd _ /-- See `add_tsub_assoc_of_le` for the equality. -/ lemma add_tsub_le_assoc : a + b - c ≤ a + (b - c) := by { rw [tsub_le_iff_left, add_left_comm], exact add_le_add_left le_add_tsub a } lemma add_le_add_add_tsub : a + b ≤ (a + c) + (b - c) := by { rw [add_assoc], exact add_le_add_left le_add_tsub a } lemma le_tsub_add_add : a + b ≤ (a - c) + (b + c) := by { rw [add_comm a, add_comm (a - c)], exact add_le_add_add_tsub } lemma tsub_le_tsub_add_tsub : a - c ≤ (a - b) + (b - c) := begin rw [tsub_le_iff_left, ← add_assoc, add_right_comm], exact le_add_tsub.trans (add_le_add_right le_add_tsub _), end lemma tsub_tsub_tsub_le_tsub : (c - a) - (c - b) ≤ b - a := begin rw [tsub_le_iff_left, tsub_le_iff_left, add_left_comm], exact le_tsub_add.trans (add_le_add_left le_add_tsub _), end lemma tsub_tsub_le_tsub_add {a b c : α} : a - (b - c) ≤ a - b + c := tsub_le_iff_right.2 $ calc a ≤ a - b + b : le_tsub_add ... ≤ a - b + (c + (b - c)) : add_le_add_left le_add_tsub _ ... = a - b + c + (b - c) : (add_assoc _ _ _).symm end cov /-! #### Lemmas that assume that an element is `add_le_cancellable` -/ namespace add_le_cancellable protected lemma le_add_tsub_swap (hb : add_le_cancellable b) : a ≤ b + a - b := hb le_add_tsub protected lemma le_add_tsub (hb : add_le_cancellable b) : a ≤ a + b - b := by { rw add_comm, exact hb.le_add_tsub_swap } protected lemma le_tsub_of_add_le_left (ha : add_le_cancellable a) (h : a + b ≤ c) : b ≤ c - a := ha $ h.trans le_add_tsub protected lemma le_tsub_of_add_le_right (hb : add_le_cancellable b) (h : a + b ≤ c) : a ≤ c - b := hb.le_tsub_of_add_le_left $ by rwa add_comm end add_le_cancellable /-! ### Lemmas where addition is order-reflecting -/ section contra variable [contravariant_class α α (+) (≤)] lemma le_add_tsub_swap : a ≤ b + a - b := contravariant.add_le_cancellable.le_add_tsub_swap lemma le_add_tsub' : a ≤ a + b - b := contravariant.add_le_cancellable.le_add_tsub lemma le_tsub_of_add_le_left (h : a + b ≤ c) : b ≤ c - a := contravariant.add_le_cancellable.le_tsub_of_add_le_left h lemma le_tsub_of_add_le_right (h : a + b ≤ c) : a ≤ c - b := contravariant.add_le_cancellable.le_tsub_of_add_le_right h end contra end add_comm_semigroup variables [add_comm_monoid α] [has_sub α] [has_ordered_sub α] {a b c d : α} lemma tsub_nonpos : a - b ≤ 0 ↔ a ≤ b := by rw [tsub_le_iff_left, add_zero] alias tsub_nonpos ↔ _ tsub_nonpos_of_le lemma add_monoid_hom.le_map_tsub [preorder β] [add_comm_monoid β] [has_sub β] [has_ordered_sub β] (f : α →+ β) (hf : monotone f) (a b : α) : f a - f b ≤ f (a - b) := f.to_add_hom.le_map_tsub hf a b end preorder /-! ### Partial order -/ variables [partial_order α] [add_comm_semigroup α] [has_sub α] [has_ordered_sub α] {a b c d : α} lemma tsub_tsub (b a c : α) : b - a - c = b - (a + c) := begin apply le_antisymm, { rw [tsub_le_iff_left, tsub_le_iff_left, ← add_assoc, ← tsub_le_iff_left] }, { rw [tsub_le_iff_left, add_assoc, ← tsub_le_iff_left, ← tsub_le_iff_left] } end section cov variable [covariant_class α α (+) (≤)] lemma tsub_add_eq_tsub_tsub (a b c : α) : a - (b + c) = a - b - c := begin refine le_antisymm (tsub_le_iff_left.mpr _) (tsub_le_iff_left.mpr $ tsub_le_iff_left.mpr _), { rw [add_assoc], refine le_trans le_add_tsub (add_le_add_left le_add_tsub _) }, { rw [← add_assoc], apply le_add_tsub } end lemma tsub_add_eq_tsub_tsub_swap (a b c : α) : a - (b + c) = a - c - b := by { rw [add_comm], apply tsub_add_eq_tsub_tsub } lemma tsub_right_comm : a - b - c = a - c - b := by simp_rw [← tsub_add_eq_tsub_tsub, add_comm] end cov /-! ### Lemmas that assume that an element is `add_le_cancellable`. -/ namespace add_le_cancellable protected lemma tsub_eq_of_eq_add (hb : add_le_cancellable b) (h : a = c + b) : a - b = c := le_antisymm (tsub_le_iff_right.mpr h.le) $ by { rw h, exact hb.le_add_tsub } protected lemma eq_tsub_of_add_eq (hc : add_le_cancellable c) (h : a + c = b) : a = b - c := (hc.tsub_eq_of_eq_add h.symm).symm protected theorem tsub_eq_of_eq_add_rev (hb : add_le_cancellable b) (h : a = b + c) : a - b = c := hb.tsub_eq_of_eq_add $ by rw [add_comm, h] @[simp] protected lemma add_tsub_cancel_right (hb : add_le_cancellable b) : a + b - b = a := hb.tsub_eq_of_eq_add $ by rw [add_comm] @[simp] protected lemma add_tsub_cancel_left (ha : add_le_cancellable a) : a + b - a = b := ha.tsub_eq_of_eq_add $ add_comm a b protected lemma lt_add_of_tsub_lt_left (hb : add_le_cancellable b) (h : a - b < c) : a < b + c := begin rw [lt_iff_le_and_ne, ← tsub_le_iff_left], refine ⟨h.le, _⟩, rintro rfl, simpa [hb] using h, end protected lemma lt_add_of_tsub_lt_right (hc : add_le_cancellable c) (h : a - c < b) : a < b + c := begin rw [lt_iff_le_and_ne, ← tsub_le_iff_right], refine ⟨h.le, _⟩, rintro rfl, simpa [hc] using h, end end add_le_cancellable /-! #### Lemmas where addition is order-reflecting. -/ section contra variable [contravariant_class α α (+) (≤)] lemma tsub_eq_of_eq_add (h : a = c + b) : a - b = c := contravariant.add_le_cancellable.tsub_eq_of_eq_add h lemma eq_tsub_of_add_eq (h : a + c = b) : a = b - c := contravariant.add_le_cancellable.eq_tsub_of_add_eq h lemma tsub_eq_of_eq_add_rev (h : a = b + c) : a - b = c := contravariant.add_le_cancellable.tsub_eq_of_eq_add_rev h @[simp] lemma add_tsub_cancel_right (a b : α) : a + b - b = a := contravariant.add_le_cancellable.add_tsub_cancel_right @[simp] lemma add_tsub_cancel_left (a b : α) : a + b - a = b := contravariant.add_le_cancellable.add_tsub_cancel_left lemma lt_add_of_tsub_lt_left (h : a - b < c) : a < b + c := contravariant.add_le_cancellable.lt_add_of_tsub_lt_left h lemma lt_add_of_tsub_lt_right (h : a - c < b) : a < b + c := contravariant.add_le_cancellable.lt_add_of_tsub_lt_right h end contra section both variables [covariant_class α α (+) (≤)] [contravariant_class α α (+) (≤)] lemma add_tsub_add_eq_tsub_right (a c b : α) : (a + c) - (b + c) = a - b := begin apply le_antisymm, { rw [tsub_le_iff_left, add_right_comm], exact add_le_add_right le_add_tsub c }, { rw [tsub_le_iff_left, add_comm b], apply le_of_add_le_add_right, rw [add_assoc], exact le_tsub_add } end lemma add_tsub_add_eq_tsub_left (a b c : α) : (a + b) - (a + c) = b - c := by rw [add_comm a b, add_comm a c, add_tsub_add_eq_tsub_right] end both end ordered_add_comm_monoid /-! ### Lemmas in a linearly ordered monoid. -/ section linear_order variables {a b c d : α} [linear_order α] [add_comm_semigroup α] [has_sub α] [has_ordered_sub α] /-- See `lt_of_tsub_lt_tsub_right_of_le` for a weaker statement in a partial order. -/ lemma lt_of_tsub_lt_tsub_right (h : a - c < b - c) : a < b := lt_imp_lt_of_le_imp_le (λ h, tsub_le_tsub_right h c) h /-- See `lt_tsub_iff_right_of_le` for a weaker statement in a partial order. -/ lemma lt_tsub_iff_right : a < b - c ↔ a + c < b := lt_iff_lt_of_le_iff_le tsub_le_iff_right /-- See `lt_tsub_iff_left_of_le` for a weaker statement in a partial order. -/ lemma lt_tsub_iff_left : a < b - c ↔ c + a < b := lt_iff_lt_of_le_iff_le tsub_le_iff_left lemma lt_tsub_comm : a < b - c ↔ c < b - a := lt_tsub_iff_left.trans lt_tsub_iff_right.symm section cov variable [covariant_class α α (+) (≤)] /-- See `lt_of_tsub_lt_tsub_left_of_le` for a weaker statement in a partial order. -/ lemma lt_of_tsub_lt_tsub_left (h : a - b < a - c) : c < b := lt_imp_lt_of_le_imp_le (λ h, tsub_le_tsub_left h a) h end cov end linear_order /-! ### Lemmas in a canonically ordered monoid. -/ section canonically_ordered_add_monoid variables [canonically_ordered_add_monoid α] [has_sub α] [has_ordered_sub α] {a b c d : α} @[simp] lemma add_tsub_cancel_of_le (h : a ≤ b) : a + (b - a) = b := begin refine le_antisymm _ le_add_tsub, obtain ⟨c, rfl⟩ := le_iff_exists_add.1 h, exact add_le_add_left add_tsub_le_left a, end lemma tsub_add_cancel_of_le (h : a ≤ b) : b - a + a = b := by { rw [add_comm], exact add_tsub_cancel_of_le h } lemma add_tsub_cancel_iff_le : a + (b - a) = b ↔ a ≤ b := ⟨λ h, le_iff_exists_add.mpr ⟨b - a, h.symm⟩, add_tsub_cancel_of_le⟩ lemma tsub_add_cancel_iff_le : b - a + a = b ↔ a ≤ b := by { rw [add_comm], exact add_tsub_cancel_iff_le } lemma add_le_of_le_tsub_right_of_le (h : b ≤ c) (h2 : a ≤ c - b) : a + b ≤ c := (add_le_add_right h2 b).trans_eq $ tsub_add_cancel_of_le h lemma add_le_of_le_tsub_left_of_le (h : a ≤ c) (h2 : b ≤ c - a) : a + b ≤ c := (add_le_add_left h2 a).trans_eq $ add_tsub_cancel_of_le h lemma tsub_le_tsub_iff_right (h : c ≤ b) : a - c ≤ b - c ↔ a ≤ b := by rw [tsub_le_iff_right, tsub_add_cancel_of_le h] lemma tsub_left_inj (h1 : c ≤ a) (h2 : c ≤ b) : a - c = b - c ↔ a = b := by simp_rw [le_antisymm_iff, tsub_le_tsub_iff_right h1, tsub_le_tsub_iff_right h2] /-- See `lt_of_tsub_lt_tsub_right` for a stronger statement in a linear order. -/ lemma lt_of_tsub_lt_tsub_right_of_le (h : c ≤ b) (h2 : a - c < b - c) : a < b := by { refine ((tsub_le_tsub_iff_right h).mp h2.le).lt_of_ne _, rintro rfl, exact h2.false } @[simp] lemma tsub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b := by rw [← nonpos_iff_eq_zero, tsub_le_iff_left, add_zero] /-- One direction of `tsub_eq_zero_iff_le`, as a `@[simp]`-lemma. -/ @[simp] lemma tsub_eq_zero_of_le (h : a ≤ b) : a - b = 0 := tsub_eq_zero_iff_le.mpr h @[simp] lemma tsub_self (a : α) : a - a = 0 := tsub_eq_zero_iff_le.mpr le_rfl @[simp] lemma tsub_le_self : a - b ≤ a := tsub_le_iff_left.mpr $ le_add_left le_rfl @[simp] lemma tsub_zero (a : α) : a - 0 = a := le_antisymm tsub_le_self $ le_add_tsub.trans_eq $ zero_add _ @[simp] lemma zero_tsub (a : α) : 0 - a = 0 := tsub_eq_zero_iff_le.mpr $ zero_le a lemma tsub_self_add (a b : α) : a - (a + b) = 0 := by { rw [tsub_eq_zero_iff_le], apply self_le_add_right } lemma tsub_inj_left (h₁ : a ≤ b) (h₂ : a ≤ c) (h₃ : b - a = c - a) : b = c := by rw [← tsub_add_cancel_of_le h₁, ← tsub_add_cancel_of_le h₂, h₃] lemma tsub_pos_iff_not_le : 0 < a - b ↔ ¬ a ≤ b := by rw [pos_iff_ne_zero, ne.def, tsub_eq_zero_iff_le] lemma tsub_pos_of_lt (h : a < b) : 0 < b - a := tsub_pos_iff_not_le.mpr h.not_le lemma tsub_add_tsub_cancel (hab : b ≤ a) (hbc : c ≤ b) : (a - b) + (b - c) = a - c := begin convert tsub_add_cancel_of_le (tsub_le_tsub_right hab c) using 2, rw [tsub_tsub, add_tsub_cancel_of_le hbc], end lemma tsub_tsub_tsub_cancel_right (h : c ≤ b) : (a - c) - (b - c) = a - b := by rw [tsub_tsub, add_tsub_cancel_of_le h] lemma tsub_lt_of_lt (h : a < b) : a - c < b := lt_of_le_of_lt tsub_le_self h /-! ### Lemmas that assume that an element is `add_le_cancellable`. -/ namespace add_le_cancellable protected lemma eq_tsub_iff_add_eq_of_le (hc : add_le_cancellable c) (h : c ≤ b) : a = b - c ↔ a + c = b := begin split, { rintro rfl, exact tsub_add_cancel_of_le h }, { rintro rfl, exact (hc.add_tsub_cancel_right).symm } end protected lemma tsub_eq_iff_eq_add_of_le (hb : add_le_cancellable b) (h : b ≤ a) : a - b = c ↔ a = c + b := by rw [eq_comm, hb.eq_tsub_iff_add_eq_of_le h, eq_comm] protected lemma add_tsub_assoc_of_le (hc : add_le_cancellable c) (h : c ≤ b) (a : α) : a + b - c = a + (b - c) := by conv_lhs { rw [← add_tsub_cancel_of_le h, add_comm c, ← add_assoc, hc.add_tsub_cancel_right] } protected lemma tsub_add_eq_add_tsub (hb : add_le_cancellable b) (h : b ≤ a) : a - b + c = a + c - b := by rw [add_comm a, hb.add_tsub_assoc_of_le h, add_comm] protected lemma tsub_tsub_assoc (hbc : add_le_cancellable (b - c)) (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := by rw [hbc.tsub_eq_iff_eq_add_of_le (tsub_le_self.trans h₁), add_assoc, add_tsub_cancel_of_le h₂, tsub_add_cancel_of_le h₁] protected lemma tsub_add_tsub_comm (hb : add_le_cancellable b) (hd : add_le_cancellable d) (hba : b ≤ a) (hdc : d ≤ c) : a - b + (c - d) = a + c - (b + d) := by rw [hb.tsub_add_eq_add_tsub hba, ←hd.add_tsub_assoc_of_le hdc, tsub_tsub, add_comm d] protected lemma le_tsub_iff_left (ha : add_le_cancellable a) (h : a ≤ c) : b ≤ c - a ↔ a + b ≤ c := ⟨add_le_of_le_tsub_left_of_le h, ha.le_tsub_of_add_le_left⟩ protected lemma le_tsub_iff_right (ha : add_le_cancellable a) (h : a ≤ c) : b ≤ c - a ↔ b + a ≤ c := by { rw [add_comm], exact ha.le_tsub_iff_left h } protected lemma tsub_lt_iff_left (hb : add_le_cancellable b) (hba : b ≤ a) : a - b < c ↔ a < b + c := begin refine ⟨hb.lt_add_of_tsub_lt_left, _⟩, intro h, refine (tsub_le_iff_left.mpr h.le).lt_of_ne _, rintro rfl, exact h.ne' (add_tsub_cancel_of_le hba) end protected lemma tsub_lt_iff_right (hb : add_le_cancellable b) (hba : b ≤ a) : a - b < c ↔ a < c + b := by { rw [add_comm], exact hb.tsub_lt_iff_left hba } protected lemma lt_tsub_of_add_lt_right (hc : add_le_cancellable c) (h : a + c < b) : a < b - c := begin apply lt_of_le_of_ne, { rw [← add_tsub_cancel_of_le h.le, add_right_comm, add_assoc], rw [hc.add_tsub_assoc_of_le], refine le_self_add, refine le_add_self }, { rintro rfl, apply h.not_le, exact le_tsub_add } end protected lemma lt_tsub_of_add_lt_left (ha : add_le_cancellable a) (h : a + c < b) : c < b - a := by { apply ha.lt_tsub_of_add_lt_right, rwa add_comm } protected lemma tsub_lt_iff_tsub_lt (hb : add_le_cancellable b) (hc : add_le_cancellable c) (h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < c ↔ a - c < b := by rw [hb.tsub_lt_iff_left h₁, hc.tsub_lt_iff_right h₂] protected lemma le_tsub_iff_le_tsub (ha : add_le_cancellable a) (hc : add_le_cancellable c) (h₁ : a ≤ b) (h₂ : c ≤ b) : a ≤ b - c ↔ c ≤ b - a := by rw [ha.le_tsub_iff_left h₁, hc.le_tsub_iff_right h₂] protected lemma lt_tsub_iff_right_of_le (hc : add_le_cancellable c) (h : c ≤ b) : a < b - c ↔ a + c < b := begin refine ⟨_, hc.lt_tsub_of_add_lt_right⟩, intro h2, refine (add_le_of_le_tsub_right_of_le h h2.le).lt_of_ne _, rintro rfl, apply h2.not_le, rw [hc.add_tsub_cancel_right] end protected lemma lt_tsub_iff_left_of_le (hc : add_le_cancellable c) (h : c ≤ b) : a < b - c ↔ c + a < b := by { rw [add_comm], exact hc.lt_tsub_iff_right_of_le h } protected lemma lt_of_tsub_lt_tsub_left_of_le [contravariant_class α α (+) (<)] (hb : add_le_cancellable b) (hca : c ≤ a) (h : a - b < a - c) : c < b := begin conv_lhs at h { rw [← tsub_add_cancel_of_le hca] }, exact lt_of_add_lt_add_left (hb.lt_add_of_tsub_lt_right h), end protected lemma tsub_le_tsub_iff_left (ha : add_le_cancellable a) (hc : add_le_cancellable c) (h : c ≤ a) : a - b ≤ a - c ↔ c ≤ b := begin refine ⟨_, λ h, tsub_le_tsub_left h a⟩, rw [tsub_le_iff_left, ← hc.add_tsub_assoc_of_le h, hc.le_tsub_iff_right (h.trans le_add_self), add_comm b], apply ha, end protected lemma tsub_right_inj (ha : add_le_cancellable a) (hb : add_le_cancellable b) (hc : add_le_cancellable c) (hba : b ≤ a) (hca : c ≤ a) : a - b = a - c ↔ b = c := by simp_rw [le_antisymm_iff, ha.tsub_le_tsub_iff_left hb hba, ha.tsub_le_tsub_iff_left hc hca, and_comm] protected lemma tsub_lt_tsub_right_of_le (hc : add_le_cancellable c) (h : c ≤ a) (h2 : a < b) : a - c < b - c := by { apply hc.lt_tsub_of_add_lt_left, rwa [add_tsub_cancel_of_le h] } protected lemma tsub_inj_right (hab : add_le_cancellable (a - b)) (h₁ : b ≤ a) (h₂ : c ≤ a) (h₃ : a - b = a - c) : b = c := by { rw ← hab.inj, rw [tsub_add_cancel_of_le h₁, h₃, tsub_add_cancel_of_le h₂] } protected lemma tsub_lt_tsub_iff_left_of_le_of_le [contravariant_class α α (+) (<)] (hb : add_le_cancellable b) (hab : add_le_cancellable (a - b)) (h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < a - c ↔ c < b := begin refine ⟨hb.lt_of_tsub_lt_tsub_left_of_le h₂, _⟩, intro h, refine (tsub_le_tsub_left h.le _).lt_of_ne _, rintro h2, exact h.ne' (hab.tsub_inj_right h₁ h₂ h2) end @[simp] protected lemma add_tsub_tsub_cancel (hac : add_le_cancellable (a - c)) (h : c ≤ a) : (a + b) - (a - c) = b + c := (hac.tsub_eq_iff_eq_add_of_le $ tsub_le_self.trans le_self_add).mpr $ by rw [add_assoc, add_tsub_cancel_of_le h, add_comm] protected lemma tsub_tsub_cancel_of_le (hba : add_le_cancellable (b - a)) (h : a ≤ b) : b - (b - a) = a := by rw [hba.tsub_eq_iff_eq_add_of_le tsub_le_self, add_tsub_cancel_of_le h] end add_le_cancellable section contra /-! ### Lemmas where addition is order-reflecting. -/ variable [contravariant_class α α (+) (≤)] lemma eq_tsub_iff_add_eq_of_le (h : c ≤ b) : a = b - c ↔ a + c = b := contravariant.add_le_cancellable.eq_tsub_iff_add_eq_of_le h lemma tsub_eq_iff_eq_add_of_le (h : b ≤ a) : a - b = c ↔ a = c + b := contravariant.add_le_cancellable.tsub_eq_iff_eq_add_of_le h /-- See `add_tsub_le_assoc` for an inequality. -/ lemma add_tsub_assoc_of_le (h : c ≤ b) (a : α) : a + b - c = a + (b - c) := contravariant.add_le_cancellable.add_tsub_assoc_of_le h a lemma tsub_add_eq_add_tsub (h : b ≤ a) : a - b + c = a + c - b := contravariant.add_le_cancellable.tsub_add_eq_add_tsub h lemma tsub_tsub_assoc (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := contravariant.add_le_cancellable.tsub_tsub_assoc h₁ h₂ lemma tsub_add_tsub_comm (hba : b ≤ a) (hdc : d ≤ c) : a - b + (c - d) = a + c - (b + d) := contravariant.add_le_cancellable.tsub_add_tsub_comm contravariant.add_le_cancellable hba hdc lemma le_tsub_iff_left (h : a ≤ c) : b ≤ c - a ↔ a + b ≤ c := contravariant.add_le_cancellable.le_tsub_iff_left h lemma le_tsub_iff_right (h : a ≤ c) : b ≤ c - a ↔ b + a ≤ c := contravariant.add_le_cancellable.le_tsub_iff_right h lemma tsub_lt_iff_left (hbc : b ≤ a) : a - b < c ↔ a < b + c := contravariant.add_le_cancellable.tsub_lt_iff_left hbc lemma tsub_lt_iff_right (hbc : b ≤ a) : a - b < c ↔ a < c + b := contravariant.add_le_cancellable.tsub_lt_iff_right hbc /-- This lemma (and some of its corollaries also holds for `ennreal`, but this proof doesn't work for it. Maybe we should add this lemma as field to `has_ordered_sub`? -/ lemma lt_tsub_of_add_lt_right (h : a + c < b) : a < b - c := contravariant.add_le_cancellable.lt_tsub_of_add_lt_right h lemma lt_tsub_of_add_lt_left (h : a + c < b) : c < b - a := contravariant.add_le_cancellable.lt_tsub_of_add_lt_left h lemma tsub_lt_iff_tsub_lt (h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < c ↔ a - c < b := contravariant.add_le_cancellable.tsub_lt_iff_tsub_lt contravariant.add_le_cancellable h₁ h₂ lemma le_tsub_iff_le_tsub (h₁ : a ≤ b) (h₂ : c ≤ b) : a ≤ b - c ↔ c ≤ b - a := contravariant.add_le_cancellable.le_tsub_iff_le_tsub contravariant.add_le_cancellable h₁ h₂ /-- See `lt_tsub_iff_right` for a stronger statement in a linear order. -/ lemma lt_tsub_iff_right_of_le (h : c ≤ b) : a < b - c ↔ a + c < b := contravariant.add_le_cancellable.lt_tsub_iff_right_of_le h /-- See `lt_tsub_iff_left` for a stronger statement in a linear order. -/ lemma lt_tsub_iff_left_of_le (h : c ≤ b) : a < b - c ↔ c + a < b := contravariant.add_le_cancellable.lt_tsub_iff_left_of_le h /-- See `lt_of_tsub_lt_tsub_left` for a stronger statement in a linear order. -/ lemma lt_of_tsub_lt_tsub_left_of_le [contravariant_class α α (+) (<)] (hca : c ≤ a) (h : a - b < a - c) : c < b := contravariant.add_le_cancellable.lt_of_tsub_lt_tsub_left_of_le hca h lemma tsub_le_tsub_iff_left (h : c ≤ a) : a - b ≤ a - c ↔ c ≤ b := contravariant.add_le_cancellable.tsub_le_tsub_iff_left contravariant.add_le_cancellable h lemma tsub_right_inj (hba : b ≤ a) (hca : c ≤ a) : a - b = a - c ↔ b = c := contravariant.add_le_cancellable.tsub_right_inj contravariant.add_le_cancellable contravariant.add_le_cancellable hba hca lemma tsub_lt_tsub_right_of_le (h : c ≤ a) (h2 : a < b) : a - c < b - c := contravariant.add_le_cancellable.tsub_lt_tsub_right_of_le h h2 lemma tsub_inj_right (h₁ : b ≤ a) (h₂ : c ≤ a) (h₃ : a - b = a - c) : b = c := contravariant.add_le_cancellable.tsub_inj_right h₁ h₂ h₃ /-- See `tsub_lt_tsub_iff_left_of_le` for a stronger statement in a linear order. -/ lemma tsub_lt_tsub_iff_left_of_le_of_le [contravariant_class α α (+) (<)] (h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < a - c ↔ c < b := contravariant.add_le_cancellable.tsub_lt_tsub_iff_left_of_le_of_le contravariant.add_le_cancellable h₁ h₂ @[simp] lemma add_tsub_tsub_cancel (h : c ≤ a) : (a + b) - (a - c) = b + c := contravariant.add_le_cancellable.add_tsub_tsub_cancel h /-- See `tsub_tsub_le` for an inequality. -/ lemma tsub_tsub_cancel_of_le (h : a ≤ b) : b - (b - a) = a := contravariant.add_le_cancellable.tsub_tsub_cancel_of_le h end contra end canonically_ordered_add_monoid /-! ### Lemmas in a linearly canonically ordered monoid. -/ section canonically_linear_ordered_add_monoid variables [canonically_linear_ordered_add_monoid α] [has_sub α] [has_ordered_sub α] {a b c d : α} @[simp] lemma tsub_pos_iff_lt : 0 < a - b ↔ b < a := by rw [tsub_pos_iff_not_le, not_le] lemma tsub_eq_tsub_min (a b : α) : a - b = a - min a b := begin cases le_total a b with h h, { rw [min_eq_left h, tsub_self, tsub_eq_zero_iff_le.mpr h] }, { rw [min_eq_right h] }, end namespace add_le_cancellable protected lemma lt_tsub_iff_right (hc : add_le_cancellable c) : a < b - c ↔ a + c < b := ⟨lt_imp_lt_of_le_imp_le tsub_le_iff_right.mpr, hc.lt_tsub_of_add_lt_right⟩ protected lemma lt_tsub_iff_left (hc : add_le_cancellable c) : a < b - c ↔ c + a < b := ⟨lt_imp_lt_of_le_imp_le tsub_le_iff_left.mpr, hc.lt_tsub_of_add_lt_left⟩ protected lemma tsub_lt_tsub_iff_right (hc : add_le_cancellable c) (h : c ≤ a) : a - c < b - c ↔ a < b := by rw [hc.lt_tsub_iff_left, add_tsub_cancel_of_le h] protected lemma tsub_lt_self (ha : add_le_cancellable a) (h₁ : 0 < a) (h₂ : 0 < b) : a - b < a := begin refine tsub_le_self.lt_of_ne (λ h, _), rw [← h, tsub_pos_iff_lt] at h₁, exact h₂.not_le (ha.add_le_iff_nonpos_left.1 $ add_le_of_le_tsub_left_of_le h₁.le h.ge), end protected lemma tsub_lt_self_iff (ha : add_le_cancellable a) : a - b < a ↔ 0 < a ∧ 0 < b := begin refine ⟨λ h, ⟨(zero_le _).trans_lt h, (zero_le b).lt_of_ne _⟩, λ h, ha.tsub_lt_self h.1 h.2⟩, rintro rfl, rw [tsub_zero] at h, exact h.false end /-- See `lt_tsub_iff_left_of_le_of_le` for a weaker statement in a partial order. -/ protected lemma tsub_lt_tsub_iff_left_of_le (ha : add_le_cancellable a) (hb : add_le_cancellable b) (h : b ≤ a) : a - b < a - c ↔ c < b := lt_iff_lt_of_le_iff_le $ ha.tsub_le_tsub_iff_left hb h end add_le_cancellable section contra variable [contravariant_class α α (+) (≤)] /-- This lemma also holds for `ennreal`, but we need a different proof for that. -/ lemma tsub_lt_tsub_iff_right (h : c ≤ a) : a - c < b - c ↔ a < b := contravariant.add_le_cancellable.tsub_lt_tsub_iff_right h lemma tsub_lt_self : 0 < a → 0 < b → a - b < a := contravariant.add_le_cancellable.tsub_lt_self lemma tsub_lt_self_iff : a - b < a ↔ 0 < a ∧ 0 < b := contravariant.add_le_cancellable.tsub_lt_self_iff /-- See `lt_tsub_iff_left_of_le_of_le` for a weaker statement in a partial order. -/ lemma tsub_lt_tsub_iff_left_of_le (h : b ≤ a) : a - b < a - c ↔ c < b := contravariant.add_le_cancellable.tsub_lt_tsub_iff_left_of_le contravariant.add_le_cancellable h end contra /-! ### Lemmas about `max` and `min`. -/ lemma tsub_add_eq_max : a - b + b = max a b := begin cases le_total a b with h h, { rw [max_eq_right h, tsub_eq_zero_iff_le.mpr h, zero_add] }, { rw [max_eq_left h, tsub_add_cancel_of_le h] } end lemma add_tsub_eq_max : a + (b - a) = max a b := by rw [add_comm, max_comm, tsub_add_eq_max] lemma tsub_min : a - min a b = a - b := begin cases le_total a b with h h, { rw [min_eq_left h, tsub_self, tsub_eq_zero_iff_le.mpr h] }, { rw [min_eq_right h] } end lemma tsub_add_min : a - b + min a b = a := by { rw [← tsub_min, tsub_add_cancel_of_le], apply min_le_left } end canonically_linear_ordered_add_monoid namespace with_top section variables [has_sub α] [has_zero α] /-- If `α` has subtraction and `0`, we can extend the subtraction to `with_top α`. -/ protected def sub : Π (a b : with_top α), with_top α | _ ⊤ := 0 | ⊤ (x : α) := ⊤ | (x : α) (y : α) := (x - y : α) instance : has_sub (with_top α) := ⟨with_top.sub⟩ @[simp, norm_cast] lemma coe_sub {a b : α} : (↑(a - b) : with_top α) = ↑a - ↑b := rfl @[simp] lemma top_sub_coe {a : α} : (⊤ : with_top α) - a = ⊤ := rfl @[simp] lemma sub_top {a : with_top α} : a - ⊤ = 0 := by { cases a; refl } end variables [canonically_ordered_add_monoid α] [has_sub α] [has_ordered_sub α] instance : has_ordered_sub (with_top α) := begin constructor, rintro x y z, induction y using with_top.rec_top_coe, { simp }, induction x using with_top.rec_top_coe, { simp }, induction z using with_top.rec_top_coe, { simp }, norm_cast, exact tsub_le_iff_right end end with_top
2a411bcfdbab87f00ca6fcc18dad6e1f970a3915
b7b549d2cf38ac9d4e49372b7ad4d37f70449409
/src/LeanLLVM/DataLayout.lean
3421170fef0099396d7af8f10f45b51222c3fa9b
[ "Apache-2.0" ]
permissive
GaloisInc/lean-llvm
7cc196172fe02ff3554edba6cc82f333c30fdc2b
36e2ec604ae22d8ec1b1b66eca0f8887880db6c6
refs/heads/master
1,637,359,020,356
1,629,332,114,000
1,629,402,464,000
146,700,234
29
1
Apache-2.0
1,631,225,695,000
1,535,607,191,000
Lean
UTF-8
Lean
false
false
4,627
lean
import Std.Data.RBMap import LeanLLVM.Alignment import LeanLLVM.AST import LeanLLVM.Parser open Std (RBMap) namespace LLVM namespace parse section Mangling open Mangling def mangling_spec : parse Mangling := parse.describe "mangling spec" $ parse.choosePrefix [ ("e", pure elf) , ("m", pure mips) , ("o", pure mach_o) , ("w", pure windows_coff) , ("x", pure windows_coff_x86) ] end Mangling section LayoutSpec open LayoutSpec def pointer_spec : parse LayoutSpec := parse.describe "pointer spec spec" $ do let addrSpace <- parse.opt 0 parse.nat; let sz <- parse.textThen ":" parse.nat; let abi <- parse.textThen ":" parse.nat; let pref <- parse.textThen ":" parse.nat; let idx <- parse.opt' (parse.textThen ":" parse.nat); pure (pointerSize addrSpace sz abi pref idx) def size_spec (t:AlignType) : parse LayoutSpec := parse.describe "size spec" $ do let sz <- parse.nat; let abi <- parse.textThen ":" parse.nat; let pref <- parse.opt' (parse.textThen ":" parse.nat); pure (alignSize t sz abi pref) def layout_spec : parse LayoutSpec := parse.describe "layout spec" $ parse.choosePrefix [ ("E", pure (endianness Endian.big)) , ("e", pure (endianness Endian.little)) , ("p", pointer_spec) , ("i", size_spec AlignType.integer) , ("v", size_spec AlignType.vector) , ("f", size_spec AlignType.float) , ("a", aggregateAlign <$> (parse.textThen ":" parse.nat) <*> (parse.textThen ":" parse.nat)) , ("n", nativeIntSize <$> parse.sepBy parse.nat (parse.text ":")) , ("S", stackAlign <$> parse.nat) , ("P", functionAddressSpace <$> parse.nat) , ("A", stackAlloca <$> parse.nat) , ("m", mangling <$> (parse.textThen ":" mangling_spec)) ] end LayoutSpec def data_layout : parse (List LayoutSpec) := parse.describe "data layout" $ parse.sepBy layout_spec (parse.text "-") end parse end LLVM namespace LLVM structure DataLayout := (intLayout : Endian) (stackAlignment : Alignment) (aggregateAlignment : Alignment) (ptrSize : Nat) -- size in bytes (ptrAlign : Alignment) (integerInfo : AlignInfo) (vectorInfo : AlignInfo) (floatInfo : AlignInfo) def default_data_layout : DataLayout := { intLayout := Endian.big , stackAlignment := unaligned , aggregateAlignment := unaligned , ptrSize := 8 -- 8 bytes, 64 bits , ptrAlign := align8 , integerInfo := Std.RBMap.fromList [ ( 1, unaligned) , ( 8, unaligned) , (16, align2) , (32, align4) , (64, align8) ] _ , floatInfo := Std.RBMap.fromList [ ( 16, align2) , ( 32, align4) , ( 64, align8) , (128, align16) ] _ , vectorInfo := Std.RBMap.fromList [ ( 64, align8) , (128, align16) ] _ } def updateAlign (x:Nat) (a:Alignment) (ai:AlignInfo) : AlignInfo := ai.insert x a def addIntegerAlignment (x:Nat) (a:Alignment) (dl:DataLayout) : DataLayout := { dl with integerInfo := updateAlign x a dl.integerInfo } def addFloatAlignment (x:Nat) (a:Alignment) (dl:DataLayout) : DataLayout := { dl with floatInfo := updateAlign x a dl.floatInfo } def addVectorAlignment (x:Nat) (a:Alignment) (dl:DataLayout) : DataLayout := { dl with vectorInfo := updateAlign x a dl.vectorInfo } section LayoutSpec open LayoutSpec open AlignType def addLayoutSpec (dl:DataLayout) : LayoutSpec → Except String DataLayout | endianness e => pure { dl with intLayout := e } | stackAlign sa => match toAlignment sa with | none => throw ("invalid stack alignment: " ++ (Nat.toDigits 10 sa).asString) | some a => pure { dl with stackAlignment := a } | aggregateAlign abi pref => match toAlignment abi with | none => throw ("invalid aggregate alignment: " ++ (Nat.toDigits 10 abi).asString) | some a => pure { dl with aggregateAlignment := a } | pointerSize addr sz abi _pref _idx => match toAlignment abi with | none => throw $ "invalid pointer alignment: " ++ (Nat.toDigits 10 abi).asString | some a => pure { dl with ptrSize := sz, ptrAlign := a } | alignSize tp sz abi _pref => match toAlignment abi with | none => throw $ "invalid alignment: " ++ (Nat.toDigits 10 abi).asString | some a => match tp with | integer => pure (addIntegerAlignment sz a dl) | vector => pure (addVectorAlignment sz a dl) | float => pure (addFloatAlignment sz a dl) | _ => pure dl -- ignore other layout specs end LayoutSpec def computeDataLayout (ls:List LayoutSpec) : Except String DataLayout := List.foldlM addLayoutSpec default_data_layout ls end LLVM
c52dd1a8294885f1ad835aaa8371259bd270ae34
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/computability/turing_machine.lean
a072fddcd3540327f31453333e0b3911d97de526
[ "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
61,707
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Define a sequence of simple machine languages, starting with Turing machines and working up to more complex lanaguages based on Wang B-machines. -/ import data.fintype data.pfun logic.relation open relation namespace turing /-- A direction for the turing machine `move` command, either left or right. -/ @[derive decidable_eq] inductive dir | left | right def tape (Γ) := Γ × list Γ × list Γ def tape.mk {Γ} [inhabited Γ] (l : list Γ) : tape Γ := (l.head, [], l.tail) def tape.mk' {Γ} [inhabited Γ] (L R : list Γ) : tape Γ := (R.head, L, R.tail) def tape.move {Γ} [inhabited Γ] : dir → tape Γ → tape Γ | dir.left (a, L, R) := (L.head, L.tail, a :: R) | dir.right (a, L, R) := (R.head, a :: L, R.tail) def tape.nth {Γ} [inhabited Γ] : tape Γ → ℤ → Γ | (a, L, R) 0 := a | (a, L, R) (n+1:ℕ) := R.inth n | (a, L, R) -[1+ n] := L.inth n @[simp] theorem tape.nth_zero {Γ} [inhabited Γ] : ∀ (T : tape Γ), T.nth 0 = T.1 | (a, L, R) := rfl @[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] := by cases L; refl | (a, L, R) 0 := by cases L; refl | (a, L, R) 1 := rfl | (a, L, R) ((n+1:ℕ)+1) := by rw add_sub_cancel; refl @[simp] theorem tape.move_right_nth {Γ} [inhabited Γ] : ∀ (T : tape Γ) (i : ℤ), (T.move dir.right).nth i = T.nth (i+1) | (a, L, R) (n+1:ℕ) := by cases R; refl | (a, L, R) 0 := by cases R; refl | (a, L, R) -1 := rfl | (a, L, R) -[1+ n+1] := show _ = tape.nth _ (-[1+ n] - 1 + 1), by rw sub_add_cancel; refl def tape.write {Γ} (b : Γ) : tape Γ → tape Γ | (a, LR) := (b, LR) @[simp] theorem tape.write_self {Γ} : ∀ (T : tape Γ), T.write T.1 = T | (a, LR) := rfl @[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 def tape.map {Γ Γ'} (f : Γ → Γ') : tape Γ → tape Γ' | (a, L, R) := (f a, L.map f, R.map f) @[simp] theorem tape.map_fst {Γ Γ'} (f : Γ → Γ') : ∀ (T : tape Γ), (T.map f).1 = f T.1 | (a, L, R) := rfl @[simp] theorem tape.map_write {Γ Γ'} (f : Γ → Γ') (b : Γ) : ∀ (T : tape Γ), (T.write b).map f = (T.map f).write (f b) | (a, L, R) := rfl @[class] def pointed_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') := f (default _) = default _ theorem tape.map_move {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') [pointed_map f] : ∀ (T : tape Γ) d, (T.move d).map f = (T.map f).move d | (a, [], R) dir.left := by simpa! | (a, b::L, R) dir.left := by simp! | (a, L, []) dir.right := by simpa! | (a, L, b::R) dir.right := by simp! theorem tape.map_mk {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') [f0 : pointed_map f] : ∀ (l : list Γ), (tape.mk l).map f = tape.mk (l.map f) | [] := by simpa! [tape.mk] | (a::l) := rfl def eval {σ} (f : σ → option σ) : σ → roption σ := pfun.fix (λ s, roption.some $ match f s with none := sum.inl s | some s' := sum.inr s' end) def reaches {σ} (f : σ → option σ) : σ → σ → Prop := refl_trans_gen (λ a b, b ∈ f a) 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 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₂) theorem mem_eval {σ} {f : σ → option σ} {a b} : b ∈ eval f a ↔ reaches f a b ∧ f b = none := ⟨λ h, begin refine pfun.fix_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⟩,⟩ 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 [respects], { 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⟩ 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 simp [frespects, 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 [frespects, respects] 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₂, by simp; exact ⟨λ h, let ⟨b₁, bb, hb⟩ := tr_eval_rev H rfl h in ⟨b₁, hb, bb⟩, λ ⟨b₁, ab, bb⟩, begin rcases tr_eval H rfl ab with ⟨_, rfl, h⟩, rwa bb at h end⟩ def dwrite {K} [decidable_eq K] {C : K → Type*} (S : ∀ k, C k) (k') (l : C k') (k) : C k := if h : k = k' then eq.rec_on h.symm l else S k @[simp] theorem dwrite_eq {K} [decidable_eq K] {C : K → Type*} (S : ∀ k, C k) (k) (l : C k) : dwrite S k l k = l := by simp [dwrite] @[simp] theorem dwrite_ne {K} [decidable_eq K] {C : K → Type*} (S : ∀ k, C k) (k') (l : C k') (k) (h : ¬ k = k') : dwrite S k' l k = S k := by simp [dwrite, h] @[simp] theorem dwrite_self {K} [decidable_eq K] {C : K → Type*} (S : ∀ k, C k) (k) : dwrite S k (S k) = S := funext $ λ k', by unfold dwrite; split_ifs; [subst h, refl] 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 /-- 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. -/ def machine := Λ → Γ → option (Λ × stmt) /-- 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 Γ) 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 Γ) := (eval (step M) (init l)).map (λ c, c.tape.2.2) /-- 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 Λ'] def stmt.map (f : Γ → Γ') : stmt Γ → stmt Γ' | (stmt.move d) := stmt.move d | (stmt.write a) := stmt.write (f a) def cfg.map (f : Γ → Γ') (g : Λ → Λ') : cfg Γ Λ → cfg Γ' Λ' | ⟨q, T⟩ := ⟨g q, T.map f⟩ variables (M : machine Γ Λ) (f₁ : Γ → Γ') (f₂ : Γ' → Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ) def machine.map : machine Γ' Λ' | q l := (M (g₂ q) (f₂ l)).map (prod.map g₁ (stmt.map f₁)) theorem machine.map_step {S} (ss : supports M S) [pointed_map f₁] (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 simp! [g₂₁ q h, f₂₁ _], rcases M q T.1 with _|⟨q', d|a⟩, {refl}, { simp! [tape.map_move f₁] }, { simp! } end theorem map_init [pointed_map f₁] [g0 : pointed_map g₁] (l : list Γ) : (init l).map f₁ g₁ = init (l.map f₁) := by simp [init, cfg.map]; exact ⟨g0, tape.map_mk _ _⟩ theorem machine.map_respects {S} (ss : supports M S) [pointed_map f₁] [pointed_map g₁] (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'; simp!, { rw [← M.map_step f₁ f₂ g₁ g₂ ss f₂₁ g₂₁ _ cs, e], refl }, { refine ⟨_, ⟨step_supports M ss e cs, rfl⟩, trans_gen.single _⟩, rw [← M.map_step f₁ f₂ g₁ g₂ ss f₂₁ g₂₁ _ cs, e], exact rfl } end end end TM0 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 /-- 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 Γ) 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⟩ def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, T⟩ := none | ⟨some l, v, T⟩ := some (step_aux (M l) v T) variables [inhabited Λ] [inhabited σ] def init (l : list Γ) : cfg := ⟨some (default _), default _, tape.mk l⟩ def eval (M : Λ → stmt) (l : list Γ) : roption (list Γ) := (eval (step M) (init l)).map (λ c, c.tape.2.2) variables [fintype Γ] 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 /-- 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) local attribute [instance] classical.dec 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; simp [stmts₁] 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 [stmts₁, finset.subset_iff] at h₁₂ ⊢, iterate 3 { rcases h₁₂ with rfl | h₁₂, { simp [stmts₁] at h₀₁, rcases h₀₁ with rfl | h; simp * }, { exact or.inr (IH h₁₂) } }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { simp [stmts₁] at h₀₁, rcases h₀₁ with rfl | h; simp * }, { simp [IH₁ h₁₂] }, { simp [IH₂ h₁₂] } }, case TM1.stmt.goto : l { subst h₁₂, simpa [stmts₁] using h₀₁ }, case TM1.stmt.halt { subst h₁₂, simpa [stmts₁] using 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 [stmts₁, supports_stmt] 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 noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bind (λ 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 [stmts]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp [stmts]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) local attribute [-simp] finset.mem_insert_none 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 [step] 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₂ { simp [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 end end TM1 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 def Λ' := option stmt₁ × σ instance : inhabited Λ' := ⟨(some (M (default _)), default _)⟩ open TM0.stmt 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 Γ Λ' def tr : TM0.machine Γ Λ' | (none, v) s := none | (some q, v) s := some (tr_aux s q v) 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}, simp!, 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₂ { simp [TM1.step_aux], cases e : p T.1 v, { exact (reaches₁_eq (by simp! [e])).2 (IH₂ _ _) }, { exact (reaches₁_eq (by simp! [e])).2 (IH₁ _ _) } }, case TM1.stmt.goto : l { apply trans_gen.single, simp! }, case TM1.stmt.halt { apply trans_gen.single, simp! } end variables [fintype Γ] [fintype σ] noncomputable def tr_stmts (S : finset Λ) : finset Λ' := (TM1.stmts M S).product finset.univ local attribute [instance] classical.dec local attribute [simp] TM1.stmts₁_self theorem tr_supports {S : finset Λ} (ss : TM1.supports M S) : TM0.supports tr (↑(tr_stmts S)) := ⟨by simp [tr_stmts]; exact finset.some_mem_insert_none.2 (finset.mem_bind.2 ⟨_, ss.1, TM1.stmts₁_self⟩), λ q a q' s h₁ h₂, begin rcases q with ⟨_|q, v⟩, {cases h₁}, cases q' with q' v', simp [tr_stmts] at h₂ ⊢, cases q', {simp [TM1.stmts]}, simp [tr] 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₂, simp [TM1.stmts₁] }, case TM1.stmt.write : b q { cases h₁, refine TM1.stmts_trans _ h₂, simp [TM1.stmts₁] }, case TM1.stmt.load : b q IH { refine IH (TM1.stmts_trans _ h₂) _ h₁ hs, simp [TM1.stmts₁] }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { simp! at h₁, cases p a v, { refine IH₂ (TM1.stmts_trans _ h₂) _ h₁ hs.2, simp [TM1.stmts₁] }, { refine IH₁ (TM1.stmts_trans _ h₂) _ h₁ hs.1, simp [TM1.stmts₁] } }, case TM1.stmt.goto : l { cases h₁, exact finset.some_mem_insert_none.2 (finset.mem_bind.2 ⟨_, hs _ _, TM1.stmts₁_self⟩) }, case TM1.stmt.halt { cases h₁ } end⟩ theorem tr_eval (l : list Γ) : TM0.eval tr l = TM1.eval M l := (congr_arg _ (tr_eval' _ _ _ tr_respects ⟨some _, _, _⟩)).trans begin simp [tr_cfg], rw [roption.map_map, TM1.eval], congr', exact funext (λ ⟨_, _, _⟩, rfl) end end end TM1to0 /- Reduce an n-symbol Turing machine to a 2-symbol Turing machine -/ 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, by simpa using congr_fun h b⟩, let H := (F.to_embedding.trans G).trans (equiv.vector_equiv_fin _ _).symm.to_embedding, 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 Γ Λ σ 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 Λ' σ 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 → Γ) def move (d : dir) (q : stmt') : stmt' := (stmt.move d)^[n] q def read (f : Γ → stmt') : stmt' := read_aux n (λ v, move dir.left $ f (dec v)) def write : list bool → stmt' → stmt' | [] q := q | (a :: l) q := stmt.write (λ _ _, a) $ stmt.move dir.right $ write l q def tr_normal : stmt₁ → stmt' | (stmt.move dir.left q) := move dir.right $ (move dir.left)^[2] $ tr_normal q | (stmt.move dir.right q) := move dir.right $ 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 := move dir.right $ move dir.left $ stmt.halt def tr_tape' (L R : list Γ) : tape bool := tape.mk' (L.bind (λ x, (enc x).to_list.reverse)) (R.bind (λ x, (enc x).to_list) ++ [default _]) def tr_tape : tape Γ → tape bool | (a, L, R) := tr_tape' L (a :: R) theorem tr_tape_drop_right : ∀ R : list Γ, list.drop n (R.bind (λ x, (enc x).to_list)) = R.tail.bind (λ x, (enc x).to_list) | [] := list.drop_nil _ | (a::R) := by simp; exact list.drop_left' (enc a).2 parameters (enc0 : enc (default _) = vector.repeat ff n) section include enc0 theorem tr_tape_take_right : ∀ R : list Γ, list.take' n (R.bind (λ x, (enc x).to_list)) = (enc R.head).to_list | [] := by simp; exact (congr_arg vector.to_list enc0).symm | (a::R) := by simp; exact list.take'_left' (enc a).2 end parameters (M : Λ → stmt₁) def tr : Λ' → stmt' | (Λ'.normal l) := tr_normal (M l) | (Λ'.write a q) := write (enc a).to_list $ move dir.left $ tr_normal q def tr_cfg : cfg₁ → cfg' | ⟨l, v, T⟩ := ⟨l.map Λ'.normal, v, tr_tape T⟩ include enc0 theorem tr_tape'_move_left (L R) : (tape.move dir.left)^[n] (tr_tape' L R) = (tr_tape' L.tail (L.head :: R)) := begin cases L with a L, { simp [enc0, vector.repeat, tr_tape'], suffices : ∀ i R', default _ ∈ R' → (tape.move dir.left^[i]) (tape.mk' [] R') = tape.mk' [] (list.repeat ff i ++ R'), from this n _ (by simp), intros i R' hR, induction i with i IH, {refl}, rw [nat.iterate_succ', IH], simp [tape.mk', tape.move], exact list.cons_head_tail (list.ne_nil_of_mem $ list.mem_append_right _ hR) }, { simp [tr_tape'], suffices : ∀ L' R' l₁ l₂ (hR : default _ ∈ R') (e : vector.to_list (enc a) = list.reverse_core l₁ l₂), (tape.move dir.left^[l₁.length]) (tape.mk' (l₁ ++ L') (l₂ ++ R')) = tape.mk' L' (vector.to_list (enc a) ++ R'), { simpa using this _ _ _ _ _ (list.reverse_reverse _).symm, simp }, intros, induction l₁ with b l₁ IH generalizing l₂, { cases e, refl }, simp [nat.iterate_succ, -add_comm], convert IH _ e, simp [tape.move, tape.mk'], exact list.cons_head_tail (list.ne_nil_of_mem $ list.mem_append_right _ hR) } end theorem tr_tape'_move_right (L R) : (tape.move dir.right)^[n] (tr_tape' L R) = (tr_tape' (R.head :: L) R.tail) := begin cases R with a R, { simp [enc0, vector.repeat, tr_tape'], suffices : ∀ i L', (tape.move dir.right^[i]) (ff, L', []) = (ff, list.repeat ff i ++ L', []), from this n _, intros, induction i; simp [nat.iterate_succ', tape.move, *]; refl }, { simp [tr_tape'], suffices : ∀ L' R' l₁ l₂ : list bool, (tape.move dir.right^[l₂.length]) (tape.mk' (l₁ ++ L') (l₂ ++ R')) = tape.mk' (list.reverse_core l₂ l₁ ++ L') R', { simpa using this _ _ [] (enc a).to_list }, intros, induction l₂ with b l₂ IH generalizing l₁, {refl}, simp [-add_comm, nat.iterate_succ], exact IH (b::l₁) } end 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 simp [move], 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 [nat.iterate_succ', step_aux, IH, ← nat.iterate_succ] 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.head :: R.tail)) := begin suffices : ∀ f, step_aux (read_aux n f) v (tr_tape' enc L R) = step_aux (f (enc R.head)) v (tr_tape' enc (R.head :: L) R.tail), { rw [read, this, step_aux_move enc enc0, encdec, tr_tape'_move_left enc enc0], refl }, cases R with a R, { suffices : ∀ i f L', step_aux (read_aux i f) v (ff, L', []) = step_aux (f (vector.repeat ff i)) v (ff, list.repeat ff i ++ L', []), { intro f, convert this n f _, simp [tr_tape', tape.mk', enc0, vector.repeat] }, clear f L, intros, induction i with i IH generalizing L', {refl}, simp [read_aux, step_aux, tape.mk', tape.move], rw [IH], congr', simpa using congr_arg (++ L') (list.repeat_add ff i 1).symm }, { simp [tr_tape'], suffices : ∀ i f L' R' l₁ l₂ h, step_aux (read_aux i f) v (tape.mk' (l₁ ++ L') (l₂ ++ R')) = step_aux (f ⟨l₂, h⟩) v (tape.mk' (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}, dsimp [read_aux, step_aux], change (tape.mk' (l₁ ++ L') (a :: (l₂ ++ R'))).1 with a, transitivity step_aux (read_aux l₂.length (λ v, f (a :: v))) v (tape.mk' (a :: l₁ ++ L') (l₂ ++ R')), { cases a; refl }, rw IH, refl } end theorem step_aux_write (q v a b L R) : step_aux (write (enc a).to_list q) v (tr_tape' L (b :: R)) = step_aux q v (tr_tape' (a :: L) R) := begin simp [tr_tape'], suffices : ∀ {L' R'} (l₁ l₂ l₂' : list bool) (e : l₂'.length = l₂.length), step_aux (write l₂ q) v (tape.mk' (l₁ ++ L') (l₂' ++ R')) = step_aux q v (tape.mk' (list.reverse_core l₂ l₁ ++ L') R'), from this [] _ _ ((enc b).2.trans (enc a).2.symm), 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, simp [write, step_aux], convert IH _ _ e, refl end theorem tr_respects : respects (step M) (step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, (a, L, R)⟩, begin cases l₁ with l₁, {exact rfl}, suffices : ∀ q R, reaches (step (tr enc dec M)) (step_aux (tr_normal dec q) v (tr_tape' enc L R)) (tr_cfg enc (step_aux q v (tape.mk' L R))), { refine trans_gen.head' rfl (this _ (a::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 [tr_normal, step_aux_move enc enc0, step_aux, tr_tape'_move_left enc enc0, tr_tape'_move_right enc enc0]; apply IH }, case TM1.stmt.write : a q IH { simp [tr_normal, step_aux_read enc dec enc0 encdec, step_aux], refine refl_trans_gen.head rfl _, simp [tr, tr_normal, step_aux, step_aux_write enc dec enc0 encdec, step_aux_move enc enc0, tr_tape'_move_left enc enc0], apply IH }, case TM1.stmt.load : a q IH { simp [tr_normal, step_aux_read enc dec enc0 encdec], apply IH }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { simp [tr_normal, step_aux_read enc dec enc0 encdec, step_aux], change (tape.mk' L R).1 with R.head, cases p R.head v; [apply IH₂, apply IH₁] }, case TM1.stmt.goto : l { simp [tr_normal, step_aux_read enc dec enc0 encdec, step_aux], apply refl_trans_gen.refl }, case TM1.stmt.halt { simp [tr_normal, step_aux, tr_cfg, step_aux_move enc enc0, tr_tape'_move_left enc enc0, tr_tape'_move_right enc enc0], apply refl_trans_gen.refl } end omit enc0 encdec local attribute [instance] classical.dec parameters [fintype Γ] 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 := ∅ noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bind (λ l, insert (Λ'.normal l) (writes (M l))) 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 [*, supports_stmt] 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 [write, supports_stmt, *] local attribute [simp] supports_stmt_move supports_stmt_write 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 simp [hf]), λ i f hf, begin induction i with i IH, {exact hf _}, split; simp [supports_stmt]; apply IH; simp [hf], end theorem tr_supports {S} (ss : supports M S) : supports tr (tr_supp S) := ⟨by simp [tr_supp]; exact ⟨_, ss.1, or.inl rfl⟩, λ q h, begin simp [tr_supp] at h, 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 h with ⟨l, hl, h⟩, have := this _ (ss.2 _ hl) (λ q' hq, by simp [tr_supp]; exact ⟨_, hl, or.inr hq⟩), rcases h with rfl | h, exacts [this.1, this.2 _ h] }, intros q hs hw, induction q, case TM1.stmt.move : d q IH { dsimp [writes] at hw ⊢, replace IH := IH hs hw, refine ⟨_, IH.2⟩, cases d; simp [tr_normal, IH] }, case TM1.stmt.write : f q IH { simp [writes] at hw ⊢, replace IH := IH hs (λ q hq, hw q (or.inl hq)), refine ⟨supports_stmt_read _ $ λ a _ s, hw _ (or.inr ⟨_, rfl⟩), λ q' hq, _⟩, rcases hq with hq | ⟨a, q₂, rfl⟩, { exact IH.2 _ hq }, { simp [tr, IH.1] } }, case TM1.stmt.load : a q IH { dsimp [writes] at hw ⊢, replace IH := IH hs hw, refine ⟨supports_stmt_read _ (λ a, _), IH.2⟩, simp [tr_normal, supports_stmt, IH.1] }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { simp [writes] 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 { simp [writes], refine supports_stmt_read _ (λ a _ s, _), simp [tr_supp], exact ⟨_, hs _ _, or.inl rfl⟩ }, case TM1.stmt.halt { simp [supports_stmt, writes, tr_normal] } end⟩ end end TM1to1 namespace TM0to1 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] 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 def tr : Λ' → stmt₁ | (Λ'.normal q) := branch (λ a _, (M q a).is_none) halt $ goto (λ a _, match M q a with | none := default _ | 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) 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 simp [TM0.step], cases e : M q T.1, { simp [frespects, TM1.step, tr_cfg, e] }, cases val with q' s, simp [frespects, TM0.step, tr_cfg, e], 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 _); simp [TM1.step, TM1.step_aux, tr, e, TM0.step], cases e' : M q' (TM0.step._match_1 T s).1, { apply refl_trans_gen.single, simp [TM1.step, e', tr, TM1.step_aux] }, { refl } end end end TM0to1 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 structure cfg := (l : option Λ) (var : σ) (stk : ∀ k, list (Γ k)) parameters {Γ Λ σ K} def step_aux : stmt → σ → (∀ k, list (Γ k)) → cfg | (push k f q) v S := step_aux q v (dwrite 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') (dwrite 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⟩ def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, S⟩ := none | ⟨some l, v, S⟩ := some (step_aux (M l) v S) def reaches (M : Λ → stmt) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) variables [inhabited Λ] [inhabited σ] def init (k) (L : list (Γ k)) : cfg := ⟨some (default _), default _, dwrite (λ _, []) k L⟩ def eval (M : Λ → stmt) (k) (L : list (Γ k)) : roption (list (Γ k)) := (eval (step M) (init k L)).map $ λ c, c.stk k variables [fintype K] [∀ k, fintype (Γ k)] [fintype σ] 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 def supports (M : Λ → stmt) (S : finset Λ) := default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) local attribute [instance] classical.dec 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; simp [stmts₁] 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 [stmts₁, finset.subset_iff] at h₁₂ ⊢, iterate 4 { rcases h₁₂ with rfl | h₁₂, { simp [stmts₁] at h₀₁, rcases h₀₁ with rfl | h; simp * }, { exact or.inr (IH h₁₂) } }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { simp [stmts₁] at h₀₁, rcases h₀₁ with rfl | h; simp * }, { simp [IH₁ h₁₂] }, { simp [IH₂ h₁₂] } }, case TM2.stmt.goto : l { subst h₁₂, simpa [stmts₁] using h₀₁ }, case TM2.stmt.halt { subst h₁₂, simpa [stmts₁] using 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 [stmts₁, supports_stmt] 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 noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bind (λ 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 [stmts]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp [stmts]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) local attribute [-simp] finset.mem_insert_none 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 [step] 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₂ { simp [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 end end TM2 namespace TM2to1 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 Γ Λ σ inductive stackel (k : K) | val : Γ k → stackel | bottom : stackel | top : stackel instance stackel.inhabited (k) : inhabited (stackel k) := ⟨stackel.top _⟩ def stackel.is_bottom {k} : stackel k → bool | (stackel.bottom _) := tt | _ := ff def stackel.is_top {k} : stackel k → bool | (stackel.top _) := tt | _ := ff def stackel.get {k} : stackel k → option (Γ k) | (stackel.val a) := some a | _ := none section open stackel def stackel_equiv {k} : stackel k ≃ option (option (Γ k)) := begin refine ⟨λ s, _, λ s, _, _, _⟩, { cases s, exacts [some (some s), none, some none] }, { rcases s with _|_|s, exacts [bottom _, top _, val s] }, { intro s, cases s; refl }, { intro s, rcases s with _|_|s; refl }, end end def Γ' := ∀ k, stackel k instance Γ'.inhabited : inhabited Γ' := ⟨λ _, default _⟩ instance stackel.fintype {k} [fintype (Γ k)] : fintype (stackel k) := fintype.of_equiv _ stackel_equiv.symm instance Γ'.fintype [fintype K] [∀ k, fintype (Γ k)] : fintype Γ' := pi.fintype inductive st_act (k : K) | push {} : (σ → Γ k) → st_act | pop {} : bool → (σ → option (Γ k) → σ) → st_act section open st_act def st_run {k : K} : st_act k → stmt₂ → stmt₂ | (push f) := TM2.stmt.push k f | (pop ff f) := TM2.stmt.peek k f | (pop tt f) := TM2.stmt.pop k f def st_var {k : K} (v : σ) (l : list (Γ k)) : st_act k → σ | (push f) := v | (pop b f) := f v l.head' def st_write {k : K} (v : σ) (l : list (Γ k)) : st_act k → list (Γ k) | (push f) := f v :: l | (pop ff f) := l | (pop tt f) := l.tail @[elab_as_eliminator] theorem {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₁ _ (pop ff f) _ (stmt_st_rec q) | (TM2.stmt.pop k f q) := H₁ _ (pop tt 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 [fintype K] [∀ k, fintype (Γ k)] [fintype σ] (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 inductive Λ' : Type (max u_1 u_2 u_3 u_4) | normal {} : Λ → Λ' | go (k) : st_act k → stmt₂ → Λ' | ret {} : K → stmt₂ → Λ' open Λ' instance : inhabited Λ' := ⟨normal (default _)⟩ local notation `stmt₁` := TM1.stmt Γ' Λ' σ local notation `cfg₁` := TM1.cfg Γ' Λ' σ open TM1.stmt def tr_st_act {k} (q : stmt₁) : st_act k → stmt₁ | (st_act.push f) := write (λ a s, dwrite a k $ stackel.val $ f s) $ move dir.right $ write (λ a s, dwrite a k $ stackel.top k) q | (st_act.pop b f) := move dir.left $ load (λ a s, f s (a k).get) $ cond b ( branch (λ a s, (a k).is_bottom) ( move dir.right q ) ( move dir.right $ write (λ a s, dwrite a k $ default _) $ move dir.left $ write (λ a s, dwrite a k $ stackel.top k) q ) ) ( move dir.right q ) def tr_init (k) (L : list (Γ k)) : list Γ' := stackel.bottom :: match L.reverse with | [] := [stackel.top] | (a::L') := dwrite stackel.top k (stackel.val a) :: (L'.map stackel.val ++ [stackel.top k]).map (dwrite (default _) k) end 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) (dwrite S k (st_write v (S k) s)) | (st_act.push f) := rfl | (st_act.pop ff f) := by simp! | (st_act.pop tt f) := rfl 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.pop ff f) q) | (TM2.stmt.pop k f q) := goto (λ _ _, go k (st_act.pop tt 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 parameters (M : Λ → stmt₂) include M def tr : Λ' → stmt₁ | (normal q) := tr_normal (M q) | (go k s q) := branch (λ a s, (a k).is_top) (tr_st_act (goto (λ _ _, ret k q)) s) (move dir.right $ goto (λ _ _, go k s q)) | (ret k q) := branch (λ a s, (a k).is_bottom) (tr_normal q) (move dir.left $ goto (λ _ _, ret k q)) def tr_stk {k} (S : list (Γ k)) (L : list (stackel k)) : Prop := ∃ n, L = (S.map stackel.val).reverse_core (stackel.top k :: list.repeat (default _) n) local attribute [pp_using_anonymous_constructor] turing.TM1.cfg inductive tr_cfg : cfg₂ → cfg₁ → Prop | mk {q v} {S : ∀ k, list (Γ k)} {L : list Γ'} : (∀ k, tr_stk (S k) (L.map (λ a, a k))) → tr_cfg ⟨q, v, S⟩ ⟨q.map normal, v, (stackel.bottom, [], L)⟩ theorem tr_respects_aux₁ {k} (o q v) : ∀ S₁ {s S₂} {T : list Γ'}, T.map (λ (a : Γ'), a k) = (list.map stackel.val S₁).reverse_core (s :: S₂) → ∃ a T₁ T₂, T = list.reverse_core T₁ (a :: T₂) ∧ a k = s ∧ T₁.map (λ (a : Γ'), a k) = S₁.map stackel.val ∧ T₂.map (λ (a : Γ'), a k) = S₂ ∧ reaches₀ (TM1.step tr) ⟨some (go k o q), v, (stackel.bottom, [], T)⟩ ⟨some (go k o q), v, (a, T₁ ++ [stackel.bottom], T₂)⟩ | [] s S₂ (a :: T) hT := by injection hT with es e₂; exact ⟨a, [], _, rfl, es, rfl, e₂, reaches₀.single rfl⟩ | (s' :: S₁) s S₂ T hT := let ⟨a, T₁, b'::T₂, e, es', e₁, e₂, H⟩ := tr_respects_aux₁ S₁ hT in by injection e₂ with es e₂; exact ⟨b', a::T₁, T₂, e, es, by simpa [es'], e₂, H.tail (by simp! [es'])⟩ local attribute [simp] TM1.step TM1.step_aux tr tr_st_act st_var st_write tape.move tape.write list.reverse_core stackel.get stackel.is_bottom theorem tr_respects_aux₂ {k q v} {S : Π k, list (Γ k)} {T₁ T₂ : list Γ'} {a : Γ'} (hT : ∀ k, tr_stk (S k) ((T₁.reverse_core (a :: T₂)).map (λ (a : Γ'), a k))) (e₁ : T₁.map (λ (a : Γ'), a k) = list.map stackel.val (S k)) (ea : a k = stackel.top k) (o) : let v' := st_var v (S k) o, Sk' := st_write v (S k) o, S' : ∀ k, list (Γ k) := dwrite S k Sk' in ∃ b (T₁' T₂' : list Γ'), (∀ (k' : K), tr_stk (S' k') ((T₁'.reverse_core (b :: T₂')).map (λ (a : Γ'), a k'))) ∧ T₁'.map (λ a, a k) = Sk'.map stackel.val ∧ b k = stackel.top k ∧ TM1.step_aux (tr_st_act q o) v (a, T₁ ++ [stackel.bottom], T₂) = TM1.step_aux q v' (b, T₁' ++ [stackel.bottom], T₂') := begin dsimp, cases o with f b f, { -- push refine ⟨_, dwrite a k (stackel.val (f v)) :: T₁, _, _, by simp [e₁]; refl, by simp, rfl⟩, intro k', cases hT k' with n e, by_cases h : k' = k, { subst k', existsi n.pred, simp [list.reverse_core_eq, e₁, list.append_left_inj] at e ⊢, simp [e] }, { cases T₂ with t T₂, { existsi n+1, simpa [h, list.reverse_core_eq, e₁, list.repeat_add] using congr_arg (++ [default Γ' k']) e }, { existsi n, simpa [h, list.reverse_core_eq] using e } } }, have dw := dwrite_self S k, cases T₁ with t T₁; cases eS : S k with s Sk; rw eS at e₁ dw; injection e₁ with tk e₁'; cases b, { -- peek nil simp [eS, dw], exact ⟨_, [], _, hT, rfl, ea, rfl⟩ }, { -- pop nil simp [eS, dw], exact ⟨_, [], _, hT, rfl, ea, rfl⟩ }, { -- peek cons dsimp at tk, simp [eS, tk, dw], exact ⟨_, t::T₁, _, hT, e₁, ea, rfl⟩ }, { -- pop cons dsimp at tk, simp [eS, tk], refine ⟨_, _, _, _, e₁', by simp, rfl⟩, intro k', cases hT k' with n e, by_cases h : k' = k, { subst k', existsi n+1, simp [list.reverse_core_eq, eS, e₁', list.append_left_inj] at e ⊢, simp [e] }, { existsi n, simpa [h, list.map_reverse_core] using e } }, end theorem tr_respects_aux₃ {k q v} {S : Π k, list (Γ k)} {T : list Γ'} (hT : ∀ k, tr_stk (S k) (T.map (λ (a : Γ'), a k))) : ∀ (T₁ : list Γ') {T₂ : list Γ'} {a : Γ'} {S₁} (e : T = T₁.reverse_core (a :: T₂)) (ha : (a k).is_bottom = ff) (e₁ : T₁.map (λ (a : Γ'), a k) = list.map stackel.val S₁), reaches₀ (TM1.step tr) ⟨some (ret k q), v, (a, T₁ ++ [stackel.bottom], T₂)⟩ ⟨some (ret k q), v, (stackel.bottom, [], T)⟩ | [] T₂ a S₁ e ha e₁ := reaches₀.single (by simp [ha, e]) | (b :: T₁) T₂ a (s :: S₁) e ha e₁ := begin injection e₁ with es e₁, dsimp at es, refine reaches₀.head _ (tr_respects_aux₃ T₁ e (by simp [es]) e₁), simp [ha] end theorem tr_respects_aux {q v T k} {S : Π k, list (Γ k)} (hT : ∀ (k : K), tr_stk (S k) (list.map (λ (a : Γ'), a k) T)) (o : st_act k) (IH : ∀ {v : σ} {S : Π (k : K), list (Γ k)} {T : list Γ'}, (∀ (k : K), tr_stk (S k) (list.map (λ (a : Γ'), a k) T)) → (∃ b, tr_cfg (TM2.step_aux q v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal q) v (stackel.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 (stackel.bottom, [], T)) b := begin rcases hT k with ⟨n, hTk⟩, simp [tr_normal_run], rcases tr_respects_aux₁ M o q v _ hTk with ⟨a, T₁, T₂, rfl, ea, e₁, e₂, hgo⟩, rcases tr_respects_aux₂ M hT e₁ ea _ with ⟨b, T₁', T₂', hT', e₁', eb, hrun⟩, have hret := tr_respects_aux₃ M hT' _ rfl (by simp [eb]) e₁', have := hgo.tail' rfl, simp [ea, tr] at this, rw [hrun, TM1.step_aux] at this, rcases IH hT' with ⟨c, gc, rc⟩, simp [step_run], refine ⟨c, gc, (this.to₀.trans hret _ (trans_gen.head' rfl rc)).to_refl⟩ 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; simp!, 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 }, { simp [IH hT] }, { simp, 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)) := ⟨λ k', begin simp [tr_init, (∘)], cases e : L.reverse with a L'; simp [tr_init], { cases list.reverse_eq_nil.1 e, simp, exact ⟨0, rfl⟩ }, by_cases k' = k, { subst k', existsi 0, simp [list.reverse_core_eq, (∘)], rw [← list.map_reverse, e], refl }, { simp [h, (∘)], existsi L'.length + 1, rw list.repeat_add, 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), (∀ k', tr_stk (S k') (L₁.map (λ a, a k'))) ∧ S k = L₂ := begin rcases (roption.mem_map_iff _).1 H₁ with ⟨c₁, h₁, rfl⟩, rcases (roption.mem_map_iff _).1 H₂ with ⟨c₂, h₂, rfl⟩, rcases tr_eval (tr_respects M) (tr_cfg_init M k L) h₂ with ⟨_, ⟨q, v, S, L₁', hT⟩, h₃⟩, cases roption.mem_unique h₁ h₃, exact ⟨S, hT, rfl⟩ end variables [fintype K] [∀ k, fintype (Γ k)] [fintype σ] local attribute [instance] classical.dec local attribute [simp] TM2.stmts₁_self noncomputable def tr_stmts₁ : stmt₂ → finset Λ' | Q@(TM2.stmt.push k f q) := {go k (st_act.push f) q, ret k q} ∪ tr_stmts₁ q | Q@(TM2.stmt.peek k f q) := {go k (st_act.pop ff f) q, ret k q} ∪ tr_stmts₁ q | Q@(TM2.stmt.pop k f q) := {go k (st_act.pop tt f) q, ret k 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 k q} ∪ tr_stmts₁ q := by rcases s with _|_|_; dsimp [tr_stmts₁, st_run]; congr noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bind (λ l, insert (normal l) (tr_stmts₁ (M l))) local attribute [simp] tr_stmts₁ tr_stmts₁_run supports_run tr_normal_run TM1.supports_stmt TM2.supports_stmt theorem tr_supports {S} (ss : TM2.supports M S) : TM1.supports tr (tr_supp S) := ⟨finset.mem_bind.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₁ M q, x ∈ tr_supp M S), TM1.supports_stmt (tr_supp M S) (tr_normal q) ∧ (∀ l' ∈ tr_stmts₁ M q, TM1.supports_stmt (tr_supp M S) (tr M l')), { simp [tr_supp] at h, rcases h with ⟨l, lS, h⟩, have := this _ (ss.2 l lS) (λ x hx, finset.mem_bind.2 ⟨_, lS, finset.mem_insert_of_mem hx⟩), rcases h with rfl | h; [exact this.1, exact this.2 _ h] }, refine stmt_st_rec _ _ _ _ _; clear h l'; intros, { -- stack op simp at sub ss', have hgo := sub _ (or.inr $ or.inr rfl), have hret := sub _ (or.inl rfl), cases IH ss' (λ x hx, sub x $ or.inr $ or.inl hx) with IH₁ IH₂, refine ⟨by simp [hgo], λ l h, _⟩, rw [tr_stmts₁_run] at h, simp at h, rcases h with rfl | h | rfl, { simp [hret], exact IH₁ }, { exact IH₂ _ h }, { simp [hgo], rcases s with _|_|_; simp! [hret] } }, { -- load dsimp at sub ⊢, exact IH ss' sub }, { -- branch simp at sub, cases IH₁ ss'.1 (λ x hx, sub x $ or.inl hx) with IH₁₁ IH₁₂, cases IH₂ ss'.2 (λ x hx, sub x $ or.inr hx) with IH₂₁ IH₂₂, refine ⟨⟨IH₁₁, IH₂₁⟩, λ l h, _⟩, rw [tr_stmts₁] at h, simp at h, rcases h with h | h; [exact IH₁₂ _ h, exact IH₂₂ _ h] }, { -- goto rw tr_stmts₁, simp [tr_normal], exact λ v, finset.mem_bind.2 ⟨_, ss' v, by simp⟩ }, { simp } -- halt end⟩ end end TM2to1 end turing
3901d1f08c25a68ca4f0bee9cf26008cc332e242
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/algebraic_geometry/Gamma_Spec_adjunction.lean
1c6a650e3882099acc4d2481f975268baaae746a
[ "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,169
lean
/- Copyright (c) 2021 Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Junyan Xu -/ import algebraic_geometry.Scheme import category_theory.adjunction.limits import category_theory.adjunction.reflective /-! # Adjunction between `Γ` and `Spec` We define the adjunction `Γ_Spec.adjunction : Γ ⊣ Spec` by defining the unit (`to_Γ_Spec`, in multiple steps in this file) and counit (done in Spec.lean) and checking that they satisfy the left and right triangle identities. The constructions and proofs make use of maps and lemmas defined and proved in structure_sheaf.lean extensively. Notice that since the adjunction is between contravariant functors, you get to choose one of the two categories to have arrows reversed, and it is equally valid to present the adjunction as `Spec ⊣ Γ` (`Spec.to_LocallyRingedSpace.right_op ⊣ Γ`), in which case the unit and the counit would switch to each other. ## Main definition * `algebraic_geometry.identity_to_Γ_Spec` : The natural transformation `𝟭 _ ⟶ Γ ⋙ Spec`. * `algebraic_geometry.Γ_Spec.LocallyRingedSpace_adjunction` : The adjunction `Γ ⊣ Spec` from `CommRingᵒᵖ` to `LocallyRingedSpace`. * `algebraic_geometry.Γ_Spec.adjunction` : The adjunction `Γ ⊣ Spec` from `CommRingᵒᵖ` to `Scheme`. -/ noncomputable theory universes u open prime_spectrum namespace algebraic_geometry open opposite open category_theory open structure_sheaf Spec (structure_sheaf) open topological_space open algebraic_geometry.LocallyRingedSpace open Top.presheaf open Top.presheaf.sheaf_condition namespace LocallyRingedSpace variable (X : LocallyRingedSpace.{u}) /-- The map from the global sections to a stalk. -/ def Γ_to_stalk (x : X) : Γ.obj (op X) ⟶ X.presheaf.stalk x := X.presheaf.germ (⟨x,trivial⟩ : (⊤ : opens X)) /-- The canonical map from the underlying set to the prime spectrum of `Γ(X)`. -/ def to_Γ_Spec_fun : X → prime_spectrum (Γ.obj (op X)) := λ x, comap (X.Γ_to_stalk x) (local_ring.closed_point (X.presheaf.stalk x)) lemma not_mem_prime_iff_unit_in_stalk (r : Γ.obj (op X)) (x : X) : r ∉ (X.to_Γ_Spec_fun x).as_ideal ↔ is_unit (X.Γ_to_stalk x r) := by erw [local_ring.mem_maximal_ideal, not_not] /-- The preimage of a basic open in `Spec Γ(X)` under the unit is the basic open in `X` defined by the same element (they are equal as sets). -/ lemma to_Γ_Spec_preim_basic_open_eq (r : Γ.obj (op X)) : X.to_Γ_Spec_fun⁻¹' (basic_open r).1 = (X.to_RingedSpace.basic_open r).1 := by { ext, erw X.to_RingedSpace.mem_top_basic_open, apply not_mem_prime_iff_unit_in_stalk } /-- `to_Γ_Spec_fun` is continuous. -/ lemma to_Γ_Spec_continuous : continuous X.to_Γ_Spec_fun := begin apply is_topological_basis_basic_opens.continuous, rintro _ ⟨r, rfl⟩, erw X.to_Γ_Spec_preim_basic_open_eq r, exact (X.to_RingedSpace.basic_open r).2, end /-- The canonical (bundled) continuous map from the underlying topological space of `X` to the prime spectrum of its global sections. -/ @[simps] def to_Γ_Spec_base : X.to_Top ⟶ Spec.Top_obj (Γ.obj (op X)) := { to_fun := X.to_Γ_Spec_fun, continuous_to_fun := X.to_Γ_Spec_continuous } variable (r : Γ.obj (op X)) /-- The preimage in `X` of a basic open in `Spec Γ(X)` (as an open set). -/ abbreviation to_Γ_Spec_map_basic_open : opens X := (opens.map X.to_Γ_Spec_base).obj (basic_open r) /-- The preimage is the basic open in `X` defined by the same element `r`. -/ lemma to_Γ_Spec_map_basic_open_eq : X.to_Γ_Spec_map_basic_open r = X.to_RingedSpace.basic_open r := subtype.eq (X.to_Γ_Spec_preim_basic_open_eq r) /-- The map from the global sections `Γ(X)` to the sections on the (preimage of) a basic open. -/ abbreviation to_to_Γ_Spec_map_basic_open : X.presheaf.obj (op ⊤) ⟶ X.presheaf.obj (op $ X.to_Γ_Spec_map_basic_open r) := X.presheaf.map (X.to_Γ_Spec_map_basic_open r).le_top.op /-- `r` is a unit as a section on the basic open defined by `r`. -/ lemma is_unit_res_to_Γ_Spec_map_basic_open : is_unit (X.to_to_Γ_Spec_map_basic_open r r) := begin convert (X.presheaf.map $ (eq_to_hom $ X.to_Γ_Spec_map_basic_open_eq r).op) .is_unit_map (X.to_RingedSpace.is_unit_res_basic_open r), rw ← comp_apply, erw ← functor.map_comp, congr end /-- Define the sheaf hom on individual basic opens for the unit. -/ def to_Γ_Spec_c_app : (structure_sheaf $ Γ.obj $ op X).val.obj (op $ basic_open r) ⟶ X.presheaf.obj (op $ X.to_Γ_Spec_map_basic_open r) := is_localization.away.lift r (is_unit_res_to_Γ_Spec_map_basic_open _ r) /-- Characterization of the sheaf hom on basic opens, direction ← (next lemma) is used at various places, but → is not used in this file. -/ lemma to_Γ_Spec_c_app_iff (f : (structure_sheaf $ Γ.obj $ op X).val.obj (op $ basic_open r) ⟶ X.presheaf.obj (op $ X.to_Γ_Spec_map_basic_open r)) : to_open _ (basic_open r) ≫ f = X.to_to_Γ_Spec_map_basic_open r ↔ f = X.to_Γ_Spec_c_app r := begin rw ← (is_localization.away.away_map.lift_comp r (X.is_unit_res_to_Γ_Spec_map_basic_open r)), swap 5, exact is_localization.to_basic_open _ r, split, { intro h, refine is_localization.ring_hom_ext _ _, swap 5, exact is_localization.to_basic_open _ r, exact h }, apply congr_arg, end lemma to_Γ_Spec_c_app_spec : to_open _ (basic_open r) ≫ X.to_Γ_Spec_c_app r = X.to_to_Γ_Spec_map_basic_open r := (X.to_Γ_Spec_c_app_iff r _).2 rfl /-- The sheaf hom on all basic opens, commuting with restrictions. -/ def to_Γ_Spec_c_basic_opens : (induced_functor basic_open).op ⋙ (structure_sheaf (Γ.obj (op X))).1 ⟶ (induced_functor basic_open).op ⋙ ((Top.sheaf.pushforward X.to_Γ_Spec_base).obj X.𝒪).1 := { app := λ r, X.to_Γ_Spec_c_app r.unop, naturality' := λ r s f, begin apply (structure_sheaf.to_basic_open_epi (Γ.obj (op X)) r.unop).1, simp only [← category.assoc], erw X.to_Γ_Spec_c_app_spec r.unop, convert X.to_Γ_Spec_c_app_spec s.unop, symmetry, apply X.presheaf.map_comp end } /-- The canonical morphism of sheafed spaces from `X` to the spectrum of its global sections. -/ @[simps] def to_Γ_Spec_SheafedSpace : X.to_SheafedSpace ⟶ Spec.to_SheafedSpace.obj (op (Γ.obj (op X))) := { base := X.to_Γ_Spec_base, c := Top.sheaf.restrict_hom_equiv_hom (structure_sheaf (Γ.obj (op X))).1 _ is_basis_basic_opens X.to_Γ_Spec_c_basic_opens } lemma to_Γ_Spec_SheafedSpace_app_eq : X.to_Γ_Spec_SheafedSpace.c.app (op (basic_open r)) = X.to_Γ_Spec_c_app r := Top.sheaf.extend_hom_app _ _ _ _ _ lemma to_Γ_Spec_SheafedSpace_app_spec (r : Γ.obj (op X)) : to_open _ (basic_open r) ≫ X.to_Γ_Spec_SheafedSpace.c.app (op (basic_open r)) = X.to_to_Γ_Spec_map_basic_open r := (X.to_Γ_Spec_SheafedSpace_app_eq r).symm ▸ X.to_Γ_Spec_c_app_spec r /-- The map on stalks induced by the unit commutes with maps from `Γ(X)` to stalks (in `Spec Γ(X)` and in `X`). -/ lemma to_stalk_stalk_map_to_Γ_Spec (x : X) : to_stalk _ _ ≫ PresheafedSpace.stalk_map X.to_Γ_Spec_SheafedSpace x = X.Γ_to_stalk x := begin rw PresheafedSpace.stalk_map, erw ← to_open_germ _ (basic_open (1 : Γ.obj (op X))) ⟨X.to_Γ_Spec_fun x, by rw basic_open_one; trivial⟩, rw [← category.assoc, category.assoc (to_open _ _)], erw stalk_functor_map_germ, rw [← category.assoc (to_open _ _), X.to_Γ_Spec_SheafedSpace_app_spec 1], unfold Γ_to_stalk, rw ← stalk_pushforward_germ _ X.to_Γ_Spec_base X.presheaf ⊤, congr' 1, change (X.to_Γ_Spec_base _* X.presheaf).map le_top.hom.op ≫ _ = _, apply germ_res, end /-- The canonical morphism from `X` to the spectrum of its global sections. -/ @[simps coe_base] def to_Γ_Spec : X ⟶ Spec.LocallyRingedSpace_obj (Γ.obj (op X)) := { val := X.to_Γ_Spec_SheafedSpace, property := begin intro x, let p : prime_spectrum (Γ.obj (op X)) := X.to_Γ_Spec_fun x, constructor, /- show stalk map is local hom ↓ -/ let S := (structure_sheaf _).presheaf.stalk p, rintros (t : S) ht, obtain ⟨⟨r, s⟩, he⟩ := is_localization.surj p.as_ideal.prime_compl t, dsimp at he, apply is_unit_of_mul_is_unit_left, rw he, refine is_localization.map_units S (⟨r, _⟩ : p.as_ideal.prime_compl), apply (not_mem_prime_iff_unit_in_stalk _ _ _).mpr, rw [← to_stalk_stalk_map_to_Γ_Spec, comp_apply], erw ← he, rw ring_hom.map_mul, exact ht.mul ((is_localization.map_units S s : _).map (PresheafedSpace.stalk_map X.to_Γ_Spec_SheafedSpace x)) end } lemma comp_ring_hom_ext {X : LocallyRingedSpace} {R : CommRing} {f : R ⟶ Γ.obj (op X)} {β : X ⟶ Spec.LocallyRingedSpace_obj R} (w : X.to_Γ_Spec.1.base ≫ (Spec.LocallyRingedSpace_map f).1.base = β.1.base) (h : ∀ r : R, f ≫ X.presheaf.map (hom_of_le le_top : (opens.map β.1.base).obj (basic_open r) ⟶ _).op = to_open R (basic_open r) ≫ β.1.c.app (op (basic_open r))) : X.to_Γ_Spec ≫ Spec.LocallyRingedSpace_map f = β := begin ext1, apply Spec.basic_open_hom_ext, { intros r _, rw LocallyRingedSpace.comp_val_c_app, erw to_open_comp_comap_assoc, rw category.assoc, erw [to_Γ_Spec_SheafedSpace_app_spec, ← X.presheaf.map_comp], convert h r }, exact w, end /-- `to_Spec_Γ _` is an isomorphism so these are mutually two-sided inverses. -/ lemma Γ_Spec_left_triangle : to_Spec_Γ (Γ.obj (op X)) ≫ X.to_Γ_Spec.1.c.app (op ⊤) = 𝟙 _ := begin unfold to_Spec_Γ, rw ← to_open_res _ (basic_open (1 : Γ.obj (op X))) ⊤ (eq_to_hom basic_open_one.symm), erw category.assoc, rw [nat_trans.naturality, ← category.assoc], erw [X.to_Γ_Spec_SheafedSpace_app_spec 1, ← functor.map_comp], convert eq_to_hom_map X.presheaf _, refl, end end LocallyRingedSpace /-- The unit as a natural transformation. -/ def identity_to_Γ_Spec : 𝟭 LocallyRingedSpace.{u} ⟶ Γ.right_op ⋙ Spec.to_LocallyRingedSpace := { app := LocallyRingedSpace.to_Γ_Spec, naturality' := λ X Y f, begin symmetry, apply LocallyRingedSpace.comp_ring_hom_ext, { ext1 x, dsimp [Spec.Top_map, LocallyRingedSpace.to_Γ_Spec_fun], rw [← subtype.val_eq_coe, ← local_ring.comap_closed_point (PresheafedSpace.stalk_map _ x), ← prime_spectrum.comap_comp_apply, ← prime_spectrum.comap_comp_apply], congr' 2, exact (PresheafedSpace.stalk_map_germ f.1 ⊤ ⟨x,trivial⟩).symm, apply_instance }, { intro r, rw [LocallyRingedSpace.comp_val_c_app, ← category.assoc], erw [Y.to_Γ_Spec_SheafedSpace_app_spec, f.1.c.naturality], refl }, end } namespace Γ_Spec lemma left_triangle (X : LocallyRingedSpace) : Spec_Γ_identity.inv.app (Γ.obj (op X)) ≫ (identity_to_Γ_Spec.app X).val.c.app (op ⊤) = 𝟙 _ := X.Γ_Spec_left_triangle /-- `Spec_Γ_identity` is iso so these are mutually two-sided inverses. -/ lemma right_triangle (R : CommRing) : identity_to_Γ_Spec.app (Spec.to_LocallyRingedSpace.obj $ op R) ≫ Spec.to_LocallyRingedSpace.map (Spec_Γ_identity.inv.app R).op = 𝟙 _ := begin apply LocallyRingedSpace.comp_ring_hom_ext, { ext (p : prime_spectrum R) x, erw ← is_localization.at_prime.to_map_mem_maximal_iff ((structure_sheaf R).presheaf.stalk p) p.as_ideal x, refl }, { intro r, apply to_open_res }, end -- Removing this makes the following definition time out. local attribute [irreducible] Spec_Γ_identity identity_to_Γ_Spec Spec.to_LocallyRingedSpace /-- The adjunction `Γ ⊣ Spec` from `CommRingᵒᵖ` to `LocallyRingedSpace`. -/ @[simps unit counit] def LocallyRingedSpace_adjunction : Γ.right_op ⊣ Spec.to_LocallyRingedSpace := adjunction.mk_of_unit_counit { unit := identity_to_Γ_Spec, counit := (nat_iso.op Spec_Γ_identity).inv, left_triangle' := by { ext X, erw category.id_comp, exact congr_arg quiver.hom.op (left_triangle X) }, right_triangle' := by { ext1, ext1 R, erw category.id_comp, exact right_triangle R.unop } } local attribute [semireducible] Spec.to_LocallyRingedSpace /-- The adjunction `Γ ⊣ Spec` from `CommRingᵒᵖ` to `Scheme`. -/ def adjunction : Scheme.Γ.right_op ⊣ Scheme.Spec := LocallyRingedSpace_adjunction.restrict_fully_faithful Scheme.forget_to_LocallyRingedSpace (𝟭 _) (nat_iso.of_components (λ X, iso.refl _) (λ _ _ f, by simpa)) (nat_iso.of_components (λ X, iso.refl _) (λ _ _ f, by simpa)) lemma adjunction_hom_equiv_apply {X : Scheme} {R : CommRingᵒᵖ} (f : (op $ Scheme.Γ.obj $ op X) ⟶ R) : Γ_Spec.adjunction.hom_equiv X R f = LocallyRingedSpace_adjunction.hom_equiv X.1 R f := by { dsimp [adjunction, adjunction.restrict_fully_faithful], simp } local attribute [irreducible] LocallyRingedSpace_adjunction Γ_Spec.adjunction lemma adjunction_hom_equiv (X : Scheme) (R : CommRingᵒᵖ) : Γ_Spec.adjunction.hom_equiv X R = LocallyRingedSpace_adjunction.hom_equiv X.1 R := equiv.ext $ λ f, adjunction_hom_equiv_apply f lemma adjunction_hom_equiv_symm_apply {X : Scheme} {R : CommRingᵒᵖ} (f : X ⟶ Scheme.Spec.obj R) : (Γ_Spec.adjunction.hom_equiv X R).symm f = (LocallyRingedSpace_adjunction.hom_equiv X.1 R).symm f := by { congr' 2, exact adjunction_hom_equiv _ _ } @[simp] lemma adjunction_counit_app {R : CommRingᵒᵖ} : Γ_Spec.adjunction.counit.app R = LocallyRingedSpace_adjunction.counit.app R := by { rw [← adjunction.hom_equiv_symm_id, ← adjunction.hom_equiv_symm_id, adjunction_hom_equiv_symm_apply], refl } @[simp] lemma adjunction_unit_app {X : Scheme} : Γ_Spec.adjunction.unit.app X = LocallyRingedSpace_adjunction.unit.app X.1 := by { rw [← adjunction.hom_equiv_id, ← adjunction.hom_equiv_id, adjunction_hom_equiv_apply], refl } local attribute [semireducible] LocallyRingedSpace_adjunction Γ_Spec.adjunction instance is_iso_LocallyRingedSpace_adjunction_counit : is_iso LocallyRingedSpace_adjunction.counit := is_iso.of_iso_inv _ instance is_iso_adjunction_counit : is_iso Γ_Spec.adjunction.counit := begin apply_with nat_iso.is_iso_of_is_iso_app { instances := ff }, intro R, rw adjunction_counit_app, apply_instance, end -- This is just -- `(Γ_Spec.adjunction.unit.app X).1.c.app (op ⊤) = Spec_Γ_identity.hom.app (X.presheaf.obj (op ⊤))` -- But lean times out when trying to unify the types of the two sides. lemma adjunction_unit_app_app_top (X : Scheme) : @eq ((Scheme.Spec.obj (op $ X.presheaf.obj (op ⊤))).presheaf.obj (op ⊤) ⟶ ((Γ_Spec.adjunction.unit.app X).1.base _* X.presheaf).obj (op ⊤)) ((Γ_Spec.adjunction.unit.app X).val.c.app (op ⊤)) (Spec_Γ_identity.hom.app (X.presheaf.obj (op ⊤))) := begin have := congr_app Γ_Spec.adjunction.left_triangle X, dsimp at this, rw ← is_iso.eq_comp_inv at this, simp only [Γ_Spec.LocallyRingedSpace_adjunction_counit, nat_trans.op_app, category.id_comp, Γ_Spec.adjunction_counit_app] at this, rw [← op_inv, nat_iso.inv_inv_app, quiver.hom.op_inj.eq_iff] at this, exact this end end Γ_Spec /-! Immediate consequences of the adjunction. -/ /-- Spec preserves limits. -/ instance : limits.preserves_limits Spec.to_LocallyRingedSpace := Γ_Spec.LocallyRingedSpace_adjunction.right_adjoint_preserves_limits instance Spec.preserves_limits : limits.preserves_limits Scheme.Spec := Γ_Spec.adjunction.right_adjoint_preserves_limits /-- Spec is a full functor. -/ instance : full Spec.to_LocallyRingedSpace := R_full_of_counit_is_iso Γ_Spec.LocallyRingedSpace_adjunction instance Spec.full : full Scheme.Spec := R_full_of_counit_is_iso Γ_Spec.adjunction /-- Spec is a faithful functor. -/ instance : faithful Spec.to_LocallyRingedSpace := R_faithful_of_counit_is_iso Γ_Spec.LocallyRingedSpace_adjunction instance Spec.faithful : faithful Scheme.Spec := R_faithful_of_counit_is_iso Γ_Spec.adjunction instance : is_right_adjoint Spec.to_LocallyRingedSpace := ⟨_, Γ_Spec.LocallyRingedSpace_adjunction⟩ instance : is_right_adjoint Scheme.Spec := ⟨_, Γ_Spec.adjunction⟩ instance : reflective Spec.to_LocallyRingedSpace := ⟨⟩ instance Spec.reflective : reflective Scheme.Spec := ⟨⟩ end algebraic_geometry
04f4695b2f0ca677b02c8fe87e795bc561a41072
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/int/order.lean
0643e5546f94109908414e4878d0c580f6e5a9f7
[]
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
35,466
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The order relation on the integers. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.int.basic import Mathlib.Lean3Lib.init.data.ordering.basic namespace Mathlib namespace int def nonneg (a : ℤ) := int.cases_on a (fun (n : ℕ) => True) fun (n : ℕ) => False protected def le (a : ℤ) (b : ℤ) := nonneg (b - a) protected instance has_le : HasLessEq ℤ := { LessEq := int.le } protected def lt (a : ℤ) (b : ℤ) := a + 1 ≤ b protected instance has_lt : HasLess ℤ := { Less := int.lt } def decidable_nonneg (a : ℤ) : Decidable (nonneg a) := int.cases_on a (fun (a : ℕ) => decidable.true) fun (a : ℕ) => decidable.false protected instance decidable_le (a : ℤ) (b : ℤ) : Decidable (a ≤ b) := decidable_nonneg (b - a) protected instance decidable_lt (a : ℤ) (b : ℤ) : Decidable (a < b) := decidable_nonneg (b - (a + 1)) theorem lt_iff_add_one_le (a : ℤ) (b : ℤ) : a < b ↔ a + 1 ≤ b := iff.refl (a < b) theorem nonneg.elim {a : ℤ} : nonneg a → ∃ (n : ℕ), a = ↑n := int.cases_on a (fun (n : ℕ) (H : nonneg (Int.ofNat n)) => exists.intro n rfl) fun (n' : ℕ) => false.elim theorem nonneg_or_nonneg_neg (a : ℤ) : nonneg a ∨ nonneg (-a) := int.cases_on a (fun (n : ℕ) => Or.inl trivial) fun (n : ℕ) => Or.inr trivial theorem le.intro_sub {a : ℤ} {b : ℤ} {n : ℕ} (h : b - a = ↑n) : a ≤ b := (fun (this : nonneg (b - a)) => this) (eq.mpr (id (Eq._oldrec (Eq.refl (nonneg (b - a))) h)) trivial) theorem le.intro {a : ℤ} {b : ℤ} {n : ℕ} (h : a + ↑n = b) : a ≤ b := sorry theorem le.dest_sub {a : ℤ} {b : ℤ} (h : a ≤ b) : ∃ (n : ℕ), b - a = ↑n := nonneg.elim h theorem le.dest {a : ℤ} {b : ℤ} (h : a ≤ b) : ∃ (n : ℕ), a + ↑n = b := sorry theorem le.elim {a : ℤ} {b : ℤ} (h : a ≤ b) {P : Prop} (h' : ∀ (n : ℕ), a + ↑n = b → P) : P := exists.elim (le.dest h) h' protected theorem le_total (a : ℤ) (b : ℤ) : a ≤ b ∨ b ≤ a := sorry theorem coe_nat_le_coe_nat_of_le {m : ℕ} {n : ℕ} (h : m ≤ n) : ↑m ≤ ↑n := sorry theorem le_of_coe_nat_le_coe_nat {m : ℕ} {n : ℕ} (h : ↑m ≤ ↑n) : m ≤ n := le.elim h fun (k : ℕ) (hk : ↑m + ↑k = ↑n) => (fun (this : m + k = n) => nat.le.intro this) (int.coe_nat_inj (Eq.trans (int.coe_nat_add m k) hk)) theorem coe_nat_le_coe_nat_iff (m : ℕ) (n : ℕ) : ↑m ≤ ↑n ↔ m ≤ n := { mp := le_of_coe_nat_le_coe_nat, mpr := coe_nat_le_coe_nat_of_le } theorem coe_zero_le (n : ℕ) : 0 ≤ ↑n := coe_nat_le_coe_nat_of_le (nat.zero_le n) theorem eq_coe_of_zero_le {a : ℤ} (h : 0 ≤ a) : ∃ (n : ℕ), a = ↑n := sorry theorem eq_succ_of_zero_lt {a : ℤ} (h : 0 < a) : ∃ (n : ℕ), a = ↑(Nat.succ n) := sorry theorem lt_add_succ (a : ℤ) (n : ℕ) : a < a + ↑(Nat.succ n) := sorry theorem lt.intro {a : ℤ} {b : ℤ} {n : ℕ} (h : a + ↑(Nat.succ n) = b) : a < b := h ▸ lt_add_succ a n theorem lt.dest {a : ℤ} {b : ℤ} (h : a < b) : ∃ (n : ℕ), a + ↑(Nat.succ n) = b := sorry theorem lt.elim {a : ℤ} {b : ℤ} (h : a < b) {P : Prop} (h' : ∀ (n : ℕ), a + ↑(Nat.succ n) = b → P) : P := exists.elim (lt.dest h) h' theorem coe_nat_lt_coe_nat_iff (n : ℕ) (m : ℕ) : ↑n < ↑m ↔ n < m := sorry theorem lt_of_coe_nat_lt_coe_nat {m : ℕ} {n : ℕ} (h : ↑m < ↑n) : m < n := iff.mp (coe_nat_lt_coe_nat_iff m n) h theorem coe_nat_lt_coe_nat_of_lt {m : ℕ} {n : ℕ} (h : m < n) : ↑m < ↑n := iff.mpr (coe_nat_lt_coe_nat_iff m n) h /- show that the integers form an ordered additive group -/ protected theorem le_refl (a : ℤ) : a ≤ a := le.intro (int.add_zero a) protected theorem le_trans {a : ℤ} {b : ℤ} {c : ℤ} (h₁ : a ≤ b) (h₂ : b ≤ c) : a ≤ c := sorry protected theorem le_antisymm {a : ℤ} {b : ℤ} (h₁ : a ≤ b) (h₂ : b ≤ a) : a = b := sorry protected theorem lt_irrefl (a : ℤ) : ¬a < a := sorry protected theorem ne_of_lt {a : ℤ} {b : ℤ} (h : a < b) : a ≠ b := fun (this : a = b) => absurd (eq.mp (Eq._oldrec (Eq.refl (a < b)) this) h) (int.lt_irrefl b) theorem le_of_lt {a : ℤ} {b : ℤ} (h : a < b) : a ≤ b := lt.elim h fun (n : ℕ) (hn : a + ↑(Nat.succ n) = b) => le.intro hn protected theorem lt_iff_le_and_ne (a : ℤ) (b : ℤ) : a < b ↔ a ≤ b ∧ a ≠ b := sorry theorem lt_succ (a : ℤ) : a < a + 1 := int.le_refl (a + 1) protected theorem add_le_add_left {a : ℤ} {b : ℤ} (h : a ≤ b) (c : ℤ) : c + a ≤ c + b := sorry protected theorem add_lt_add_left {a : ℤ} {b : ℤ} (h : a < b) (c : ℤ) : c + a < c + b := sorry protected theorem mul_nonneg {a : ℤ} {b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := sorry protected theorem mul_pos {a : ℤ} {b : ℤ} (ha : 0 < a) (hb : 0 < b) : 0 < a * b := sorry protected theorem zero_lt_one : 0 < 1 := trivial protected theorem lt_iff_le_not_le {a : ℤ} {b : ℤ} : a < b ↔ a ≤ b ∧ ¬b ≤ a := sorry protected instance linear_order : linear_order ℤ := linear_order.mk int.le int.lt int.le_refl int.le_trans int.le_antisymm int.le_total int.decidable_le int.decidable_eq int.decidable_lt theorem eq_nat_abs_of_zero_le {a : ℤ} (h : 0 ≤ a) : a = ↑(nat_abs a) := sorry theorem le_nat_abs {a : ℤ} : a ≤ ↑(nat_abs a) := sorry theorem neg_succ_lt_zero (n : ℕ) : Int.negSucc n < 0 := sorry theorem eq_neg_succ_of_lt_zero {a : ℤ} : a < 0 → ∃ (n : ℕ), a = Int.negSucc n := sorry /- int is an ordered add comm group -/ protected theorem eq_neg_of_eq_neg {a : ℤ} {b : ℤ} (h : a = -b) : b = -a := eq.mpr (id (Eq._oldrec (Eq.refl (b = -a)) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (b = --b)) (int.neg_neg b))) (Eq.refl b)) protected theorem neg_add_cancel_left (a : ℤ) (b : ℤ) : -a + (a + b) = b := eq.mpr (id (Eq._oldrec (Eq.refl (-a + (a + b) = b)) (Eq.symm (int.add_assoc (-a) a b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (-a + a + b = b)) (int.add_left_neg a))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 + b = b)) (int.zero_add b))) (Eq.refl b))) protected theorem add_neg_cancel_left (a : ℤ) (b : ℤ) : a + (-a + b) = b := eq.mpr (id (Eq._oldrec (Eq.refl (a + (-a + b) = b)) (Eq.symm (int.add_assoc a (-a) b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a + -a + b = b)) (int.add_right_neg a))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 + b = b)) (int.zero_add b))) (Eq.refl b))) protected theorem add_neg_cancel_right (a : ℤ) (b : ℤ) : a + b + -b = a := eq.mpr (id (Eq._oldrec (Eq.refl (a + b + -b = a)) (int.add_assoc a b (-b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a + (b + -b) = a)) (int.add_right_neg b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a + 0 = a)) (int.add_zero a))) (Eq.refl a))) protected theorem neg_add_cancel_right (a : ℤ) (b : ℤ) : a + -b + b = a := eq.mpr (id (Eq._oldrec (Eq.refl (a + -b + b = a)) (int.add_assoc a (-b) b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a + (-b + b) = a)) (int.add_left_neg b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a + 0 = a)) (int.add_zero a))) (Eq.refl a))) protected theorem sub_self (a : ℤ) : a - a = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a - a = 0)) int.sub_eq_add_neg)) (eq.mpr (id (Eq._oldrec (Eq.refl (a + -a = 0)) (int.add_right_neg a))) (Eq.refl 0)) protected theorem sub_eq_zero_of_eq {a : ℤ} {b : ℤ} (h : a = b) : a - b = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a - b = 0)) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (b - b = 0)) (int.sub_self b))) (Eq.refl 0)) protected theorem eq_of_sub_eq_zero {a : ℤ} {b : ℤ} (h : a - b = 0) : a = b := sorry protected theorem sub_eq_zero_iff_eq {a : ℤ} {b : ℤ} : a - b = 0 ↔ a = b := { mp := int.eq_of_sub_eq_zero, mpr := int.sub_eq_zero_of_eq } @[simp] protected theorem neg_eq_of_add_eq_zero {a : ℤ} {b : ℤ} (h : a + b = 0) : -a = b := sorry protected theorem neg_mul_eq_neg_mul (a : ℤ) (b : ℤ) : -(a * b) = -a * b := sorry protected theorem neg_mul_eq_mul_neg (a : ℤ) (b : ℤ) : -(a * b) = a * -b := sorry @[simp] theorem neg_mul_eq_neg_mul_symm (a : ℤ) (b : ℤ) : -a * b = -(a * b) := Eq.symm (int.neg_mul_eq_neg_mul a b) @[simp] theorem mul_neg_eq_neg_mul_symm (a : ℤ) (b : ℤ) : a * -b = -(a * b) := Eq.symm (int.neg_mul_eq_mul_neg a b) protected theorem neg_mul_neg (a : ℤ) (b : ℤ) : -a * -b = a * b := sorry protected theorem neg_mul_comm (a : ℤ) (b : ℤ) : -a * b = a * -b := sorry protected theorem mul_sub (a : ℤ) (b : ℤ) (c : ℤ) : a * (b - c) = a * b - a * c := sorry protected theorem sub_mul (a : ℤ) (b : ℤ) (c : ℤ) : (a - b) * c = a * c - b * c := sorry protected theorem le_of_add_le_add_left {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b ≤ a + c) : b ≤ c := sorry protected theorem lt_of_add_lt_add_left {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b < a + c) : b < c := sorry protected theorem add_le_add_right {a : ℤ} {b : ℤ} (h : a ≤ b) (c : ℤ) : a + c ≤ b + c := int.add_comm c a ▸ int.add_comm c b ▸ int.add_le_add_left h c protected theorem add_lt_add_right {a : ℤ} {b : ℤ} (h : a < b) (c : ℤ) : a + c < b + c := eq.mpr (id (Eq._oldrec (Eq.refl (a + c < b + c)) (int.add_comm a c))) (eq.mpr (id (Eq._oldrec (Eq.refl (c + a < b + c)) (int.add_comm b c))) (int.add_lt_add_left h c)) protected theorem add_le_add {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d := le_trans (int.add_le_add_right h₁ c) (int.add_le_add_left h₂ b) protected theorem le_add_of_nonneg_right {a : ℤ} {b : ℤ} (h : b ≥ 0) : a ≤ a + b := (fun (this : a + b ≥ a + 0) => eq.mp (Eq._oldrec (Eq.refl (a + b ≥ a + 0)) (int.add_zero a)) this) (int.add_le_add_left h a) protected theorem le_add_of_nonneg_left {a : ℤ} {b : ℤ} (h : b ≥ 0) : a ≤ b + a := (fun (this : 0 + a ≤ b + a) => eq.mp (Eq._oldrec (Eq.refl (0 + a ≤ b + a)) (int.zero_add a)) this) (int.add_le_add_right h a) protected theorem add_lt_add {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (h₁ : a < b) (h₂ : c < d) : a + c < b + d := lt_trans (int.add_lt_add_right h₁ c) (int.add_lt_add_left h₂ b) protected theorem add_lt_add_of_le_of_lt {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (h₁ : a ≤ b) (h₂ : c < d) : a + c < b + d := lt_of_le_of_lt (int.add_le_add_right h₁ c) (int.add_lt_add_left h₂ b) protected theorem add_lt_add_of_lt_of_le {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (h₁ : a < b) (h₂ : c ≤ d) : a + c < b + d := lt_of_lt_of_le (int.add_lt_add_right h₁ c) (int.add_le_add_left h₂ b) protected theorem lt_add_of_pos_right (a : ℤ) {b : ℤ} (h : b > 0) : a < a + b := (fun (this : a + 0 < a + b) => eq.mp (Eq._oldrec (Eq.refl (a + 0 < a + b)) (int.add_zero a)) this) (int.add_lt_add_left h a) protected theorem lt_add_of_pos_left (a : ℤ) {b : ℤ} (h : b > 0) : a < b + a := (fun (this : 0 + a < b + a) => eq.mp (Eq._oldrec (Eq.refl (0 + a < b + a)) (int.zero_add a)) this) (int.add_lt_add_right h a) protected theorem le_of_add_le_add_right {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b ≤ c + b) : a ≤ c := sorry protected theorem lt_of_add_lt_add_right {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b < c + b) : a < c := sorry -- here we start using properties of zero. protected theorem add_nonneg {a : ℤ} {b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b := int.zero_add 0 ▸ int.add_le_add ha hb protected theorem add_pos {a : ℤ} {b : ℤ} (ha : 0 < a) (hb : 0 < b) : 0 < a + b := int.zero_add 0 ▸ int.add_lt_add ha hb protected theorem add_pos_of_pos_of_nonneg {a : ℤ} {b : ℤ} (ha : 0 < a) (hb : 0 ≤ b) : 0 < a + b := int.zero_add 0 ▸ int.add_lt_add_of_lt_of_le ha hb protected theorem add_pos_of_nonneg_of_pos {a : ℤ} {b : ℤ} (ha : 0 ≤ a) (hb : 0 < b) : 0 < a + b := int.zero_add 0 ▸ int.add_lt_add_of_le_of_lt ha hb protected theorem add_nonpos {a : ℤ} {b : ℤ} (ha : a ≤ 0) (hb : b ≤ 0) : a + b ≤ 0 := int.zero_add 0 ▸ int.add_le_add ha hb protected theorem add_neg {a : ℤ} {b : ℤ} (ha : a < 0) (hb : b < 0) : a + b < 0 := int.zero_add 0 ▸ int.add_lt_add ha hb protected theorem add_neg_of_neg_of_nonpos {a : ℤ} {b : ℤ} (ha : a < 0) (hb : b ≤ 0) : a + b < 0 := int.zero_add 0 ▸ int.add_lt_add_of_lt_of_le ha hb protected theorem add_neg_of_nonpos_of_neg {a : ℤ} {b : ℤ} (ha : a ≤ 0) (hb : b < 0) : a + b < 0 := int.zero_add 0 ▸ int.add_lt_add_of_le_of_lt ha hb protected theorem lt_add_of_le_of_pos {a : ℤ} {b : ℤ} {c : ℤ} (hbc : b ≤ c) (ha : 0 < a) : b < c + a := int.add_zero b ▸ int.add_lt_add_of_le_of_lt hbc ha protected theorem sub_add_cancel (a : ℤ) (b : ℤ) : a - b + b = a := int.neg_add_cancel_right a b protected theorem add_sub_cancel (a : ℤ) (b : ℤ) : a + b - b = a := int.add_neg_cancel_right a b protected theorem add_sub_assoc (a : ℤ) (b : ℤ) (c : ℤ) : a + b - c = a + (b - c) := sorry protected theorem neg_le_neg {a : ℤ} {b : ℤ} (h : a ≤ b) : -b ≤ -a := sorry protected theorem le_of_neg_le_neg {a : ℤ} {b : ℤ} (h : -b ≤ -a) : a ≤ b := sorry protected theorem nonneg_of_neg_nonpos {a : ℤ} (h : -a ≤ 0) : 0 ≤ a := (fun (this : -a ≤ -0) => int.le_of_neg_le_neg this) (eq.mpr (id (Eq._oldrec (Eq.refl (-a ≤ -0)) int.neg_zero)) h) protected theorem neg_nonpos_of_nonneg {a : ℤ} (h : 0 ≤ a) : -a ≤ 0 := (fun (this : -a ≤ -0) => eq.mp (Eq._oldrec (Eq.refl (-a ≤ -0)) int.neg_zero) this) (int.neg_le_neg h) protected theorem nonpos_of_neg_nonneg {a : ℤ} (h : 0 ≤ -a) : a ≤ 0 := (fun (this : -0 ≤ -a) => int.le_of_neg_le_neg this) (eq.mpr (id (Eq._oldrec (Eq.refl (-0 ≤ -a)) int.neg_zero)) h) protected theorem neg_nonneg_of_nonpos {a : ℤ} (h : a ≤ 0) : 0 ≤ -a := (fun (this : -0 ≤ -a) => eq.mp (Eq._oldrec (Eq.refl (-0 ≤ -a)) int.neg_zero) this) (int.neg_le_neg h) protected theorem neg_lt_neg {a : ℤ} {b : ℤ} (h : a < b) : -b < -a := sorry protected theorem lt_of_neg_lt_neg {a : ℤ} {b : ℤ} (h : -b < -a) : a < b := int.neg_neg a ▸ int.neg_neg b ▸ int.neg_lt_neg h protected theorem pos_of_neg_neg {a : ℤ} (h : -a < 0) : 0 < a := (fun (this : -a < -0) => int.lt_of_neg_lt_neg this) (eq.mpr (id (Eq._oldrec (Eq.refl (-a < -0)) int.neg_zero)) h) protected theorem neg_neg_of_pos {a : ℤ} (h : 0 < a) : -a < 0 := (fun (this : -a < -0) => eq.mp (Eq._oldrec (Eq.refl (-a < -0)) int.neg_zero) this) (int.neg_lt_neg h) protected theorem neg_of_neg_pos {a : ℤ} (h : 0 < -a) : a < 0 := (fun (this : -0 < -a) => int.lt_of_neg_lt_neg this) (eq.mpr (id (Eq._oldrec (Eq.refl (-0 < -a)) int.neg_zero)) h) protected theorem neg_pos_of_neg {a : ℤ} (h : a < 0) : 0 < -a := (fun (this : -0 < -a) => eq.mp (Eq._oldrec (Eq.refl (-0 < -a)) int.neg_zero) this) (int.neg_lt_neg h) protected theorem le_neg_of_le_neg {a : ℤ} {b : ℤ} (h : a ≤ -b) : b ≤ -a := eq.mp (Eq._oldrec (Eq.refl ( --b ≤ -a)) (int.neg_neg b)) (int.neg_le_neg h) protected theorem neg_le_of_neg_le {a : ℤ} {b : ℤ} (h : -a ≤ b) : -b ≤ a := eq.mp (Eq._oldrec (Eq.refl (-b ≤ --a)) (int.neg_neg a)) (int.neg_le_neg h) protected theorem lt_neg_of_lt_neg {a : ℤ} {b : ℤ} (h : a < -b) : b < -a := eq.mp (Eq._oldrec (Eq.refl ( --b < -a)) (int.neg_neg b)) (int.neg_lt_neg h) protected theorem neg_lt_of_neg_lt {a : ℤ} {b : ℤ} (h : -a < b) : -b < a := eq.mp (Eq._oldrec (Eq.refl (-b < --a)) (int.neg_neg a)) (int.neg_lt_neg h) protected theorem sub_nonneg_of_le {a : ℤ} {b : ℤ} (h : b ≤ a) : 0 ≤ a - b := eq.mp (Eq._oldrec (Eq.refl (b + -b ≤ a + -b)) (int.add_right_neg b)) (int.add_le_add_right h (-b)) protected theorem le_of_sub_nonneg {a : ℤ} {b : ℤ} (h : 0 ≤ a - b) : b ≤ a := eq.mp (Eq._oldrec (Eq.refl (0 + b ≤ a)) (int.zero_add b)) (eq.mp (Eq._oldrec (Eq.refl (0 + b ≤ a - b + b)) (int.sub_add_cancel a b)) (int.add_le_add_right h b)) protected theorem sub_nonpos_of_le {a : ℤ} {b : ℤ} (h : a ≤ b) : a - b ≤ 0 := eq.mp (Eq._oldrec (Eq.refl (a + -b ≤ b + -b)) (int.add_right_neg b)) (int.add_le_add_right h (-b)) protected theorem le_of_sub_nonpos {a : ℤ} {b : ℤ} (h : a - b ≤ 0) : a ≤ b := eq.mp (Eq._oldrec (Eq.refl (a ≤ 0 + b)) (int.zero_add b)) (eq.mp (Eq._oldrec (Eq.refl (a - b + b ≤ 0 + b)) (int.sub_add_cancel a b)) (int.add_le_add_right h b)) protected theorem sub_pos_of_lt {a : ℤ} {b : ℤ} (h : b < a) : 0 < a - b := eq.mp (Eq._oldrec (Eq.refl (b + -b < a + -b)) (int.add_right_neg b)) (int.add_lt_add_right h (-b)) protected theorem lt_of_sub_pos {a : ℤ} {b : ℤ} (h : 0 < a - b) : b < a := eq.mp (Eq._oldrec (Eq.refl (0 + b < a)) (int.zero_add b)) (eq.mp (Eq._oldrec (Eq.refl (0 + b < a - b + b)) (int.sub_add_cancel a b)) (int.add_lt_add_right h b)) protected theorem sub_neg_of_lt {a : ℤ} {b : ℤ} (h : a < b) : a - b < 0 := eq.mp (Eq._oldrec (Eq.refl (a + -b < b + -b)) (int.add_right_neg b)) (int.add_lt_add_right h (-b)) protected theorem lt_of_sub_neg {a : ℤ} {b : ℤ} (h : a - b < 0) : a < b := eq.mp (Eq._oldrec (Eq.refl (a < 0 + b)) (int.zero_add b)) (eq.mp (Eq._oldrec (Eq.refl (a - b + b < 0 + b)) (int.sub_add_cancel a b)) (int.add_lt_add_right h b)) protected theorem add_le_of_le_neg_add {a : ℤ} {b : ℤ} {c : ℤ} (h : b ≤ -a + c) : a + b ≤ c := eq.mp (Eq._oldrec (Eq.refl (a + b ≤ a + (-a + c))) (int.add_neg_cancel_left a c)) (int.add_le_add_left h a) protected theorem le_neg_add_of_add_le {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b ≤ c) : b ≤ -a + c := eq.mp (Eq._oldrec (Eq.refl (-a + (a + b) ≤ -a + c)) (int.neg_add_cancel_left a b)) (int.add_le_add_left h (-a)) protected theorem add_le_of_le_sub_left {a : ℤ} {b : ℤ} {c : ℤ} (h : b ≤ c - a) : a + b ≤ c := eq.mp (Eq._oldrec (Eq.refl (a + b ≤ c + a - a)) (int.add_sub_cancel c a)) (eq.mp (Eq._oldrec (Eq.refl (a + b ≤ a + c - a)) (int.add_comm a c)) (eq.mp (Eq._oldrec (Eq.refl (a + b ≤ a + (c - a))) (Eq.symm (int.add_sub_assoc a c a))) (int.add_le_add_left h a))) protected theorem le_sub_left_of_add_le {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b ≤ c) : b ≤ c - a := eq.mp (Eq._oldrec (Eq.refl (b + a + -a ≤ c + -a)) (int.add_neg_cancel_right b a)) (eq.mp (Eq._oldrec (Eq.refl (a + b + -a ≤ c + -a)) (int.add_comm a b)) (int.add_le_add_right h (-a))) protected theorem add_le_of_le_sub_right {a : ℤ} {b : ℤ} {c : ℤ} (h : a ≤ c - b) : a + b ≤ c := eq.mp (Eq._oldrec (Eq.refl (a + b ≤ c - b + b)) (int.sub_add_cancel c b)) (int.add_le_add_right h b) protected theorem le_sub_right_of_add_le {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b ≤ c) : a ≤ c - b := eq.mp (Eq._oldrec (Eq.refl (a + b + -b ≤ c + -b)) (int.add_neg_cancel_right a b)) (int.add_le_add_right h (-b)) protected theorem le_add_of_neg_add_le {a : ℤ} {b : ℤ} {c : ℤ} (h : -b + a ≤ c) : a ≤ b + c := eq.mp (Eq._oldrec (Eq.refl (b + (-b + a) ≤ b + c)) (int.add_neg_cancel_left b a)) (int.add_le_add_left h b) protected theorem neg_add_le_of_le_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a ≤ b + c) : -b + a ≤ c := eq.mp (Eq._oldrec (Eq.refl (-b + a ≤ -b + (b + c))) (int.neg_add_cancel_left b c)) (int.add_le_add_left h (-b)) protected theorem le_add_of_sub_left_le {a : ℤ} {b : ℤ} {c : ℤ} (h : a - b ≤ c) : a ≤ b + c := eq.mp (Eq._oldrec (Eq.refl (a ≤ c + b)) (int.add_comm c b)) (eq.mp (Eq._oldrec (Eq.refl (a - b + b ≤ c + b)) (int.sub_add_cancel a b)) (int.add_le_add_right h b)) protected theorem sub_left_le_of_le_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a ≤ b + c) : a - b ≤ c := eq.mp (Eq._oldrec (Eq.refl (a + -b ≤ c + b + -b)) (int.add_neg_cancel_right c b)) (eq.mp (Eq._oldrec (Eq.refl (a + -b ≤ b + c + -b)) (int.add_comm b c)) (int.add_le_add_right h (-b))) protected theorem le_add_of_sub_right_le {a : ℤ} {b : ℤ} {c : ℤ} (h : a - c ≤ b) : a ≤ b + c := eq.mp (Eq._oldrec (Eq.refl (a - c + c ≤ b + c)) (int.sub_add_cancel a c)) (int.add_le_add_right h c) protected theorem sub_right_le_of_le_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a ≤ b + c) : a - c ≤ b := eq.mp (Eq._oldrec (Eq.refl (a + -c ≤ b + c + -c)) (int.add_neg_cancel_right b c)) (int.add_le_add_right h (-c)) protected theorem le_add_of_neg_add_le_left {a : ℤ} {b : ℤ} {c : ℤ} (h : -b + a ≤ c) : a ≤ b + c := int.le_add_of_sub_left_le (eq.mp (Eq._oldrec (Eq.refl (-b + a ≤ c)) (int.add_comm (-b) a)) h) protected theorem neg_add_le_left_of_le_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a ≤ b + c) : -b + a ≤ c := eq.mpr (id (Eq._oldrec (Eq.refl (-b + a ≤ c)) (int.add_comm (-b) a))) (int.sub_left_le_of_le_add h) protected theorem le_add_of_neg_add_le_right {a : ℤ} {b : ℤ} {c : ℤ} (h : -c + a ≤ b) : a ≤ b + c := int.le_add_of_sub_right_le (eq.mp (Eq._oldrec (Eq.refl (-c + a ≤ b)) (int.add_comm (-c) a)) h) protected theorem neg_add_le_right_of_le_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a ≤ b + c) : -c + a ≤ b := int.neg_add_le_left_of_le_add (eq.mp (Eq._oldrec (Eq.refl (a ≤ b + c)) (int.add_comm b c)) h) protected theorem le_add_of_neg_le_sub_left {a : ℤ} {b : ℤ} {c : ℤ} (h : -a ≤ b - c) : c ≤ a + b := int.le_add_of_neg_add_le_left (int.add_le_of_le_sub_right h) protected theorem neg_le_sub_left_of_le_add {a : ℤ} {b : ℤ} {c : ℤ} (h : c ≤ a + b) : -a ≤ b - c := eq.mp (Eq._oldrec (Eq.refl (-a ≤ -c + b)) (int.add_comm (-c) b)) (int.le_neg_add_of_add_le (int.sub_left_le_of_le_add h)) protected theorem le_add_of_neg_le_sub_right {a : ℤ} {b : ℤ} {c : ℤ} (h : -b ≤ a - c) : c ≤ a + b := int.le_add_of_sub_right_le (int.add_le_of_le_sub_left h) protected theorem neg_le_sub_right_of_le_add {a : ℤ} {b : ℤ} {c : ℤ} (h : c ≤ a + b) : -b ≤ a - c := int.le_sub_left_of_add_le (int.sub_right_le_of_le_add h) protected theorem sub_le_of_sub_le {a : ℤ} {b : ℤ} {c : ℤ} (h : a - b ≤ c) : a - c ≤ b := int.sub_left_le_of_le_add (int.le_add_of_sub_right_le h) protected theorem sub_le_sub_left {a : ℤ} {b : ℤ} (h : a ≤ b) (c : ℤ) : c - b ≤ c - a := int.add_le_add_left (int.neg_le_neg h) c protected theorem sub_le_sub_right {a : ℤ} {b : ℤ} (h : a ≤ b) (c : ℤ) : a - c ≤ b - c := int.add_le_add_right h (-c) protected theorem sub_le_sub {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c := int.add_le_add hab (int.neg_le_neg hcd) protected theorem add_lt_of_lt_neg_add {a : ℤ} {b : ℤ} {c : ℤ} (h : b < -a + c) : a + b < c := eq.mp (Eq._oldrec (Eq.refl (a + b < a + (-a + c))) (int.add_neg_cancel_left a c)) (int.add_lt_add_left h a) protected theorem lt_neg_add_of_add_lt {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b < c) : b < -a + c := eq.mp (Eq._oldrec (Eq.refl (-a + (a + b) < -a + c)) (int.neg_add_cancel_left a b)) (int.add_lt_add_left h (-a)) protected theorem add_lt_of_lt_sub_left {a : ℤ} {b : ℤ} {c : ℤ} (h : b < c - a) : a + b < c := eq.mp (Eq._oldrec (Eq.refl (a + b < c + a - a)) (int.add_sub_cancel c a)) (eq.mp (Eq._oldrec (Eq.refl (a + b < a + c - a)) (int.add_comm a c)) (eq.mp (Eq._oldrec (Eq.refl (a + b < a + (c - a))) (Eq.symm (int.add_sub_assoc a c a))) (int.add_lt_add_left h a))) protected theorem lt_sub_left_of_add_lt {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b < c) : b < c - a := eq.mp (Eq._oldrec (Eq.refl (b + a + -a < c + -a)) (int.add_neg_cancel_right b a)) (eq.mp (Eq._oldrec (Eq.refl (a + b + -a < c + -a)) (int.add_comm a b)) (int.add_lt_add_right h (-a))) protected theorem add_lt_of_lt_sub_right {a : ℤ} {b : ℤ} {c : ℤ} (h : a < c - b) : a + b < c := eq.mp (Eq._oldrec (Eq.refl (a + b < c - b + b)) (int.sub_add_cancel c b)) (int.add_lt_add_right h b) protected theorem lt_sub_right_of_add_lt {a : ℤ} {b : ℤ} {c : ℤ} (h : a + b < c) : a < c - b := eq.mp (Eq._oldrec (Eq.refl (a + b + -b < c + -b)) (int.add_neg_cancel_right a b)) (int.add_lt_add_right h (-b)) protected theorem lt_add_of_neg_add_lt {a : ℤ} {b : ℤ} {c : ℤ} (h : -b + a < c) : a < b + c := eq.mp (Eq._oldrec (Eq.refl (b + (-b + a) < b + c)) (int.add_neg_cancel_left b a)) (int.add_lt_add_left h b) protected theorem neg_add_lt_of_lt_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a < b + c) : -b + a < c := eq.mp (Eq._oldrec (Eq.refl (-b + a < -b + (b + c))) (int.neg_add_cancel_left b c)) (int.add_lt_add_left h (-b)) protected theorem lt_add_of_sub_left_lt {a : ℤ} {b : ℤ} {c : ℤ} (h : a - b < c) : a < b + c := eq.mp (Eq._oldrec (Eq.refl (a < c + b)) (int.add_comm c b)) (eq.mp (Eq._oldrec (Eq.refl (a - b + b < c + b)) (int.sub_add_cancel a b)) (int.add_lt_add_right h b)) protected theorem sub_left_lt_of_lt_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a < b + c) : a - b < c := eq.mp (Eq._oldrec (Eq.refl (a + -b < c + b + -b)) (int.add_neg_cancel_right c b)) (eq.mp (Eq._oldrec (Eq.refl (a + -b < b + c + -b)) (int.add_comm b c)) (int.add_lt_add_right h (-b))) protected theorem lt_add_of_sub_right_lt {a : ℤ} {b : ℤ} {c : ℤ} (h : a - c < b) : a < b + c := eq.mp (Eq._oldrec (Eq.refl (a - c + c < b + c)) (int.sub_add_cancel a c)) (int.add_lt_add_right h c) protected theorem sub_right_lt_of_lt_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a < b + c) : a - c < b := eq.mp (Eq._oldrec (Eq.refl (a + -c < b + c + -c)) (int.add_neg_cancel_right b c)) (int.add_lt_add_right h (-c)) protected theorem lt_add_of_neg_add_lt_left {a : ℤ} {b : ℤ} {c : ℤ} (h : -b + a < c) : a < b + c := int.lt_add_of_sub_left_lt (eq.mp (Eq._oldrec (Eq.refl (-b + a < c)) (int.add_comm (-b) a)) h) protected theorem neg_add_lt_left_of_lt_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a < b + c) : -b + a < c := eq.mpr (id (Eq._oldrec (Eq.refl (-b + a < c)) (int.add_comm (-b) a))) (int.sub_left_lt_of_lt_add h) protected theorem lt_add_of_neg_add_lt_right {a : ℤ} {b : ℤ} {c : ℤ} (h : -c + a < b) : a < b + c := int.lt_add_of_sub_right_lt (eq.mp (Eq._oldrec (Eq.refl (-c + a < b)) (int.add_comm (-c) a)) h) protected theorem neg_add_lt_right_of_lt_add {a : ℤ} {b : ℤ} {c : ℤ} (h : a < b + c) : -c + a < b := int.neg_add_lt_left_of_lt_add (eq.mp (Eq._oldrec (Eq.refl (a < b + c)) (int.add_comm b c)) h) protected theorem lt_add_of_neg_lt_sub_left {a : ℤ} {b : ℤ} {c : ℤ} (h : -a < b - c) : c < a + b := int.lt_add_of_neg_add_lt_left (int.add_lt_of_lt_sub_right h) protected theorem neg_lt_sub_left_of_lt_add {a : ℤ} {b : ℤ} {c : ℤ} (h : c < a + b) : -a < b - c := eq.mp (Eq._oldrec (Eq.refl (-a < -c + b)) (int.add_comm (-c) b)) (int.lt_neg_add_of_add_lt (int.sub_left_lt_of_lt_add h)) protected theorem lt_add_of_neg_lt_sub_right {a : ℤ} {b : ℤ} {c : ℤ} (h : -b < a - c) : c < a + b := int.lt_add_of_sub_right_lt (int.add_lt_of_lt_sub_left h) protected theorem neg_lt_sub_right_of_lt_add {a : ℤ} {b : ℤ} {c : ℤ} (h : c < a + b) : -b < a - c := int.lt_sub_left_of_add_lt (int.sub_right_lt_of_lt_add h) protected theorem sub_lt_of_sub_lt {a : ℤ} {b : ℤ} {c : ℤ} (h : a - b < c) : a - c < b := int.sub_left_lt_of_lt_add (int.lt_add_of_sub_right_lt h) protected theorem sub_lt_sub_left {a : ℤ} {b : ℤ} (h : a < b) (c : ℤ) : c - b < c - a := int.add_lt_add_left (int.neg_lt_neg h) c protected theorem sub_lt_sub_right {a : ℤ} {b : ℤ} (h : a < b) (c : ℤ) : a - c < b - c := int.add_lt_add_right h (-c) protected theorem sub_lt_sub {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (hab : a < b) (hcd : c < d) : a - d < b - c := int.add_lt_add hab (int.neg_lt_neg hcd) protected theorem sub_lt_sub_of_le_of_lt {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (hab : a ≤ b) (hcd : c < d) : a - d < b - c := int.add_lt_add_of_le_of_lt hab (int.neg_lt_neg hcd) protected theorem sub_lt_sub_of_lt_of_le {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (hab : a < b) (hcd : c ≤ d) : a - d < b - c := int.add_lt_add_of_lt_of_le hab (int.neg_le_neg hcd) protected theorem sub_le_self (a : ℤ) {b : ℤ} (h : b ≥ 0) : a - b ≤ a := trans_rel_left LessEq (trans_rel_right LessEq rfl (int.add_le_add_left (int.neg_nonpos_of_nonneg h) a)) (eq.mpr (id (Eq._oldrec (Eq.refl (a + 0 = a)) (int.add_zero a))) (Eq.refl a)) protected theorem sub_lt_self (a : ℤ) {b : ℤ} (h : b > 0) : a - b < a := trans_rel_left Less (trans_rel_right Less rfl (int.add_lt_add_left (int.neg_neg_of_pos h) a)) (eq.mpr (id (Eq._oldrec (Eq.refl (a + 0 = a)) (int.add_zero a))) (Eq.refl a)) protected theorem add_le_add_three {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} {e : ℤ} {f : ℤ} (h₁ : a ≤ d) (h₂ : b ≤ e) (h₃ : c ≤ f) : a + b + c ≤ d + e + f := le_trans (int.add_le_add (int.add_le_add h₁ h₂) h₃) (le_refl (d + e + f)) /- missing facts -/ protected theorem mul_lt_mul_of_pos_left {a : ℤ} {b : ℤ} {c : ℤ} (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := sorry protected theorem mul_lt_mul_of_pos_right {a : ℤ} {b : ℤ} {c : ℤ} (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := sorry protected theorem mul_le_mul_of_nonneg_left {a : ℤ} {b : ℤ} {c : ℤ} (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := sorry protected theorem mul_le_mul_of_nonneg_right {a : ℤ} {b : ℤ} {c : ℤ} (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := sorry -- TODO: there are four variations, depending on which variables we assume to be nonneg protected theorem mul_le_mul {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (hac : a ≤ c) (hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := le_trans (int.mul_le_mul_of_nonneg_right hac nn_b) (int.mul_le_mul_of_nonneg_left hbd nn_c) protected theorem mul_nonpos_of_nonneg_of_nonpos {a : ℤ} {b : ℤ} (ha : a ≥ 0) (hb : b ≤ 0) : a * b ≤ 0 := (fun (h : a * b ≤ a * 0) => eq.mp (Eq._oldrec (Eq.refl (a * b ≤ a * 0)) (int.mul_zero a)) h) (int.mul_le_mul_of_nonneg_left hb ha) protected theorem mul_nonpos_of_nonpos_of_nonneg {a : ℤ} {b : ℤ} (ha : a ≤ 0) (hb : b ≥ 0) : a * b ≤ 0 := (fun (h : a * b ≤ 0 * b) => eq.mp (Eq._oldrec (Eq.refl (a * b ≤ 0 * b)) (int.zero_mul b)) h) (int.mul_le_mul_of_nonneg_right ha hb) protected theorem mul_lt_mul {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := lt_of_lt_of_le (int.mul_lt_mul_of_pos_right hac pos_b) (int.mul_le_mul_of_nonneg_left hbd nn_c) protected theorem mul_lt_mul' {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (h1 : a ≤ c) (h2 : b < d) (h3 : b ≥ 0) (h4 : c > 0) : a * b < c * d := lt_of_le_of_lt (int.mul_le_mul_of_nonneg_right h1 h3) (int.mul_lt_mul_of_pos_left h2 h4) protected theorem mul_neg_of_pos_of_neg {a : ℤ} {b : ℤ} (ha : a > 0) (hb : b < 0) : a * b < 0 := (fun (h : a * b < a * 0) => eq.mp (Eq._oldrec (Eq.refl (a * b < a * 0)) (int.mul_zero a)) h) (int.mul_lt_mul_of_pos_left hb ha) protected theorem mul_neg_of_neg_of_pos {a : ℤ} {b : ℤ} (ha : a < 0) (hb : b > 0) : a * b < 0 := (fun (h : a * b < 0 * b) => eq.mp (Eq._oldrec (Eq.refl (a * b < 0 * b)) (int.zero_mul b)) h) (int.mul_lt_mul_of_pos_right ha hb) protected theorem mul_le_mul_of_nonpos_right {a : ℤ} {b : ℤ} {c : ℤ} (h : b ≤ a) (hc : c ≤ 0) : a * c ≤ b * c := sorry protected theorem mul_nonneg_of_nonpos_of_nonpos {a : ℤ} {b : ℤ} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b := (fun (this : 0 * b ≤ a * b) => eq.mp (Eq._oldrec (Eq.refl (0 * b ≤ a * b)) (int.zero_mul b)) this) (int.mul_le_mul_of_nonpos_right ha hb) protected theorem mul_lt_mul_of_neg_left {a : ℤ} {b : ℤ} {c : ℤ} (h : b < a) (hc : c < 0) : c * a < c * b := sorry protected theorem mul_lt_mul_of_neg_right {a : ℤ} {b : ℤ} {c : ℤ} (h : b < a) (hc : c < 0) : a * c < b * c := sorry protected theorem mul_pos_of_neg_of_neg {a : ℤ} {b : ℤ} (ha : a < 0) (hb : b < 0) : 0 < a * b := (fun (this : 0 * b < a * b) => eq.mp (Eq._oldrec (Eq.refl (0 * b < a * b)) (int.zero_mul b)) this) (int.mul_lt_mul_of_neg_right ha hb) protected theorem mul_self_le_mul_self {a : ℤ} {b : ℤ} (h1 : 0 ≤ a) (h2 : a ≤ b) : a * a ≤ b * b := int.mul_le_mul h2 h2 h1 (le_trans h1 h2) protected theorem mul_self_lt_mul_self {a : ℤ} {b : ℤ} (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b := int.mul_lt_mul' (le_of_lt h2) h2 h1 (lt_of_le_of_lt h1 h2) /- more facts specific to int -/ theorem of_nat_nonneg (n : ℕ) : 0 ≤ Int.ofNat n := trivial theorem coe_succ_pos (n : ℕ) : ↑(Nat.succ n) > 0 := coe_nat_lt_coe_nat_of_lt (nat.succ_pos n) theorem exists_eq_neg_of_nat {a : ℤ} (H : a ≤ 0) : ∃ (n : ℕ), a = -↑n := sorry theorem nat_abs_of_nonneg {a : ℤ} (H : a ≥ 0) : ↑(nat_abs a) = a := sorry theorem of_nat_nat_abs_of_nonpos {a : ℤ} (H : a ≤ 0) : ↑(nat_abs a) = -a := eq.mpr (id (Eq._oldrec (Eq.refl (↑(nat_abs a) = -a)) (Eq.symm (nat_abs_neg a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(nat_abs (-a)) = -a)) (nat_abs_of_nonneg (int.neg_nonneg_of_nonpos H)))) (Eq.refl (-a))) theorem lt_of_add_one_le {a : ℤ} {b : ℤ} (H : a + 1 ≤ b) : a < b := H theorem add_one_le_of_lt {a : ℤ} {b : ℤ} (H : a < b) : a + 1 ≤ b := H theorem lt_add_one_of_le {a : ℤ} {b : ℤ} (H : a ≤ b) : a < b + 1 := int.add_le_add_right H 1 theorem le_of_lt_add_one {a : ℤ} {b : ℤ} (H : a < b + 1) : a ≤ b := int.le_of_add_le_add_right H theorem sub_one_le_of_lt {a : ℤ} {b : ℤ} (H : a ≤ b) : a - 1 < b := int.sub_right_lt_of_lt_add (lt_add_one_of_le H) theorem lt_of_sub_one_le {a : ℤ} {b : ℤ} (H : a - 1 < b) : a ≤ b := le_of_lt_add_one (int.lt_add_of_sub_right_lt H) theorem le_sub_one_of_lt {a : ℤ} {b : ℤ} (H : a < b) : a ≤ b - 1 := int.le_sub_right_of_add_le H theorem lt_of_le_sub_one {a : ℤ} {b : ℤ} (H : a ≤ b - 1) : a < b := int.add_le_of_le_sub_right H theorem sign_of_succ (n : ℕ) : sign ↑(Nat.succ n) = 1 := rfl theorem sign_eq_one_of_pos {a : ℤ} (h : 0 < a) : sign a = 1 := sorry theorem sign_eq_neg_one_of_neg {a : ℤ} (h : a < 0) : sign a = -1 := sorry theorem eq_zero_of_sign_eq_zero {a : ℤ} : sign a = 0 → a = 0 := sorry theorem pos_of_sign_eq_one {a : ℤ} : sign a = 1 → 0 < a := sorry theorem neg_of_sign_eq_neg_one {a : ℤ} : sign a = -1 → a < 0 := sorry theorem sign_eq_one_iff_pos (a : ℤ) : sign a = 1 ↔ 0 < a := { mp := pos_of_sign_eq_one, mpr := sign_eq_one_of_pos } theorem sign_eq_neg_one_iff_neg (a : ℤ) : sign a = -1 ↔ a < 0 := { mp := neg_of_sign_eq_neg_one, mpr := sign_eq_neg_one_of_neg } theorem sign_eq_zero_iff_zero (a : ℤ) : sign a = 0 ↔ a = 0 := sorry protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {a : ℤ} {b : ℤ} (h : a * b = 0) : a = 0 ∨ b = 0 := sorry protected theorem eq_of_mul_eq_mul_right {a : ℤ} {b : ℤ} {c : ℤ} (ha : a ≠ 0) (h : b * a = c * a) : b = c := sorry protected theorem eq_of_mul_eq_mul_left {a : ℤ} {b : ℤ} {c : ℤ} (ha : a ≠ 0) (h : a * b = a * c) : b = c := sorry theorem eq_one_of_mul_eq_self_left {a : ℤ} {b : ℤ} (Hpos : a ≠ 0) (H : b * a = a) : b = 1 := int.eq_of_mul_eq_mul_right Hpos (eq.mpr (id (Eq._oldrec (Eq.refl (b * a = 1 * a)) (int.one_mul a))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a = a)) H)) (Eq.refl a))) theorem eq_one_of_mul_eq_self_right {a : ℤ} {b : ℤ} (Hpos : b ≠ 0) (H : b * a = b) : a = 1 := int.eq_of_mul_eq_mul_left Hpos (eq.mpr (id (Eq._oldrec (Eq.refl (b * a = b * 1)) (int.mul_one b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a = b)) H)) (Eq.refl b)))
6aff0315a6bb921771e0dd1e12f93612d81da6f3
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/DeclarationRange.lean
7e0c2a099a6b8f102989f1c54fc53608e1976311
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,498
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.MonadEnv import Lean.AuxRecursor import Lean.ToExpr namespace Lean /-- Store position information for declarations. -/ structure DeclarationRange where pos : Position /-- A precomputed UTF-16 `character` field as in `Lean.Lsp.Position`. We need to store this because LSP clients want us to report the range in terms of UTF-16, but converting a Unicode codepoint stored in `Lean.Position` to UTF-16 requires loading and mapping the target source file, which is IO-heavy. -/ charUtf16 : Nat endPos : Position /-- See `charUtf16`. -/ endCharUtf16 : Nat deriving Inhabited, DecidableEq, Repr instance : ToExpr DeclarationRange where toExpr r := mkAppN (mkConst ``DeclarationRange.mk) #[toExpr r.pos, toExpr r.charUtf16, toExpr r.endPos, toExpr r.endCharUtf16] toTypeExpr := mkConst ``DeclarationRange structure DeclarationRanges where range : DeclarationRange selectionRange : DeclarationRange deriving Inhabited, Repr instance : ToExpr DeclarationRanges where toExpr r := mkAppN (mkConst ``DeclarationRanges.mk) #[toExpr r.range, toExpr r.selectionRange] toTypeExpr := mkConst ``DeclarationRanges builtin_initialize builtinDeclRanges : IO.Ref (NameMap DeclarationRanges) ← IO.mkRef {} builtin_initialize declRangeExt : MapDeclarationExtension DeclarationRanges ← mkMapDeclarationExtension def addBuiltinDeclarationRanges (declName : Name) (declRanges : DeclarationRanges) : IO Unit := builtinDeclRanges.modify (·.insert declName declRanges) def addDeclarationRanges [MonadEnv m] (declName : Name) (declRanges : DeclarationRanges) : m Unit := modifyEnv fun env => declRangeExt.insert env declName declRanges def findDeclarationRangesCore? [Monad m] [MonadEnv m] (declName : Name) : m (Option DeclarationRanges) := return declRangeExt.find? (← getEnv) declName def findDeclarationRanges? [Monad m] [MonadEnv m] [MonadLiftT IO m] (declName : Name) : m (Option DeclarationRanges) := do let env ← getEnv let ranges ← if isAuxRecursor env declName || isNoConfusion env declName || (← isRec declName) then findDeclarationRangesCore? declName.getPrefix else findDeclarationRangesCore? declName match ranges with | none => return (← builtinDeclRanges.get (m := IO)).find? declName | some _ => return ranges end Lean
944660dafc84c8d72c275f105e66091587ce7237
968e2f50b755d3048175f176376eff7139e9df70
/examples/pred_logic/unnamed_538.lean
ddee66aee3c4c4aaa08828b1cb7ab9fe2a001eef
[]
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
314
lean
variables (U : Type*) (P Q : U → Prop) -- BEGIN example (u : U) (h₁ : P u → Q u) (h₂ : P u) : ∃ x, Q x := begin have h₃ : Q u, from h₁ h₂, -- We have `Q u` from `→` elim. on `h₁` and `h₂`. exact exists.intro u h₃, -- The result follows from exists intro. on `u` and `h₃`. end -- END
ebcfe17344800489a9a9b749030f62918311b421
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebraic_geometry/Spec.lean
fa176f103806e294d0a9acb8486cc2e9a561be11
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
15,620
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Justus Springer -/ import algebraic_geometry.locally_ringed_space import algebraic_geometry.structure_sheaf import logic.equiv.transfer_instance import ring_theory.localization.localization_localization import topology.sheaves.sheaf_condition.sites import topology.sheaves.functors import algebra.module.localized_module /-! # $Spec$ as a functor to locally ringed spaces. We define the functor $Spec$ from commutative rings to locally ringed spaces. ## Implementation notes We define $Spec$ in three consecutive steps, each with more structure than the last: 1. `Spec.to_Top`, valued in the category of topological spaces, 2. `Spec.to_SheafedSpace`, valued in the category of sheafed spaces and 3. `Spec.to_LocallyRingedSpace`, valued in the category of locally ringed spaces. Additionally, we provide `Spec.to_PresheafedSpace` as a composition of `Spec.to_SheafedSpace` with a forgetful functor. ## Related results The adjunction `Γ ⊣ Spec` is constructed in `algebraic_geometry/Gamma_Spec_adjunction.lean`. -/ noncomputable theory universes u v namespace algebraic_geometry open opposite open category_theory open structure_sheaf Spec (structure_sheaf) /-- The spectrum of a commutative ring, as a topological space. -/ def Spec.Top_obj (R : CommRing) : Top := Top.of (prime_spectrum R) /-- The induced map of a ring homomorphism on the ring spectra, as a morphism of topological spaces. -/ def Spec.Top_map {R S : CommRing} (f : R ⟶ S) : Spec.Top_obj S ⟶ Spec.Top_obj R := prime_spectrum.comap f @[simp] lemma Spec.Top_map_id (R : CommRing) : Spec.Top_map (𝟙 R) = 𝟙 (Spec.Top_obj R) := prime_spectrum.comap_id lemma Spec.Top_map_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) : Spec.Top_map (f ≫ g) = Spec.Top_map g ≫ Spec.Top_map f := prime_spectrum.comap_comp _ _ /-- The spectrum, as a contravariant functor from commutative rings to topological spaces. -/ @[simps] def Spec.to_Top : CommRingᵒᵖ ⥤ Top := { obj := λ R, Spec.Top_obj (unop R), map := λ R S f, Spec.Top_map f.unop, map_id' := λ R, by rw [unop_id, Spec.Top_map_id], map_comp' := λ R S T f g, by rw [unop_comp, Spec.Top_map_comp] } /-- The spectrum of a commutative ring, as a `SheafedSpace`. -/ @[simps] def Spec.SheafedSpace_obj (R : CommRing) : SheafedSpace CommRing := { carrier := Spec.Top_obj R, presheaf := (structure_sheaf R).1, is_sheaf := (structure_sheaf R).2 } /-- The induced map of a ring homomorphism on the ring spectra, as a morphism of sheafed spaces. -/ @[simps] def Spec.SheafedSpace_map {R S : CommRing.{u}} (f : R ⟶ S) : Spec.SheafedSpace_obj S ⟶ Spec.SheafedSpace_obj R := { base := Spec.Top_map f, c := { app := λ U, comap f (unop U) ((topological_space.opens.map (Spec.Top_map f)).obj (unop U)) (λ p, id), naturality' := λ U V i, ring_hom.ext $ λ s, subtype.eq $ funext $ λ p, rfl } } @[simp] lemma Spec.SheafedSpace_map_id {R : CommRing} : Spec.SheafedSpace_map (𝟙 R) = 𝟙 (Spec.SheafedSpace_obj R) := PresheafedSpace.ext _ _ (Spec.Top_map_id R) $ nat_trans.ext _ _ $ funext $ λ U, begin dsimp, erw [PresheafedSpace.id_c_app, comap_id], swap, { rw [Spec.Top_map_id, topological_space.opens.map_id_obj_unop] }, simpa [eq_to_hom_map], end lemma Spec.SheafedSpace_map_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) : Spec.SheafedSpace_map (f ≫ g) = Spec.SheafedSpace_map g ≫ Spec.SheafedSpace_map f := PresheafedSpace.ext _ _ (Spec.Top_map_comp f g) $ nat_trans.ext _ _ $ funext $ λ U, by { dsimp, rw category_theory.functor.map_id, rw category.comp_id, erw comap_comp f g, refl } /-- Spec, as a contravariant functor from commutative rings to sheafed spaces. -/ @[simps] def Spec.to_SheafedSpace : CommRingᵒᵖ ⥤ SheafedSpace CommRing := { obj := λ R, Spec.SheafedSpace_obj (unop R), map := λ R S f, Spec.SheafedSpace_map f.unop, map_id' := λ R, by rw [unop_id, Spec.SheafedSpace_map_id], map_comp' := λ R S T f g, by rw [unop_comp, Spec.SheafedSpace_map_comp] } /-- Spec, as a contravariant functor from commutative rings to presheafed spaces. -/ def Spec.to_PresheafedSpace : CommRingᵒᵖ ⥤ PresheafedSpace.{u} CommRing.{u} := Spec.to_SheafedSpace ⋙ SheafedSpace.forget_to_PresheafedSpace @[simp] lemma Spec.to_PresheafedSpace_obj (R : CommRingᵒᵖ) : Spec.to_PresheafedSpace.obj R = (Spec.SheafedSpace_obj (unop R)).to_PresheafedSpace := rfl lemma Spec.to_PresheafedSpace_obj_op (R : CommRing) : Spec.to_PresheafedSpace.obj (op R) = (Spec.SheafedSpace_obj R).to_PresheafedSpace := rfl @[simp] lemma Spec.to_PresheafedSpace_map (R S : CommRingᵒᵖ) (f : R ⟶ S) : Spec.to_PresheafedSpace.map f = Spec.SheafedSpace_map f.unop := rfl lemma Spec.to_PresheafedSpace_map_op (R S : CommRing) (f : R ⟶ S) : Spec.to_PresheafedSpace.map f.op = Spec.SheafedSpace_map f := rfl lemma Spec.basic_open_hom_ext {X : RingedSpace} {R : CommRing} {α β : X ⟶ Spec.SheafedSpace_obj R} (w : α.base = β.base) (h : ∀ r : R, let U := prime_spectrum.basic_open r in (to_open R U ≫ α.c.app (op U)) ≫ X.presheaf.map (eq_to_hom (by rw w)) = to_open R U ≫ β.c.app (op U)) : α = β := begin ext1, { apply ((Top.sheaf.pushforward β.base).obj X.sheaf).hom_ext _ prime_spectrum.is_basis_basic_opens, intro r, apply (structure_sheaf.to_basic_open_epi R r).1, simpa using h r }, exact w, end /-- The spectrum of a commutative ring, as a `LocallyRingedSpace`. -/ @[simps] def Spec.LocallyRingedSpace_obj (R : CommRing) : LocallyRingedSpace := { local_ring := λ x, @@ring_equiv.local_ring _ (show local_ring (localization.at_prime _), by apply_instance) _ (iso.CommRing_iso_to_ring_equiv $ stalk_iso R x).symm, .. Spec.SheafedSpace_obj R } @[elementwise] lemma stalk_map_to_stalk {R S : CommRing} (f : R ⟶ S) (p : prime_spectrum S) : to_stalk R (prime_spectrum.comap f p) ≫ PresheafedSpace.stalk_map (Spec.SheafedSpace_map f) p = f ≫ to_stalk S p := begin erw [← to_open_germ S ⊤ ⟨p, trivial⟩, ← to_open_germ R ⊤ ⟨prime_spectrum.comap f p, trivial⟩, category.assoc, PresheafedSpace.stalk_map_germ (Spec.SheafedSpace_map f) ⊤ ⟨p, trivial⟩, Spec.SheafedSpace_map_c_app, to_open_comp_comap_assoc], refl end /-- Under the isomorphisms `stalk_iso`, the map `stalk_map (Spec.SheafedSpace_map f) p` corresponds to the induced local ring homomorphism `localization.local_ring_hom`. -/ @[elementwise] lemma local_ring_hom_comp_stalk_iso {R S : CommRing} (f : R ⟶ S) (p : prime_spectrum S) : (stalk_iso R (prime_spectrum.comap f p)).hom ≫ @category_struct.comp _ _ (CommRing.of (localization.at_prime (prime_spectrum.comap f p).as_ideal)) (CommRing.of (localization.at_prime p.as_ideal)) _ (localization.local_ring_hom (prime_spectrum.comap f p).as_ideal p.as_ideal f rfl) (stalk_iso S p).inv = PresheafedSpace.stalk_map (Spec.SheafedSpace_map f) p := (stalk_iso R (prime_spectrum.comap f p)).eq_inv_comp.mp $ (stalk_iso S p).comp_inv_eq.mpr $ localization.local_ring_hom_unique _ _ _ _ $ λ x, by rw [stalk_iso_hom, stalk_iso_inv, comp_apply, comp_apply, localization_to_stalk_of, stalk_map_to_stalk_apply, stalk_to_fiber_ring_hom_to_stalk] /-- The induced map of a ring homomorphism on the prime spectra, as a morphism of locally ringed spaces. -/ @[simps] def Spec.LocallyRingedSpace_map {R S : CommRing} (f : R ⟶ S) : Spec.LocallyRingedSpace_obj S ⟶ Spec.LocallyRingedSpace_obj R := LocallyRingedSpace.hom.mk (Spec.SheafedSpace_map f) $ λ p, is_local_ring_hom.mk $ λ a ha, begin -- Here, we are showing that the map on prime spectra induced by `f` is really a morphism of -- *locally* ringed spaces, i.e. that the induced map on the stalks is a local ring homomorphism. rw ← local_ring_hom_comp_stalk_iso_apply at ha, replace ha := (stalk_iso S p).hom.is_unit_map ha, rw iso.inv_hom_id_apply at ha, replace ha := is_local_ring_hom.map_nonunit _ ha, convert ring_hom.is_unit_map (stalk_iso R (prime_spectrum.comap f p)).inv ha, rw iso.hom_inv_id_apply end @[simp] lemma Spec.LocallyRingedSpace_map_id (R : CommRing) : Spec.LocallyRingedSpace_map (𝟙 R) = 𝟙 (Spec.LocallyRingedSpace_obj R) := LocallyRingedSpace.hom.ext _ _ $ by { rw [Spec.LocallyRingedSpace_map_val, Spec.SheafedSpace_map_id], refl } lemma Spec.LocallyRingedSpace_map_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) : Spec.LocallyRingedSpace_map (f ≫ g) = Spec.LocallyRingedSpace_map g ≫ Spec.LocallyRingedSpace_map f := LocallyRingedSpace.hom.ext _ _ $ by { rw [Spec.LocallyRingedSpace_map_val, Spec.SheafedSpace_map_comp], refl } /-- Spec, as a contravariant functor from commutative rings to locally ringed spaces. -/ @[simps] def Spec.to_LocallyRingedSpace : CommRingᵒᵖ ⥤ LocallyRingedSpace := { obj := λ R, Spec.LocallyRingedSpace_obj (unop R), map := λ R S f, Spec.LocallyRingedSpace_map f.unop, map_id' := λ R, by rw [unop_id, Spec.LocallyRingedSpace_map_id], map_comp' := λ R S T f g, by rw [unop_comp, Spec.LocallyRingedSpace_map_comp] } section Spec_Γ open algebraic_geometry.LocallyRingedSpace /-- The counit morphism `R ⟶ Γ(Spec R)` given by `algebraic_geometry.structure_sheaf.to_open`. -/ @[simps {rhs_md := tactic.transparency.semireducible}] def to_Spec_Γ (R : CommRing) : R ⟶ Γ.obj (op (Spec.to_LocallyRingedSpace.obj (op R))) := structure_sheaf.to_open R ⊤ instance is_iso_to_Spec_Γ (R : CommRing) : is_iso (to_Spec_Γ R) := by { cases R, apply structure_sheaf.is_iso_to_global } @[reassoc] lemma Spec_Γ_naturality {R S : CommRing} (f : R ⟶ S) : f ≫ to_Spec_Γ S = to_Spec_Γ R ≫ Γ.map (Spec.to_LocallyRingedSpace.map f.op).op := by { ext, symmetry, apply localization.local_ring_hom_to_map } /-- The counit (`Spec_Γ_identity.inv.op`) of the adjunction `Γ ⊣ Spec` is an isomorphism. -/ @[simps hom_app inv_app] def Spec_Γ_identity : Spec.to_LocallyRingedSpace.right_op ⋙ Γ ≅ 𝟭 _ := iso.symm $ nat_iso.of_components (λ R, as_iso (to_Spec_Γ R) : _) (λ _ _, Spec_Γ_naturality) end Spec_Γ /-- The stalk map of `Spec M⁻¹R ⟶ Spec R` is an iso for each `p : Spec M⁻¹R`. -/ lemma Spec_map_localization_is_iso (R : CommRing) (M : submonoid R) (x : prime_spectrum (localization M)) : is_iso (PresheafedSpace.stalk_map (Spec.to_PresheafedSpace.map (CommRing.of_hom (algebra_map R (localization M))).op) x) := begin erw ← local_ring_hom_comp_stalk_iso, apply_with is_iso.comp_is_iso { instances := ff }, apply_instance, apply_with is_iso.comp_is_iso { instances := ff }, /- I do not know why this is defeq to the goal, but I'm happy to accept that it is. -/ exact (show is_iso (is_localization.localization_localization_at_prime_iso_localization M x.as_ideal).to_ring_equiv.to_CommRing_iso.hom, by apply_instance), apply_instance end namespace structure_sheaf variables {R S : CommRing.{u}} (f : R ⟶ S) (p : prime_spectrum R) /-- For an algebra `f : R →+* S`, this is the ring homomorphism `S →+* (f∗ 𝒪ₛ)ₚ` for a `p : Spec R`. This is shown to be the localization at `p` in `is_localized_module_to_pushforward_stalk_alg_hom`. -/ def to_pushforward_stalk : S ⟶ (Spec.Top_map f _* (structure_sheaf S).1).stalk p := structure_sheaf.to_open S ⊤ ≫ @Top.presheaf.germ _ _ _ _ (Spec.Top_map f _* (structure_sheaf S).1) ⊤ ⟨p, trivial⟩ @[reassoc] lemma to_pushforward_stalk_comp : f ≫ structure_sheaf.to_pushforward_stalk f p = structure_sheaf.to_stalk R p ≫ (Top.presheaf.stalk_functor _ _).map (Spec.SheafedSpace_map f).c := begin rw structure_sheaf.to_stalk, erw category.assoc, rw Top.presheaf.stalk_functor_map_germ, exact Spec_Γ_naturality_assoc f _, end instance : algebra R ((Spec.Top_map f _* (structure_sheaf S).1).stalk p) := (f ≫ structure_sheaf.to_pushforward_stalk f p).to_algebra lemma algebra_map_pushforward_stalk : algebra_map R ((Spec.Top_map f _* (structure_sheaf S).1).stalk p) = f ≫ structure_sheaf.to_pushforward_stalk f p := rfl variables (R S) [algebra R S] /-- This is the `alg_hom` version of `to_pushforward_stalk`, which is the map `S ⟶ (f∗ 𝒪ₛ)ₚ` for some algebra `R ⟶ S` and some `p : Spec R`. -/ @[simps] def to_pushforward_stalk_alg_hom : S →ₐ[R] (Spec.Top_map (algebra_map R S) _* (structure_sheaf S).1).stalk p := { commutes' := λ _, rfl, ..(structure_sheaf.to_pushforward_stalk (algebra_map R S) p) } . lemma is_localized_module_to_pushforward_stalk_alg_hom_aux (y) : ∃ (x : S × p.as_ideal.prime_compl), x.2 • y = to_pushforward_stalk_alg_hom R S p x.1 := begin obtain ⟨U, hp, s, e⟩ := Top.presheaf.germ_exist _ _ y, obtain ⟨_, ⟨r, rfl⟩, hpr, hrU⟩ := prime_spectrum.is_topological_basis_basic_opens .exists_subset_of_mem_open (show p ∈ U.1, from hp) U.2, change prime_spectrum.basic_open r ≤ U at hrU, replace e := ((Spec.Top_map (algebra_map R S) _* (structure_sheaf S).1) .germ_res_apply (hom_of_le hrU) ⟨p, hpr⟩ _).trans e, set s' := (Spec.Top_map (algebra_map R S) _* (structure_sheaf S).1).map (hom_of_le hrU).op s with h, rw ← h at e, clear_value s', clear_dependent U, obtain ⟨⟨s, ⟨_, n, rfl⟩⟩, hsn⟩ := @is_localization.surj _ _ _ _ _ _ (structure_sheaf.is_localization.to_basic_open S $ algebra_map R S r) s', refine ⟨⟨s, ⟨r, hpr⟩ ^ n⟩, _⟩, rw [submonoid.smul_def, algebra.smul_def, algebra_map_pushforward_stalk, to_pushforward_stalk, comp_apply, comp_apply], iterate 2 { erw ← (Spec.Top_map (algebra_map R S) _* (structure_sheaf S).1).germ_res_apply (hom_of_le le_top) ⟨p, hpr⟩ }, rw [← e, ← map_mul, mul_comm], dsimp only [subtype.coe_mk] at hsn, rw ← map_pow (algebra_map R S) at hsn, congr' 1 end instance is_localized_module_to_pushforward_stalk_alg_hom : is_localized_module p.as_ideal.prime_compl (to_pushforward_stalk_alg_hom R S p).to_linear_map := begin apply is_localized_module.mk_of_algebra, { intros x hx, rw [algebra_map_pushforward_stalk, to_pushforward_stalk_comp, comp_apply], exact (is_localization.map_units ((structure_sheaf R).presheaf.stalk p) ⟨x, hx⟩).map _ }, { apply is_localized_module_to_pushforward_stalk_alg_hom_aux }, { intros x hx, rw [to_pushforward_stalk_alg_hom_apply, ring_hom.to_fun_eq_coe, ← (to_pushforward_stalk (algebra_map R S) p).map_zero, to_pushforward_stalk, comp_apply, comp_apply, map_zero] at hx, obtain ⟨U, hpU, i₁, i₂, e⟩ := Top.presheaf.germ_eq _ _ _ _ _ _ hx, obtain ⟨_, ⟨r, rfl⟩, hpr, hrU⟩ := prime_spectrum.is_topological_basis_basic_opens .exists_subset_of_mem_open (show p ∈ U.1, from hpU) U.2, change prime_spectrum.basic_open r ≤ U at hrU, apply_fun (Spec.Top_map (algebra_map R S) _* (structure_sheaf S).1).map (hom_of_le hrU).op at e, simp only [Top.presheaf.pushforward_obj_map, functor.op_map, map_zero, ← comp_apply, to_open_res] at e, have : to_open S (prime_spectrum.basic_open $ algebra_map R S r) x = 0, { refine eq.trans _ e, refl }, have := (@is_localization.mk'_one _ _ _ _ _ _ (structure_sheaf.is_localization.to_basic_open S $ algebra_map R S r) x).trans this, obtain ⟨⟨_, n, rfl⟩, e⟩ := (is_localization.mk'_eq_zero_iff _ _).mp this, refine ⟨⟨r, hpr⟩ ^ n, _⟩, rw [submonoid.smul_def, algebra.smul_def, submonoid.coe_pow, subtype.coe_mk, mul_comm, map_pow], exact e }, end end structure_sheaf end algebraic_geometry
243f262a500f52724fa6fcff297b7f145317bd98
efce24474b28579aba3272fdb77177dc2b11d7aa
/src/for_mathlib/data_equiv.lean
6d9c03dbecd22b2df4b10afe39b2ad46bec76391
[ "Apache-2.0" ]
permissive
rwbarton/lean-homotopy-theory
cff499f24268d60e1c546e7c86c33f58c62888ed
39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee
refs/heads/lean-3.4.2
1,622,711,883,224
1,598,550,958,000
1,598,550,958,000
136,023,667
12
6
Apache-2.0
1,573,187,573,000
1,528,116,262,000
Lean
UTF-8
Lean
false
false
975
lean
import data.equiv.basic namespace equiv @[simp] lemma symm_comp_self_eq_id {α β : Sort*} (e : α ≃ β) : e.symm ∘ e = id := function.left_inverse.comp_eq_id e.left_inverse_symm @[simp] lemma self_comp_symm_eq_id {α β : Sort*} (e : α ≃ β) : e ∘ e.symm = id := function.right_inverse.comp_eq_id e.right_inverse_symm def subtype_prod_subtype_equiv_subtype {α β : Type*} {p : α → Prop} {q : β → Prop} : ({a // p a} × {b // q b}) ≃ {c : α × β // p c.1 ∧ q c.2} := ⟨λ apbq, ⟨(apbq.fst.val, apbq.snd.val), ⟨apbq.fst.property, apbq.snd.property⟩⟩, λ abpq, (⟨abpq.val.fst, abpq.property.left⟩, ⟨abpq.val.snd, abpq.property.right⟩), λ ⟨⟨a, p⟩, ⟨b, q⟩⟩, rfl, λ ⟨⟨a, b⟩, ⟨p, q⟩⟩, rfl⟩ def replace_to_fun {α β : Sort*} (e : α ≃ β) (f : α → β) (h : ⇑e = f) : α ≃ β := { to_fun := f, inv_fun := e.inv_fun, left_inv := h ▸ e.left_inv, right_inv := h ▸ e.right_inv } end equiv
a2c507adb7ca8a9ebae88b90d08a9f78b50e90eb
4fa161becb8ce7378a709f5992a594764699e268
/src/measure_theory/bochner_integration.lean
68718b57e0e175c66e4fbc7953d34b3ba92806eb
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
54,383
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import measure_theory.simple_func_dense import analysis.normed_space.bounded_linear_maps /-! # Bochner integral The Bochner integral extends the definition of the Lebesgue integral to functions that map from a measure space into a Banach space (complete normed vector space). It is constructed here by extending the integral on simple functions. ## Main definitions The Bochner integral is defined following these steps: 1. Define the integral on simple functions of the type `simple_func α β` (notation : `α →ₛ β`) where `β` is a real normed space. (See `simple_func.bintegral` and section `bintegral` for details. Also see `simple_func.integral` for the integral on simple functions of the type `simple_func α ennreal`.) 2. Use `simple_func α β` to cut out the simple functions from L1 functions, and define integral on these. The type of simple functions in L1 space is written as `α →₁ₛ β`. 3. Show that the embedding of `α →₁ₛ β` into L1 is a dense and uniform one. 4. Show that the integral defined on `α →₁ₛ β` is a continuous linear map. 5. Define the Bochner integral on L1 functions by extending the integral on integrable simple functions `α →₁ₛ β` using `continuous_linear_map.extend`. Define the Bochner integral on functions as the Bochner integral of its equivalence class in L1 space. ## Main statements 1. Basic properties of the Bochner integral on functions of type `α → β`, where `α` is a measure space and `β` is a real normed space. * `integral_zero` : `∫ 0 = 0` * `integral_add` : `∫ f + g = ∫ f + ∫ g` * `integral_neg` : `∫ -f = - ∫ f` * `integral_sub` : `∫ f - g = ∫ f - ∫ g` * `integral_smul` : `∫ r • f = r • ∫ f` * `integral_congr_ae` : `∀ₘ a, f a = g a → ∫ f = ∫ g` * `norm_integral_le_integral_norm` : `∥∫ f∥ ≤ ∫ ∥f∥` 2. Basic properties of the Bochner integral on functions of type `α → ℝ`, where `α` is a measure space. * `integral_nonneg_of_ae` : `∀ₘ a, 0 ≤ f a → 0 ≤ ∫ f` * `integral_nonpos_of_nonpos_ae` : `∀ₘ a, f a ≤ 0 → ∫ f ≤ 0` * `integral_le_integral_of_le_ae` : `∀ₘ a, f a ≤ g a → ∫ f ≤ ∫ g` 3. Propositions connecting the Bochner integral with the integral on `ennreal`-valued functions, which is called `lintegral` and has the notation `∫⁻`. * `integral_eq_lintegral_max_sub_lintegral_min` : `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, where `f⁺` is the positive part of `f` and `f⁻` is the negative part of `f`. * `integral_eq_lintegral_of_nonneg_ae` : `∀ₘ a, 0 ≤ f a → ∫ f = ∫⁻ f` 4. `tendsto_integral_of_dominated_convergence` : the Lebesgue dominated convergence theorem ## Notes Some tips on how to prove a proposition if the API for the Bochner integral is not enough so that you need to unfold the definition of the Bochner integral and go back to simple functions. See `integral_eq_lintegral_max_sub_lintegral_min` for a complicated example, which proves that `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, with the first integral sign being the Bochner integral of a real-valued function f : α → ℝ, and second and third integral sign being the integral on ennreal-valued functions (called `lintegral`). The proof of `integral_eq_lintegral_max_sub_lintegral_min` is scattered in sections with the name `pos_part`. Here are the usual steps of proving that a property `p`, say `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, holds for all functions : 1. First go to the `L¹` space. For example, if you see `ennreal.to_real (∫⁻ a, ennreal.of_real $ ∥f a∥)`, that is the norm of `f` in `L¹` space. Rewrite using `l1.norm_of_fun_eq_lintegral_norm`. 2. Show that the set `{f ∈ L¹ | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻}` is closed in `L¹` using `is_closed_eq`. 3. Show that the property holds for all simple functions `s` in `L¹` space. Typically, you need to convert various notions to their `simple_func` counterpart, using lemmas like `l1.integral_coe_eq_integral`. 4. Since simple functions are dense in `L¹`, ``` univ = closure {s simple} = closure {s simple | ∫ s = ∫⁻ s⁺ - ∫⁻ s⁻} : the property holds for all simple functions ⊆ closure {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} = {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} : closure of a closed set is itself ``` Use `is_closed_property` or `dense_range.induction_on` for this argument. ## Notations * `α →ₛ β` : simple functions (defined in `measure_theory/integration`) * `α →₁ β` : functions in L1 space, i.e., equivalence classes of integrable functions (defined in `measure_theory/l1_space`) * `α →₁ₛ β` : simple functions in L1 space, i.e., equivalence classes of integrable simple functions Note : `ₛ` is typed using `\_s`. Sometimes it shows as a box if font is missing. ## Tags Bochner integral, simple function, function space, Lebesgue dominated convergence theorem -/ noncomputable theory open_locale classical topological_space big_operators namespace measure_theory universes u v w variables {α : Type u} [measurable_space α] {β : Type v} [decidable_linear_order β] [has_zero β] local infixr ` →ₛ `:25 := simple_func namespace simple_func section pos_part /-- Positive part of a simple function. -/ def pos_part (f : α →ₛ β) : α →ₛ β := f.map (λb, max b 0) /-- Negative part of a simple function. -/ def neg_part [has_neg β] (f : α →ₛ β) : α →ₛ β := pos_part (-f) lemma pos_part_map_norm (f : α →ₛ ℝ) : (pos_part f).map norm = pos_part f := begin ext, rw [map_apply, real.norm_eq_abs, abs_of_nonneg], rw [pos_part, map_apply], exact le_max_right _ _ end lemma neg_part_map_norm (f : α →ₛ ℝ) : (neg_part f).map norm = neg_part f := by { rw neg_part, exact pos_part_map_norm _ } lemma pos_part_sub_neg_part (f : α →ₛ ℝ) : f.pos_part - f.neg_part = f := begin simp only [pos_part, neg_part], ext, exact max_zero_sub_eq_self (f a) end end pos_part end simple_func end measure_theory namespace measure_theory open set filter topological_space ennreal emetric universes u v w variables {α : Type u} [measure_space α] {β : Type v} {γ : Type w} local infixr ` →ₛ `:25 := simple_func namespace simple_func section bintegral /-! ### The Bochner integral of simple functions Define the Bochner integral of simple functions of the type `α →ₛ β` where `β` is a normed group, and prove basic property of this integral. -/ open finset variables [normed_group β] [normed_group γ] lemma integrable_iff_integral_lt_top {f : α →ₛ β} : integrable f ↔ integral (f.map (coe ∘ nnnorm)) < ⊤ := by { rw [integrable, ← lintegral_eq_integral, lintegral_map] } lemma fin_vol_supp_of_integrable {f : α →ₛ β} (hf : integrable f) : f.fin_vol_supp := begin rw [integrable_iff_integral_lt_top] at hf, have hf := fin_vol_supp_of_integral_lt_top hf, refine fin_vol_supp_of_fin_vol_supp_map f hf _, assume b, simp [nnnorm_eq_zero] end lemma integrable_of_fin_vol_supp {f : α →ₛ β} (h : f.fin_vol_supp) : integrable f := by { rw [integrable_iff_integral_lt_top], exact integral_map_coe_lt_top h nnnorm_zero } /-- For simple functions with a `normed_group` as codomain, being integrable is the same as having finite volume support. -/ lemma integrable_iff_fin_vol_supp (f : α →ₛ β) : integrable f ↔ f.fin_vol_supp := iff.intro fin_vol_supp_of_integrable integrable_of_fin_vol_supp lemma integrable_pair {f : α →ₛ β} {g : α →ₛ γ} (hf : integrable f) (hg : integrable g) : integrable (pair f g) := by { rw integrable_iff_fin_vol_supp at *, apply fin_vol_supp_pair; assumption } variables [normed_space ℝ γ] /-- Bochner integral of simple functions whose codomain is a real `normed_space`. The name `simple_func.integral` has been taken in the file `integration.lean`, which calculates the integral of a simple function with type `α → ennreal`. The name `bintegral` stands for Bochner integral. -/ def bintegral [normed_space ℝ β] (f : α →ₛ β) : β := ∑ x in f.range, (ennreal.to_real (volume (f ⁻¹' {x}))) • x /-- Calculate the integral of `g ∘ f : α →ₛ γ`, where `f` is an integrable function from `α` to `β` and `g` is a function from `β` to `γ`. We require `g 0 = 0` so that `g ∘ f` is integrable. -/ lemma map_bintegral (f : α →ₛ β) (g : β → γ) (hf : integrable f) (hg : g 0 = 0) : (f.map g).bintegral = ∑ x in f.range, (ennreal.to_real (volume (f ⁻¹' {x}))) • (g x) := begin /- Just a complicated calculation with `finset.sum`. Real work is done by `map_preimage_singleton`, `simple_func.volume_bUnion_preimage` and `ennreal.to_real_sum` -/ rw integrable_iff_fin_vol_supp at hf, simp only [bintegral, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, let s' := f.range.filter (λb, g b = g (f a)), calc (ennreal.to_real (volume ((f.map g) ⁻¹' {g (f a)}))) • (g (f a)) = (ennreal.to_real (volume (⋃b∈s', f ⁻¹' {b}))) • (g (f a)) : by rw map_preimage_singleton ... = (ennreal.to_real ∑ b in s', volume (f ⁻¹' {b})) • (g (f a)) : by rw volume_bUnion_preimage ... = (∑ b in s', ennreal.to_real (volume (f ⁻¹' {b}))) • (g (f a)) : begin by_cases h : g (f a) = 0, { rw [h, smul_zero, smul_zero] }, { rw ennreal.to_real_sum, simp only [mem_filter], rintros b ⟨_, hb⟩, have : b ≠ 0, { assume hb', rw [← hb, hb'] at h, contradiction }, apply hf, assumption } end ... = ∑ b in s', (ennreal.to_real (volume (f ⁻¹' {b}))) • (g (f a)) : finset.sum_smul ... = ∑ b in s', (ennreal.to_real (volume (f ⁻¹' {b}))) • (g b) : finset.sum_congr rfl $ by { assume x, simp only [mem_filter], rintro ⟨_, h⟩, rw h } end /-- `simple_func.bintegral` and `simple_func.integral` agree when the integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. See `bintegral_eq_integral'` for a simpler version. -/ lemma bintegral_eq_integral {f : α →ₛ β} {g : β → ennreal} (hf : integrable f) (hg0 : g 0 = 0) (hgt : ∀b, g b < ⊤): (f.map (ennreal.to_real ∘ g)).bintegral = ennreal.to_real (f.map g).integral := begin have hf' : f.fin_vol_supp, { rwa integrable_iff_fin_vol_supp at hf }, rw [map_bintegral f _ hf, map_integral, ennreal.to_real_sum], { refine finset.sum_congr rfl (λb hb, _), rw [smul_eq_mul], rw [to_real_mul_to_real, mul_comm] }, { assume a ha, by_cases a0 : a = 0, { rw [a0, hg0, zero_mul], exact with_top.zero_lt_top }, apply mul_lt_top (hgt a) (hf' _ a0) }, { simp [hg0] } end /-- `simple_func.bintegral` and `lintegral : (α → ennreal) → ennreal` are the same when the integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. See `bintegral_eq_lintegral'` for a simpler version. -/ lemma bintegral_eq_lintegral (f : α →ₛ β) (g : β → ennreal) (hf : integrable f) (hg0 : g 0 = 0) (hgt : ∀b, g b < ⊤): (f.map (ennreal.to_real ∘ g)).bintegral = ennreal.to_real (∫⁻ a, g (f a)) := by { rw [bintegral_eq_integral hf hg0 hgt, ← lintegral_eq_integral], refl } variables [normed_space ℝ β] lemma bintegral_congr {f g : α →ₛ β} (hf : integrable f) (hg : integrable g) (h : ∀ₘ a, f a = g a): bintegral f = bintegral g := show ((pair f g).map prod.fst).bintegral = ((pair f g).map prod.snd).bintegral, from begin have inte := integrable_pair hf hg, rw [map_bintegral (pair f g) _ inte prod.fst_zero, map_bintegral (pair f g) _ inte prod.snd_zero], refine finset.sum_congr rfl (assume p hp, _), rcases mem_range.1 hp with ⟨a, rfl⟩, by_cases eq : f a = g a, { dsimp only [pair_apply], rw eq }, { have : volume ((pair f g) ⁻¹' {(f a, g a)}) = 0, { refine measure_mono_null (assume a' ha', _) h, simp only [set.mem_preimage, mem_singleton_iff, pair_apply, prod.mk.inj_iff] at ha', show f a' ≠ g a', rwa [ha'.1, ha'.2] }, simp only [this, pair_apply, zero_smul, ennreal.zero_to_real] }, end /-- `simple_func.bintegral` and `simple_func.integral` agree when the integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. -/ lemma bintegral_eq_integral' {f : α →ₛ ℝ} (hf : integrable f) (h_pos : ∀ₘ a, 0 ≤ f a) : f.bintegral = ennreal.to_real (f.map ennreal.of_real).integral := begin have : ∀ₘ a, f a = (f.map (ennreal.to_real ∘ ennreal.of_real)) a, { filter_upwards [h_pos], assume a, simp only [mem_set_of_eq, map_apply, function.comp_apply], assume h, exact (ennreal.to_real_of_real h).symm }, rw ← bintegral_eq_integral hf, { refine bintegral_congr hf _ this, exact integrable_of_ae_eq hf this }, { exact ennreal.of_real_zero }, { assume b, rw ennreal.lt_top_iff_ne_top, exact ennreal.of_real_ne_top } end /-- `simple_func.bintegral` and `lintegral : (α → ennreal) → ennreal` agree when the integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. -/ lemma bintegral_eq_lintegral' {f : α →ₛ ℝ} (hf : integrable f) (h_pos : ∀ₘ a, 0 ≤ f a) : f.bintegral = ennreal.to_real (∫⁻ a, (f.map ennreal.of_real a)) := by rw [bintegral_eq_integral' hf h_pos, ← lintegral_eq_integral] lemma bintegral_add {f g : α →ₛ β} (hf : integrable f) (hg : integrable g) : bintegral (f + g) = bintegral f + bintegral g := calc bintegral (f + g) = ∑ x in (pair f g).range, ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • (x.fst + x.snd) : begin rw [add_eq_map₂, map_bintegral (pair f g)], { exact integrable_pair hf hg }, { simp only [add_zero, prod.fst_zero, prod.snd_zero] } end ... = ∑ x in (pair f g).range, (ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • x.fst + ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • x.snd) : finset.sum_congr rfl $ assume a ha, smul_add _ _ _ ... = ∑ x in (pair f g).range, ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • x.fst + ∑ x in (pair f g).range, ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • x.snd : by rw finset.sum_add_distrib ... = ((pair f g).map prod.fst).bintegral + ((pair f g).map prod.snd).bintegral : begin rw [map_bintegral (pair f g), map_bintegral (pair f g)], { exact integrable_pair hf hg }, { refl }, { exact integrable_pair hf hg }, { refl } end ... = bintegral f + bintegral g : rfl lemma bintegral_neg {f : α →ₛ β} (hf : integrable f) : bintegral (-f) = - bintegral f := calc bintegral (-f) = bintegral (f.map (has_neg.neg)) : rfl ... = - bintegral f : begin rw [map_bintegral f _ hf neg_zero, bintegral, ← sum_neg_distrib], refine finset.sum_congr rfl (λx h, smul_neg _ _), end lemma bintegral_sub {f g : α →ₛ β} (hf : integrable f) (hg : integrable g) : bintegral (f - g) = bintegral f - bintegral g := begin have : f - g = f + (-g) := rfl, rw [this, bintegral_add hf _, bintegral_neg hg], { refl }, exact hg.neg end lemma bintegral_smul (r : ℝ) {f : α →ₛ β} (hf : integrable f) : bintegral (r • f) = r • bintegral f := calc bintegral (r • f) = ∑ x in f.range, ennreal.to_real (volume (f ⁻¹' {x})) • r • x : by rw [smul_eq_map r f, map_bintegral f _ hf (smul_zero _)] ... = ∑ x in f.range, ((ennreal.to_real (volume (f ⁻¹' {x}))) * r) • x : finset.sum_congr rfl $ λb hb, by apply smul_smul ... = r • bintegral f : begin rw [bintegral, smul_sum], refine finset.sum_congr rfl (λb hb, _), rw [smul_smul, mul_comm] end lemma norm_bintegral_le_bintegral_norm (f : α →ₛ β) (hf : integrable f) : ∥f.bintegral∥ ≤ (f.map norm).bintegral := begin rw map_bintegral f norm hf norm_zero, rw bintegral, calc ∥∑ x in f.range, ennreal.to_real (volume (f ⁻¹' {x})) • x∥ ≤ ∑ x in f.range, ∥ennreal.to_real (volume (f ⁻¹' {x})) • x∥ : norm_sum_le _ _ ... = ∑ x in f.range, ennreal.to_real (volume (f ⁻¹' {x})) • ∥x∥ : begin refine finset.sum_congr rfl (λb hb, _), rw [norm_smul, smul_eq_mul, real.norm_eq_abs, abs_of_nonneg to_real_nonneg] end end end bintegral end simple_func namespace l1 open ae_eq_fun variables [normed_group β] [second_countable_topology β] [measurable_space β] [borel_space β] [normed_group γ] [second_countable_topology γ] [measurable_space γ] [borel_space γ] variables (α β) /-- `l1.simple_func` is a subspace of L1 consisting of equivalence classes of an integrable simple function. -/ def simple_func : Type (max u v) := { f : α →₁ β // ∃ (s : α →ₛ β), integrable s ∧ ae_eq_fun.mk s s.measurable = f} -- TODO: it seems that `ae_eq_fun.mk s s.measurable = f` implies `integrable s` variables {α β} infixr ` →₁ₛ `:25 := measure_theory.l1.simple_func namespace simple_func section instances /-! Simple functions in L1 space form a `normed_space`. -/ instance : has_coe (α →₁ₛ β) (α →₁ β) := ⟨subtype.val⟩ protected lemma eq {f g : α →₁ₛ β} : (f : α →₁ β) = (g : α →₁ β) → f = g := subtype.eq protected lemma eq' {f g : α →₁ₛ β} : (f : α →ₘ β) = (g : α →ₘ β) → f = g := subtype.eq ∘ subtype.eq @[norm_cast] protected lemma eq_iff {f g : α →₁ₛ β} : (f : α →₁ β) = (g : α →₁ β) ↔ f = g := iff.intro (subtype.eq) (congr_arg coe) @[norm_cast] protected lemma eq_iff' {f g : α →₁ₛ β} : (f : α →ₘ β) = (g : α →ₘ β) ↔ f = g := iff.intro (simple_func.eq') (congr_arg _) /-- L1 simple functions forms a `emetric_space`, with the emetric being inherited from L1 space, i.e., `edist f g = ∫⁻ a, edist (f a) (g a)`. Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def emetric_space : emetric_space (α →₁ₛ β) := subtype.emetric_space /-- L1 simple functions forms a `metric_space`, with the metric being inherited from L1 space, i.e., `dist f g = ennreal.to_real (∫⁻ a, edist (f a) (g a)`). Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def metric_space : metric_space (α →₁ₛ β) := subtype.metric_space local attribute [instance] protected lemma is_add_subgroup : is_add_subgroup (λf:α →₁ β, ∃ (s : α →ₛ β), integrable s ∧ ae_eq_fun.mk s s.measurable = f) := { zero_mem := ⟨0, integrable_zero _ _, rfl⟩, add_mem := begin rintros f g ⟨s, hsi, hs⟩ ⟨t, hti, ht⟩, use s + t, split, { exact hsi.add s.measurable t.measurable hti }, { rw [coe_add, ← hs, ← ht], refl } end, neg_mem := begin rintros f ⟨s, hsi, hs⟩, use -s, split, { exact hsi.neg }, { rw [coe_neg, ← hs], refl } end } /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def add_comm_group : add_comm_group (α →₁ₛ β) := subtype.add_comm_group local attribute [instance] simple_func.add_comm_group simple_func.metric_space simple_func.emetric_space instance : inhabited (α →₁ₛ β) := ⟨0⟩ @[simp, norm_cast] lemma coe_zero : ((0 : α →₁ₛ β) : α →₁ β) = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : α →₁ₛ β) : ((f + g : α →₁ₛ β) : α →₁ β) = f + g := rfl @[simp, norm_cast] lemma coe_neg (f : α →₁ₛ β) : ((-f : α →₁ₛ β) : α →₁ β) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : α →₁ₛ β) : ((f - g : α →₁ₛ β) : α →₁ β) = f - g := rfl @[simp] lemma edist_eq (f g : α →₁ₛ β) : edist f g = edist (f : α →₁ β) (g : α →₁ β) := rfl @[simp] lemma dist_eq (f g : α →₁ₛ β) : dist f g = dist (f : α →₁ β) (g : α →₁ β) := rfl /-- The norm on `α →₁ₛ β` is inherited from L1 space. That is, `∥f∥ = ∫⁻ a, edist (f a) 0`. Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def has_norm : has_norm (α →₁ₛ β) := ⟨λf, ∥(f : α →₁ β)∥⟩ local attribute [instance] simple_func.has_norm lemma norm_eq (f : α →₁ₛ β) : ∥f∥ = ∥(f : α →₁ β)∥ := rfl lemma norm_eq' (f : α →₁ₛ β) : ∥f∥ = ennreal.to_real (edist (f : α →ₘ β) 0) := rfl /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def normed_group : normed_group (α →₁ₛ β) := normed_group.of_add_dist (λ x, rfl) $ by { intros, simp only [dist_eq, coe_add, l1.dist_eq, l1.coe_add], rw edist_eq_add_add } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def has_scalar : has_scalar 𝕜 (α →₁ₛ β) := ⟨λk f, ⟨k • f, begin rcases f with ⟨f, ⟨s, hsi, hs⟩⟩, use k • s, split, { exact integrable.smul _ hsi }, { rw [coe_smul, subtype.coe_mk, ← hs], refl } end ⟩⟩ local attribute [instance, priority 10000] simple_func.has_scalar @[simp, norm_cast] lemma coe_smul (c : 𝕜) (f : α →₁ₛ β) : ((c • f : α →₁ₛ β) : α →₁ β) = c • (f : α →₁ β) := rfl /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def semimodule : semimodule 𝕜 (α →₁ₛ β) := { one_smul := λf, simple_func.eq (by { simp only [coe_smul], exact one_smul _ _ }), mul_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact mul_smul _ _ _ }), smul_add := λx f g, simple_func.eq (by { simp only [coe_smul, coe_add], exact smul_add _ _ _ }), smul_zero := λx, simple_func.eq (by { simp only [coe_zero, coe_smul], exact smul_zero _ }), add_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact add_smul _ _ _ }), zero_smul := λf, simple_func.eq (by { simp only [coe_smul], exact zero_smul _ _ }) } local attribute [instance] simple_func.normed_group simple_func.semimodule /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def normed_space : normed_space 𝕜 (α →₁ₛ β) := ⟨ λc f, by { rw [norm_eq, norm_eq, coe_smul, norm_smul] } ⟩ end instances local attribute [instance] simple_func.normed_group simple_func.normed_space section of_simple_func /-- Construct the equivalence class `[f]` of an integrable simple function `f`. -/ @[reducible] def of_simple_func (f : α →ₛ β) (hf : integrable f) : (α →₁ₛ β) := ⟨l1.of_fun f f.measurable hf, ⟨f, ⟨hf, rfl⟩⟩⟩ lemma of_simple_func_eq_of_fun (f : α →ₛ β) (hf : integrable f) : (of_simple_func f hf : α →₁ β) = l1.of_fun f f.measurable hf := rfl lemma of_simple_func_eq_mk (f : α →ₛ β) (hf : integrable f) : (of_simple_func f hf : α →ₘ β) = ae_eq_fun.mk f f.measurable := rfl lemma of_simple_func_zero : of_simple_func (0 : α →ₛ β) (integrable_zero α β) = 0 := rfl lemma of_simple_func_add (f g : α →ₛ β) (hf hg) : of_simple_func (f + g) (integrable.add f.measurable hf g.measurable hg) = of_simple_func f hf + of_simple_func g hg := rfl lemma of_simple_func_neg (f : α →ₛ β) (hf) : of_simple_func (-f) (integrable.neg hf) = -of_simple_func f hf := rfl lemma of_simple_func_sub (f g : α →ₛ β) (hf hg) : of_simple_func (f - g) (integrable.sub f.measurable hf g.measurable hg) = of_simple_func f hf - of_simple_func g hg := rfl variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma of_simple_func_smul (f : α →ₛ β) (hf) (c : 𝕜) : of_simple_func (c • f) (integrable.smul _ hf) = c • of_simple_func f hf := rfl lemma norm_of_simple_func (f : α →ₛ β) (hf) : ∥of_simple_func f hf∥ = ennreal.to_real (∫⁻ a, edist (f a) 0) := rfl end of_simple_func section to_simple_func /-- Find a representative of a `l1.simple_func`. -/ def to_simple_func (f : α →₁ₛ β) : α →ₛ β := classical.some f.2 /-- `f.to_simple_func` is measurable. -/ protected lemma measurable (f : α →₁ₛ β) : measurable f.to_simple_func := f.to_simple_func.measurable /-- `f.to_simple_func` is integrable. -/ protected lemma integrable (f : α →₁ₛ β) : integrable f.to_simple_func := let ⟨h, _⟩ := classical.some_spec f.2 in h lemma of_simple_func_to_simple_func (f : α →₁ₛ β) : of_simple_func (f.to_simple_func) f.integrable = f := by { rw ← simple_func.eq_iff', exact (classical.some_spec f.2).2 } lemma to_simple_func_of_simple_func (f : α →ₛ β) (hfi) : ∀ₘ a, (of_simple_func f hfi).to_simple_func a = f a := by { rw ← mk_eq_mk, exact (classical.some_spec (of_simple_func f hfi).2).2 } lemma to_simple_func_eq_to_fun (f : α →₁ₛ β) : ∀ₘ a, (f.to_simple_func) a = (f : α →₁ β).to_fun a := begin rw [← of_fun_eq_of_fun (f.to_simple_func) (f : α →₁ β).to_fun f.measurable f.integrable (f:α→₁β).measurable (f:α→₁β).integrable, ← l1.eq_iff], simp only [of_fun_eq_mk], rcases classical.some_spec f.2 with ⟨_, h⟩, convert h, rw mk_to_fun, refl end variables (α β) lemma zero_to_simple_func : ∀ₘ a, (0 : α →₁ₛ β).to_simple_func a = 0 := begin filter_upwards [to_simple_func_eq_to_fun (0 : α →₁ₛ β), l1.zero_to_fun α β], assume a, simp only [mem_set_of_eq], assume h, rw h, assume h, exact h end variables {α β} lemma add_to_simple_func (f g : α →₁ₛ β) : ∀ₘ a, (f + g).to_simple_func a = f.to_simple_func a + g.to_simple_func a := begin filter_upwards [to_simple_func_eq_to_fun (f + g), to_simple_func_eq_to_fun f, to_simple_func_eq_to_fun g, l1.add_to_fun (f:α→₁β) g], assume a, simp only [mem_set_of_eq], repeat { assume h, rw h }, assume h, rw ← h, refl end lemma neg_to_simple_func (f : α →₁ₛ β) : ∀ₘ a, (-f).to_simple_func a = - f.to_simple_func a := begin filter_upwards [to_simple_func_eq_to_fun (-f), to_simple_func_eq_to_fun f, l1.neg_to_fun (f:α→₁β)], assume a, simp only [mem_set_of_eq], repeat { assume h, rw h }, assume h, rw ← h, refl end lemma sub_to_simple_func (f g : α →₁ₛ β) : ∀ₘ a, (f - g).to_simple_func a = f.to_simple_func a - g.to_simple_func a := begin filter_upwards [to_simple_func_eq_to_fun (f - g), to_simple_func_eq_to_fun f, to_simple_func_eq_to_fun g, l1.sub_to_fun (f:α→₁β) g], assume a, simp only [mem_set_of_eq], repeat { assume h, rw h }, assume h, rw ← h, refl end variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma smul_to_simple_func (k : 𝕜) (f : α →₁ₛ β) : ∀ₘ a, (k • f).to_simple_func a = k • f.to_simple_func a := begin filter_upwards [to_simple_func_eq_to_fun (k • f), to_simple_func_eq_to_fun f, l1.smul_to_fun k (f:α→₁β)], assume a, simp only [mem_set_of_eq], repeat { assume h, rw h }, assume h, rw ← h, refl end lemma lintegral_edist_to_simple_func_lt_top (f g : α →₁ₛ β) : (∫⁻ (x : α), edist ((to_simple_func f) x) ((to_simple_func g) x)) < ⊤ := begin rw lintegral_rw₂ (to_simple_func_eq_to_fun f) (to_simple_func_eq_to_fun g), exact lintegral_edist_to_fun_lt_top _ _ end lemma dist_to_simple_func (f g : α →₁ₛ β) : dist f g = ennreal.to_real (∫⁻ x, edist (f.to_simple_func x) (g.to_simple_func x)) := begin rw [dist_eq, l1.dist_to_fun, ennreal.to_real_eq_to_real], { rw lintegral_rw₂, repeat { exact ae_eq_symm (to_simple_func_eq_to_fun _) } }, { exact l1.lintegral_edist_to_fun_lt_top _ _ }, { exact lintegral_edist_to_simple_func_lt_top _ _ } end lemma norm_to_simple_func (f : α →₁ₛ β) : ∥f∥ = ennreal.to_real (∫⁻ (a : α), nnnorm ((to_simple_func f) a)) := calc ∥f∥ = ennreal.to_real (∫⁻x, edist (f.to_simple_func x) ((0 : α →₁ₛ β).to_simple_func x)) : begin rw [← dist_zero_right, dist_to_simple_func] end ... = ennreal.to_real (∫⁻ (x : α), (coe ∘ nnnorm) (f.to_simple_func x)) : begin rw lintegral_nnnorm_eq_lintegral_edist, have : (∫⁻ (x : α), edist ((to_simple_func f) x) ((to_simple_func (0:α→₁ₛβ)) x)) = ∫⁻ (x : α), edist ((to_simple_func f) x) 0, { apply lintegral_congr_ae, filter_upwards [zero_to_simple_func α β], assume a, simp only [mem_set_of_eq], assume h, rw h }, rw [ennreal.to_real_eq_to_real], { exact this }, { exact lintegral_edist_to_simple_func_lt_top _ _ }, { rw ← this, exact lintegral_edist_to_simple_func_lt_top _ _ } end lemma norm_eq_bintegral (f : α →₁ₛ β) : ∥f∥ = (f.to_simple_func.map norm).bintegral := calc ∥f∥ = ennreal.to_real (∫⁻ (x : α), (coe ∘ nnnorm) (f.to_simple_func x)) : by { rw norm_to_simple_func } ... = (f.to_simple_func.map norm).bintegral : begin rw ← f.to_simple_func.bintegral_eq_lintegral (coe ∘ nnnorm) f.integrable, { congr }, { simp only [nnnorm_zero, function.comp_app, ennreal.coe_zero] }, { assume b, exact coe_lt_top } end end to_simple_func section coe_to_l1 /-! The embedding of integrable simple functions `α →₁ₛ β` into L1 is a uniform and dense embedding. -/ lemma exists_simple_func_near (f : α →₁ β) {ε : ℝ} (ε0 : 0 < ε) : ∃ s : α →₁ₛ β, dist f s < ε := begin rcases f with ⟨⟨f, hfm⟩, hfi⟩, simp only [integrable_mk, quot_mk_eq_mk] at hfi, rcases simple_func_sequence_tendsto' hfm hfi with ⟨F, ⟨h₁, h₂⟩⟩, rw ennreal.tendsto_at_top at h₂, rcases h₂ (ennreal.of_real (ε/2)) (of_real_pos.2 $ half_pos ε0) with ⟨N, hN⟩, have : (∫⁻ (x : α), nndist (F N x) (f x)) < ennreal.of_real ε := calc (∫⁻ (x : α), nndist (F N x) (f x)) ≤ 0 + ennreal.of_real (ε/2) : (hN N (le_refl _)).2 ... < ennreal.of_real ε : by { simp only [zero_add, of_real_lt_of_real_iff ε0], exact half_lt_self ε0 }, { refine ⟨of_simple_func (F N) (h₁ N), _⟩, rw dist_comm, rw lt_of_real_iff_to_real_lt _ at this, { simpa [edist_mk_mk', of_simple_func, l1.of_fun, l1.dist_eq] }, rw ← lt_top_iff_ne_top, exact lt_trans this (by simp [lt_top_iff_ne_top, of_real_ne_top]) }, { exact zero_ne_top } end protected lemma uniform_continuous : uniform_continuous (coe : (α →₁ₛ β) → (α →₁ β)) := uniform_continuous_comap protected lemma uniform_embedding : uniform_embedding (coe : (α →₁ₛ β) → (α →₁ β)) := uniform_embedding_comap subtype.val_injective protected lemma uniform_inducing : uniform_inducing (coe : (α →₁ₛ β) → (α →₁ β)) := simple_func.uniform_embedding.to_uniform_inducing protected lemma dense_embedding : dense_embedding (coe : (α →₁ₛ β) → (α →₁ β)) := simple_func.uniform_embedding.dense_embedding $ λ f, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨s, h⟩ := exists_simple_func_near f ε0 in ⟨_, hε (metric.mem_ball'.2 h), s, rfl⟩ protected lemma dense_inducing : dense_inducing (coe : (α →₁ₛ β) → (α →₁ β)) := simple_func.dense_embedding.to_dense_inducing protected lemma dense_range : dense_range (coe : (α →₁ₛ β) → (α →₁ β)) := simple_func.dense_inducing.dense variables (𝕜 : Type*) [normed_field 𝕜] [normed_space 𝕜 β] variables (α β) /-- The uniform and dense embedding of L1 simple functions into L1 functions. -/ def coe_to_l1 : (α →₁ₛ β) →L[𝕜] (α →₁ β) := { to_fun := (coe : (α →₁ₛ β) → (α →₁ β)), map_add' := λf g, rfl, map_smul' := λk f, rfl, cont := l1.simple_func.uniform_continuous.continuous, } variables {α β 𝕜} end coe_to_l1 section pos_part /-- Positive part of a simple function in L1 space. -/ def pos_part (f : α →₁ₛ ℝ) : α →₁ₛ ℝ := ⟨l1.pos_part (f : α →₁ ℝ), begin rcases f with ⟨f, s, hsi, hsf⟩, use s.pos_part, split, { exact integrable.max_zero hsi }, { simp only [subtype.coe_mk], rw [l1.coe_pos_part, ← hsf, ae_eq_fun.pos_part, ae_eq_fun.zero_def, comp₂_mk_mk, mk_eq_mk], filter_upwards [], simp only [mem_set_of_eq], assume a, refl } end ⟩ /-- Negative part of a simple function in L1 space. -/ def neg_part (f : α →₁ₛ ℝ) : α →₁ₛ ℝ := pos_part (-f) @[norm_cast] lemma coe_pos_part (f : α →₁ₛ ℝ) : (f.pos_part : α →₁ ℝ) = (f : α →₁ ℝ).pos_part := rfl @[norm_cast] lemma coe_neg_part (f : α →₁ₛ ℝ) : (f.neg_part : α →₁ ℝ) = (f : α →₁ ℝ).neg_part := rfl end pos_part section simple_func_integral /-! Define the Bochner integral on `α →₁ₛ β` and prove basic properties of this integral. -/ variables [normed_space ℝ β] /-- The Bochner integral over simple functions in l1 space. -/ def integral (f : α →₁ₛ β) : β := (f.to_simple_func).bintegral lemma integral_eq_bintegral (f : α →₁ₛ β) : integral f = (f.to_simple_func).bintegral := rfl lemma integral_eq_lintegral {f : α →₁ₛ ℝ} (h_pos : ∀ₘ a, 0 ≤ f.to_simple_func a) : integral f = ennreal.to_real (∫⁻ a, ennreal.of_real (f.to_simple_func a)) := by { rw [integral, simple_func.bintegral_eq_lintegral' f.integrable h_pos], refl } lemma integral_congr (f g : α →₁ₛ β) (h : ∀ₘ a, f.to_simple_func a = g.to_simple_func a) : integral f = integral g := by { simp only [integral], apply simple_func.bintegral_congr f.integrable g.integrable, exact h } lemma integral_add (f g : α →₁ₛ β) : integral (f + g) = integral f + integral g := begin simp only [integral], rw ← simple_func.bintegral_add f.integrable g.integrable, apply simple_func.bintegral_congr (f + g).integrable, { exact f.integrable.add f.measurable g.measurable g.integrable }, { apply add_to_simple_func }, end lemma integral_smul (r : ℝ) (f : α →₁ₛ β) : integral (r • f) = r • integral f := begin simp only [integral], rw ← simple_func.bintegral_smul _ f.integrable, apply simple_func.bintegral_congr (r • f).integrable, { exact integrable.smul _ f.integrable }, { apply smul_to_simple_func } end lemma norm_integral_le_norm (f : α →₁ₛ β) : ∥ integral f ∥ ≤ ∥f∥ := begin rw [integral, norm_eq_bintegral], exact f.to_simple_func.norm_bintegral_le_bintegral_norm f.integrable end /-- The Bochner integral over simple functions in l1 space as a continuous linear map. -/ def integral_clm : (α →₁ₛ β) →L[ℝ] β := linear_map.mk_continuous ⟨integral, integral_add, integral_smul⟩ 1 (λf, le_trans (norm_integral_le_norm _) $ by rw one_mul) local notation `Integral` := @integral_clm α _ β _ _ _ _ _ open continuous_linear_map lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 := linear_map.mk_continuous_norm_le _ (zero_le_one) _ section pos_part lemma pos_part_to_simple_func (f : α →₁ₛ ℝ) : ∀ₘ a, f.pos_part.to_simple_func a = f.to_simple_func.pos_part a := begin have eq : ∀ a, f.to_simple_func.pos_part a = max (f.to_simple_func a) 0 := λa, rfl, have ae_eq : ∀ₘ a, f.pos_part.to_simple_func a = max (f.to_simple_func a) 0, { filter_upwards [to_simple_func_eq_to_fun f.pos_part, pos_part_to_fun (f : α →₁ ℝ), to_simple_func_eq_to_fun f], simp only [mem_set_of_eq], assume a h₁ h₂ h₃, rw [h₁, coe_pos_part, h₂, ← h₃] }, filter_upwards [ae_eq], simp only [mem_set_of_eq], assume a h, rw [h, eq] end lemma neg_part_to_simple_func (f : α →₁ₛ ℝ) : ∀ₘ a, f.neg_part.to_simple_func a = f.to_simple_func.neg_part a := begin rw [simple_func.neg_part, measure_theory.simple_func.neg_part], filter_upwards [pos_part_to_simple_func (-f), neg_to_simple_func f], simp only [mem_set_of_eq], assume a h₁ h₂, rw h₁, show max _ _ = max _ _, rw h₂, refl end lemma integral_eq_norm_pos_part_sub (f : α →₁ₛ ℝ) : f.integral = ∥f.pos_part∥ - ∥f.neg_part∥ := begin -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq₁ : ∀ₘ a, f.to_simple_func.pos_part a = (f.pos_part).to_simple_func.map norm a, { filter_upwards [pos_part_to_simple_func f], simp only [mem_set_of_eq], assume a h, rw [simple_func.map_apply, h], conv_lhs { rw [← simple_func.pos_part_map_norm, simple_func.map_apply] } }, -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq₂ : ∀ₘ a, f.to_simple_func.neg_part a = (f.neg_part).to_simple_func.map norm a, { filter_upwards [neg_part_to_simple_func f], simp only [mem_set_of_eq], assume a h, rw [simple_func.map_apply, h], conv_lhs { rw [← simple_func.neg_part_map_norm, simple_func.map_apply] } }, -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq : ∀ₘ a, f.to_simple_func.pos_part a - f.to_simple_func.neg_part a = (f.pos_part).to_simple_func.map norm a - (f.neg_part).to_simple_func.map norm a, { filter_upwards [ae_eq₁, ae_eq₂], simp only [mem_set_of_eq], assume a h₁ h₂, rw [h₁, h₂] }, rw [integral, norm_eq_bintegral, norm_eq_bintegral, ← simple_func.bintegral_sub], { show f.to_simple_func.bintegral = ((f.pos_part.to_simple_func).map norm - f.neg_part.to_simple_func.map norm).bintegral, apply simple_func.bintegral_congr f.integrable, { show integrable (f.pos_part.to_simple_func.map norm - f.neg_part.to_simple_func.map norm), refine integrable_of_ae_eq _ _, { exact (f.to_simple_func.pos_part - f.to_simple_func.neg_part) }, { exact (integrable.max_zero f.integrable).sub f.to_simple_func.pos_part.measurable f.to_simple_func.neg_part.measurable (integrable.max_zero f.integrable.neg) }, exact ae_eq }, filter_upwards [ae_eq₁, ae_eq₂], simp only [mem_set_of_eq], assume a h₁ h₂, show _ = _ - _, rw [← h₁, ← h₂], have := f.to_simple_func.pos_part_sub_neg_part, conv_lhs {rw ← this}, refl }, { refine integrable_of_ae_eq (integrable.max_zero f.integrable) ae_eq₁ }, { refine integrable_of_ae_eq (integrable.max_zero f.integrable.neg) ae_eq₂ } end end pos_part end simple_func_integral end simple_func open simple_func variables [normed_space ℝ β] [normed_space ℝ γ] [complete_space β] section integration_in_l1 local notation `to_l1` := coe_to_l1 α β ℝ local attribute [instance] simple_func.normed_group simple_func.normed_space open continuous_linear_map /-- The Bochner integral in l1 space as a continuous linear map. -/ def integral_clm : (α →₁ β) →L[ℝ] β := integral_clm.extend to_l1 simple_func.dense_range simple_func.uniform_inducing /-- The Bochner integral in l1 space -/ def integral (f : α →₁ β) : β := (integral_clm).to_fun f lemma integral_eq (f : α →₁ β) : integral f = (integral_clm).to_fun f := rfl @[norm_cast] lemma simple_func.integral_eq_integral (f : α →₁ₛ β) : integral (f : α →₁ β) = f.integral := uniformly_extend_of_ind simple_func.uniform_inducing simple_func.dense_range simple_func.integral_clm.uniform_continuous _ variables (α β) @[simp] lemma integral_zero : integral (0 : α →₁ β) = 0 := map_zero integral_clm variables {α β} lemma integral_add (f g : α →₁ β) : integral (f + g) = integral f + integral g := map_add integral_clm f g lemma integral_neg (f : α →₁ β) : integral (-f) = - integral f := map_neg integral_clm f lemma integral_sub (f g : α →₁ β) : integral (f - g) = integral f - integral g := map_sub integral_clm f g lemma integral_smul (r : ℝ) (f : α →₁ β) : integral (r • f) = r • integral f := map_smul r integral_clm f local notation `Integral` := @integral_clm α _ β _ _ _ _ _ _ local notation `sIntegral` := @simple_func.integral_clm α _ β _ _ _ _ _ lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 := calc ∥Integral∥ ≤ (1 : nnreal) * ∥sIntegral∥ : op_norm_extend_le _ _ _ $ λs, by {rw [nnreal.coe_one, one_mul], refl} ... = ∥sIntegral∥ : one_mul _ ... ≤ 1 : norm_Integral_le_one lemma norm_integral_le (f : α →₁ β) : ∥integral f∥ ≤ ∥f∥ := calc ∥integral f∥ = ∥Integral f∥ : rfl ... ≤ ∥Integral∥ * ∥f∥ : le_op_norm _ _ ... ≤ 1 * ∥f∥ : mul_le_mul_of_nonneg_right norm_Integral_le_one $ norm_nonneg _ ... = ∥f∥ : one_mul _ section pos_part lemma integral_eq_norm_pos_part_sub (f : α →₁ ℝ) : integral f = ∥pos_part f∥ - ∥neg_part f∥ := begin -- Use `is_closed_property` and `is_closed_eq` refine @is_closed_property _ _ _ (coe : (α →₁ₛ ℝ) → (α →₁ ℝ)) (λ f : α →₁ ℝ, integral f = ∥pos_part f∥ - ∥neg_part f∥) l1.simple_func.dense_range (is_closed_eq _ _) _ f, { exact cont _ }, { refine continuous.sub (continuous_norm.comp l1.continuous_pos_part) (continuous_norm.comp l1.continuous_neg_part) }, -- Show that the property holds for all simple functions in the `L¹` space. { assume s, norm_cast, rw [← simple_func.norm_eq, ← simple_func.norm_eq], exact simple_func.integral_eq_norm_pos_part_sub _} end end pos_part end integration_in_l1 end l1 variables [normed_group β] [second_countable_topology β] [normed_space ℝ β] [complete_space β] [measurable_space β] [borel_space β] [normed_group γ] [second_countable_topology γ] [normed_space ℝ γ] [complete_space γ] [measurable_space γ] [borel_space γ] /-- The Bochner integral -/ def integral (f : α → β) : β := if hf : measurable f ∧ integrable f then (l1.of_fun f hf.1 hf.2).integral else 0 notation `∫` binders `, ` r:(scoped f, integral f) := r section properties open continuous_linear_map measure_theory.simple_func variables {f g : α → β} lemma integral_eq (f : α → β) (h₁ : measurable f) (h₂ : integrable f) : (∫ a, f a) = (l1.of_fun f h₁ h₂).integral := dif_pos ⟨h₁, h₂⟩ lemma integral_undef (h : ¬ (measurable f ∧ integrable f)) : (∫ a, f a) = 0 := dif_neg h lemma integral_non_integrable (h : ¬ integrable f) : (∫ a, f a) = 0 := integral_undef $ not_and_of_not_right _ h lemma integral_non_measurable (h : ¬ measurable f) : (∫ a, f a) = 0 := integral_undef $ not_and_of_not_left _ h variables (α β) @[simp] lemma integral_zero : (∫ a : α, (0:β)) = 0 := by rw [integral_eq, l1.of_fun_zero, l1.integral_zero] variables {α β} lemma integral_add (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) : (∫ a, f a + g a) = (∫ a, f a) + (∫ a, g a) := by rw [integral_eq, integral_eq f hfm hfi, integral_eq g hgm hgi, l1.of_fun_add, l1.integral_add] lemma integral_neg (f : α → β) : (∫ a, -f a) = - (∫ a, f a) := begin by_cases hf : measurable f ∧ integrable f, { rw [integral_eq f hf.1 hf.2, integral_eq (λa, - f a) hf.1.neg hf.2.neg, l1.of_fun_neg, l1.integral_neg] }, { have hf' : ¬(measurable (λa, -f a) ∧ integrable (λa, -f a)), { rwa [measurable_neg_iff, integrable_neg_iff] }, rw [integral_undef hf, integral_undef hf', neg_zero] } end lemma integral_sub (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) : (∫ a, f a - g a) = (∫ a, f a) - (∫ a, g a) := by { rw [sub_eq_add_neg, ← integral_neg], exact integral_add hfm hfi hgm.neg hgi.neg } lemma integral_smul (r : ℝ) (f : α → β) : (∫ a, r • (f a)) = r • (∫ a, f a) := begin by_cases hf : measurable f ∧ integrable f, { rw [integral_eq f hf.1 hf.2, integral_eq (λa, r • (f a)), l1.of_fun_smul, l1.integral_smul] }, { by_cases hr : r = 0, { simp only [hr, measure_theory.integral_zero, zero_smul] }, have hf' : ¬(measurable (λa, r • f a) ∧ integrable (λa, r • f a)), { rwa [measurable_const_smul_iff hr, integrable_smul_iff hr f]; apply_instance }, rw [integral_undef hf, integral_undef hf', smul_zero] } end lemma integral_mul_left (r : ℝ) (f : α → ℝ) : (∫ a, r * (f a)) = r * (∫ a, f a) := integral_smul r f lemma integral_mul_right (r : ℝ) (f : α → ℝ) : (∫ a, (f a) * r) = (∫ a, f a) * r := by { simp only [mul_comm], exact integral_mul_left r f } lemma integral_div (r : ℝ) (f : α → ℝ) : (∫ a, (f a) / r) = (∫ a, f a) / r := integral_mul_right r⁻¹ f lemma integral_congr_ae (hfm : measurable f) (hgm : measurable g) (h : ∀ₘ a, f a = g a) : (∫ a, f a) = (∫ a, g a) := begin by_cases hfi : integrable f, { have hgi : integrable g := integrable_of_ae_eq hfi h, rw [integral_eq f hfm hfi, integral_eq g hgm hgi, (l1.of_fun_eq_of_fun f g hfm hfi hgm hgi).2 h] }, { have hgi : ¬ integrable g, { rw integrable_congr_ae h at hfi, exact hfi }, rw [integral_non_integrable hfi, integral_non_integrable hgi] }, end lemma norm_integral_le_lintegral_norm (f : α → β) : ∥(∫ a, f a)∥ ≤ ennreal.to_real (∫⁻ a, ennreal.of_real ∥f a∥) := begin by_cases hf : measurable f ∧ integrable f, { rw [integral_eq f hf.1 hf.2, ← l1.norm_of_fun_eq_lintegral_norm f hf.1 hf.2], exact l1.norm_integral_le _ }, { rw [integral_undef hf, _root_.norm_zero], exact to_real_nonneg } end /-- Lebesgue dominated convergence theorem provides sufficient conditions under which almost everywhere convergence of a sequence of functions implies the convergence of their integrals. -/ theorem tendsto_integral_of_dominated_convergence {F : ℕ → α → β} {f : α → β} (bound : α → ℝ) (F_measurable : ∀ n, measurable (F n)) (f_measurable : measurable f) (bound_integrable : integrable bound) (h_bound : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫ a, F n a) at_top (𝓝 $ (∫ a, f a)) := begin /- To show `(∫ a, F n a) --> (∫ f)`, suffices to show `∥∫ a, F n a - ∫ f∥ --> 0` -/ rw tendsto_iff_norm_tendsto_zero, /- But `0 ≤ ∥∫ a, F n a - ∫ f∥ = ∥∫ a, (F n a - f a) ∥ ≤ ∫ a, ∥F n a - f a∥, and thus we apply the sandwich theorem and prove that `∫ a, ∥F n a - f a∥ --> 0` -/ have lintegral_norm_tendsto_zero : tendsto (λn, ennreal.to_real $ ∫⁻ a, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0) := (tendsto_to_real (zero_ne_top)).comp (tendsto_lintegral_norm_of_dominated_convergence F_measurable f_measurable bound_integrable h_bound h_lim), -- Use the sandwich theorem refine squeeze_zero (λ n, norm_nonneg _) _ lintegral_norm_tendsto_zero, -- Show `∥∫ a, F n a - ∫ f∥ ≤ ∫ a, ∥F n a - f a∥` for all `n` { assume n, have h₁ : integrable (F n) := integrable_of_integrable_bound bound_integrable (h_bound _), have h₂ : integrable f := integrable_of_dominated_convergence bound_integrable h_bound h_lim, rw ← integral_sub (F_measurable _) h₁ f_measurable h₂, exact norm_integral_le_lintegral_norm _ } end /-- Lebesgue dominated convergence theorem for filters with a countable basis -/ lemma tendsto_integral_filter_of_dominated_convergence {ι} {l : filter ι} {F : ι → α → β} {f : α → β} (bound : α → ℝ) (hl_cb : l.is_countably_generated) (hF_meas : ∀ᶠ n in l, measurable (F n)) (f_measurable : measurable f) (h_bound : ∀ᶠ n in l, ∀ₘ a, ∥F n a∥ ≤ bound a) (bound_integrable : integrable bound) (h_lim : ∀ₘ a, tendsto (λ n, F n a) l (𝓝 (f a))) : tendsto (λn, ∫ a, F n a) l (𝓝 $ (∫ a, f a)) := begin rw hl_cb.tendsto_iff_seq_tendsto, { intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem_sets hF_meas h_bound, replace h := hxl _ h, rcases h with ⟨k, h⟩, rw ← tendsto_add_at_top_iff_nat k, refine tendsto_integral_of_dominated_convergence _ _ _ _ _ _, { exact bound }, { intro, refine (h _ _).1, exact nat.le_add_left _ _ }, { assumption }, { assumption }, { intro, refine (h _ _).2, exact nat.le_add_left _ _ }, { filter_upwards [h_lim], simp only [mem_set_of_eq], assume a h_lim, apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a), { assumption }, rw tendsto_add_at_top_iff_nat, assumption } }, end /-- The Bochner integral of a real-valued function `f : α → ℝ` is the difference between the integral of the positive part of `f` and the integral of the negative part of `f`. -/ lemma integral_eq_lintegral_max_sub_lintegral_min {f : α → ℝ} (hfm : measurable f) (hfi : integrable f) : (∫ a, f a) = ennreal.to_real (∫⁻ a, ennreal.of_real $ max (f a) 0) - ennreal.to_real (∫⁻ a, ennreal.of_real $ - min (f a) 0) := let f₁ : α →₁ ℝ := l1.of_fun f hfm hfi in -- Go to the `L¹` space have eq₁ : ennreal.to_real (∫⁻ a, ennreal.of_real $ max (f a) 0) = ∥l1.pos_part f₁∥ := begin rw l1.norm_eq_norm_to_fun, congr' 1, apply lintegral_congr_ae, filter_upwards [l1.pos_part_to_fun f₁, l1.to_fun_of_fun f hfm hfi], simp only [mem_set_of_eq], assume a h₁ h₂, rw [h₁, h₂, real.norm_eq_abs, abs_of_nonneg], exact le_max_right _ _ end, -- Go to the `L¹` space have eq₂ : ennreal.to_real (∫⁻ a, ennreal.of_real $ -min (f a) 0) = ∥l1.neg_part f₁∥ := begin rw l1.norm_eq_norm_to_fun, congr' 1, apply lintegral_congr_ae, filter_upwards [l1.neg_part_to_fun_eq_min f₁, l1.to_fun_of_fun f hfm hfi], simp only [mem_set_of_eq], assume a h₁ h₂, rw [h₁, h₂, real.norm_eq_abs, abs_of_nonneg], rw [min_eq_neg_max_neg_neg, _root_.neg_neg, neg_zero], exact le_max_right _ _ end, begin rw [eq₁, eq₂, integral, dif_pos], exact l1.integral_eq_norm_pos_part_sub _, { exact ⟨hfm, hfi⟩ } end lemma integral_eq_lintegral_of_nonneg_ae {f : α → ℝ} (hf : ∀ₘ a, 0 ≤ f a) (hfm : measurable f) : (∫ a, f a) = ennreal.to_real (∫⁻ a, ennreal.of_real $ f a) := begin by_cases hfi : integrable f, { rw integral_eq_lintegral_max_sub_lintegral_min hfm hfi, have h_min : (∫⁻ a, ennreal.of_real (-min (f a) 0)) = 0, { rw lintegral_eq_zero_iff, { filter_upwards [hf], simp only [mem_set_of_eq], assume a h, simp only [min_eq_right h, neg_zero, ennreal.of_real_zero] }, { refine measurable_of_real.comp ((measurable.neg measurable_id).comp $ measurable.min hfm measurable_const) } }, have h_max : (∫⁻ a, ennreal.of_real (max (f a) 0)) = (∫⁻ a, ennreal.of_real $ f a), { apply lintegral_congr_ae, filter_upwards [hf], simp only [mem_set_of_eq], assume a h, rw max_eq_left h }, rw [h_min, h_max, zero_to_real, _root_.sub_zero] }, { rw integral_non_integrable hfi, rw [integrable_iff_norm, lt_top_iff_ne_top, ne.def, not_not] at hfi, have : (∫⁻ (a : α), ennreal.of_real (f a)) = (∫⁻ a, ennreal.of_real ∥f a∥), { apply lintegral_congr_ae, filter_upwards [hf], simp only [mem_set_of_eq], assume a h, rw [real.norm_eq_abs, abs_of_nonneg h] }, rw [this, hfi], refl } end lemma integral_nonneg_of_ae {f : α → ℝ} (hf : ∀ₘ a, 0 ≤ f a) : 0 ≤ (∫ a, f a) := begin by_cases hfm : measurable f, { rw integral_eq_lintegral_of_nonneg_ae hf hfm, exact to_real_nonneg }, { rw integral_non_measurable hfm } end lemma integral_nonpos_of_nonpos_ae {f : α → ℝ} (hf : ∀ₘ a, f a ≤ 0) : (∫ a, f a) ≤ 0 := begin have hf : ∀ₘ a, 0 ≤ (-f) a, { filter_upwards [hf], simp only [mem_set_of_eq], assume a h, rwa [pi.neg_apply, neg_nonneg] }, have : 0 ≤ (∫ a, -f a) := integral_nonneg_of_ae hf, rwa [integral_neg, neg_nonneg] at this, end lemma integral_le_integral_ae {f g : α → ℝ} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) (h : ∀ₘ a, f a ≤ g a) : (∫ a, f a) ≤ (∫ a, g a) := le_of_sub_nonneg begin rw ← integral_sub hgm hgi hfm hfi, apply integral_nonneg_of_ae, filter_upwards [h], simp only [mem_set_of_eq], assume a, exact sub_nonneg_of_le end lemma integral_le_integral {f g : α → ℝ} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) (h : ∀ a, f a ≤ g a) : (∫ a, f a) ≤ (∫ a, g a) := integral_le_integral_ae hfm hfi hgm hgi $ univ_mem_sets' h lemma norm_integral_le_integral_norm (f : α → β) : ∥(∫ a, f a)∥ ≤ ∫ a, ∥f a∥ := have le_ae : ∀ₘ (a : α), 0 ≤ ∥f a∥ := by filter_upwards [] λa, norm_nonneg _, classical.by_cases ( λh : measurable f, calc ∥(∫ a, f a)∥ ≤ ennreal.to_real (∫⁻ a, ennreal.of_real ∥f a∥) : norm_integral_le_lintegral_norm _ ... = ∫ a, ∥f a∥ : (integral_eq_lintegral_of_nonneg_ae le_ae $ measurable.norm h).symm ) ( λh : ¬measurable f, begin rw [integral_non_measurable h, _root_.norm_zero], exact integral_nonneg_of_ae le_ae end ) lemma integral_finset_sum {ι} (s : finset ι) {f : ι → α → β} (hfm : ∀ i, measurable (f i)) (hfi : ∀ i, integrable (f i)) : (∫ a, ∑ i in s, f i a) = ∑ i in s, ∫ a, f i a := begin refine finset.induction_on s _ _, { simp only [integral_zero, finset.sum_empty] }, { assume i s his ih, simp only [his, finset.sum_insert, not_false_iff], rw [integral_add (hfm _) (hfi _) (s.measurable_sum hfm) (integrable_finset_sum s hfm hfi), ih] } end end properties mk_simp_attribute integral_simps "Simp set for integral rules." attribute [integral_simps] integral_neg integral_smul l1.integral_add l1.integral_sub l1.integral_smul l1.integral_neg attribute [irreducible] integral l1.integral end measure_theory
e81bae1402ce8565abb7d78446658394a1f97a48
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/field_theory/subfield.lean
dc67432a1eeff4cfa93c6ab137f4097a96f8bb67
[ "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
27,814
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import algebra.algebra.basic import algebra.order.field.inj_surj /-! # Subfields > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Let `K` be a field. This file defines the "bundled" subfield type `subfield K`, a type whose terms correspond to subfields of `K`. This is the preferred way to talk about subfields in mathlib. Unbundled subfields (`s : set K` and `is_subfield s`) are not in this file, and they will ultimately be deprecated. We prove that subfields are a complete lattice, and that you can `map` (pushforward) and `comap` (pull back) them along ring homomorphisms. We define the `closure` construction from `set R` to `subfield R`, sending a subset of `R` to the subfield it generates, and prove that it is a Galois insertion. ## Main definitions Notation used here: `(K : Type u) [field K] (L : Type u) [field L] (f g : K →+* L)` `(A : subfield K) (B : subfield L) (s : set K)` * `subfield R` : the type of subfields of a ring `R`. * `instance : complete_lattice (subfield R)` : the complete lattice structure on the subfields. * `subfield.closure` : subfield closure of a set, i.e., the smallest subfield that includes the set. * `subfield.gi` : `closure : set M → subfield M` and coercion `coe : subfield M → set M` form a `galois_insertion`. * `comap f B : subfield K` : the preimage of a subfield `B` along the ring homomorphism `f` * `map f A : subfield L` : the image of a subfield `A` along the ring homomorphism `f`. * `prod A B : subfield (K × L)` : the product of subfields * `f.field_range : subfield B` : the range of the ring homomorphism `f`. * `eq_locus_field f g : subfield K` : given ring homomorphisms `f g : K →+* R`, the subfield of `K` where `f x = g x` ## Implementation notes A subfield is implemented as a subring which is is closed under `⁻¹`. Lattice inclusion (e.g. `≤` and `⊓`) is used rather than set notation (`⊆` and `∩`), although `∈` is defined as membership of a subfield's underlying set. ## Tags subfield, subfields -/ open_locale big_operators universes u v w variables {K : Type u} {L : Type v} {M : Type w} [field K] [field L] [field M] /-- `subfield_class S K` states `S` is a type of subsets `s ⊆ K` closed under field operations. -/ class subfield_class (S K : Type*) [field K] [set_like S K] extends subring_class S K, inv_mem_class S K : Prop namespace subfield_class variables (S : Type*) [set_like S K] [h : subfield_class S K] include h /-- A subfield contains `1`, products and inverses. Be assured that we're not actually proving that subfields are subgroups: `subgroup_class` is really an abbreviation of `subgroup_with_or_without_zero_class`. -/ @[priority 100] -- See note [lower instance priority] instance subfield_class.to_subgroup_class : subgroup_class S K := { .. h } variables {S} lemma coe_rat_mem (s : S) (x : ℚ) : (x : K) ∈ s := by simpa only [rat.cast_def] using div_mem (coe_int_mem s x.num) (coe_nat_mem s x.denom) instance (s : S) : has_rat_cast s := ⟨λ x, ⟨↑x, coe_rat_mem s x⟩⟩ @[simp] lemma coe_rat_cast (s : S) (x : ℚ) : ((x : s) : K) = x := rfl lemma rat_smul_mem (s : S) (a : ℚ) (x : s) : (a • x : K) ∈ s := by simpa only [rat.smul_def] using mul_mem (coe_rat_mem s a) x.prop instance (s : S) : has_smul ℚ s := ⟨λ a x, ⟨a • x, rat_smul_mem s a x⟩⟩ @[simp] lemma coe_rat_smul (s : S) (a : ℚ) (x : s) : (↑(a • x) : K) = a • x := rfl variables (S) /-- A subfield inherits a field structure -/ @[priority 75] -- Prefer subclasses of `field` over subclasses of `subfield_class`. instance to_field (s : S) : field s := subtype.coe_injective.field (coe : s → K) rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl) (λ _, rfl) omit h /-- A subfield of a `linear_ordered_field` is a `linear_ordered_field`. -/ @[priority 75] -- Prefer subclasses of `field` over subclasses of `subfield_class`. instance to_linear_ordered_field {K} [linear_ordered_field K] [set_like S K] [subfield_class S K] (s : S) : linear_ordered_field s := subtype.coe_injective.linear_ordered_field coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) end subfield_class set_option old_structure_cmd true /-- `subfield R` is the type of subfields of `R`. A subfield of `R` is a subset `s` that is a multiplicative submonoid and an additive subgroup. Note in particular that it shares the same 0 and 1 as R. -/ structure subfield (K : Type u) [field K] extends subring K := (inv_mem' : ∀ x ∈ carrier, x⁻¹ ∈ carrier) /-- Reinterpret a `subfield` as a `subring`. -/ add_decl_doc subfield.to_subring namespace subfield /-- The underlying `add_subgroup` of a subfield. -/ def to_add_subgroup (s : subfield K) : add_subgroup K := { ..s.to_subring.to_add_subgroup } /-- The underlying submonoid of a subfield. -/ def to_submonoid (s : subfield K) : submonoid K := { ..s.to_subring.to_submonoid } instance : set_like (subfield K) K := ⟨subfield.carrier, λ p q h, by cases p; cases q; congr'⟩ instance : subfield_class (subfield K) K := { add_mem := add_mem', zero_mem := zero_mem', neg_mem := neg_mem', mul_mem := mul_mem', one_mem := one_mem', inv_mem := inv_mem' } @[simp] lemma mem_carrier {s : subfield K} {x : K} : x ∈ s.carrier ↔ x ∈ s := iff.rfl @[simp] lemma mem_mk {S : set K} {x : K} (h₁ h₂ h₃ h₄ h₅ h₆) : x ∈ (⟨S, h₁, h₂, h₃, h₄, h₅, h₆⟩ : subfield K) ↔ x ∈ S := iff.rfl @[simp] lemma coe_set_mk (S : set K) (h₁ h₂ h₃ h₄ h₅ h₆) : ((⟨S, h₁, h₂, h₃, h₄, h₅, h₆⟩ : subfield K) : set K) = S := rfl @[simp] lemma mk_le_mk {S S' : set K} (h₁ h₂ h₃ h₄ h₅ h₆ h₁' h₂' h₃' h₄' h₅' h₆') : (⟨S, h₁, h₂, h₃, h₄, h₅, h₆⟩ : subfield K) ≤ (⟨S', h₁', h₂', h₃', h₄', h₅', h₆'⟩ : subfield K) ↔ S ⊆ S' := iff.rfl /-- Two subfields are equal if they have the same elements. -/ @[ext] theorem ext {S T : subfield K} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h /-- Copy of a subfield with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (S : subfield K) (s : set K) (hs : s = ↑S) : subfield K := { carrier := s, inv_mem' := hs.symm ▸ S.inv_mem', ..S.to_subring.copy s hs } @[simp] lemma coe_copy (S : subfield K) (s : set K) (hs : s = ↑S) : (S.copy s hs : set K) = s := rfl lemma copy_eq (S : subfield K) (s : set K) (hs : s = ↑S) : S.copy s hs = S := set_like.coe_injective hs @[simp] lemma coe_to_subring (s : subfield K) : (s.to_subring : set K) = s := rfl @[simp] lemma mem_to_subring (s : subfield K) (x : K) : x ∈ s.to_subring ↔ x ∈ s := iff.rfl end subfield /-- A `subring` containing inverses is a `subfield`. -/ def subring.to_subfield (s : subring K) (hinv : ∀ x ∈ s, x⁻¹ ∈ s) : subfield K := { inv_mem' := hinv ..s } namespace subfield variables (s t : subfield K) section derived_from_subfield_class /-- A subfield contains the field's 1. -/ protected theorem one_mem : (1 : K) ∈ s := one_mem s /-- A subfield contains the field's 0. -/ protected theorem zero_mem : (0 : K) ∈ s := zero_mem s /-- A subfield is closed under multiplication. -/ protected theorem mul_mem {x y : K} : x ∈ s → y ∈ s → x * y ∈ s := mul_mem /-- A subfield is closed under addition. -/ protected theorem add_mem {x y : K} : x ∈ s → y ∈ s → x + y ∈ s := add_mem /-- A subfield is closed under negation. -/ protected theorem neg_mem {x : K} : x ∈ s → -x ∈ s := neg_mem /-- A subfield is closed under subtraction. -/ protected theorem sub_mem {x y : K} : x ∈ s → y ∈ s → x - y ∈ s := sub_mem /-- A subfield is closed under inverses. -/ protected theorem inv_mem {x : K} : x ∈ s → x⁻¹ ∈ s := inv_mem /-- A subfield is closed under division. -/ protected theorem div_mem {x y : K} : x ∈ s → y ∈ s → x / y ∈ s := div_mem /-- Product of a list of elements in a subfield is in the subfield. -/ protected lemma list_prod_mem {l : list K} : (∀ x ∈ l, x ∈ s) → l.prod ∈ s := list_prod_mem /-- Sum of a list of elements in a subfield is in the subfield. -/ protected lemma list_sum_mem {l : list K} : (∀ x ∈ l, x ∈ s) → l.sum ∈ s := list_sum_mem /-- Product of a multiset of elements in a subfield is in the subfield. -/ protected lemma multiset_prod_mem (m : multiset K) : (∀ a ∈ m, a ∈ s) → m.prod ∈ s := multiset_prod_mem m /-- Sum of a multiset of elements in a `subfield` is in the `subfield`. -/ protected lemma multiset_sum_mem (m : multiset K) : (∀ a ∈ m, a ∈ s) → m.sum ∈ s := multiset_sum_mem m /-- Product of elements of a subfield indexed by a `finset` is in the subfield. -/ protected lemma prod_mem {ι : Type*} {t : finset ι} {f : ι → K} (h : ∀ c ∈ t, f c ∈ s) : ∏ i in t, f i ∈ s := prod_mem h /-- Sum of elements in a `subfield` indexed by a `finset` is in the `subfield`. -/ protected lemma sum_mem {ι : Type*} {t : finset ι} {f : ι → K} (h : ∀ c ∈ t, f c ∈ s) : ∑ i in t, f i ∈ s := sum_mem h protected lemma pow_mem {x : K} (hx : x ∈ s) (n : ℕ) : x^n ∈ s := pow_mem hx n protected lemma zsmul_mem {x : K} (hx : x ∈ s) (n : ℤ) : n • x ∈ s := zsmul_mem hx n protected lemma coe_int_mem (n : ℤ) : (n : K) ∈ s := coe_int_mem s n lemma zpow_mem {x : K} (hx : x ∈ s) (n : ℤ) : x^n ∈ s := begin cases n, { simpa using s.pow_mem hx n }, { simpa [pow_succ] using s.inv_mem (s.mul_mem hx (s.pow_mem hx n)) }, end instance : ring s := s.to_subring.to_ring instance : has_div s := ⟨λ x y, ⟨x / y, s.div_mem x.2 y.2⟩⟩ instance : has_inv s := ⟨λ x, ⟨x⁻¹, s.inv_mem x.2⟩⟩ instance : has_pow s ℤ := ⟨λ x z, ⟨x ^ z, s.zpow_mem x.2 z⟩⟩ /-- A subfield inherits a field structure -/ instance to_field : field s := subtype.coe_injective.field (coe : s → K) rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl) (λ _, rfl) /-- A subfield of a `linear_ordered_field` is a `linear_ordered_field`. -/ instance to_linear_ordered_field {K} [linear_ordered_field K] (s : subfield K) : linear_ordered_field s := subtype.coe_injective.linear_ordered_field coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) @[simp, norm_cast] lemma coe_add (x y : s) : (↑(x + y) : K) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_sub (x y : s) : (↑(x - y) : K) = ↑x - ↑y := rfl @[simp, norm_cast] lemma coe_neg (x : s) : (↑(-x) : K) = -↑x := rfl @[simp, norm_cast] lemma coe_mul (x y : s) : (↑(x * y) : K) = ↑x * ↑y := rfl @[simp, norm_cast] lemma coe_div (x y : s) : (↑(x / y) : K) = ↑x / ↑y := rfl @[simp, norm_cast] lemma coe_inv (x : s) : (↑(x⁻¹) : K) = (↑x)⁻¹ := rfl @[simp, norm_cast] lemma coe_zero : ((0 : s) : K) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : s) : K) = 1 := rfl end derived_from_subfield_class /-- The embedding from a subfield of the field `K` to `K`. -/ def subtype (s : subfield K) : s →+* K := { to_fun := coe, .. s.to_submonoid.subtype, .. s.to_add_subgroup.subtype } instance to_algebra : algebra s K := ring_hom.to_algebra s.subtype @[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl lemma to_subring.subtype_eq_subtype (F : Type*) [field F] (S : subfield F) : S.to_subring.subtype = S.subtype := rfl /-! # Partial order -/ variables (s t) @[simp] lemma mem_to_submonoid {s : subfield K} {x : K} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_submonoid : (s.to_submonoid : set K) = s := rfl @[simp] lemma mem_to_add_subgroup {s : subfield K} {x : K} : x ∈ s.to_add_subgroup ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_add_subgroup : (s.to_add_subgroup : set K) = s := rfl /-! # top -/ /-- The subfield of `K` containing all elements of `K`. -/ instance : has_top (subfield K) := ⟨{ inv_mem' := λ x _, subring.mem_top x, .. (⊤ : subring K)}⟩ instance : inhabited (subfield K) := ⟨⊤⟩ @[simp] lemma mem_top (x : K) : x ∈ (⊤ : subfield K) := set.mem_univ x @[simp] lemma coe_top : ((⊤ : subfield K) : set K) = set.univ := rfl /-- The ring equiv between the top element of `subfield K` and `K`. -/ @[simps] def top_equiv : (⊤ : subfield K) ≃+* K := subsemiring.top_equiv /-! # comap -/ variables (f : K →+* L) /-- The preimage of a subfield along a ring homomorphism is a subfield. -/ def comap (s : subfield L) : subfield K := { inv_mem' := λ x hx, show f (x⁻¹) ∈ s, by { rw map_inv₀ f, exact s.inv_mem hx }, .. s.to_subring.comap f } @[simp] lemma coe_comap (s : subfield L) : (s.comap f : set K) = f ⁻¹' s := rfl @[simp] lemma mem_comap {s : subfield L} {f : K →+* L} {x : K} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl lemma comap_comap (s : subfield M) (g : L →+* M) (f : K →+* L) : (s.comap g).comap f = s.comap (g.comp f) := rfl /-! # map -/ /-- The image of a subfield along a ring homomorphism is a subfield. -/ def map (s : subfield K) : subfield L := { inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, s.inv_mem hx, map_inv₀ f x⟩ }, .. s.to_subring.map f } @[simp] lemma coe_map : (s.map f : set L) = f '' s := rfl @[simp] lemma mem_map {f : K →+* L} {s : subfield K} {y : L} : y ∈ s.map f ↔ ∃ x ∈ s, f x = y := set.mem_image_iff_bex lemma map_map (g : L →+* M) (f : K →+* L) : (s.map f).map g = s.map (g.comp f) := set_like.ext' $ set.image_image _ _ _ lemma map_le_iff_le_comap {f : K →+* L} {s : subfield K} {t : subfield L} : s.map f ≤ t ↔ s ≤ t.comap f := set.image_subset_iff lemma gc_map_comap (f : K →+* L) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap end subfield namespace ring_hom variables (g : L →+* M) (f : K →+* L) /-! # range -/ /-- The range of a ring homomorphism, as a subfield of the target. See Note [range copy pattern]. -/ def field_range : subfield L := ((⊤ : subfield K).map f).copy (set.range f) set.image_univ.symm @[simp] lemma coe_field_range : (f.field_range : set L) = set.range f := rfl @[simp] lemma mem_field_range {f : K →+* L} {y : L} : y ∈ f.field_range ↔ ∃ x, f x = y := iff.rfl lemma field_range_eq_map : f.field_range = subfield.map f ⊤ := by { ext, simp } lemma map_field_range : f.field_range.map g = (g.comp f).field_range := by simpa only [field_range_eq_map] using (⊤ : subfield K).map_map g f /-- The range of a morphism of fields is a fintype, if the domain is a fintype. Note that this instance can cause a diamond with `subtype.fintype` if `L` is also a fintype.-/ instance fintype_field_range [fintype K] [decidable_eq L] (f : K →+* L) : fintype f.field_range := set.fintype_range f end ring_hom namespace subfield /-! # inf -/ /-- The inf of two subfields is their intersection. -/ instance : has_inf (subfield K) := ⟨λ s t, { inv_mem' := λ x hx, subring.mem_inf.mpr ⟨s.inv_mem (subring.mem_inf.mp hx).1, t.inv_mem (subring.mem_inf.mp hx).2⟩, .. s.to_subring ⊓ t.to_subring }⟩ @[simp] lemma coe_inf (p p' : subfield K) : ((p ⊓ p' : subfield K) : set K) = p ∩ p' := rfl @[simp] lemma mem_inf {p p' : subfield K} {x : K} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl instance : has_Inf (subfield K) := ⟨λ S, { inv_mem' := begin rintros x hx, apply subring.mem_Inf.mpr, rintro _ ⟨p, p_mem, rfl⟩, exact p.inv_mem (subring.mem_Inf.mp hx p.to_subring ⟨p, p_mem, rfl⟩), end, .. Inf (subfield.to_subring '' S) }⟩ @[simp, norm_cast] lemma coe_Inf (S : set (subfield K)) : ((Inf S : subfield K) : set K) = ⋂ s ∈ S, ↑s := show ((Inf (subfield.to_subring '' S) : subring K) : set K) = ⋂ s ∈ S, ↑s, begin ext x, rw [subring.coe_Inf, set.mem_Inter, set.mem_Inter], exact ⟨λ h s s' ⟨s_mem, s'_eq⟩, h s.to_subring _ ⟨⟨s, s_mem, rfl⟩, s'_eq⟩, λ h s s' ⟨⟨s'', s''_mem, s_eq⟩, (s'_eq : ↑s = s')⟩, h s'' _ ⟨s''_mem, by simp [←s_eq, ← s'_eq]⟩⟩ end lemma mem_Inf {S : set (subfield K)} {x : K} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := subring.mem_Inf.trans ⟨λ h p hp, h p.to_subring ⟨p, hp, rfl⟩, λ h p ⟨p', hp', p_eq⟩, p_eq ▸ h p' hp'⟩ @[simp] lemma Inf_to_subring (s : set (subfield K)) : (Inf s).to_subring = ⨅ t ∈ s, subfield.to_subring t := begin ext x, rw [mem_to_subring, mem_Inf], erw subring.mem_Inf, exact ⟨λ h p ⟨p', hp⟩, hp ▸ subring.mem_Inf.mpr (λ p ⟨hp', hp⟩, hp ▸ h _ hp'), λ h p hp, h p.to_subring ⟨p, subring.ext (λ x, ⟨λ hx, subring.mem_Inf.mp hx _ ⟨hp, rfl⟩, λ hx, subring.mem_Inf.mpr (λ p' ⟨hp, p'_eq⟩, p'_eq ▸ hx)⟩)⟩⟩ end lemma is_glb_Inf (S : set (subfield K)) : is_glb S (Inf S) := begin refine is_glb.of_image (λ s t, show (s : set K) ≤ t ↔ s ≤ t, from set_like.coe_subset_coe) _, convert is_glb_binfi, exact coe_Inf _ end /-- Subfields of a ring form a complete lattice. -/ instance : complete_lattice (subfield K) := { top := ⊤, le_top := λ s x hx, trivial, inf := (⊓), inf_le_left := λ s t x, and.left, inf_le_right := λ s t x, and.right, le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩, .. complete_lattice_of_Inf (subfield K) is_glb_Inf } /-! # subfield closure of a subset -/ /-- The `subfield` generated by a set. -/ def closure (s : set K) : subfield K := { carrier := { (x / y) | (x ∈ subring.closure s) (y ∈ subring.closure s) }, zero_mem' := ⟨0, subring.zero_mem _, 1, subring.one_mem _, div_one _⟩, one_mem' := ⟨1, subring.one_mem _, 1, subring.one_mem _, div_one _⟩, neg_mem' := λ x ⟨y, hy, z, hz, x_eq⟩, ⟨-y, subring.neg_mem _ hy, z, hz, x_eq ▸ neg_div _ _⟩, inv_mem' := λ x ⟨y, hy, z, hz, x_eq⟩, ⟨z, hz, y, hy, x_eq ▸ (inv_div _ _).symm⟩, add_mem' := λ x y x_mem y_mem, begin obtain ⟨nx, hnx, dx, hdx, rfl⟩ := id x_mem, obtain ⟨ny, hny, dy, hdy, rfl⟩ := id y_mem, by_cases hx0 : dx = 0, { rwa [hx0, div_zero, zero_add] }, by_cases hy0 : dy = 0, { rwa [hy0, div_zero, add_zero] }, exact ⟨nx * dy + dx * ny, subring.add_mem _ (subring.mul_mem _ hnx hdy) (subring.mul_mem _ hdx hny), dx * dy, subring.mul_mem _ hdx hdy, (div_add_div nx ny hx0 hy0).symm⟩ end, mul_mem' := λ x y x_mem y_mem, begin obtain ⟨nx, hnx, dx, hdx, rfl⟩ := id x_mem, obtain ⟨ny, hny, dy, hdy, rfl⟩ := id y_mem, exact ⟨nx * ny, subring.mul_mem _ hnx hny, dx * dy, subring.mul_mem _ hdx hdy, (div_mul_div_comm _ _ _ _).symm⟩ end } lemma mem_closure_iff {s : set K} {x} : x ∈ closure s ↔ ∃ (y ∈ subring.closure s) (z ∈ subring.closure s), y / z = x := iff.rfl lemma subring_closure_le (s : set K) : subring.closure s ≤ (closure s).to_subring := λ x hx, ⟨x, hx, 1, subring.one_mem _, div_one x⟩ /-- The subfield generated by a set includes the set. -/ @[simp] lemma subset_closure {s : set K} : s ⊆ closure s := set.subset.trans subring.subset_closure (subring_closure_le s) lemma not_mem_of_not_mem_closure {s : set K} {P : K} (hP : P ∉ closure s) : P ∉ s := λ h, hP (subset_closure h) lemma mem_closure {x : K} {s : set K} : x ∈ closure s ↔ ∀ S : subfield K, s ⊆ S → x ∈ S := ⟨λ ⟨y, hy, z, hz, x_eq⟩ t le, x_eq ▸ t.div_mem (subring.mem_closure.mp hy t.to_subring le) (subring.mem_closure.mp hz t.to_subring le), λ h, h (closure s) subset_closure⟩ /-- A subfield `t` includes `closure s` if and only if it includes `s`. -/ @[simp] lemma closure_le {s : set K} {t : subfield K} : closure s ≤ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, λ h x hx, mem_closure.mp hx t h⟩ /-- Subfield closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ lemma closure_mono ⦃s t : set K⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ set.subset.trans h subset_closure lemma closure_eq_of_le {s : set K} {t : subfield K} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) : closure s = t := le_antisymm (closure_le.2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `1`, and all elements of `s`, and is preserved under addition, negation, and multiplication, then `p` holds for all elements of the closure of `s`. -/ @[elab_as_eliminator] lemma closure_induction {s : set K} {p : K → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H1 : p 1) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hneg : ∀ x, p x → p (-x)) (Hinv : ∀ x, p x → p (x⁻¹)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, Hmul, H1, Hadd, @add_neg_self K _ 1 ▸ Hadd _ _ H1 (Hneg _ H1), Hneg, Hinv⟩).2 Hs h variable (K) /-- `closure` forms a Galois insertion with the coercion to set. -/ protected def gi : galois_insertion (@closure K _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {K} /-- Closure of a subfield `S` equals `S`. -/ lemma closure_eq (s : subfield K) : closure (s : set K) = s := (subfield.gi K).l_u_eq s @[simp] lemma closure_empty : closure (∅ : set K) = ⊥ := (subfield.gi K).gc.l_bot @[simp] lemma closure_univ : closure (set.univ : set K) = ⊤ := @coe_top K _ ▸ closure_eq ⊤ lemma closure_union (s t : set K) : closure (s ∪ t) = closure s ⊔ closure t := (subfield.gi K).gc.l_sup lemma closure_Union {ι} (s : ι → set K) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subfield.gi K).gc.l_supr lemma closure_sUnion (s : set (set K)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t := (subfield.gi K).gc.l_Sup lemma map_sup (s t : subfield K) (f : K →+* L) : (s ⊔ t).map f = s.map f ⊔ t.map f := (gc_map_comap f).l_sup lemma map_supr {ι : Sort*} (f : K →+* L) (s : ι → subfield K) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr lemma comap_inf (s t : subfield L) (f : K →+* L) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f := (gc_map_comap f).u_inf lemma comap_infi {ι : Sort*} (f : K →+* L) (s : ι → subfield L) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp] lemma map_bot (f : K →+* L) : (⊥ : subfield K).map f = ⊥ := (gc_map_comap f).l_bot @[simp] lemma comap_top (f : K →+* L) : (⊤ : subfield L).comap f = ⊤ := (gc_map_comap f).u_top /-- The underlying set of a non-empty directed Sup of subfields is just a union of the subfields. Note that this fails without the directedness assumption (the union of two subfields is typically not a subfield) -/ lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subfield K} (hS : directed (≤) S) {x : K} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩, suffices : x ∈ closure (⋃ i, (S i : set K)) → ∃ i, x ∈ S i, by simpa only [closure_Union, closure_eq], refine λ hx, closure_induction hx (λ x, set.mem_Union.mp) _ _ _ _ _, { exact hι.elim (λ i, ⟨i, (S i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, obtain ⟨k, hki, hkj⟩ := hS i j, exact ⟨k, (S k).add_mem (hki hi) (hkj hj)⟩ }, { rintros x ⟨i, hi⟩, exact ⟨i, (S i).neg_mem hi⟩ }, { rintros x ⟨i, hi⟩, exact ⟨i, (S i).inv_mem hi⟩ }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, obtain ⟨k, hki, hkj⟩ := hS i j, exact ⟨k, (S k).mul_mem (hki hi) (hkj hj)⟩ } end lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subfield K} (hS : directed (≤) S) : ((⨆ i, S i : subfield K) : set K) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] lemma mem_Sup_of_directed_on {S : set (subfield K)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : K} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] end lemma coe_Sup_of_directed_on {S : set (subfield K)} (Sne : S.nonempty) (hS : directed_on (≤) S) : (↑(Sup S) : set K) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS] end subfield namespace ring_hom variables {s : subfield K} open subfield /-- Restriction of a ring homomorphism to its range interpreted as a subfield. -/ def range_restrict_field (f : K →+* L) : K →+* f.field_range := f.srange_restrict @[simp] lemma coe_range_restrict_field (f : K →+* L) (x : K) : (f.range_restrict_field x : L) = f x := rfl /-- The subfield of elements `x : R` such that `f x = g x`, i.e., the equalizer of f and g as a subfield of R -/ def eq_locus_field (f g : K →+* L) : subfield K := { inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [map_inv₀ f, map_inv₀ g, hx], carrier := {x | f x = g x}, .. (f : K →+* L).eq_locus g } /-- If two ring homomorphisms are equal on a set, then they are equal on its subfield closure. -/ lemma eq_on_field_closure {f g : K →+* L} {s : set K} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_locus_field g, from closure_le.2 h lemma eq_of_eq_on_subfield_top {f g : K →+* L} (h : set.eq_on f g (⊤ : subfield K)) : f = g := ext $ λ x, h trivial lemma eq_of_eq_on_of_field_closure_eq_top {s : set K} (hs : closure s = ⊤) {f g : K →+* L} (h : s.eq_on f g) : f = g := eq_of_eq_on_subfield_top $ hs ▸ eq_on_field_closure h lemma field_closure_preimage_le (f : K →+* L) (s : set L) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a ring homomorphism of the subfield generated by a set equals the subfield generated by the image of the set. -/ lemma map_field_closure (f : K →+* L) (s : set K) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (field_closure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) end ring_hom namespace subfield open ring_hom /-- The ring homomorphism associated to an inclusion of subfields. -/ def inclusion {S T : subfield K} (h : S ≤ T) : S →+* T := S.subtype.cod_restrict _ (λ x, h x.2) @[simp] lemma field_range_subtype (s : subfield K) : s.subtype.field_range = s := set_like.ext' $ (coe_srange _).trans subtype.range_coe end subfield namespace ring_equiv variables {s t : subfield K} /-- Makes the identity isomorphism from a proof two subfields of a multiplicative monoid are equal. -/ def subfield_congr (h : s = t) : s ≃+* t := { map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ set_like.ext'_iff.1 h } end ring_equiv namespace subfield variables {s : set K} lemma closure_preimage_le (f : K →+* L) (s : set L) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx end subfield
65f56fbe23bdffc4ddd93b7698d3f6698c77be6d
4727251e0cd73359b15b664c3170e5d754078599
/src/tactic/interactive.lean
3fa89e69cb0b5cd20ffa8bd4008ae1181813f8bc
[ "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
40,243
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Sébastien Gouëzel, Scott Morrison -/ import logic.nonempty import tactic.lint import tactic.dependencies setup_tactic_parser namespace tactic namespace interactive open interactive interactive.types expr /-- Similar to `constructor`, but does not reorder goals. -/ meta def fconstructor : tactic unit := concat_tags tactic.fconstructor add_tactic_doc { name := "fconstructor", category := doc_category.tactic, decl_names := [`tactic.interactive.fconstructor], tags := ["logic", "goal management"] } /-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal. Never fails. Useful for debugging. -/ meta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit := do max ← i_to_expr_strict max >>= tactic.eval_expr nat, λ s, match _root_.try_for max (tac s) with | some r := r | none := (tactic.trace "try_for timeout, using sorry" >> tactic.admit) s end /-- Multiple `subst`. `substs x y z` is the same as `subst x, subst y, subst z`. -/ meta def substs (l : parse ident*) : tactic unit := propagate_tags $ l.mmap' (λ h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible) add_tactic_doc { name := "substs", category := doc_category.tactic, decl_names := [`tactic.interactive.substs], tags := ["rewriting"] } /-- Unfold coercion-related definitions -/ meta def unfold_coes (loc : parse location) : tactic unit := unfold [ ``coe, ``coe_t, ``has_coe_t.coe, ``coe_b,``has_coe.coe, ``lift, ``has_lift.lift, ``lift_t, ``has_lift_t.lift, ``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc add_tactic_doc { name := "unfold_coes", category := doc_category.tactic, decl_names := [`tactic.interactive.unfold_coes], tags := ["simplification"] } /-- Unfold `has_well_founded.r`, `sizeof` and other such definitions. -/ meta def unfold_wf := propagate_tags (well_founded_tactics.unfold_wf_rel; well_founded_tactics.unfold_sizeof) /-- Unfold auxiliary definitions associated with the current declaration. -/ meta def unfold_aux : tactic unit := do tgt ← target, name ← decl_name, let to_unfold := (tgt.list_names_with_prefix name), guard (¬ to_unfold.empty), -- should we be using simp_lemmas.mk_default? simp_lemmas.mk.dsimplify to_unfold.to_list tgt >>= tactic.change /-- For debugging only. This tactic checks the current state for any missing dropped goals and restores them. Useful when there are no goals to solve but "result contains meta-variables". -/ meta def recover : tactic unit := metavariables >>= tactic.set_goals /-- Like `try { tac }`, but in the case of failure it continues from the failure state instead of reverting to the original state. -/ meta def continue (tac : itactic) : tactic unit := λ s, result.cases_on (tac s) (λ a, result.success ()) (λ e ref, result.success ()) /-- `id { tac }` is the same as `tac`, but it is useful for creating a block scope without requiring the goal to be solved at the end like `{ tac }`. It can also be used to enclose a non-interactive tactic for patterns like `tac1; id {tac2}` where `tac2` is non-interactive. -/ @[inline] protected meta def id (tac : itactic) : tactic unit := tac /-- `work_on_goal n { tac }` creates a block scope for the `n`-goal, and does not require that the goal be solved at the end (any remaining subgoals are inserted back into the list of goals). Typically usage might look like: ```` intros, simp, apply lemma_1, work_on_goal 3 { dsimp, simp }, refl ```` See also `id { tac }`, which is equivalent to `work_on_goal 1 { tac }`. -/ meta def work_on_goal : parse small_nat → itactic → tactic unit | 0 t := fail "work_on_goal failed: goals are 1-indexed" | (n+1) t := do goals ← get_goals, let earlier_goals := goals.take n, let later_goals := goals.drop (n+1), set_goals (goals.nth n).to_list, t, new_goals ← get_goals, set_goals (earlier_goals ++ new_goals ++ later_goals) /-- `swap n` will move the `n`th goal to the front. `swap` defaults to `swap 2`, and so interchanges the first and second goals. See also `tactic.interactive.rotate`, which moves the first `n` goals to the back. -/ meta def swap (n := 2) : tactic unit := do gs ← get_goals, match gs.nth (n-1) with | (some g) := set_goals (g :: gs.remove_nth (n-1)) | _ := skip end add_tactic_doc { name := "swap", category := doc_category.tactic, decl_names := [`tactic.interactive.swap], tags := ["goal management"] } /-- `rotate` moves the first goal to the back. `rotate n` will do this `n` times. See also `tactic.interactive.swap`, which moves the `n`th goal to the front. -/ meta def rotate (n := 1) : tactic unit := tactic.rotate n add_tactic_doc { name := "rotate", category := doc_category.tactic, decl_names := [`tactic.interactive.rotate], tags := ["goal management"] } /-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/ meta def clear_ : tactic unit := tactic.repeat $ do l ← local_context, l.reverse.mfirst $ λ h, do name.mk_string s p ← return $ local_pp_name h, guard (s.front = '_'), cl ← infer_type h >>= is_class, guard (¬ cl), tactic.clear h add_tactic_doc { name := "clear_", category := doc_category.tactic, decl_names := [`tactic.interactive.clear_], tags := ["context management"] } /-- Acts like `have`, but removes a hypothesis with the same name as this one. For example if the state is `h : p ⊢ goal` and `f : p → q`, then after `replace h := f h` the goal will be `h : q ⊢ goal`, where `have h := f h` would result in the state `h : p, h : q ⊢ goal`. This can be used to simulate the `specialize` and `apply at` tactics of Coq. -/ meta def replace (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := do let h := h.get_or_else `this, old ← try_core (get_local h), «have» h q₁ q₂, match old, q₂ with | none, _ := skip | some o, some _ := tactic.clear o | some o, none := swap >> tactic.clear o >> swap end add_tactic_doc { name := "replace", category := doc_category.tactic, decl_names := [`tactic.interactive.replace], tags := ["context management"] } /-- Make every proposition in the context decidable. -/ meta def classical := tactic.classical add_tactic_doc { name := "classical", category := doc_category.tactic, decl_names := [`tactic.interactive.classical], tags := ["classical logic", "type class"] } private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def generalize_arg_p : parser (pexpr × name) := with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux @[nolint def_lemma] noncomputable lemma {u} generalize_a_aux {α : Sort u} (h : ∀ x : Sort u, (α → x) → x) : α := h α id /-- Like `generalize` but also considers assumptions specified by the user. The user can also specify to omit the goal. -/ meta def generalize_hyp (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) (l : parse location) : tactic unit := do h' ← get_unused_name `h, x' ← get_unused_name `x, g ← if ¬ l.include_goal then do refine ``(generalize_a_aux _), some <$> (prod.mk <$> tactic.intro x' <*> tactic.intro h') else pure none, n ← l.get_locals >>= tactic.revert_lst, generalize h () p, intron n, match g with | some (x',h') := do tactic.apply h', tactic.clear h', tactic.clear x' | none := return () end add_tactic_doc { name := "generalize_hyp", category := doc_category.tactic, decl_names := [`tactic.interactive.generalize_hyp], tags := ["context management"] } meta def compact_decl_aux : list name → binder_info → expr → list expr → tactic (list (list name × binder_info × expr)) | ns bi t [] := pure [(ns.reverse, bi, t)] | ns bi t (v'@(local_const n pp bi' t') :: xs) := do t' ← infer_type v', if bi = bi' ∧ t = t' then compact_decl_aux (pp :: ns) bi t xs else do vs ← compact_decl_aux [pp] bi' t' xs, pure $ (ns.reverse, bi, t) :: vs | ns bi t (_ :: xs) := compact_decl_aux ns bi t xs /-- go from (x₀ : t₀) (x₁ : t₀) (x₂ : t₀) to (x₀ x₁ x₂ : t₀) -/ meta def compact_decl : list expr → tactic (list (list name × binder_info × expr)) | [] := pure [] | (v@(local_const n pp bi t) :: xs) := do t ← infer_type v, compact_decl_aux [pp] bi t xs | (_ :: xs) := compact_decl xs /-- Remove identity functions from a term. These are normally automatically generated with terms like `show t, from p` or `(p : t)` which translate to some variant on `@id t p` in order to retain the type. -/ meta def clean (q : parse texpr) : tactic unit := do tgt : expr ← target, e ← i_to_expr_strict ``(%%q : %%tgt), tactic.exact $ e.clean meta def source_fields (missing : list name) (e : pexpr) : tactic (list (name × pexpr)) := do e ← to_expr e, t ← infer_type e, let struct_n : name := t.get_app_fn.const_name, fields ← expanded_field_list struct_n, let exp_fields := fields.filter (λ x, x.2 ∈ missing), exp_fields.mmap $ λ ⟨p,n⟩, (prod.mk n ∘ to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e] meta def collect_struct' : pexpr → state_t (list $ expr×structure_instance_info) tactic pexpr | e := do some str ← pure (e.get_structure_instance_info) | e.traverse collect_struct', v ← monad_lift mk_mvar, modify (list.cons (v,str)), pure $ to_pexpr v meta def collect_struct (e : pexpr) : tactic $ pexpr × list (expr×structure_instance_info) := prod.map id list.reverse <$> (collect_struct' e).run [] meta def refine_one (str : structure_instance_info) : tactic $ list (expr×structure_instance_info) := do tgt ← target >>= whnf, let struct_n : name := tgt.get_app_fn.const_name, exp_fields ← expanded_field_list struct_n, let missing_f := exp_fields.filter (λ f, (f.2 : name) ∉ str.field_names), (src_field_names,src_field_vals) ← (@list.unzip name _ ∘ list.join) <$> str.sources.mmap (source_fields $ missing_f.map prod.snd), let provided := exp_fields.filter (λ f, (f.2 : name) ∈ str.field_names), let missing_f' := missing_f.filter (λ x, x.2 ∉ src_field_names), vs ← mk_mvar_list missing_f'.length, (field_values,new_goals) ← list.unzip <$> (str.field_values.mmap collect_struct : tactic _), e' ← to_expr $ pexpr.mk_structure_instance { struct := some struct_n , field_names := str.field_names ++ missing_f'.map prod.snd ++ src_field_names , field_values := field_values ++ vs.map to_pexpr ++ src_field_vals }, tactic.exact e', gs ← with_enable_tags ( mzip_with (λ (n : name × name) v, do set_goals [v], try (dsimp_target simp_lemmas.mk), apply_auto_param <|> apply_opt_param <|> (set_main_tag [`_field,n.2,n.1]), get_goals) missing_f' vs), set_goals gs.join, return new_goals.join meta def refine_recursively : expr × structure_instance_info → tactic (list expr) | (e,str) := do set_goals [e], rs ← refine_one str, gs ← get_goals, gs' ← rs.mmap refine_recursively, return $ gs'.join ++ gs /-- `refine_struct { .. }` acts like `refine` but works only with structure instance literals. It creates a goal for each missing field and tags it with the name of the field so that `have_field` can be used to generically refer to the field currently being refined. As an example, we can use `refine_struct` to automate the construction of semigroup instances: ```lean refine_struct ( { .. } : semigroup α ), -- case semigroup, mul -- α : Type u, -- ⊢ α → α → α -- case semigroup, mul_assoc -- α : Type u, -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) ``` `have_field`, used after `refine_struct _`, poses `field` as a local constant with the type of the field of the current goal: ```lean refine_struct ({ .. } : semigroup α), { have_field, ... }, { have_field, ... }, ``` behaves like ```lean refine_struct ({ .. } : semigroup α), { have field := @semigroup.mul, ... }, { have field := @semigroup.mul_assoc, ... }, ``` -/ meta def refine_struct : parse texpr → tactic unit | e := do (x,xs) ← collect_struct e, refine x, gs ← get_goals, xs' ← xs.mmap refine_recursively, set_goals (xs'.join ++ gs) /-- `guard_hyp' h : t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. Fixes `guard_hyp` by instantiating meta variables -/ meta def guard_hyp' (n : parse ident) (p : parse $ tk ":" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p /-- `match_hyp h : t` fails if the hypothesis `h` does not match the type `t` (which may be a pattern). We use this tactic for writing tests. -/ meta def match_hyp (n : parse ident) (p : parse $ tk ":" *> texpr) (m := reducible) : tactic (list expr) := do h ← get_local n >>= infer_type >>= instantiate_mvars, match_expr p h m /-- `guard_expr_strict t := e` fails if the expr `t` is not equal to `e`. By contrast to `guard_expr`, this tests strict (syntactic) equality. We use this tactic for writing tests. -/ meta def guard_expr_strict (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, guard (t = e) /-- `guard_target_strict t` fails if the target of the main goal is not syntactically `t`. We use this tactic for writing tests. -/ meta def guard_target_strict (p : parse texpr) : tactic unit := do t ← target, guard_expr_strict t p /-- `guard_hyp_strict h : t` fails if the hypothesis `h` does not have type syntactically equal to `t`. We use this tactic for writing tests. -/ meta def guard_hyp_strict (n : parse ident) (p : parse $ tk ":" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_strict h p /-- Tests that there are `n` hypotheses in the current context. -/ meta def guard_hyp_nums (n : ℕ) : tactic unit := do k ← local_context, guard (n = k.length) <|> fail format!"{k.length} hypotheses found" /-- `guard_hyp_mod_implicit h : t` fails if the type of the hypothesis `h` is not definitionally equal to `t` modulo none transparency (i.e., unifying the implicit arguments modulo semireducible transparency). We use this tactic for writing tests. -/ meta def guard_hyp_mod_implicit (n : parse ident) (p : parse $ tk ":" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, e ← to_expr p, is_def_eq h e transparency.none /-- `guard_target_mod_implicit t` fails if the target of the main goal is not definitionally equal to `t` modulo none transparency (i.e., unifying the implicit arguments modulo semireducible transparency). We use this tactic for writing tests. -/ meta def guard_target_mod_implicit (p : parse texpr) : tactic unit := do tgt ← target, e ← to_expr p, is_def_eq tgt e transparency.none /-- Test that `t` is the tag of the main goal. -/ meta def guard_tags (tags : parse ident*) : tactic unit := do (t : list name) ← get_main_tag, guard (t = tags) /-- `guard_proof_term { t } e` applies tactic `t` and tests whether the resulting proof term unifies with `p`. -/ meta def guard_proof_term (t : itactic) (p : parse texpr) : itactic := do g :: _ ← get_goals, e ← to_expr p, t, g ← instantiate_mvars g, unify e g /-- `success_if_fail_with_msg { tac } msg` succeeds if the interactive tactic `tac` fails with error message `msg` (for test writing purposes). -/ meta def success_if_fail_with_msg (tac : tactic.interactive.itactic) := tactic.success_if_fail_with_msg tac /-- Get the field of the current goal. -/ meta def get_current_field : tactic name := do [_,field,str] ← get_main_tag, expr.const_name <$> resolve_name (field.update_prefix str) meta def field (n : parse ident) (tac : itactic) : tactic unit := do gs ← get_goals, ts ← gs.mmap get_tag, ([g],gs') ← pure $ (list.zip gs ts).partition (λ x, x.snd.nth 1 = some n), set_goals [g.1], tac, done, set_goals $ gs'.map prod.fst /-- `have_field`, used after `refine_struct _` poses `field` as a local constant with the type of the field of the current goal: ```lean refine_struct ({ .. } : semigroup α), { have_field, ... }, { have_field, ... }, ``` behaves like ```lean refine_struct ({ .. } : semigroup α), { have field := @semigroup.mul, ... }, { have field := @semigroup.mul_assoc, ... }, ``` -/ meta def have_field : tactic unit := propagate_tags $ get_current_field >>= mk_const >>= note `field none >> return () /-- `apply_field` functions as `have_field, apply field, clear field` -/ meta def apply_field : tactic unit := propagate_tags $ get_current_field >>= applyc add_tactic_doc { name := "refine_struct", category := doc_category.tactic, decl_names := [`tactic.interactive.refine_struct, `tactic.interactive.apply_field, `tactic.interactive.have_field], tags := ["structures"], inherit_description_from := `tactic.interactive.refine_struct } /-- `apply_rules hs with attrs n` applies the list of lemmas `hs` and all lemmas tagged with an attribute from the list `attrs`, as well as the `assumption` tactic on the first goal and the resulting subgoals, iteratively, at most `n` times. `n` is optional, equal to 50 by default. You can pass an `apply_cfg` option argument as `apply_rules hs n opt`. (A typical usage would be with `apply_rules hs n { md := reducible })`, which asks `apply_rules` to not unfold `semireducible` definitions (i.e. most) when checking if a lemma matches the goal.) For instance: ```lean @[user_attribute] meta def mono_rules : user_attribute := { name := `mono_rules, descr := "lemmas usable to prove monotonicity" } attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right lemma my_test {a b c d e : real} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := -- any of the following lines solve the goal: add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3 by apply_rules [add_le_add, mul_le_mul_of_nonneg_right] by apply_rules with mono_rules by apply_rules [add_le_add] with mono_rules ``` -/ meta def apply_rules (args : parse opt_pexpr_list) (attrs : parse with_ident_list) (n : nat := 50) (opt : apply_cfg := {}) : tactic unit := tactic.apply_rules args attrs n opt add_tactic_doc { name := "apply_rules", category := doc_category.tactic, decl_names := [`tactic.interactive.apply_rules], tags := ["lemma application"] } meta def return_cast (f : option expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) (e x x' eq_h : expr) : tactic (option (expr × expr) × list (expr × expr × expr)) := (do guard (¬ e.has_var), unify x x', u ← mk_meta_univ, f ← f <|> mk_mapp ``_root_.id [(expr.sort u : expr)], t' ← infer_type e, some (f',t) ← pure t | return (some (f,t'), (e,x',eq_h) :: es), infer_type e >>= is_def_eq t, unify f f', return (some (f,t), (e,x',eq_h) :: es)) <|> return (t, es) meta def list_cast_of_aux (x : expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) : expr → tactic (option (expr × expr) × list (expr × expr × expr)) | e@`(cast %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mp %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mpr %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast none t es e x x' | e@`(@eq.subst %%α %%p %%a %%b %%eq_h %%x') := return_cast p t es e x x' eq_h | e@`(@eq.substr %%α %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x' | e@`(@eq.rec %%α %%a %%f %%x' _ %%eq_h) := return_cast f t es e x x' eq_h | e@`(@eq.rec_on %%α %%a %%f %%b %%eq_h %%x') := return_cast f t es e x x' eq_h | e := return (t,es) meta def list_cast_of (x tgt : expr) : tactic (list (expr × expr × expr)) := (list.reverse ∘ prod.snd) <$> tgt.mfold (none, []) (λ e i es, list_cast_of_aux x es.1 es.2 e) private meta def h_generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `heq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def h_generalize_arg_p : parser (pexpr × name) := with_desc "expr == id" $ parser.pexpr 0 >>= h_generalize_arg_p_aux /-- `h_generalize Hx : e == x` matches on `cast _ e` in the goal and replaces it with `x`. It also adds `Hx : e == x` as an assumption. If `cast _ e` appears multiple times (not necessarily with the same proof), they are all replaced by `x`. `cast` `eq.mp`, `eq.mpr`, `eq.subst`, `eq.substr`, `eq.rec` and `eq.rec_on` are all treated as casts. - `h_generalize Hx : e == x with h` adds hypothesis `α = β` with `e : α, x : β`; - `h_generalize Hx : e == x with _` chooses automatically chooses the name of assumption `α = β`; - `h_generalize! Hx : e == x` reverts `Hx`; - when `Hx` is omitted, assumption `Hx : e == x` is not added. -/ meta def h_generalize (rev : parse (tk "!")?) (h : parse ident_?) (_ : parse (tk ":")) (arg : parse h_generalize_arg_p) (eqs_h : parse ( (tk "with" *> pure <$> ident_) <|> pure [])) : tactic unit := do let (e,n) := arg, let h' := if h = `_ then none else h, h' ← (h' : tactic name) <|> get_unused_name ("h" ++ n.to_string : string), e ← to_expr e, tgt ← target, ((e,x,eq_h)::es) ← list_cast_of e tgt | fail "no cast found", interactive.generalize h' () (to_pexpr e, n), asm ← get_local h', v ← get_local n, hs ← es.mmap (λ ⟨e,_⟩, mk_app `eq [e,v]), (eqs_h.zip [e]).mmap' (λ ⟨h,e⟩, do h ← if h ≠ `_ then pure h else get_unused_name `h, () <$ note h none eq_h ), hs.mmap' (λ h, do h' ← assert `h h, tactic.exact asm, try (rewrite_target h'), tactic.clear h' ), when h.is_some (do (to_expr ``(heq_of_eq_rec_left %%eq_h %%asm) <|> to_expr ``(heq_of_cast_eq %%eq_h %%asm)) >>= note h' none >> pure ()), tactic.clear asm, when rev.is_some (interactive.revert [n]) add_tactic_doc { name := "h_generalize", category := doc_category.tactic, decl_names := [`tactic.interactive.h_generalize], tags := ["context management"] } /-- Tests whether `t` is definitionally equal to `p`. The difference with `guard_expr_eq` is that this uses definitional equality instead of alpha-equivalence. -/ meta def guard_expr_eq' (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, is_def_eq t e /-- `guard_target' t` fails if the target of the main goal is not definitionally equal to `t`. We use this tactic for writing tests. The difference with `guard_target` is that this uses definitional equality instead of alpha-equivalence. -/ meta def guard_target' (p : parse texpr) : tactic unit := do t ← target, guard_expr_eq' t p add_tactic_doc { name := "guard_target'", category := doc_category.tactic, decl_names := [`tactic.interactive.guard_target'], tags := ["testing"] } /-- Tries to solve the goal using a canonical proof of `true` or the `reflexivity` tactic. Unlike `trivial` or `trivial'`, does not the `contradiction` tactic. -/ meta def triv : tactic unit := tactic.triv <|> tactic.reflexivity <|> fail "triv tactic failed" add_tactic_doc { name := "triv", category := doc_category.tactic, decl_names := [`tactic.interactive.triv], tags := ["finishing"] } /-- A weaker version of `trivial` that tries to solve the goal using a canonical proof of `true` or the `reflexivity` tactic (unfolding only `reducible` constants, so can fail faster than `trivial`), and otherwise tries the `contradiction` tactic. -/ meta def trivial' : tactic unit := tactic.triv' <|> tactic.reflexivity reducible <|> tactic.contradiction <|> fail "trivial' tactic failed" add_tactic_doc { name := "trivial'", category := doc_category.tactic, decl_names := [`tactic.interactive.trivial'], tags := ["finishing"] } /-- Similar to `existsi`. `use x` will instantiate the first term of an `∃` or `Σ` goal with `x`. It will then try to close the new goal using `trivial'`, or try to simplify it by applying `exists_prop`. Unlike `existsi`, `x` is elaborated with respect to the expected type. `use` will alternatively take a list of terms `[x0, ..., xn]`. `use` will work with constructors of arbitrary inductive types. Examples: ```lean example (α : Type) : ∃ S : set α, S = S := by use ∅ example : ∃ x : ℤ, x = x := by use 42 example : ∃ n > 0, n = n := begin use 1, -- goal is now 1 > 0 ∧ 1 = 1, whereas it would be ∃ (H : 1 > 0), 1 = 1 after existsi 1. exact ⟨zero_lt_one, rfl⟩, end example : ∃ a b c : ℤ, a + b + c = 6 := by use [1, 2, 3] example : ∃ p : ℤ × ℤ, p.1 = 1 := by use ⟨1, 42⟩ example : Σ x y : ℤ, (ℤ × ℤ) × ℤ := by use [1, 2, 3, 4, 5] inductive foo | mk : ℕ → bool × ℕ → ℕ → foo example : foo := by use [100, tt, 4, 3] ``` -/ meta def use (l : parse pexpr_list_or_texpr) : tactic unit := focus1 $ tactic.use l; try (trivial' <|> (do `(Exists %%p) ← target, to_expr ``(exists_prop.mpr) >>= tactic.apply >> skip)) add_tactic_doc { name := "use", category := doc_category.tactic, decl_names := [`tactic.interactive.use, `tactic.interactive.existsi], tags := ["logic"], inherit_description_from := `tactic.interactive.use } /-- `clear_aux_decl` clears every `aux_decl` in the local context for the current goal. This includes the induction hypothesis when using the equation compiler and `_let_match` and `_fun_match`. It is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these auxiliary declarations, and produce an error saying the recursion is not well founded. ```lean example (n m : ℕ) (h₁ : n = m) (h₂ : ∃ a : ℕ, a = n ∧ a = m) : 2 * m = 2 * n := let ⟨a, ha⟩ := h₂ in begin clear_aux_decl, -- subst will fail without this line subst h₁ end example (x y : ℕ) (h₁ : ∃ n : ℕ, n * 1 = 2) (h₂ : 1 + 1 = 2 → x * 1 = y) : x = y := let ⟨n, hn⟩ := h₁ in begin clear_aux_decl, -- finish produces an error without this line finish end ``` -/ meta def clear_aux_decl : tactic unit := tactic.clear_aux_decl add_tactic_doc { name := "clear_aux_decl", category := doc_category.tactic, decl_names := [`tactic.interactive.clear_aux_decl, `tactic.clear_aux_decl], tags := ["context management"], inherit_description_from := `tactic.interactive.clear_aux_decl } meta def loc.get_local_pp_names : loc → tactic (list name) | loc.wildcard := list.map expr.local_pp_name <$> local_context | (loc.ns l) := return l.reduce_option meta def loc.get_local_uniq_names (l : loc) : tactic (list name) := list.map expr.local_uniq_name <$> l.get_locals /-- The logic of `change x with y at l` fails when there are dependencies. `change'` mimics the behavior of `change`, except in the case of `change x with y at l`. In this case, it will correctly replace occurences of `x` with `y` at all possible hypotheses in `l`. As long as `x` and `y` are defeq, it should never fail. -/ meta def change' (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit | none (loc.ns [none]) := do e ← i_to_expr q, change_core e none | none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh) | none _ := fail "change-at does not support multiple locations" | (some w) l := do l' ← loc.get_local_pp_names l, l'.mmap' (λ e, try (change_with_at q w e)), when l.include_goal $ change q w (loc.ns [none]) add_tactic_doc { name := "change'", category := doc_category.tactic, decl_names := [`tactic.interactive.change', `tactic.interactive.change], tags := ["renaming"], inherit_description_from := `tactic.interactive.change' } private meta def opt_dir_with : parser (option (bool × name)) := (tk "with" *> ((λ arrow h, (option.is_some arrow, h)) <$> (tk "<-")? <*> ident))? /-- `set a := t with h` is a variant of `let a := t`. It adds the hypothesis `h : a = t` to the local context and replaces `t` with `a` everywhere it can. `set a := t with ←h` will add `h : t = a` instead. `set! a := t with h` does not do any replacing. ```lean example (x : ℕ) (h : x = 3) : x + x + x = 9 := begin set y := x with ←h_xy, /- x : ℕ, y : ℕ := x, h_xy : x = y, h : y = 3 ⊢ y + y + y = 9 -/ end ``` -/ meta def set (h_simp : parse (tk "!")?) (a : parse ident) (tp : parse ((tk ":") *> texpr)?) (_ : parse (tk ":=")) (pv : parse texpr) (rev_name : parse opt_dir_with) := do tp ← i_to_expr $ tp.get_or_else pexpr.mk_placeholder, pv ← to_expr ``(%%pv : %%tp), tp ← instantiate_mvars tp, definev a tp pv, when h_simp.is_none $ change' ``(%%pv) (some (expr.const a [])) $ interactive.loc.wildcard, match rev_name with | some (flip, id) := do nv ← get_local a, mk_app `eq (cond flip [pv, nv] [nv, pv]) >>= assert id, reflexivity | none := skip end add_tactic_doc { name := "set", category := doc_category.tactic, decl_names := [`tactic.interactive.set], tags := ["context management"] } /-- `clear_except h₀ h₁` deletes all the assumptions it can except for `h₀` and `h₁`. -/ meta def clear_except (xs : parse ident *) : tactic unit := do n ← xs.mmap (try_core ∘ get_local) >>= revert_lst ∘ list.filter_map id, ls ← local_context, ls.reverse.mmap' $ try ∘ tactic.clear, intron_no_renames n add_tactic_doc { name := "clear_except", category := doc_category.tactic, decl_names := [`tactic.interactive.clear_except], tags := ["context management"] } meta def format_names (ns : list name) : format := format.join $ list.intersperse " " (ns.map to_fmt) private meta def indent_bindents (l r : string) : option (list name) → expr → tactic format | none e := do e ← pp e, pformat!"{l}{format.nest l.length e}{r}" | (some ns) e := do e ← pp e, let ns := format_names ns, let margin := l.length + ns.to_string.length + " : ".length, pformat!"{l}{ns} : {format.nest margin e}{r}" private meta def format_binders : list name × binder_info × expr → tactic format | (ns, binder_info.default, t) := indent_bindents "(" ")" ns t | (ns, binder_info.implicit, t) := indent_bindents "{" "}" ns t | (ns, binder_info.strict_implicit, t) := indent_bindents "⦃" "⦄" ns t | ([n], binder_info.inst_implicit, t) := if "_".is_prefix_of n.to_string then indent_bindents "[" "]" none t else indent_bindents "[" "]" [n] t | (ns, binder_info.inst_implicit, t) := indent_bindents "[" "]" ns t | (ns, binder_info.aux_decl, t) := indent_bindents "(" ")" ns t private meta def partition_vars' (s : name_set) : list expr → list expr → list expr → tactic (list expr × list expr) | [] as bs := pure (as.reverse, bs.reverse) | (x :: xs) as bs := do t ← infer_type x, if t.has_local_in s then partition_vars' xs as (x :: bs) else partition_vars' xs (x :: as) bs private meta def partition_vars : tactic (list expr × list expr) := do ls ← local_context, partition_vars' (name_set.of_list $ ls.map expr.local_uniq_name) ls [] [] /-- Format the current goal as a stand-alone example. Useful for testing tactics or creating [minimal working examples](https://leanprover-community.github.io/mwe.html). * `extract_goal`: formats the statement as an `example` declaration * `extract_goal my_decl`: formats the statement as a `lemma` or `def` declaration called `my_decl` * `extract_goal with i j k:` only use local constants `i`, `j`, `k` in the declaration Examples: ```lean example (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := begin extract_goal, -- prints: -- example (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := -- begin -- admit, -- end extract_goal my_lemma -- prints: -- lemma my_lemma (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := -- begin -- admit, -- end end example {i j k x y z w p q r m n : ℕ} (h₀ : i ≤ j) (h₁ : j ≤ k) (h₁ : k ≤ p) (h₁ : p ≤ q) : i ≤ k := begin extract_goal my_lemma, -- prints: -- lemma my_lemma {i j k x y z w p q r m n : ℕ} -- (h₀ : i ≤ j) -- (h₁ : j ≤ k) -- (h₁ : k ≤ p) -- (h₁ : p ≤ q) : -- i ≤ k := -- begin -- admit, -- end extract_goal my_lemma with i j k -- prints: -- lemma my_lemma {p i j k : ℕ} -- (h₀ : i ≤ j) -- (h₁ : j ≤ k) -- (h₁ : k ≤ p) : -- i ≤ k := -- begin -- admit, -- end end example : true := begin let n := 0, have m : ℕ, admit, have k : fin n, admit, have : n + m + k.1 = 0, extract_goal, -- prints: -- example (m : ℕ) : let n : ℕ := 0 in ∀ (k : fin n), n + m + k.val = 0 := -- begin -- intros n k, -- admit, -- end end ``` -/ meta def extract_goal (print_use : parse $ (tk "!" *> pure tt) <|> pure ff) (n : parse ident?) (vs : parse (tk "with" *> ident*)?) : tactic unit := do tgt ← target, solve_aux tgt $ do { ((cxt₀,cxt₁,ls,tgt),_) ← solve_aux tgt $ do { vs.mmap clear_except, ls ← local_context, ls ← ls.mfilter $ succeeds ∘ is_local_def, n ← revert_lst ls, (c₀,c₁) ← partition_vars, tgt ← target, ls ← intron' n, pure (c₀,c₁,ls,tgt) }, is_prop ← is_prop tgt, let title := match n, is_prop with | none, _ := to_fmt "example" | (some n), tt := format!"lemma {n}" | (some n), ff := format!"def {n}" end, cxt₀ ← compact_decl cxt₀ >>= list.mmap format_binders, cxt₁ ← compact_decl cxt₁ >>= list.mmap format_binders, stmt ← pformat!"{tgt} :=", let fmt := format.group $ format.nest 2 $ title ++ cxt₀.foldl (λ acc x, acc ++ format.group (format.line ++ x)) "" ++ format.join (list.map (λ x, format.line ++ x) cxt₁) ++ " :" ++ format.line ++ stmt, trace $ fmt.to_string $ options.mk.set_nat `pp.width 80, let var_names := format.intercalate " " $ ls.map (to_fmt ∘ local_pp_name), let call_intron := if ls.empty then to_fmt "" else format!"\n intros {var_names},", trace!"begin{call_intron}\n admit,\nend\n" }, skip add_tactic_doc { name := "extract_goal", category := doc_category.tactic, decl_names := [`tactic.interactive.extract_goal], tags := ["goal management", "proof extraction", "debugging"] } /-- `inhabit α` tries to derive a `nonempty α` instance and then upgrades this to an `inhabited α` instance. If the target is a `Prop`, this is done constructively; otherwise, it uses `classical.choice`. ```lean example (α) [nonempty α] : ∃ a : α, true := begin inhabit α, existsi default, trivial end ``` -/ meta def inhabit (t : parse parser.pexpr) (inst_name : parse ident?) : tactic unit := do ty ← i_to_expr t, nm ← returnopt inst_name <|> get_unused_name `inst, tgt ← target, tgt_is_prop ← is_prop tgt, if tgt_is_prop then do decorate_error "could not infer nonempty instance:" $ mk_mapp ``nonempty.elim_to_inhabited [ty, none, tgt] >>= tactic.apply, introI nm else do decorate_error "could not infer nonempty instance:" $ mk_mapp ``classical.inhabited_of_nonempty' [ty, none] >>= note nm none, resetI add_tactic_doc { name := "inhabit", category := doc_category.tactic, decl_names := [`tactic.interactive.inhabit], tags := ["context management", "type class"] } /-- `revert_deps n₁ n₂ ...` reverts all the hypotheses that depend on one of `n₁, n₂, ...` It does not revert `n₁, n₂, ...` themselves (unless they depend on another `nᵢ`). -/ meta def revert_deps (ns : parse ident*) : tactic unit := propagate_tags $ ns.mmap get_local >>= revert_reverse_dependencies_of_hyps >> skip add_tactic_doc { name := "revert_deps", category := doc_category.tactic, decl_names := [`tactic.interactive.revert_deps], tags := ["context management", "goal management"] } /-- `revert_after n` reverts all the hypotheses after `n`. -/ meta def revert_after (n : parse ident) : tactic unit := propagate_tags $ get_local n >>= tactic.revert_after >> skip add_tactic_doc { name := "revert_after", category := doc_category.tactic, decl_names := [`tactic.interactive.revert_after], tags := ["context management", "goal management"] } /-- Reverts all local constants on which the target depends (recursively). -/ meta def revert_target_deps : tactic unit := propagate_tags $ tactic.revert_target_deps >> skip add_tactic_doc { name := "revert_target_deps", category := doc_category.tactic, decl_names := [`tactic.interactive.revert_target_deps], tags := ["context management", "goal management"] } /-- `clear_value n₁ n₂ ...` clears the bodies of the local definitions `n₁, n₂ ...`, changing them into regular hypotheses. A hypothesis `n : α := t` is changed to `n : α`. -/ meta def clear_value (ns : parse ident*) : tactic unit := propagate_tags $ ns.reverse.mmap get_local >>= tactic.clear_value add_tactic_doc { name := "clear_value", category := doc_category.tactic, decl_names := [`tactic.interactive.clear_value], tags := ["context management"] } /-- `generalize' : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type. `generalize' h : e = x` in addition registers the hypothesis `h : e = x`. `generalize'` is similar to `generalize`. The difference is that `generalize' : e = x` also succeeds when `e` does not occur in the goal. It is similar to `set`, but the resulting hypothesis `x` is not a local definition. -/ meta def generalize' (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) : tactic unit := propagate_tags $ do let (p, x) := p, e ← i_to_expr p, some h ← pure h | tactic.generalize' e x >> skip, -- `h` is given, the regular implementation of `generalize` works. tgt ← target, tgt' ← do { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize e x >> target), to_expr ``(Π x, %%e = x → %%(tgt'.binding_body.lift_vars 0 1)) } <|> to_expr ``(Π x, %%e = x → %%tgt), t ← assert h tgt', swap, exact ``(%%t %%e rfl), intro x, intro h add_tactic_doc { name := "generalize'", category := doc_category.tactic, decl_names := [`tactic.interactive.generalize'], tags := ["context management"] } /-- If the expression `q` is a local variable with type `x = t` or `t = x`, where `x` is a local constant, `tactic.interactive.subst' q` substitutes `x` by `t` everywhere in the main goal and then clears `q`. If `q` is another local variable, then we find a local constant with type `q = t` or `t = q` and substitute `t` for `q`. Like `tactic.interactive.subst`, but fails with a nicer error message if the substituted variable is a local definition. It is trickier to fix this in core, since `tactic.is_local_def` is in mathlib. -/ meta def subst' (q : parse texpr) : tactic unit := do i_to_expr q >>= tactic.subst' >> try (tactic.reflexivity reducible) add_tactic_doc { name := "subst'", category := doc_category.tactic, decl_names := [`tactic.interactive.subst'], tags := ["context management"] } end interactive end tactic
e60c8d703a9431197611e82a6a19f5ef17da056d
26ac254ecb57ffcb886ff709cf018390161a9225
/src/topology/metric_space/emetric_space.lean
d83846b2b503882efd45652d8cf01209045d3e24
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
40,065
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import data.real.ennreal import topology.uniform_space.uniform_embedding import topology.uniform_space.pi import topology.uniform_space.uniform_convergence /-! # Extended metric spaces This file is devoted to the definition and study of `emetric_spaces`, i.e., metric spaces in which the distance is allowed to take the value ∞. This extended distance is called `edist`, and takes values in `ennreal`. Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity The class `emetric_space` therefore extends `uniform_space` (and `topological_space`). -/ open set filter classical noncomputable theory open_locale uniformity topological_space big_operators filter universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Characterizing uniformities associated to a (generalized) distance function `D` in terms of the elements of the uniformity. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>z, 𝓟 {p:α×α | D p.1 p.2 < ε} := le_antisymm (le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩) (λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in mem_infi_sets ε $ mem_infi_sets ε0 $ mem_principal_sets.2 $ λ ⟨a, b⟩, h) class has_edist (α : Type*) := (edist : α → α → ennreal) export has_edist (edist) /-- Creating a uniform space from an extended distance. -/ def uniform_space_of_edist (edist : α → α → ennreal) (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, have (2 : ennreal) = (2 : ℕ) := by simp, have A : 0 < ε / 2 := ennreal.div_pos_iff.2 ⟨ne_of_gt h, by { convert ennreal.nat_ne_top 2 }⟩, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets A (subset.refl _)) $ have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε, from assume a b c hac hcb, calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _ ... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb ... = ε : by rw [ennreal.add_halves], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [edist_comm] } section prio set_option default_priority 100 -- see Note [default priority] -- the uniform structure is embedded in the emetric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- Extended metric spaces, with an extended distance `edist` possibly taking the value ∞ Each emetric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating an `emetric_space` structure, the uniformity fields are not necessary, they will be filled in by default. There is a default value for the uniformity, that can be substituted in cases of interest, for instance when instantiating an `emetric_space` structure on a product. Continuity of `edist` is proved in `topology.instances.ennreal` -/ @[nolint ge_or_gt] -- see Note [nolint_ge] class emetric_space (α : Type u) extends has_edist α : Type u := (edist_self : ∀ x : α, edist x x = 0) (eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) (to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle) (uniformity_edist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} . control_laws_tac) end prio /- emetric spaces are less common than metric spaces. Therefore, we work in a dedicated namespace, while notions associated to metric spaces are mostly in the root namespace. -/ variables [emetric_space α] @[priority 100] -- see Note [lower instance priority] instance emetric_space.to_uniform_space' : uniform_space α := emetric_space.to_uniform_space export emetric_space (edist_self eq_of_edist_eq_zero edist_comm edist_triangle) attribute [simp] edist_self /-- Characterize the equality of points by the vanishing of their extended distance -/ @[simp] theorem edist_eq_zero {x y : α} : edist x y = 0 ↔ x = y := iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _) @[simp] theorem zero_eq_edist {x y : α} : 0 = edist x y ↔ x = y := iff.intro (assume h, eq_of_edist_eq_zero (h.symm)) (assume : x = y, this ▸ (edist_self _).symm) theorem edist_le_zero {x y : α} : (edist x y ≤ 0) ↔ x = y := le_zero_iff_eq.trans edist_eq_zero /-- Triangle inequality for the extended distance -/ theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y := by rw edist_comm z; apply edist_triangle theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z := by rw edist_comm y; apply edist_triangle lemma edist_triangle4 (x y z t : α) : edist x t ≤ edist x y + edist y z + edist z t := calc edist x t ≤ edist x z + edist z t : edist_triangle x z t ... ≤ (edist x y + edist y z) + edist z t : add_le_add_right (edist_triangle x y z) _ /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, edist (f i) (f (i + 1)) := begin revert n, refine nat.le_induction _ _, { simp only [finset.sum_empty, finset.Ico.self_eq_empty, edist_self], -- TODO: Why doesn't Lean close this goal automatically? `apply le_refl` fails too. exact le_refl (0:ennreal) }, { assume n hn hrec, calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _ ... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec (le_refl _) ... = ∑ i in finset.Ico m (n+1), _ : by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) : edist (f 0) (f n) ≤ ∑ i in finset.range n, edist (f i) (f (i + 1)) := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_edist f (nat.zero_le n) /-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ennreal} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i := le_trans (edist_le_Ico_sum_edist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2 /-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ennreal} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f 0) (f n) ≤ ∑ i in finset.range n, d i := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd) /-- Two points coincide if their distance is `< ε` for all positive ε -/ theorem eq_of_forall_edist_le {x y : α} (h : ∀ε > 0, edist x y ≤ ε) : x = y := eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h) /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} := emetric_space.uniformity_edist theorem uniformity_basis_edist : (𝓤 α).has_basis (λ ε : ennreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := (@uniformity_edist α _).symm ▸ has_basis_binfi_principal (λ r hr p hp, ⟨min r p, lt_min hr hp, λ x hx, lt_of_lt_of_le hx (min_le_left _ _), λ x hx, lt_of_lt_of_le hx (min_le_right _ _)⟩) ⟨1, ennreal.zero_lt_one⟩ /-- Characterization of the elements of the uniformity in terms of the extended distance -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := uniformity_basis_edist.mem_uniformity_iff /-- Given `f : β → ennreal`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist`, `uniformity_basis_edist'`, `uniformity_basis_edist_nnreal`, and `uniformity_basis_edist_inv_nat`. -/ protected theorem emetric.mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ennreal} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 < f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases hf ε ε₀ with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end /-- Given `f : β → ennreal`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist_le` and `uniformity_basis_edist_le'`. -/ protected theorem emetric.mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ennreal} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases dense ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x hx, H (le_of_lt hx)⟩ } end theorem uniformity_basis_edist_le : (𝓤 α).has_basis (λ ε : ennreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_edist' (ε' : ennreal) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ennreal, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := dense hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_le' (ε' : ennreal) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ennreal, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := dense hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_nnreal : (𝓤 α).has_basis (λ ε : nnreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, ennreal.coe_pos.2) (λ ε ε₀, let ⟨δ, hδ⟩ := ennreal.lt_iff_exists_nnreal_btwn.1 ε₀ in ⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩) theorem uniformity_basis_edist_inv_nat : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < (↑n)⁻¹}) := emetric.mk_uniformity_basis (λ n _, ennreal.inv_pos.2 $ ennreal.nat_ne_top n) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_nat_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) /-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/ theorem edist_mem_uniformity {ε:ennreal} (ε0 : 0 < ε) : {p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩ namespace emetric theorem uniformity_has_countable_basis : is_countably_generated (𝓤 α) := is_countably_generated_of_seq ⟨_, uniformity_basis_edist_inv_nat.eq_infi⟩ /-- ε-δ characterization of uniform continuity on emetric spaces -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem uniform_continuous_iff [emetric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_iff uniformity_basis_edist /-- ε-δ characterization of uniform embeddings on emetric spaces -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem uniform_embedding_iff [emetric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem uniform_embedding_iff' [emetric_space β] {f : α → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ) := begin split, { assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : edist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : edist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end /-- ε-δ characterization of Cauchy sequences on emetric spaces -/ @[nolint ge_or_gt] -- see Note [nolint_ge] protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε := uniformity_basis_edist.cauchy_iff /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem complete_of_convergent_controlled_sequences (B : ℕ → ennreal) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := uniform_space.complete_of_convergent_controlled_sequences uniformity_has_countable_basis (λ n, {p:α×α | edist p.1 p.2 < B n}) (λ n, edist_mem_uniformity $ hB n) H /-- A sequentially complete emetric space is complete. -/ theorem complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := uniform_space.complete_of_cauchy_seq_tendsto uniformity_has_countable_basis /-- Expressing locally uniform convergence on a set using `edist`. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ nhds_within x s, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `edist`. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, edist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `edist`. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := by simp [← nhds_within_univ, ← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff] /-- Expressing uniform convergence using `edist`. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, edist (f x) (F n x) < ε := by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp } end emetric open emetric /-- An emetric space is separated -/ @[priority 100] -- see Note [lower instance priority] instance to_separated : separated_space α := separated_def.2 $ λ x y h, eq_of_forall_edist_le $ λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0)) /-- Auxiliary function to replace the uniformity on an emetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct an emetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def emetric_space.replace_uniformity {α} [U : uniform_space α] (m : emetric_space α) (H : @uniformity _ U = @uniformity _ emetric_space.to_uniform_space) : emetric_space α := { edist := @edist _ m.to_has_edist, edist_self := edist_self, eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@emetric_space.uniformity_edist α _) } /-- The extended metric induced by an injective function taking values in an emetric space. -/ def emetric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : emetric_space β) : emetric_space α := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h), edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Emetric space instance on subsets of emetric spaces -/ instance {α : Type*} {p : α → Prop} [t : emetric_space α] : emetric_space (subtype p) := t.induced coe (λ x y, subtype.ext_iff_val.2) /-- The extended distance on a subset of an emetric space is the restriction of the original distance, by definition -/ theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist (x : α) y := rfl /-- The product of two emetric spaces, with the max distance, is an extended metric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.emetric_space_max [emetric_space β] : emetric_space (α × β) := { edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_self := λ x, by simp, eq_of_edist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, have A : x.fst = y.fst := edist_le_zero.1 h₁, have B : x.snd = y.snd := edist_le_zero.1 h₂, exact prod.ext_iff.2 ⟨A, B⟩ end, edist_comm := λ x y, by simp [edist_comm], edist_triangle := λ x y z, max_le (le_trans (edist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (edist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), uniformity_edist := begin refine uniformity_prod.trans _, simp [emetric_space.uniformity_edist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.edist_eq [emetric_space β] (x y : α × β) : edist x y = max (edist x.1 y.1) (edist x.2 y.2) := rfl section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of emetric spaces, with the max distance, is still an emetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) := { edist := λ f g, finset.sup univ (λb, edist (f b) (g b)), edist_self := assume f, bot_unique $ finset.sup_le $ by simp, edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _, edist_triangle := assume f g h, begin simp only [finset.sup_le_iff], assume b hb, exact le_trans (edist_triangle _ (g b) _) (add_le_add (le_sup hb) (le_sup hb)) end, eq_of_edist_eq_zero := assume f g eq0, begin have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0, simp only [finset.sup_le_iff] at eq1, exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b), end, to_uniform_space := Pi.uniform_space _, uniformity_edist := begin simp only [Pi.uniformity, emetric_space.uniformity_edist, comap_infi, gt_iff_lt, preimage_set_of_eq, comap_principal], rw infi_comm, congr, funext ε, rw infi_comm, congr, funext εpos, change 0 < ε at εpos, simp [set.ext_iff, εpos] end } end pi namespace emetric variables {x y z : α} {ε ε₁ ε₂ : ennreal} {s : set α} /-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/ def ball (x : α) (ε : ennreal) : set α := {y | edist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw edist_comm; refl /-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/ def closed_ball (x : α) (ε : ennreal) := {y | edist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y, by simp; intros h; apply le_of_lt h theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := lt_of_le_of_lt (zero_le _) hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show edist x x < ε, by rw edist_self; assumption theorem mem_closed_ball_self : x ∈ closed_ball x ε := show edist x x ≤ ε, by rw edist_self; exact bot_le theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [edist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (edist_triangle_left x y z) (lt_of_lt_of_le (ennreal.add_lt_add h₁ h₂) h) theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y < ⊤) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, calc edist z y ≤ edist z x + edist x y : edist_triangle _ _ _ ... = edist x y + edist z x : add_comm _ _ ... < edist x y + ε₁ : (ennreal.add_lt_add_iff_left h').2 zx ... ≤ ε₂ : h @[nolint ge_or_gt] -- see Note [nolint_ge] theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := begin have : 0 < ε - edist y x := by simpa using h, refine ⟨ε - edist y x, this, ball_subset _ _⟩, { rw ennreal.add_sub_cancel_of_le (le_of_lt h), apply le_refl _}, { have : edist y x ≠ ⊤ := ne_top_of_lt h, apply lt_top_iff_ne_top.2 this } end theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 := eq_empty_iff_forall_not_mem.trans ⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))), λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩ /-- Relation “two points are at a finite edistance” is an equivalence relation. -/ def edist_lt_top_setoid : setoid α := { r := λ x y, edist x y < ⊤, iseqv := ⟨λ x, by { rw edist_self, exact ennreal.coe_lt_top }, λ x y h, by rwa edist_comm, λ x y z hxy hyz, lt_of_le_of_lt (edist_triangle x y z) (ennreal.add_lt_top.2 ⟨hxy, hyz⟩)⟩ } @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [emetric.ball_eq_empty_iff] theorem nhds_basis_eball : (𝓝 x).has_basis (λ ε:ennreal, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_edist theorem nhds_basis_closed_eball : (𝓝 x).has_basis (λ ε:ennreal, 0 < ε) (closed_ball x) := nhds_basis_uniformity uniformity_basis_edist_le @[nolint ge_or_gt] -- see Note [nolint_ge] theorem nhds_eq : 𝓝 x = (⨅ε>0, 𝓟 (ball x ε)) := nhds_basis_eball.eq_binfi @[nolint ge_or_gt] -- see Note [nolint_ge] theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_eball.mem_iff @[nolint ge_or_gt] -- see Note [nolint_ge] theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem is_closed_ball_top : is_closed (ball x ⊤) := is_open_iff.2 $ λ y hy, ⟨⊤, ennreal.coe_lt_top, subset_compl_iff_disjoint.2 $ ball_disjoint $ by { rw ennreal.top_add, exact le_of_not_lt hy }⟩ theorem ball_mem_nhds (x : α) {ε : ennreal} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := mem_nhds_sets is_open_ball (mem_ball_self ε0) /-- ε-characterization of the closure in emetric spaces -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem mem_closure_iff : x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε := (mem_closure_iff_nhds_basis nhds_basis_eball).trans $ by simp only [mem_ball, edist_comm x] @[nolint ge_or_gt] -- see Note [nolint_ge] theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, edist (u x) a < ε := nhds_basis_eball.tendsto_right_iff @[nolint ge_or_gt] -- see Note [nolint_ge] theorem tendsto_at_top [nonempty β] [semilattice_sup β] (u : β → α) {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_eball).trans $ by simp only [exists_prop, true_and, mem_Ici, mem_ball] /-- In an emetric space, Cauchy sequences are characterized by the fact that, eventually, the edistance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy_seq_iff [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u m) (u n) < ε := uniformity_basis_edist.cauchy_seq_iff /-- A variation around the emetric characterization of Cauchy sequences -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy_seq_iff' [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>(0 : ennreal), ∃N, ∀n≥N, edist (u n) (u N) < ε := uniformity_basis_edist.cauchy_seq_iff' /-- A variation of the emetric characterization of Cauchy sequences that deals with `nnreal` upper bounds. -/ theorem cauchy_seq_iff_nnreal [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ ε : nnreal, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u n) (u N) < ε := uniformity_basis_edist_nnreal.cauchy_seq_iff' @[nolint ge_or_gt] -- see Note [nolint_ge] theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem totally_bounded_iff' {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, _, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ section compact /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set -/ lemma countable_closure_of_compact {α : Type u} [emetric_space α] {s : set α} (hs : is_compact s) : ∃ t ⊆ s, (countable t ∧ s = closure t) := begin have A : ∀ (e:ennreal), e > 0 → ∃ t ⊆ s, (finite t ∧ s ⊆ (⋃x∈t, ball x e)) := totally_bounded_iff'.1 (compact_iff_totally_bounded_complete.1 hs).1, -- assume e, finite_cover_balls_of_compact hs, have B : ∀ (e:ennreal), ∃ t ⊆ s, finite t ∧ (e > 0 → s ⊆ (⋃x∈t, ball x e)), { intro e, cases le_or_gt e 0 with h, { exact ⟨∅, by finish⟩ }, { rcases A e h with ⟨s, ⟨finite_s, closure_s⟩⟩, existsi s, finish }}, /-The desired countable set is obtained by taking for each `n` the centers of a finite cover by balls of radius `1/n`, and then the union over `n`. -/ choose T T_in_s finite_T using B, let t := ⋃n:ℕ, T n⁻¹, have T₁ : t ⊆ s := begin apply Union_subset, assume n, apply T_in_s end, have T₂ : countable t := by finish [countable_Union, finite.countable], have T₃ : s ⊆ closure t, { intros x x_in_s, apply mem_closure_iff.2, intros ε εpos, rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 εpos) with ⟨n, hn⟩, have inv_n_pos : (0 : ennreal) < (n : ℕ)⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have C : x ∈ (⋃y∈ T (n : ℕ)⁻¹, ball y (n : ℕ)⁻¹) := mem_of_mem_of_subset x_in_s ((finite_T (n : ℕ)⁻¹).2 inv_n_pos), rcases mem_Union.1 C with ⟨y, _, ⟨y_in_T, rfl⟩, Dxy⟩, simp at Dxy, -- Dxy : edist x y < 1 / ↑n have : y ∈ t := mem_of_mem_of_subset y_in_T (by apply subset_Union (λ (n:ℕ), T (n : ℕ)⁻¹)), have : edist x y < ε := lt_trans Dxy hn, exact ⟨y, ‹y ∈ t›, ‹edist x y < ε›⟩ }, have T₄ : closure t ⊆ s := calc closure t ⊆ closure s : closure_mono T₁ ... = s : hs.is_closed.closure_eq, exact ⟨t, ⟨T₁, T₂, subset.antisymm T₃ T₄⟩⟩ end end compact section first_countable @[priority 100] -- see Note [lower instance priority] instance (α : Type u) [emetric_space α] : topological_space.first_countable_topology α := uniform_space.first_countable_topology uniformity_has_countable_basis end first_countable section second_countable open topological_space /-- A separable emetric space is second countable: one obtains a countable basis by taking the balls centered at points in a dense subset, and with rational radii. We do not register this as an instance, as there is already an instance going in the other direction from second countable spaces to separable spaces, and we want to avoid loops. -/ lemma second_countable_of_separable (α : Type u) [emetric_space α] [separable_space α] : second_countable_topology α := let ⟨S, ⟨S_countable, S_dense⟩⟩ := separable_space.exists_countable_closure_eq_univ in ⟨⟨⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, ⟨show countable ⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, { apply S_countable.bUnion, intros a aS, apply countable_Union, simp }, show uniform_space.to_topological_space = generate_from (⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}), { have A : ∀ (u : set α), (u ∈ ⋃x ∈ S, ⋃ (n : nat), ({ball x ((n : ennreal)⁻¹)} : set (set α))) → is_open u, { simp only [and_imp, exists_prop, set.mem_Union, set.mem_singleton_iff, exists_imp_distrib], intros u x hx i u_ball, rw [u_ball], exact is_open_ball }, have B : is_topological_basis (⋃x ∈ S, ⋃ (n : nat), ({ball x (n⁻¹)} : set (set α))), { refine is_topological_basis_of_open_of_nhds A (λa u au open_u, _), rcases is_open_iff.1 open_u a au with ⟨ε, εpos, εball⟩, have : ε / 2 > 0 := ennreal.half_pos εpos, /- The ball `ball a ε` is included in `u`. We need to find one of our balls `ball x (n⁻¹)` containing `a` and contained in `ball a ε`. For this, we take `n` larger than `2/ε`, and then `x` in `S` at distance at most `n⁻¹` of `a` -/ rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 (ennreal.half_pos εpos)) with ⟨n, εn⟩, have : (0 : ennreal) < n⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have : (a : α) ∈ closure (S : set α) := by rw [S_dense]; simp, rcases mem_closure_iff.1 this _ ‹(0 : ennreal) < n⁻¹› with ⟨x, xS, xdist⟩, existsi ball x (↑n)⁻¹, have I : ball x (n⁻¹) ⊆ ball a ε := λy ydist, calc edist y a = edist a y : edist_comm _ _ ... ≤ edist a x + edist y x : edist_triangle_right _ _ _ ... < n⁻¹ + n⁻¹ : ennreal.add_lt_add xdist ydist ... < ε/2 + ε/2 : ennreal.add_lt_add εn εn ... = ε : ennreal.add_halves _, simp only [emetric.mem_ball, exists_prop, set.mem_Union, set.mem_singleton_iff], exact ⟨⟨x, ⟨xS, ⟨n, rfl⟩⟩⟩, ⟨by simpa, subset.trans I εball⟩⟩ }, exact B.2.2 }⟩⟩⟩ end second_countable section diam /-- The diameter of a set in an emetric space, named `emetric.diam` -/ def diam (s : set α) := ⨆ (x ∈ s) (y ∈ s), edist x y lemma diam_le_iff_forall_edist_le {d : ennreal} : diam s ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist x y ≤ d := by simp only [diam, supr_le_iff] /-- If two points belong to some set, their edistance is bounded by the diameter of the set -/ lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s := diam_le_iff_forall_edist_le.1 (le_refl _) x hx y hy /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_edist_le {d : ennreal} (h : ∀ (x ∈ s) (y ∈ s), edist x y ≤ d) : diam s ≤ d := diam_le_iff_forall_edist_le.2 h /-- The diameter of a subsingleton vanishes. -/ lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := le_zero_iff_eq.1 $ diam_le_of_forall_edist_le $ λ x hx y hy, (hs hx hy).symm ▸ edist_self y ▸ le_refl _ /-- The diameter of the empty set vanishes -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- The diameter of a singleton vanishes -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton lemma diam_eq_zero_iff : diam s = 0 ↔ s.subsingleton := ⟨λ h x hx y hy, edist_le_zero.1 $ h ▸ edist_le_diam_of_mem hx hy, diam_subsingleton⟩ lemma diam_pos_iff : 0 < diam s ↔ ∃ (x ∈ s) (y ∈ s), x ≠ y := begin have := not_congr (@diam_eq_zero_iff _ _ s), dunfold set.subsingleton at this, push_neg at this, simpa only [zero_lt_iff_ne_zero, exists_prop] using this end lemma diam_insert : diam (insert x s) = max (⨆ y ∈ s, edist x y) (diam s) := eq_of_forall_ge_iff $ λ d, by simp only [diam_le_iff_forall_edist_le, ball_insert_iff, edist_self, edist_comm x, max_le_iff, supr_le_iff, zero_le, true_and, forall_and_distrib, and_self, ← and_assoc] lemma diam_pair : diam ({x, y} : set α) = edist x y := by simp only [supr_singleton, diam_insert, diam_singleton, ennreal.max_zero_right] lemma diam_triple : diam ({x, y, z} : set α) = max (max (edist x y) (edist x z)) (edist y z) := by simp only [diam_insert, supr_insert, supr_singleton, diam_singleton, ennreal.max_zero_right, ennreal.sup_eq_max] /-- The diameter is monotonous with respect to inclusion -/ lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t := diam_le_of_forall_edist_le $ λ x hx y hy, edist_le_diam_of_mem (h hx) (h hy) /-- The diameter of a union is controlled by the diameter of the sets, and the edistance between two points in the sets. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t := begin have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _ ... ≤ diam s + edist x y + diam t : add_le_add (add_le_add (edist_le_diam_of_mem ha xs) (le_refl _)) (edist_le_diam_of_mem yt hb), refine diam_le_of_forall_edist_le (λa ha b hb, _), cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b ... ≤ diam s + (edist x y + diam t) : le_add_right (le_refl _) ... = diam s + edist x y + diam t : by simp only [add_comm, eq_self_iff_true, add_left_comm] }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [edist_comm] at Z }, { calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b ... ≤ (diam s + edist x y) + diam t : le_add_left (le_refl _) } end lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := let ⟨x, ⟨xs, xt⟩⟩ := h in by simpa using diam_union xs xt lemma diam_closed_ball {r : ennreal} : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_edist_le $ λa ha b hb, calc edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add ha hb ... = 2 * r : by simp [mul_two, mul_comm] lemma diam_ball {r : ennreal} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball end diam end emetric --namespace
7029346f431509aaa60a4fe4eeecc8f47d43bd51
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/order/monoid/cancel/basic.lean
e0c897c779871d78a66d8bb8c83457cb800c8904
[ "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,236
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.order.monoid.basic import algebra.order.monoid.cancel.defs /-! # Basic results on ordered cancellative monoids. We pull back ordered cancellative monoids along injective maps. -/ universe u variables {α : Type u} open function section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid α] /-- Pullback an `ordered_cancel_comm_monoid` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.ordered_cancel_add_comm_monoid "Pullback an `ordered_cancel_add_comm_monoid` under an injective map."] def function.injective.ordered_cancel_comm_monoid {β : Type*} [has_one β] [has_mul β] [has_pow β ℕ] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) : ordered_cancel_comm_monoid β := { le_of_mul_le_mul_left := λ a b c (bc : f (a * b) ≤ f (a * c)), (mul_le_mul_iff_left (f a)).mp (by rwa [← mul, ← mul]), ..hf.ordered_comm_monoid f one mul npow } end ordered_cancel_comm_monoid section linear_ordered_cancel_comm_monoid variables [linear_ordered_cancel_comm_monoid α] /-- Pullback a `linear_ordered_cancel_comm_monoid` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.linear_ordered_cancel_add_comm_monoid "Pullback a `linear_ordered_cancel_add_comm_monoid` under an injective map."] def function.injective.linear_ordered_cancel_comm_monoid {β : Type*} [has_one β] [has_mul β] [has_pow β ℕ] [has_sup β] [has_inf β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (hsup : ∀ x y, f (x ⊔ y) = max (f x) (f y)) (hinf : ∀ x y, f (x ⊓ y) = min (f x) (f y)) : linear_ordered_cancel_comm_monoid β := { ..hf.linear_ordered_comm_monoid f one mul npow hsup hinf, ..hf.ordered_cancel_comm_monoid f one mul npow } end linear_ordered_cancel_comm_monoid
1ac41a0355a9e9bf7fa49e19c8a5dea49c96313d
968e2f50b755d3048175f176376eff7139e9df70
/examples/pred_logic/unnamed_288.lean
eda77446f46c2ff17f276bb37a2f8a948249643f
[]
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
248
lean
variables (U : Type*) (P : U → Prop) (u : U) -- BEGIN example (h : ∀ x, P x) : P u := begin specialize h u, -- By for all elimination on `h` and `u`, we have `h : P u` show P u, from h, -- We show `P u` by reiteration on `h`. end -- END
75558cdb210ac17c8fa4f987b2fef94f3a77220f
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/linear_algebra/finite_dimensional.lean
220da0dab679b4ab5305e01ec1a546327a292fc5
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
56,098
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import linear_algebra.dimension import ring_theory.principal_ideal_domain import algebra.algebra.subalgebra /-! # Finite dimensional vector spaces Definition and basic properties of finite dimensional vector spaces, of their dimensions, and of linear maps on such spaces. ## Main definitions Assume `V` is a vector space over a field `K`. There are (at least) three equivalent definitions of finite-dimensionality of `V`: - it admits a finite basis. - it is finitely generated. - it is noetherian, i.e., every subspace is finitely generated. We introduce a typeclass `finite_dimensional K V` capturing this property. For ease of transfer of proof, it is defined using the third point of view, i.e., as `is_noetherian`. However, we prove that all these points of view are equivalent, with the following lemmas (in the namespace `finite_dimensional`): - `exists_is_basis_finite` states that a finite-dimensional vector space has a finite basis - `of_fintype_basis` states that the existence of a basis indexed by a finite type implies finite-dimensionality - `of_finset_basis` states that the existence of a basis indexed by a `finset` implies finite-dimensionality - `of_finite_basis` states that the existence of a basis indexed by a finite set implies finite-dimensionality - `iff_fg` states that the space is finite-dimensional if and only if it is finitely generated Also defined is `findim`, the dimension of a finite dimensional space, returning a `nat`, as opposed to `dim`, which returns a `cardinal`. When the space has infinite dimension, its `findim` is by convention set to `0`. Preservation of finite-dimensionality and formulas for the dimension are given for - submodules - quotients (for the dimension of a quotient, see `findim_quotient_add_findim`) - linear equivs, in `linear_equiv.finite_dimensional` and `linear_equiv.findim_eq` - image under a linear map (the rank-nullity formula is in `findim_range_add_findim_ker`) Basic properties of linear maps of a finite-dimensional vector space are given. Notably, the equivalence of injectivity and surjectivity is proved in `linear_map.injective_iff_surjective`, and the equivalence between left-inverse and right-inverse in `mul_eq_one_comm` and `comp_eq_id_comm`. ## Implementation notes Most results are deduced from the corresponding results for the general dimension (as a cardinal), in `dimension.lean`. Not all results have been ported yet. One of the characterizations of finite-dimensionality is in terms of finite generation. This property is currently defined only for submodules, so we express it through the fact that the maximal submodule (which, as a set, coincides with the whole space) is finitely generated. This is not very convenient to use, although there are some helper functions. However, this becomes very convenient when speaking of submodules which are finite-dimensional, as this notion coincides with the fact that the submodule is finitely generated (as a submodule of the whole space). This equivalence is proved in `submodule.fg_iff_finite_dimensional`. -/ universes u v v' w open_locale classical open vector_space cardinal submodule module function variables {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] {V₂ : Type v'} [add_comm_group V₂] [vector_space K V₂] /-- `finite_dimensional` vector spaces are defined to be noetherian modules. Use `finite_dimensional.iff_fg` or `finite_dimensional.of_fintype_basis` to prove finite dimension from a conventional definition. -/ @[reducible] def finite_dimensional (K V : Type*) [field K] [add_comm_group V] [vector_space K V] := is_noetherian K V namespace finite_dimensional open is_noetherian /-- A vector space is finite-dimensional if and only if its dimension (as a cardinal) is strictly less than the first infinite cardinal `omega`. -/ lemma finite_dimensional_iff_dim_lt_omega : finite_dimensional K V ↔ dim K V < omega.{v} := begin cases exists_is_basis K V with b hb, have := is_basis.mk_eq_dim hb, simp only [lift_id] at this, rw [← this, lt_omega_iff_fintype, ← @set.set_of_mem_eq _ b, ← subtype.range_coe_subtype], split, { intro, resetI, convert finite_of_linear_independent hb.1, simp }, { assume hbfinite, refine @is_noetherian_of_linear_equiv K (⊤ : submodule K V) V _ _ _ _ _ (linear_equiv.of_top _ rfl) (id _), refine is_noetherian_of_fg_of_noetherian _ ⟨set.finite.to_finset hbfinite, _⟩, rw [set.finite.coe_to_finset, ← hb.2], refl } end /-- The dimension of a finite-dimensional vector space, as a cardinal, is strictly less than the first infinite cardinal `omega`. -/ lemma dim_lt_omega (K V : Type*) [field K] [add_comm_group V] [vector_space K V] : ∀ [finite_dimensional K V], dim K V < omega.{v} := finite_dimensional_iff_dim_lt_omega.1 /-- In a finite dimensional space, there exists a finite basis. A basis is in general given as a function from an arbitrary type to the vector space. Here, we think of a basis as a set (instead of a function), and use as parametrizing type this set (and as a function the coercion `coe : s → V`). -/ variables (K V) lemma exists_is_basis_finite [finite_dimensional K V] : ∃ s : set V, (is_basis K (coe : s → V)) ∧ s.finite := begin cases exists_is_basis K V with s hs, exact ⟨s, hs, finite_of_linear_independent hs.1⟩ end /-- In a finite dimensional space, there exists a finite basis. Provides the basis as a finset. This is in contrast to `exists_is_basis_finite`, which provides a set and a `set.finite`. -/ lemma exists_is_basis_finset [finite_dimensional K V] : ∃ b : finset V, is_basis K (coe : (↑b : set V) → V) := begin obtain ⟨s, s_basis, s_finite⟩ := exists_is_basis_finite K V, refine ⟨s_finite.to_finset, _⟩, rw set.finite.coe_to_finset, exact s_basis, end /-- A finite dimensional vector space over a finite field is finite -/ noncomputable def fintype_of_fintype [fintype K] [finite_dimensional K V] : fintype V := module.fintype_of_fintype (classical.some_spec (finite_dimensional.exists_is_basis_finset K V) : _) variables {K V} /-- A vector space is finite-dimensional if and only if it is finitely generated. As the finitely-generated property is a property of submodules, we formulate this in terms of the maximal submodule, equal to the whole space as a set by definition.-/ lemma iff_fg : finite_dimensional K V ↔ (⊤ : submodule K V).fg := begin split, { introI h, rcases exists_is_basis_finite K V with ⟨s, s_basis, s_finite⟩, exact ⟨s_finite.to_finset, by { convert s_basis.2, simp }⟩ }, { rintros ⟨s, hs⟩, rw [finite_dimensional_iff_dim_lt_omega, ← dim_top, ← hs], exact lt_of_le_of_lt (dim_span_le _) (lt_omega_iff_finite.2 (set.finite_mem_finset s)) } end /-- If a vector space has a finite basis, then it is finite-dimensional. -/ lemma of_fintype_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) : finite_dimensional K V := iff_fg.2 $ ⟨finset.univ.image b, by {convert h.2, simp} ⟩ /-- If a vector space has a basis indexed by elements of a finite set, then it is finite-dimensional. -/ lemma of_finite_basis {ι} {s : set ι} {b : s → V} (h : is_basis K b) (hs : set.finite s) : finite_dimensional K V := by haveI := hs.fintype; exact of_fintype_basis h /-- If a vector space has a finite basis, then it is finite-dimensional, finset style. -/ lemma of_finset_basis {ι} {s : finset ι} {b : (↑s : set ι) → V} (h : is_basis K b) : finite_dimensional K V := of_finite_basis h s.finite_to_set /-- A subspace of a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_submodule [finite_dimensional K V] (S : submodule K V) : finite_dimensional K S := finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_submodule_le _) (dim_lt_omega K V)) /-- A quotient of a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_quotient [finite_dimensional K V] (S : submodule K V) : finite_dimensional K (quotient S) := finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_quotient_le _) (dim_lt_omega K V)) /-- The dimension of a finite-dimensional vector space as a natural number. Defined by convention to be `0` if the space is infinite-dimensional. -/ noncomputable def findim (K V : Type*) [field K] [add_comm_group V] [vector_space K V] : ℕ := if h : dim K V < omega.{v} then classical.some (lt_omega.1 h) else 0 /-- In a finite-dimensional space, its dimension (seen as a cardinal) coincides with its `findim`. -/ lemma findim_eq_dim (K : Type u) (V : Type v) [field K] [add_comm_group V] [vector_space K V] [finite_dimensional K V] : (findim K V : cardinal.{v}) = dim K V := begin have : findim K V = classical.some (lt_omega.1 (dim_lt_omega K V)) := dif_pos (dim_lt_omega K V), rw this, exact (classical.some_spec (lt_omega.1 (dim_lt_omega K V))).symm end lemma findim_of_infinite_dimensional {K V : Type*} [field K] [add_comm_group V] [vector_space K V] (h : ¬finite_dimensional K V) : findim K V = 0 := dif_neg $ mt finite_dimensional_iff_dim_lt_omega.2 h lemma finite_dimensional_of_findim {K V : Type*} [field K] [add_comm_group V] [vector_space K V] (h : 0 < findim K V) : finite_dimensional K V := by { contrapose h, simp [findim_of_infinite_dimensional h] } /-- We can infer `finite_dimensional K V` in the presence of `[fact (findim K V = n + 1)]`. Declare this as a local instance where needed. -/ lemma finite_dimensional_of_findim_eq_succ {K V : Type*} [field K] [add_comm_group V] [vector_space K V] (n : ℕ) [fact (findim K V = n + 1)] : finite_dimensional K V := finite_dimensional_of_findim $ by convert nat.succ_pos n /-- If a vector space has a finite basis, then its dimension (seen as a cardinal) is equal to the cardinality of the basis. -/ lemma dim_eq_card_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) : dim K V = fintype.card ι := by rw [←h.mk_range_eq_dim, cardinal.fintype_card, set.card_range_of_injective h.injective] /-- If a vector space has a finite basis, then its dimension is equal to the cardinality of the basis. -/ lemma findim_eq_card_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) : findim K V = fintype.card ι := begin haveI : finite_dimensional K V := of_fintype_basis h, have := dim_eq_card_basis h, rw ← findim_eq_dim at this, exact_mod_cast this end /-- If a vector space is finite-dimensional, then the cardinality of any basis is equal to its `findim`. -/ lemma findim_eq_card_basis' [finite_dimensional K V] {ι : Type w} {b : ι → V} (h : is_basis K b) : (findim K V : cardinal.{w}) = cardinal.mk ι := begin rcases exists_is_basis_finite K V with ⟨s, s_basis, s_finite⟩, letI: fintype s := s_finite.fintype, have A : cardinal.mk s = fintype.card s := fintype_card _, have B : findim K V = fintype.card s := findim_eq_card_basis s_basis, have C : cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{v w} (cardinal.mk s) := mk_eq_mk_of_basis h s_basis, rw [A, ← B, lift_nat_cast] at C, have : cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{w v} (findim K V), by { simp, exact C }, exact (lift_inj.mp this).symm end /-- If a vector space has a finite basis, then its dimension is equal to the cardinality of the basis. This lemma uses a `finset` instead of indexed types. -/ lemma findim_eq_card_finset_basis {b : finset V} (h : is_basis K (subtype.val : (↑b : set V) -> V)) : findim K V = finset.card b := by { rw [findim_eq_card_basis h, fintype.subtype_card], intros x, refl } lemma equiv_fin {ι : Type*} [finite_dimensional K V] {v : ι → V} (hv : is_basis K v) : ∃ g : fin (findim K V) ≃ ι, is_basis K (v ∘ g) := begin have : (cardinal.mk (fin $ findim K V)).lift = (cardinal.mk ι).lift, { simp [cardinal.mk_fin (findim K V), ← findim_eq_card_basis' hv] }, rcases cardinal.lift_mk_eq.mp this with ⟨g⟩, exact ⟨g, hv.comp _ g.bijective⟩ end lemma equiv_fin_of_dim_eq {ι : Type*} [finite_dimensional K V] {n : ℕ} (hn : findim K V = n) {v : ι → V} (hv : is_basis K v) : ∃ g : fin n ≃ ι, is_basis K (v ∘ g) := let ⟨g₁, hg₁⟩ := equiv_fin hv, ⟨g₂⟩ := fin.equiv_iff_eq.mpr hn in ⟨g₂.symm.trans g₁, hv.comp _ (g₂.symm.trans g₁).bijective⟩ variables (K V) lemma fin_basis [finite_dimensional K V] : ∃ v : fin (findim K V) → V, is_basis K v := let ⟨B, hB, B_fin⟩ := exists_is_basis_finite K V, ⟨g, hg⟩ := finite_dimensional.equiv_fin hB in ⟨coe ∘ g, hg⟩ variables {K V} lemma cardinal_mk_le_findim_of_linear_independent [finite_dimensional K V] {ι : Type w} {b : ι → V} (h : linear_independent K b) : cardinal.mk ι ≤ findim K V := begin rw ← lift_le.{_ (max v w)}, simpa [← findim_eq_dim K V] using cardinal_lift_le_dim_of_linear_independent.{_ _ _ (max v w)} h end lemma fintype_card_le_findim_of_linear_independent [finite_dimensional K V] {ι : Type*} [fintype ι] {b : ι → V} (h : linear_independent K b) : fintype.card ι ≤ findim K V := by simpa [fintype_card] using cardinal_mk_le_findim_of_linear_independent h lemma finset_card_le_findim_of_linear_independent [finite_dimensional K V] {b : finset V} (h : linear_independent K (λ x, x : (↑b : set V) → V)) : b.card ≤ findim K V := begin rw ←fintype.card_coe, exact fintype_card_le_findim_of_linear_independent h, end lemma lt_omega_of_linear_independent {ι : Type w} [finite_dimensional K V] {v : ι → V} (h : linear_independent K v) : cardinal.mk ι < cardinal.omega := begin apply cardinal.lift_lt.1, apply lt_of_le_of_lt, apply linear_independent_le_dim h, rw [←findim_eq_dim, cardinal.lift_omega, cardinal.lift_nat_cast], apply cardinal.nat_lt_omega, end lemma not_linear_independent_of_infinite {ι : Type w} [inf : infinite ι] [finite_dimensional K V] (v : ι → V) : ¬ linear_independent K v := begin intro h_lin_indep, have : ¬ omega ≤ mk ι := not_le.mpr (lt_omega_of_linear_independent h_lin_indep), have : omega ≤ mk ι := infinite_iff.mp inf, contradiction end /-- A finite dimensional space has positive `findim` iff it has a nonzero element. -/ lemma findim_pos_iff_exists_ne_zero [finite_dimensional K V] : 0 < findim K V ↔ ∃ x : V, x ≠ 0 := iff.trans (by { rw ← findim_eq_dim, norm_cast }) (@dim_pos_iff_exists_ne_zero K V _ _ _) /-- A finite dimensional space has positive `findim` iff it is nontrivial. -/ lemma findim_pos_iff [finite_dimensional K V] : 0 < findim K V ↔ nontrivial V := iff.trans (by { rw ← findim_eq_dim, norm_cast }) (@dim_pos_iff_nontrivial K V _ _ _) /-- A nontrivial finite dimensional space has positive `findim`. -/ lemma findim_pos [finite_dimensional K V] [h : nontrivial V] : 0 < findim K V := findim_pos_iff.mpr h /-- A finite dimensional space has zero `findim` iff it is a subsingleton. This is the `findim` version of `dim_zero_iff`. -/ lemma findim_zero_iff [finite_dimensional K V] : findim K V = 0 ↔ subsingleton V := iff.trans (by { rw ← findim_eq_dim, norm_cast }) (@dim_zero_iff K V _ _ _) /-- A finite dimensional space that is a subsingleton has zero `findim`. -/ lemma findim_zero_of_subsingleton [finite_dimensional K V] [h : subsingleton V] : findim K V = 0 := findim_zero_iff.2 h section open_locale big_operators open finset /-- If a finset has cardinality larger than the dimension of the space, then there is a nontrivial linear relation amongst its elements. -/ lemma exists_nontrivial_relation_of_dim_lt_card [finite_dimensional K V] {t : finset V} (h : findim K V < t.card) : ∃ f : V → K, ∑ e in t, f e • e = 0 ∧ ∃ x ∈ t, f x ≠ 0 := begin have := mt finset_card_le_findim_of_linear_independent (by { simpa using h }), rw linear_dependent_iff at this, obtain ⟨s, g, sum, z, zm, nonzero⟩ := this, -- Now we have to extend `g` to all of `t`, then to all of `V`. let f : V → K := λ x, if h : x ∈ t then if (⟨x, h⟩ : (↑t : set V)) ∈ s then g ⟨x, h⟩ else 0 else 0, -- and finally clean up the mess caused by the extension. refine ⟨f, _, _⟩, { dsimp [f], rw ← sum, fapply sum_bij_ne_zero (λ v hvt _, (⟨v, hvt⟩ : {v // v ∈ t})), { intros v hvt H, dsimp, rw [dif_pos hvt] at H, contrapose! H, rw [if_neg H, zero_smul], }, { intros _ _ _ _ _ _, exact subtype.mk.inj, }, { intros b hbs hb, use b, simpa only [hbs, exists_prop, dif_pos, finset.mk_coe, and_true, if_true, finset.coe_mem, eq_self_iff_true, exists_prop_of_true, ne.def] using hb, }, { intros a h₁, dsimp, rw [dif_pos h₁], intro h₂, rw [if_pos], contrapose! h₂, rw [if_neg h₂, zero_smul], }, }, { refine ⟨z, z.2, _⟩, dsimp only [f], erw [dif_pos z.2, if_pos]; rwa [subtype.coe_eta] }, end /-- If a finset has cardinality larger than `findim + 1`, then there is a nontrivial linear relation amongst its elements, such that the coefficients of the relation sum to zero. -/ lemma exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card [finite_dimensional K V] {t : finset V} (h : findim K V + 1 < t.card) : ∃ f : V → K, ∑ e in t, f e • e = 0 ∧ ∑ e in t, f e = 0 ∧ ∃ x ∈ t, f x ≠ 0 := begin -- Pick an element x₀ ∈ t, have card_pos : 0 < t.card := lt_trans (nat.succ_pos _) h, obtain ⟨x₀, m⟩ := (finset.card_pos.1 card_pos).bex, -- and apply the previous lemma to the {xᵢ - x₀} let shift : V ↪ V := ⟨λ x, x - x₀, sub_left_injective⟩, let t' := (t.erase x₀).map shift, have h' : findim K V < t'.card, { simp only [t', card_map, finset.card_erase_of_mem m], exact nat.lt_pred_iff.mpr h, }, -- to obtain a function `g`. obtain ⟨g, gsum, x₁, x₁_mem, nz⟩ := exists_nontrivial_relation_of_dim_lt_card h', -- Then obtain `f` by translating back by `x₀`, -- and setting the value of `f` at `x₀` to ensure `∑ e in t, f e = 0`. let f : V → K := λ z, if z = x₀ then - ∑ z in (t.erase x₀), g (z - x₀) else g (z - x₀), refine ⟨f, _ ,_ ,_⟩, -- After this, it's a matter of verifiying the properties, -- based on the corresponding properties for `g`. { show ∑ (e : V) in t, f e • e = 0, -- We prove this by splitting off the `x₀` term of the sum, -- which is itself a sum over `t.erase x₀`, -- combining the two sums, and -- observing that after reindexing we have exactly -- ∑ (x : V) in t', g x • x = 0. simp only [f], conv_lhs { apply_congr, skip, rw [ite_smul], }, rw [finset.sum_ite], conv { congr, congr, apply_congr, simp [filter_eq', m], }, conv { congr, congr, skip, apply_congr, simp [filter_ne'], }, rw [sum_singleton, neg_smul, add_comm, ←sub_eq_add_neg, sum_smul, ←sum_sub_distrib], simp only [←smul_sub], -- At the end we have to reindex the sum, so we use `change` to -- express the summand using `shift`. change (∑ (x : V) in t.erase x₀, (λ e, g e • e) (shift x)) = 0, rw ←sum_map _ shift, exact gsum, }, { show ∑ (e : V) in t, f e = 0, -- Again we split off the `x₀` term, -- observing that it exactly cancels the other terms. rw [← insert_erase m, sum_insert (not_mem_erase x₀ t)], dsimp [f], rw [if_pos rfl], conv_lhs { congr, skip, apply_congr, skip, rw if_neg (show x ≠ x₀, from (mem_erase.mp H).1), }, exact neg_add_self _, }, { show ∃ (x : V) (H : x ∈ t), f x ≠ 0, -- We can use x₁ + x₀. refine ⟨x₁ + x₀, _, _⟩, { rw finset.mem_map at x₁_mem, rcases x₁_mem with ⟨x₁, x₁_mem, rfl⟩, rw mem_erase at x₁_mem, simp only [x₁_mem, sub_add_cancel, function.embedding.coe_fn_mk], }, { dsimp only [f], rwa [if_neg, add_sub_cancel], rw [add_left_eq_self], rintro rfl, simpa only [sub_eq_zero, exists_prop, finset.mem_map, embedding.coe_fn_mk, eq_self_iff_true, mem_erase, not_true, exists_eq_right, ne.def, false_and] using x₁_mem, } }, end section variables {L : Type*} [linear_ordered_field L] variables {W : Type v} [add_comm_group W] [vector_space L W] /-- A slight strengthening of `exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card` available when working over an ordered field: we can ensure a positive coefficient, not just a nonzero coefficient. -/ lemma exists_relation_sum_zero_pos_coefficient_of_dim_succ_lt_card [finite_dimensional L W] {t : finset W} (h : findim L W + 1 < t.card) : ∃ f : W → L, ∑ e in t, f e • e = 0 ∧ ∑ e in t, f e = 0 ∧ ∃ x ∈ t, 0 < f x := begin obtain ⟨f, sum, total, nonzero⟩ := exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card h, exact ⟨f, sum, total, exists_pos_of_sum_zero_of_exists_nonzero f total nonzero⟩, end end end /-- If a submodule has maximal dimension in a finite dimensional space, then it is equal to the whole space. -/ lemma eq_top_of_findim_eq [finite_dimensional K V] {S : submodule K V} (h : findim K S = findim K V) : S = ⊤ := begin cases exists_is_basis K S with bS hbS, have : linear_independent K (subtype.val : (subtype.val '' bS : set V) → V), from @linear_independent.image_subtype _ _ _ _ _ _ _ _ _ (submodule.subtype S) hbS.1 (by simp), cases exists_subset_is_basis this with b hb, letI : fintype b := classical.choice (finite_of_linear_independent hb.2.1), letI : fintype (subtype.val '' bS) := classical.choice (finite_of_linear_independent this), letI : fintype bS := classical.choice (finite_of_linear_independent hbS.1), have : subtype.val '' bS = b, from set.eq_of_subset_of_card_le hb.1 (by rw [set.card_image_of_injective _ subtype.val_injective, ← findim_eq_card_basis hbS, ← findim_eq_card_basis hb.2, h]; apply_instance), erw [← hb.2.2, subtype.range_coe, ← this, ← subtype_eq_val, span_image], have := hbS.2, erw [subtype.range_coe] at this, rw [this, map_top (submodule.subtype S), range_subtype], end variable (K) /-- A field is one-dimensional as a vector space over itself. -/ @[simp] lemma findim_of_field : findim K K = 1 := begin have := dim_of_field K, rw [← findim_eq_dim] at this, exact_mod_cast this end /-- The vector space of functions on a fintype has finite dimension. -/ instance finite_dimensional_fintype_fun {ι : Type*} [fintype ι] : finite_dimensional K (ι → K) := by { rw [finite_dimensional_iff_dim_lt_omega, dim_fun'], exact nat_lt_omega _ } /-- The vector space of functions on a fintype ι has findim equal to the cardinality of ι. -/ @[simp] lemma findim_fintype_fun_eq_card {ι : Type v} [fintype ι] : findim K (ι → K) = fintype.card ι := begin have : vector_space.dim K (ι → K) = fintype.card ι := dim_fun', rwa [← findim_eq_dim, nat_cast_inj] at this, end /-- The vector space of functions on `fin n` has findim equal to `n`. -/ @[simp] lemma findim_fin_fun {n : ℕ} : findim K (fin n → K) = n := by simp /-- The submodule generated by a finite set is finite-dimensional. -/ theorem span_of_finite {A : set V} (hA : set.finite A) : finite_dimensional K (submodule.span K A) := is_noetherian_span_of_finite K hA /-- The submodule generated by a single element is finite-dimensional. -/ instance (x : V) : finite_dimensional K (K ∙ x) := by {apply span_of_finite, simp} end finite_dimensional section zero_dim open vector_space finite_dimensional lemma finite_dimensional_of_dim_eq_zero (h : vector_space.dim K V = 0) : finite_dimensional K V := by rw [finite_dimensional_iff_dim_lt_omega, h]; exact cardinal.omega_pos lemma finite_dimensional_of_dim_eq_one (h : vector_space.dim K V = 1) : finite_dimensional K V := by rw [finite_dimensional_iff_dim_lt_omega, h]; exact one_lt_omega lemma findim_eq_zero_of_dim_eq_zero [finite_dimensional K V] (h : vector_space.dim K V = 0) : findim K V = 0 := begin convert findim_eq_dim K V, rw h, norm_cast end variables (K V) lemma finite_dimensional_bot : finite_dimensional K (⊥ : submodule K V) := finite_dimensional_of_dim_eq_zero $ by simp @[simp] lemma findim_bot : findim K (⊥ : submodule K V) = 0 := begin haveI := finite_dimensional_bot K V, convert findim_eq_dim K (⊥ : submodule K V), rw dim_bot, norm_cast end variables {K V} lemma bot_eq_top_of_dim_eq_zero (h : vector_space.dim K V = 0) : (⊥ : submodule K V) = ⊤ := begin haveI := finite_dimensional_of_dim_eq_zero h, apply eq_top_of_findim_eq, rw [findim_bot, findim_eq_zero_of_dim_eq_zero h] end @[simp] theorem dim_eq_zero {S : submodule K V} : dim K S = 0 ↔ S = ⊥ := ⟨λ h, (submodule.eq_bot_iff _).2 $ λ x hx, congr_arg subtype.val $ ((submodule.eq_bot_iff _).1 $ eq.symm $ bot_eq_top_of_dim_eq_zero h) ⟨x, hx⟩ submodule.mem_top, λ h, by rw [h, dim_bot]⟩ @[simp] theorem findim_eq_zero {S : submodule K V} [finite_dimensional K S] : findim K S = 0 ↔ S = ⊥ := by rw [← dim_eq_zero, ← findim_eq_dim, ← @nat.cast_zero cardinal, cardinal.nat_cast_inj] end zero_dim namespace submodule open finite_dimensional /-- A submodule is finitely generated if and only if it is finite-dimensional -/ theorem fg_iff_finite_dimensional (s : submodule K V) : s.fg ↔ finite_dimensional K s := ⟨λh, is_noetherian_of_fg_of_noetherian s h, λh, by { rw ← map_subtype_top s, exact fg_map (iff_fg.1 h) }⟩ /-- A submodule contained in a finite-dimensional submodule is finite-dimensional. -/ lemma finite_dimensional_of_le {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (h : S₁ ≤ S₂) : finite_dimensional K S₁ := finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_le_of_submodule _ _ h) (dim_lt_omega K S₂)) /-- The inf of two submodules, the first finite-dimensional, is finite-dimensional. -/ instance finite_dimensional_inf_left (S₁ S₂ : submodule K V) [finite_dimensional K S₁] : finite_dimensional K (S₁ ⊓ S₂ : submodule K V) := finite_dimensional_of_le inf_le_left /-- The inf of two submodules, the second finite-dimensional, is finite-dimensional. -/ instance finite_dimensional_inf_right (S₁ S₂ : submodule K V) [finite_dimensional K S₂] : finite_dimensional K (S₁ ⊓ S₂ : submodule K V) := finite_dimensional_of_le inf_le_right /-- The sup of two finite-dimensional submodules is finite-dimensional. -/ instance finite_dimensional_sup (S₁ S₂ : submodule K V) [h₁ : finite_dimensional K S₁] [h₂ : finite_dimensional K S₂] : finite_dimensional K (S₁ ⊔ S₂ : submodule K V) := begin rw ←submodule.fg_iff_finite_dimensional at *, exact submodule.fg_sup h₁ h₂ end /-- In a finite-dimensional vector space, the dimensions of a submodule and of the corresponding quotient add up to the dimension of the space. -/ theorem findim_quotient_add_findim [finite_dimensional K V] (s : submodule K V) : findim K s.quotient + findim K s = findim K V := begin have := dim_quotient_add_dim s, rw [← findim_eq_dim, ← findim_eq_dim, ← findim_eq_dim] at this, exact_mod_cast this end /-- The dimension of a submodule is bounded by the dimension of the ambient space. -/ lemma findim_le [finite_dimensional K V] (s : submodule K V) : findim K s ≤ findim K V := by { rw ← s.findim_quotient_add_findim, exact nat.le_add_left _ _ } /-- The dimension of a strict submodule is strictly bounded by the dimension of the ambient space. -/ lemma findim_lt [finite_dimensional K V] {s : submodule K V} (h : s < ⊤) : findim K s < findim K V := begin rw [← s.findim_quotient_add_findim, add_comm], exact nat.lt_add_of_zero_lt_left _ _ (findim_pos_iff.mpr (quotient.nontrivial_of_lt_top _ h)) end /-- The dimension of a quotient is bounded by the dimension of the ambient space. -/ lemma findim_quotient_le [finite_dimensional K V] (s : submodule K V) : findim K s.quotient ≤ findim K V := by { rw ← s.findim_quotient_add_findim, exact nat.le_add_right _ _ } /-- The sum of the dimensions of s + t and s ∩ t is the sum of the dimensions of s and t -/ theorem dim_sup_add_dim_inf_eq (s t : submodule K V) [finite_dimensional K s] [finite_dimensional K t] : findim K ↥(s ⊔ t) + findim K ↥(s ⊓ t) = findim K ↥s + findim K ↥t := begin have key : dim K ↥(s ⊔ t) + dim K ↥(s ⊓ t) = dim K s + dim K t := dim_sup_add_dim_inf_eq s t, repeat { rw ←findim_eq_dim at key }, norm_cast at key, exact key end lemma eq_top_of_disjoint [finite_dimensional K V] (s t : submodule K V) (hdim : findim K s + findim K t = findim K V) (hdisjoint : disjoint s t) : s ⊔ t = ⊤ := begin have h_findim_inf : findim K ↥(s ⊓ t) = 0, { rw [disjoint, le_bot_iff] at hdisjoint, rw [hdisjoint, findim_bot] }, apply eq_top_of_findim_eq, rw ←hdim, convert s.dim_sup_add_dim_inf_eq t, rw h_findim_inf, refl, end end submodule namespace linear_equiv open finite_dimensional /-- Finite dimensionality is preserved under linear equivalence. -/ protected theorem finite_dimensional (f : V ≃ₗ[K] V₂) [finite_dimensional K V] : finite_dimensional K V₂ := is_noetherian_of_linear_equiv f /-- The dimension of a finite dimensional space is preserved under linear equivalence. -/ theorem findim_eq (f : V ≃ₗ[K] V₂) [finite_dimensional K V] : findim K V = findim K V₂ := begin haveI : finite_dimensional K V₂ := f.finite_dimensional, simpa [← findim_eq_dim] using f.lift_dim_eq end end linear_equiv namespace finite_dimensional /-- Two finite-dimensional vector spaces are isomorphic if they have the same (finite) dimension. -/ theorem nonempty_linear_equiv_of_findim_eq [finite_dimensional K V] [finite_dimensional K V₂] (cond : findim K V = findim K V₂) : nonempty (V ≃ₗ[K] V₂) := nonempty_linear_equiv_of_lift_dim_eq $ by simp only [← findim_eq_dim, cond, lift_nat_cast] /-- Two finite-dimensional vector spaces are isomorphic if and only if they have the same (finite) dimension. -/ theorem nonempty_linear_equiv_iff_findim_eq [finite_dimensional K V] [finite_dimensional K V₂] : nonempty (V ≃ₗ[K] V₂) ↔ findim K V = findim K V₂ := ⟨λ ⟨h⟩, h.findim_eq, λ h, nonempty_linear_equiv_of_findim_eq h⟩ section variables (V V₂) /-- Two finite-dimensional vector spaces are isomorphic if they have the same (finite) dimension. -/ noncomputable def linear_equiv.of_findim_eq [finite_dimensional K V] [finite_dimensional K V₂] (cond : findim K V = findim K V₂) : V ≃ₗ[K] V₂ := classical.choice $ nonempty_linear_equiv_of_findim_eq cond end lemma eq_of_le_of_findim_le {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (hle : S₁ ≤ S₂) (hd : findim K S₂ ≤ findim K S₁) : S₁ = S₂ := begin rw ←linear_equiv.findim_eq (submodule.comap_subtype_equiv_of_le hle) at hd, exact le_antisymm hle (submodule.comap_subtype_eq_top.1 (eq_top_of_findim_eq (le_antisymm (comap (submodule.subtype S₂) S₁).findim_le hd))), end /-- If a submodule is less than or equal to a finite-dimensional submodule with the same dimension, they are equal. -/ lemma eq_of_le_of_findim_eq {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (hle : S₁ ≤ S₂) (hd : findim K S₁ = findim K S₂) : S₁ = S₂ := eq_of_le_of_findim_le hle hd.ge variables [finite_dimensional K V] [finite_dimensional K V₂] /-- Given isomorphic subspaces `p q` of vector spaces `V` and `V₁` respectively, `p.quotient` is isomorphic to `q.quotient`. -/ noncomputable def linear_equiv.quot_equiv_of_equiv {p : subspace K V} {q : subspace K V₂} (f₁ : p ≃ₗ[K] q) (f₂ : V ≃ₗ[K] V₂) : p.quotient ≃ₗ[K] q.quotient := linear_equiv.of_findim_eq _ _ begin rw [← @add_right_cancel_iff _ _ (findim K p), submodule.findim_quotient_add_findim, linear_equiv.findim_eq f₁, submodule.findim_quotient_add_findim, linear_equiv.findim_eq f₂], end /-- Given the subspaces `p q`, if `p.quotient ≃ₗ[K] q`, then `q.quotient ≃ₗ[K] p` -/ noncomputable def linear_equiv.quot_equiv_of_quot_equiv {p q : subspace K V} (f : p.quotient ≃ₗ[K] q) : q.quotient ≃ₗ[K] p := linear_equiv.of_findim_eq _ _ begin rw [← @add_right_cancel_iff _ _ (findim K q), submodule.findim_quotient_add_findim, ← linear_equiv.findim_eq f, add_comm, submodule.findim_quotient_add_findim] end end finite_dimensional namespace linear_map open finite_dimensional /-- On a finite-dimensional space, an injective linear map is surjective. -/ lemma surjective_of_injective [finite_dimensional K V] {f : V →ₗ[K] V} (hinj : injective f) : surjective f := begin have h := dim_eq_of_injective _ hinj, rw [← findim_eq_dim, ← findim_eq_dim, nat_cast_inj] at h, exact range_eq_top.1 (eq_top_of_findim_eq h.symm) end /-- On a finite-dimensional space, a linear map is injective if and only if it is surjective. -/ lemma injective_iff_surjective [finite_dimensional K V] {f : V →ₗ[K] V} : injective f ↔ surjective f := ⟨surjective_of_injective, λ hsurj, let ⟨g, hg⟩ := f.exists_right_inverse_of_surjective (range_eq_top.2 hsurj) in have function.right_inverse g f, from linear_map.ext_iff.1 hg, (left_inverse_of_surjective_of_right_inverse (surjective_of_injective this.injective) this).injective⟩ lemma ker_eq_bot_iff_range_eq_top [finite_dimensional K V] {f : V →ₗ[K] V} : f.ker = ⊥ ↔ f.range = ⊤ := by rw [range_eq_top, ker_eq_bot, injective_iff_surjective] /-- In a finite-dimensional space, if linear maps are inverse to each other on one side then they are also inverse to each other on the other side. -/ lemma mul_eq_one_of_mul_eq_one [finite_dimensional K V] {f g : V →ₗ[K] V} (hfg : f * g = 1) : g * f = 1 := have ginj : injective g, from has_left_inverse.injective ⟨f, (λ x, show (f * g) x = (1 : V →ₗ[K] V) x, by rw hfg; refl)⟩, let ⟨i, hi⟩ := g.exists_right_inverse_of_surjective (range_eq_top.2 (injective_iff_surjective.1 ginj)) in have f * (g * i) = f * 1, from congr_arg _ hi, by rw [← mul_assoc, hfg, one_mul, mul_one] at this; rwa ← this /-- In a finite-dimensional space, linear maps are inverse to each other on one side if and only if they are inverse to each other on the other side. -/ lemma mul_eq_one_comm [finite_dimensional K V] {f g : V →ₗ[K] V} : f * g = 1 ↔ g * f = 1 := ⟨mul_eq_one_of_mul_eq_one, mul_eq_one_of_mul_eq_one⟩ /-- In a finite-dimensional space, linear maps are inverse to each other on one side if and only if they are inverse to each other on the other side. -/ lemma comp_eq_id_comm [finite_dimensional K V] {f g : V →ₗ[K] V} : f.comp g = id ↔ g.comp f = id := mul_eq_one_comm /-- The image under an onto linear map of a finite-dimensional space is also finite-dimensional. -/ lemma finite_dimensional_of_surjective [h : finite_dimensional K V] (f : V →ₗ[K] V₂) (hf : f.range = ⊤) : finite_dimensional K V₂ := is_noetherian_of_surjective V f hf /-- The range of a linear map defined on a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_range [h : finite_dimensional K V] (f : V →ₗ[K] V₂) : finite_dimensional K f.range := f.quot_ker_equiv_range.finite_dimensional /-- rank-nullity theorem : the dimensions of the kernel and the range of a linear map add up to the dimension of the source space. -/ theorem findim_range_add_findim_ker [finite_dimensional K V] (f : V →ₗ[K] V₂) : findim K f.range + findim K f.ker = findim K V := by { rw [← f.quot_ker_equiv_range.findim_eq], exact submodule.findim_quotient_add_findim _ } end linear_map namespace linear_equiv open finite_dimensional variables [finite_dimensional K V] /-- The linear equivalence corresponging to an injective endomorphism. -/ noncomputable def of_injective_endo (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) : V ≃ₗ[K] V := (linear_equiv.of_injective f h_inj).trans (linear_equiv.of_top _ (linear_map.ker_eq_bot_iff_range_eq_top.1 h_inj)) @[simp] lemma coe_of_injective_endo (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) : ⇑(of_injective_endo f h_inj) = f := rfl @[simp] lemma of_injective_endo_right_inv (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) : f * (of_injective_endo f h_inj).symm = 1 := linear_map.ext $ (of_injective_endo f h_inj).apply_symm_apply @[simp] lemma of_injective_endo_left_inv (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) : ((of_injective_endo f h_inj).symm : V →ₗ[K] V) * f = 1 := linear_map.ext $ (of_injective_endo f h_inj).symm_apply_apply end linear_equiv namespace linear_map lemma is_unit_iff [finite_dimensional K V] (f : V →ₗ[K] V): is_unit f ↔ f.ker = ⊥ := begin split, { rintro ⟨u, rfl⟩, exact linear_map.ker_eq_bot_of_inverse u.inv_mul }, { intro h_inj, exact ⟨⟨f, (linear_equiv.of_injective_endo f h_inj).symm.to_linear_map, linear_equiv.of_injective_endo_right_inv f h_inj, linear_equiv.of_injective_endo_left_inv f h_inj⟩, rfl⟩ } end end linear_map open vector_space finite_dimensional section top @[simp] theorem findim_top : findim K (⊤ : submodule K V) = findim K V := by { unfold findim, simp [dim_top] } end top lemma findim_zero_iff_forall_zero [finite_dimensional K V] : findim K V = 0 ↔ ∀ x : V, x = 0 := findim_zero_iff.trans (subsingleton_iff_forall_eq 0) lemma is_basis_of_findim_zero [finite_dimensional K V] {ι : Type*} (h : ¬ nonempty ι) (hV : findim K V = 0) : is_basis K (λ x : ι, (0 : V)) := begin haveI : subsingleton V := findim_zero_iff.1 hV, exact is_basis_empty _ h end lemma is_basis_of_findim_zero' [finite_dimensional K V] (hV : findim K V = 0) : is_basis K (λ x : fin 0, (0 : V)) := is_basis_of_findim_zero (finset.univ_eq_empty.mp rfl) hV namespace linear_map theorem injective_iff_surjective_of_findim_eq_findim [finite_dimensional K V] [finite_dimensional K V₂] (H : findim K V = findim K V₂) {f : V →ₗ[K] V₂} : function.injective f ↔ function.surjective f := begin have := findim_range_add_findim_ker f, rw [← ker_eq_bot, ← range_eq_top], refine ⟨λ h, _, λ h, _⟩, { rw [h, findim_bot, add_zero, H] at this, exact eq_top_of_findim_eq this }, { rw [h, findim_top, H] at this, exact findim_eq_zero.1 (add_right_injective _ this) } end theorem findim_le_findim_of_injective [finite_dimensional K V] [finite_dimensional K V₂] {f : V →ₗ[K] V₂} (hf : function.injective f) : findim K V ≤ findim K V₂ := calc findim K V = findim K f.range + findim K f.ker : (findim_range_add_findim_ker f).symm ... = findim K f.range : by rw [ker_eq_bot.2 hf, findim_bot, add_zero] ... ≤ findim K V₂ : submodule.findim_le _ end linear_map namespace alg_hom lemma bijective {F : Type*} [field F] {E : Type*} [field E] [algebra F E] [finite_dimensional F E] (ϕ : E →ₐ[F] E) : function.bijective ϕ := have inj : function.injective ϕ.to_linear_map := ϕ.to_ring_hom.injective, ⟨inj, (linear_map.injective_iff_surjective_of_findim_eq_findim rfl).mp inj⟩ end alg_hom /-- Bijection between algebra equivalences and algebra homomorphisms -/ noncomputable def alg_equiv_equiv_alg_hom (F : Type u) [field F] (E : Type v) [field E] [algebra F E] [finite_dimensional F E] : (E ≃ₐ[F] E) ≃ (E →ₐ[F] E) := { to_fun := λ ϕ, ϕ.to_alg_hom, inv_fun := λ ϕ, alg_equiv.of_bijective ϕ ϕ.bijective, left_inv := λ _, by {ext, refl}, right_inv := λ _, by {ext, refl} } section /-- An integral domain that is module-finite as an algebra over a field is a field. -/ noncomputable def field_of_finite_dimensional (F K : Type*) [field F] [integral_domain K] [algebra F K] [finite_dimensional F K] : field K := { inv := λ x, if H : x = 0 then 0 else classical.some $ (show function.surjective (algebra.lmul_left F x), from linear_map.injective_iff_surjective.1 $ λ _ _, (mul_right_inj' H).1) 1, mul_inv_cancel := λ x hx, show x * dite _ _ _ = _, by { rw dif_neg hx, exact classical.some_spec ((show function.surjective (algebra.lmul_left F x), from linear_map.injective_iff_surjective.1 $ λ _ _, (mul_right_inj' hx).1) 1) }, inv_zero := dif_pos rfl, .. ‹integral_domain K› } end namespace submodule lemma findim_mono [finite_dimensional K V] : monotone (λ (s : submodule K V), findim K s) := λ s t hst, calc findim K s = findim K (comap t.subtype s) : linear_equiv.findim_eq (comap_subtype_equiv_of_le hst).symm ... ≤ findim K t : submodule.findim_le _ lemma lt_of_le_of_findim_lt_findim {s t : submodule K V} (le : s ≤ t) (lt : findim K s < findim K t) : s < t := lt_of_le_of_ne le (λ h, ne_of_lt lt (by rw h)) lemma lt_top_of_findim_lt_findim {s : submodule K V} (lt : findim K s < findim K V) : s < ⊤ := begin rw ← @findim_top K V at lt, exact lt_of_le_of_findim_lt_findim le_top lt end lemma findim_lt_findim_of_lt [finite_dimensional K V] {s t : submodule K V} (hst : s < t) : findim K s < findim K t := begin rw linear_equiv.findim_eq (comap_subtype_equiv_of_le (le_of_lt hst)).symm, refine findim_lt (lt_of_le_of_ne le_top _), intro h_eq_top, rw comap_subtype_eq_top at h_eq_top, apply not_le_of_lt hst h_eq_top, end end submodule section span open submodule lemma findim_span_le_card (s : set V) [fin : fintype s] : findim K (span K s) ≤ s.to_finset.card := begin haveI := span_of_finite K ⟨fin⟩, have : dim K (span K s) ≤ (mk s : cardinal) := dim_span_le s, rw [←findim_eq_dim, cardinal.fintype_card, ←set.to_finset_card] at this, exact_mod_cast this end lemma findim_span_eq_card {ι : Type*} [fintype ι] {b : ι → V} (hb : linear_independent K b) : findim K (span K (set.range b)) = fintype.card ι := begin haveI : finite_dimensional K (span K (set.range b)) := span_of_finite K (set.finite_range b), have : dim K (span K (set.range b)) = (mk (set.range b) : cardinal) := dim_span hb, rwa [←findim_eq_dim, ←lift_inj, mk_range_eq_of_injective hb.injective, cardinal.fintype_card, lift_nat_cast, lift_nat_cast, nat_cast_inj] at this, end lemma findim_span_set_eq_card (s : set V) [fin : fintype s] (hs : linear_independent K (coe : s → V)) : findim K (span K s) = s.to_finset.card := begin haveI := span_of_finite K ⟨fin⟩, have : dim K (span K s) = (mk s : cardinal) := dim_span_set hs, rw [←findim_eq_dim, cardinal.fintype_card, ←set.to_finset_card] at this, exact_mod_cast this end lemma span_lt_of_subset_of_card_lt_findim {s : set V} [fintype s] {t : submodule K V} (subset : s ⊆ t) (card_lt : s.to_finset.card < findim K t) : span K s < t := lt_of_le_of_findim_lt_findim (span_le.mpr subset) (lt_of_le_of_lt (findim_span_le_card _) card_lt) lemma span_lt_top_of_card_lt_findim {s : set V} [fintype s] (card_lt : s.to_finset.card < findim K V) : span K s < ⊤ := lt_top_of_findim_lt_findim (lt_of_le_of_lt (findim_span_le_card _) card_lt) lemma findim_span_singleton {v : V} (hv : v ≠ 0) : findim K (K ∙ v) = 1 := begin apply le_antisymm, { exact findim_span_le_card ({v} : set V) }, { rw [nat.succ_le_iff, findim_pos_iff], use [⟨v, mem_span_singleton_self v⟩, 0], simp [hv] } end end span section is_basis lemma linear_independent_of_span_eq_top_of_card_eq_findim {ι : Type*} [fintype ι] {b : ι → V} (span_eq : span K (set.range b) = ⊤) (card_eq : fintype.card ι = findim K V) : linear_independent K b := linear_independent_iff'.mpr $ λ s g dependent i i_mem_s, begin by_contra gx_ne_zero, -- We'll derive a contradiction by showing `b '' (univ \ {i})` of cardinality `n - 1` -- spans a vector space of dimension `n`. refine ne_of_lt (span_lt_top_of_card_lt_findim (show (b '' (set.univ \ {i})).to_finset.card < findim K V, from _)) _, { calc (b '' (set.univ \ {i})).to_finset.card = ((set.univ \ {i}).to_finset.image b).card : by rw [set.to_finset_card, fintype.card_of_finset] ... ≤ (set.univ \ {i}).to_finset.card : finset.card_image_le ... = (finset.univ.erase i).card : congr_arg finset.card (finset.ext (by simp [and_comm])) ... < finset.univ.card : finset.card_erase_lt_of_mem (finset.mem_univ i) ... = findim K V : card_eq }, -- We already have that `b '' univ` spans the whole space, -- so we only need to show that the span of `b '' (univ \ {i})` contains each `b j`. refine trans (le_antisymm (span_mono (set.image_subset_range _ _)) (span_le.mpr _)) span_eq, rintros _ ⟨j, rfl, rfl⟩, -- The case that `j ≠ i` is easy because `b j ∈ b '' (univ \ {i})`. by_cases j_eq : j = i, swap, { refine subset_span ⟨j, (set.mem_diff _).mpr ⟨set.mem_univ _, _⟩, rfl⟩, exact mt set.mem_singleton_iff.mp j_eq }, -- To show `b i ∈ span (b '' (univ \ {i}))`, we use that it's a weighted sum -- of the other `b j`s. rw [j_eq, mem_coe, show b i = -((g i)⁻¹ • (s.erase i).sum (λ j, g j • b j)), from _], { refine submodule.neg_mem _ (smul_mem _ _ (sum_mem _ (λ k hk, _))), obtain ⟨k_ne_i, k_mem⟩ := finset.mem_erase.mp hk, refine smul_mem _ _ (subset_span ⟨k, _, rfl⟩), simpa using k_mem }, -- To show `b i` is a weighted sum of the other `b j`s, we'll rewrite this sum -- to have the form of the assumption `dependent`. apply eq_neg_of_add_eq_zero, calc b i + (g i)⁻¹ • (s.erase i).sum (λ j, g j • b j) = (g i)⁻¹ • (g i • b i + (s.erase i).sum (λ j, g j • b j)) : by rw [smul_add, ←mul_smul, inv_mul_cancel gx_ne_zero, one_smul] ... = (g i)⁻¹ • 0 : congr_arg _ _ ... = 0 : smul_zero _, -- And then it's just a bit of manipulation with finite sums. rwa [← finset.insert_erase i_mem_s, finset.sum_insert (finset.not_mem_erase _ _)] at dependent end /-- A finite family of vectors is linearly independent if and only if its cardinality equals the dimension of its span. -/ lemma linear_independent_iff_card_eq_findim_span {ι : Type*} [fintype ι] {b : ι → V} : linear_independent K b ↔ fintype.card ι = findim K (span K (set.range b)) := begin split, { intro h, exact (findim_span_eq_card h).symm }, { intro hc, let f := (submodule.subtype (span K (set.range b))), let b' : ι → span K (set.range b) := λ i, ⟨b i, mem_span.2 (λ p hp, hp (set.mem_range_self _))⟩, have hs : span K (set.range b') = ⊤, { rw eq_top_iff', intro x, have h : span K (f '' (set.range b')) = map f (span K (set.range b')) := span_image f, have hf : f '' (set.range b') = set.range b, { ext x, simp [set.mem_image, set.mem_range] }, rw hf at h, have hx : (x : V) ∈ span K (set.range b) := x.property, conv at hx { congr, skip, rw h }, simpa [mem_map] using hx }, have hi : f.ker = ⊥ := ker_subtype _, convert (linear_independent_of_span_eq_top_of_card_eq_findim hs hc).map' _ hi } end lemma is_basis_of_span_eq_top_of_card_eq_findim {ι : Type*} [fintype ι] {b : ι → V} (span_eq : span K (set.range b) = ⊤) (card_eq : fintype.card ι = findim K V) : is_basis K b := ⟨linear_independent_of_span_eq_top_of_card_eq_findim span_eq card_eq, span_eq⟩ lemma finset_is_basis_of_span_eq_top_of_card_eq_findim {s : finset V} (span_eq : span K (↑s : set V) = ⊤) (card_eq : s.card = findim K V) : is_basis K (coe : (↑s : set V) → V) := is_basis_of_span_eq_top_of_card_eq_findim ((@subtype.range_coe_subtype _ (λ x, x ∈ s)).symm ▸ span_eq) (trans (fintype.card_coe _) card_eq) lemma set_is_basis_of_span_eq_top_of_card_eq_findim {s : set V} [fintype s] (span_eq : span K s = ⊤) (card_eq : s.to_finset.card = findim K V) : is_basis K (λ (x : s), (x : V)) := is_basis_of_span_eq_top_of_card_eq_findim ((@subtype.range_coe_subtype _ s).symm ▸ span_eq) (trans s.to_finset_card.symm card_eq) lemma span_eq_top_of_linear_independent_of_card_eq_findim {ι : Type*} [hι : nonempty ι] [fintype ι] {b : ι → V} (lin_ind : linear_independent K b) (card_eq : fintype.card ι = findim K V) : span K (set.range b) = ⊤ := begin by_cases fin : (finite_dimensional K V), { haveI := fin, by_contra ne_top, have lt_top : span K (set.range b) < ⊤ := lt_of_le_of_ne le_top ne_top, exact ne_of_lt (submodule.findim_lt lt_top) (trans (findim_span_eq_card lin_ind) card_eq) }, { exfalso, apply ne_of_lt (fintype.card_pos_iff.mpr hι), symmetry, calc fintype.card ι = findim K V : card_eq ... = 0 : dif_neg (mt finite_dimensional_iff_dim_lt_omega.mpr fin) } end lemma is_basis_of_linear_independent_of_card_eq_findim {ι : Type*} [nonempty ι] [fintype ι] {b : ι → V} (lin_ind : linear_independent K b) (card_eq : fintype.card ι = findim K V) : is_basis K b := ⟨lin_ind, span_eq_top_of_linear_independent_of_card_eq_findim lin_ind card_eq⟩ lemma finset_is_basis_of_linear_independent_of_card_eq_findim {s : finset V} (hs : s.nonempty) (lin_ind : linear_independent K (coe : (↑s : set V) → V)) (card_eq : s.card = findim K V) : is_basis K (coe : (↑s : set V) → V) := @is_basis_of_linear_independent_of_card_eq_findim _ _ _ _ _ _ ⟨(⟨hs.some, hs.some_spec⟩ : (↑s : set V))⟩ _ _ lin_ind (trans (fintype.card_coe _) card_eq) lemma set_is_basis_of_linear_independent_of_card_eq_findim {s : set V} [nonempty s] [fintype s] (lin_ind : linear_independent K (coe : s → V)) (card_eq : s.to_finset.card = findim K V) : is_basis K (coe : s → V) := is_basis_of_linear_independent_of_card_eq_findim lin_ind (trans s.to_finset_card.symm card_eq) end is_basis section subalgebra_dim open vector_space variables {F E : Type*} [field F] [field E] [algebra F E] lemma subalgebra.dim_eq_one_of_eq_bot {S : subalgebra F E} (h : S = ⊥) : dim F S = 1 := begin rw [← S.to_submodule_equiv.dim_eq, h, (linear_equiv.of_eq ↑(⊥ : subalgebra F E) _ algebra.to_submodule_bot).dim_eq, dim_span_set], exacts [mk_singleton _, linear_independent_singleton one_ne_zero] end @[simp] lemma subalgebra.dim_bot : dim F (⊥ : subalgebra F E) = 1 := subalgebra.dim_eq_one_of_eq_bot rfl lemma subalgebra_top_dim_eq_submodule_top_dim : dim F (⊤ : subalgebra F E) = dim F (⊤ : submodule F E) := by { rw ← algebra.coe_top, refl } lemma subalgebra_top_findim_eq_submodule_top_findim : findim F (⊤ : subalgebra F E) = findim F (⊤ : submodule F E) := by { rw ← algebra.coe_top, refl } lemma subalgebra.dim_top : dim F (⊤ : subalgebra F E) = dim F E := by { rw subalgebra_top_dim_eq_submodule_top_dim, exact dim_top } lemma subalgebra.finite_dimensional_bot : finite_dimensional F (⊥ : subalgebra F E) := finite_dimensional_of_dim_eq_one subalgebra.dim_bot @[simp] lemma subalgebra.findim_bot : findim F (⊥ : subalgebra F E) = 1 := begin haveI : finite_dimensional F (⊥ : subalgebra F E) := subalgebra.finite_dimensional_bot, have : dim F (⊥ : subalgebra F E) = 1 := subalgebra.dim_bot, rw ← findim_eq_dim at this, norm_cast at *, simp *, end lemma subalgebra.findim_eq_one_of_eq_bot {S : subalgebra F E} (h : S = ⊥) : findim F S = 1 := by { rw h, exact subalgebra.findim_bot } lemma subalgebra.eq_bot_of_findim_one {S : subalgebra F E} (h : findim F S = 1) : S = ⊥ := begin rw eq_bot_iff, let b : set S := {1}, have : fintype b := unique.fintype, have b_lin_ind : linear_independent F (coe : b → S) := linear_independent_singleton one_ne_zero, have b_card : fintype.card b = 1 := fintype.card_of_subsingleton _, obtain ⟨_, b_spans⟩ := set_is_basis_of_linear_independent_of_card_eq_findim b_lin_ind (by simp only [*, set.to_finset_card]), intros x hx, rw [subalgebra.mem_coe, algebra.mem_bot], have x_in_span_b : (⟨x, hx⟩ : S) ∈ submodule.span F b, { rw subtype.range_coe at b_spans, rw b_spans, exact submodule.mem_top, }, obtain ⟨a, ha⟩ := submodule.mem_span_singleton.mp x_in_span_b, replace ha : a • 1 = x := by injections with ha, exact ⟨a, by rw [← ha, algebra.smul_def, mul_one]⟩, end lemma subalgebra.eq_bot_of_dim_one {S : subalgebra F E} (h : dim F S = 1) : S = ⊥ := begin haveI : finite_dimensional F S := finite_dimensional_of_dim_eq_one h, rw ← findim_eq_dim at h, norm_cast at h, exact subalgebra.eq_bot_of_findim_one h, end @[simp] lemma subalgebra.bot_eq_top_of_dim_eq_one (h : dim F E = 1) : (⊥ : subalgebra F E) = ⊤ := begin rw [← dim_top, ← subalgebra_top_dim_eq_submodule_top_dim] at h, exact eq.symm (subalgebra.eq_bot_of_dim_one h), end @[simp] lemma subalgebra.bot_eq_top_of_findim_eq_one (h : findim F E = 1) : (⊥ : subalgebra F E) = ⊤ := begin rw [← findim_top, ← subalgebra_top_findim_eq_submodule_top_findim] at h, exact eq.symm (subalgebra.eq_bot_of_findim_one h), end @[simp] theorem subalgebra.dim_eq_one_iff {S : subalgebra F E} : dim F S = 1 ↔ S = ⊥ := ⟨subalgebra.eq_bot_of_dim_one, subalgebra.dim_eq_one_of_eq_bot⟩ @[simp] theorem subalgebra.findim_eq_one_iff {S : subalgebra F E} : findim F S = 1 ↔ S = ⊥ := ⟨subalgebra.eq_bot_of_findim_one, subalgebra.findim_eq_one_of_eq_bot⟩ end subalgebra_dim namespace module namespace End lemma exists_ker_pow_eq_ker_pow_succ [finite_dimensional K V] (f : End K V) : ∃ (k : ℕ), k ≤ findim K V ∧ (f ^ k).ker = (f ^ k.succ).ker := begin classical, by_contradiction h_contra, simp_rw [not_exists, not_and] at h_contra, have h_le_ker_pow : ∀ (n : ℕ), n ≤ (findim K V).succ → n ≤ findim K (f ^ n).ker, { intros n hn, induction n with n ih, { exact zero_le (findim _ _) }, { have h_ker_lt_ker : (f ^ n).ker < (f ^ n.succ).ker, { refine lt_of_le_of_ne _ (h_contra n (nat.le_of_succ_le_succ hn)), rw pow_succ, apply linear_map.ker_le_ker_comp }, have h_findim_lt_findim : findim K (f ^ n).ker < findim K (f ^ n.succ).ker, { apply submodule.findim_lt_findim_of_lt h_ker_lt_ker }, calc n.succ ≤ (findim K ↥(linear_map.ker (f ^ n))).succ : nat.succ_le_succ (ih (nat.le_of_succ_le hn)) ... ≤ findim K ↥(linear_map.ker (f ^ n.succ)) : nat.succ_le_of_lt h_findim_lt_findim } }, have h_le_findim_V : ∀ n, findim K (f ^ n).ker ≤ findim K V := λ n, submodule.findim_le _, have h_any_n_lt: ∀ n, n ≤ (findim K V).succ → n ≤ findim K V := λ n hn, (h_le_ker_pow n hn).trans (h_le_findim_V n), show false, from nat.not_succ_le_self _ (h_any_n_lt (findim K V).succ (findim K V).succ.le_refl), end lemma ker_pow_constant {f : End K V} {k : ℕ} (h : (f ^ k).ker = (f ^ k.succ).ker) : ∀ m, (f ^ k).ker = (f ^ (k + m)).ker | 0 := by simp | (m + 1) := begin apply le_antisymm, { rw [add_comm, pow_add], apply linear_map.ker_le_ker_comp }, { rw [ker_pow_constant m, add_comm m 1, ←add_assoc, pow_add, pow_add f k m], change linear_map.ker ((f ^ (k + 1)).comp (f ^ m)) ≤ linear_map.ker ((f ^ k).comp (f ^ m)), rw [linear_map.ker_comp, linear_map.ker_comp, h, nat.add_one], exact le_refl _, } end lemma ker_pow_eq_ker_pow_findim_of_le [finite_dimensional K V] {f : End K V} {m : ℕ} (hm : findim K V ≤ m) : (f ^ m).ker = (f ^ findim K V).ker := begin obtain ⟨k, h_k_le, hk⟩ : ∃ k, k ≤ findim K V ∧ linear_map.ker (f ^ k) = linear_map.ker (f ^ k.succ) := exists_ker_pow_eq_ker_pow_succ f, calc (f ^ m).ker = (f ^ (k + (m - k))).ker : by rw nat.add_sub_of_le (h_k_le.trans hm) ... = (f ^ k).ker : by rw ker_pow_constant hk _ ... = (f ^ (k + (findim K V - k))).ker : ker_pow_constant hk (findim K V - k) ... = (f ^ findim K V).ker : by rw nat.add_sub_of_le h_k_le end lemma ker_pow_le_ker_pow_findim [finite_dimensional K V] (f : End K V) (m : ℕ) : (f ^ m).ker ≤ (f ^ findim K V).ker := begin by_cases h_cases: m < findim K V, { rw [←nat.add_sub_of_le (nat.le_of_lt h_cases), add_comm, pow_add], apply linear_map.ker_le_ker_comp }, { rw [ker_pow_eq_ker_pow_findim_of_le (le_of_not_lt h_cases)], exact le_refl _ } end end End end module
345479eb870155b26c3c73dc3589cc60e97706be
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/lean/parser.lean
73694a63f31e2bb926fbe88d1a565098322bae5c
[ "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
5,263
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ prelude import init.meta.tactic init.meta.has_reflect init.control.alternative namespace lean -- TODO: make inspectable (and pure) meta constant parser_state : Type meta constant parser_state.env : parser_state → environment meta constant parser_state.options : parser_state → options meta constant parser_state.cur_pos : parser_state → pos @[reducible] meta def parser := interaction_monad parser_state @[reducible] meta def parser_result := interaction_monad.result parser_state open interaction_monad open interaction_monad.result namespace parser variable {α : Type} meta def val (p : lean.parser (reflected_value α)) : lean.parser α := reflected_value.val <$> p protected meta class reflectable (p : parser α) := (full : parser (reflected_value α)) namespace reflectable meta def expr {p : parser α} (r : reflectable p) : parser expr := reflected_value.expr <$> r.full meta def to_parser {p : parser α} (r : reflectable p) : parser α := val r.full end reflectable meta def get_env : parser environment := λ s, success s.env s meta constant set_env : environment → parser unit /-- Make sure the next token is an identifier, consume it, and produce the quoted name `t, where t is the identifier. -/ meta constant ident : parser name /-- Make sure the next token is a small nat, consume it, and produce it -/ meta constant small_nat : parser nat /-- Check that the next token is `tk` and consume it. `tk` must be a registered token. -/ meta constant tk (tk : string) : parser unit /-- Parse an unelaborated expression using the given right-binding power. When `pat := tt`, the expression is parsed as a pattern, i.e. local constants are not checked. -/ protected meta constant pexpr (rbp := std.prec.max) (pat := ff) : parser pexpr /-- a variable to local scope -/ meta constant add_local (v: expr) : parser unit meta constant add_local_level (v: name) : parser unit meta constant list_include_var_names : parser (list name) meta constant list_available_include_vars : parser (list expr) meta constant include_var : name → parser unit meta constant omit_var : name → parser unit meta constant push_local_scope : parser unit meta constant pop_local_scope : parser unit /-- Run the parser in a local declaration scope. Local declarations added via `add_local` do not propagate outside of this scope. -/ @[inline] meta def with_local_scope {α} (p : parser α) : parser α := interaction_monad.bracket push_local_scope p pop_local_scope protected meta constant itactic_reflected : parser (reflected_value (tactic unit)) /-- Parse an interactive tactic block: `begin` .. `end` -/ @[reducible] protected meta def itactic : parser (tactic unit) := val parser.itactic_reflected /-- Do not report info from content parsed by `p`. -/ meta constant skip_info (p : parser α) : parser α /-- Set goal info position of content parsed by `p` to current position. Nested calls take precedence. -/ meta constant set_goal_info_pos (p : parser α) : parser α /-- Return the current parser position without consuming any input. -/ meta def cur_pos : parser pos := λ s, success (parser_state.cur_pos s) s /-- Temporarily replace input of the parser state, run `p`, and return remaining input. -/ meta constant with_input (p : parser α) (input : string) : parser (α × string) /-- Parse a top-level command. -/ meta constant command_like : parser unit meta def parser_orelse (p₁ p₂ : parser α) : parser α := λ s, let pos₁ := parser_state.cur_pos s in result.cases_on (p₁ s) success (λ e₁ ref₁ s', let pos₂ := parser_state.cur_pos s' in if pos₁ ≠ pos₂ then exception e₁ ref₁ s' else result.cases_on (p₂ s) success exception) meta instance : alternative parser := { failure := @interaction_monad.failed _, orelse := @parser_orelse, ..interaction_monad.monad } -- TODO: move meta def {u v} many {f : Type u → Type v} [monad f] [alternative f] {a : Type u} : f a → f (list a) | x := (do y ← x, ys ← many x, return $ y::ys) <|> pure list.nil local postfix `?`:100 := optional local postfix `*`:100 := many meta def sep_by : parser unit → parser α → parser (list α) | s p := (list.cons <$> p <*> (s *> p)*) <|> return [] meta constant of_tactic : tactic α → parser α meta instance : has_coe (tactic α) (parser α) := ⟨of_tactic⟩ namespace reflectable meta instance cast (p : lean.parser (reflected_value α)) : reflectable (val p) := {full := p} meta instance has_reflect [r : has_reflect α] (p : lean.parser α) : reflectable p := {full := do rp ← p, return ⟨rp⟩} meta instance optional {α : Type} [reflected _ α] (p : parser α) [r : reflectable p] : reflectable (optional p) := {full := reflected_value.subst some <$> r.full <|> return ⟨none⟩} end reflectable meta def reflect (p : parser α) [r : reflectable p] : parser expr := r.expr meta constant run {α} : parser α → tactic α meta def run_with_input {α} : parser α → string → tactic α := λ p s, prod.fst <$> run (with_input p s) end parser end lean
880693349300fb1163d16de6424b69868012c01f
8be24982c807641260370bd09243eac768750811
/src/pi_transcendental.lean
162a3a35dabda09f5e40ebee4160e5bd82a94cb9
[]
no_license
jjaassoonn/transcendental
8008813253af3aa80b5a5c56551317e7ab4246ab
99bc6ea6089f04ed90a0f55f0533ebb7f47b22ff
refs/heads/master
1,607,869,957,944
1,599,659,687,000
1,599,659,687,000
234,444,826
9
1
null
1,598,218,307,000
1,579,224,232,000
HTML
UTF-8
Lean
false
false
144
lean
import data.real.pi import ring_theory.algebraic theorem pi_transcendental : ¬ (is_algebraic rat real.pi) := begin sorry end #check real.pi