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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
865d3677dce4bb8872759ed1ee1f0da01208a06e | 59a4b050600ed7b3d5826a8478db0a9bdc190252 | /src/category_theory/filtered.lean | 22021282762a0fe908343ca1460fbabaeade0423 | [] | no_license | rwbarton/lean-category-theory | f720268d800b62a25d69842ca7b5d27822f00652 | 00df814d463406b7a13a56f5dcda67758ba1b419 | refs/heads/master | 1,585,366,296,767 | 1,536,151,349,000 | 1,536,151,349,000 | 147,652,096 | 0 | 0 | null | 1,536,226,960,000 | 1,536,226,960,000 | null | UTF-8 | Lean | false | false | 926 | lean | import category_theory.limits.shape
import category_theory.preorder
import order.filter
open category_theory.limits
namespace category_theory
universes u₁ v₁
variables α : Type u₁
class directed [preorder α] :=
(bound (x₁ x₂ : α) : α)
(i₁ (x₁ x₂ : α) : x₁ ≤ bound x₁ x₂)
(i₂ (x₁ x₂ : α) : x₂ ≤ bound x₁ x₂)
variables (C : Type u₁) [𝒞 : category.{u₁ v₁} C]
include 𝒞
class filtered :=
(default : C)
(obj_bound (X Y : C) : cospan X Y)
(hom_bound {X Y : C} (f g : X ⟶ Y) : cofork f g)
instance [inhabited α] [preorder α] [directed α] : filtered.{u₁ u₁} α :=
{ default := default α,
obj_bound := λ x y, { X := directed.bound x y, ι₁ := ⟨ ⟨ directed.i₁ x y ⟩ ⟩, ι₂ := ⟨ ⟨ directed.i₂ x y ⟩ ⟩ },
hom_bound := λ _ y f g, { X := y, π := 𝟙 y, w := begin cases f, cases f, cases g, cases g, simp end } }
end category_theory |
3db6b47b89a197c03a4f55d33bb735acc20dda03 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/algebra/module/torsion.lean | 40f0f8bba13ed0303bb71830f12522e2b9ac00f6 | [
"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 | 27,501 | lean | /-
Copyright (c) 2022 Pierre-Alexandre Bazin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Pierre-Alexandre Bazin
-/
import algebra.direct_sum.module
import linear_algebra.isomorphisms
import group_theory.torsion
import ring_theory.coprime.ideal
import ring_theory.finiteness
/-!
# Torsion submodules
## Main definitions
* `torsion_of R M x` : the torsion ideal of `x`, containing all `a` such that `a • x = 0`.
* `submodule.torsion_by R M a` : the `a`-torsion submodule, containing all elements `x` of `M` such
that `a • x = 0`.
* `submodule.torsion_by_set R M s` : the submodule containing all elements `x` of `M` such that
`a • x = 0` for all `a` in `s`.
* `submodule.torsion' R M S` : the `S`-torsion submodule, containing all elements `x` of `M` such
that `a • x = 0` for some `a` in `S`.
* `submodule.torsion R M` : the torsion submoule, containing all elements `x` of `M` such that
`a • x = 0` for some non-zero-divisor `a` in `R`.
* `module.is_torsion_by R M a` : the property that defines a `a`-torsion module. Similarly,
`is_torsion_by_set`, `is_torsion'` and `is_torsion`.
* `module.is_torsion_by_set.module` : Creates a `R ⧸ I`-module from a `R`-module that
`is_torsion_by_set R _ I`.
## Main statements
* `quot_torsion_of_equiv_span_singleton` : isomorphism between the span of an element of `M` and
the quotient by its torsion ideal.
* `torsion' R M S` and `torsion R M` are submodules.
* `torsion_by_set_eq_torsion_by_span` : torsion by a set is torsion by the ideal generated by it.
* `submodule.torsion_by_is_torsion_by` : the `a`-torsion submodule is a `a`-torsion module.
Similar lemmas for `torsion'` and `torsion`.
* `submodule.torsion_by_is_internal` : a `∏ i, p i`-torsion module is the internal direct sum of its
`p i`-torsion submodules when the `p i` are pairwise coprime. A more general version with coprime
ideals is `submodule.torsion_by_set_is_internal`.
* `submodule.no_zero_smul_divisors_iff_torsion_bot` : a module over a domain has
`no_zero_smul_divisors` (that is, there is no non-zero `a`, `x` such that `a • x = 0`)
iff its torsion submodule is trivial.
* `submodule.quotient_torsion.torsion_eq_bot` : quotienting by the torsion submodule makes the
torsion submodule of the new module trivial. If `R` is a domain, we can derive an instance
`submodule.quotient_torsion.no_zero_smul_divisors : no_zero_smul_divisors R (M ⧸ torsion R M)`.
## Notation
* The notions are defined for a `comm_semiring R` and a `module R M`. Some additional hypotheses on
`R` and `M` are required by some lemmas.
* The letters `a`, `b`, ... are used for scalars (in `R`), while `x`, `y`, ... are used for vectors
(in `M`).
## Tags
Torsion, submodule, module, quotient
-/
namespace ideal
section torsion_of
variables (R M : Type*) [semiring R] [add_comm_monoid M] [module R M]
/--The torsion ideal of `x`, containing all `a` such that `a • x = 0`.-/
@[simps] def torsion_of (x : M) : ideal R := (linear_map.to_span_singleton R M x).ker
@[simp] lemma torsion_of_zero : torsion_of R M (0 : M) = ⊤ := by simp [torsion_of]
variables {R M}
@[simp] lemma mem_torsion_of_iff (x : M) (a : R) : a ∈ torsion_of R M x ↔ a • x = 0 := iff.rfl
variables (R)
@[simp] lemma torsion_of_eq_top_iff (m : M) : torsion_of R M m = ⊤ ↔ m = 0 :=
begin
refine ⟨λ h, _, λ h, by simp [h]⟩,
rw [← one_smul R m, ← mem_torsion_of_iff m (1 : R), h],
exact submodule.mem_top,
end
@[simp] lemma torsion_of_eq_bot_iff_of_no_zero_smul_divisors
[nontrivial R] [no_zero_smul_divisors R M] (m : M) :
torsion_of R M m = ⊥ ↔ m ≠ 0 :=
begin
refine ⟨λ h contra, _, λ h, (submodule.eq_bot_iff _).mpr $ λ r hr, _⟩,
{ rw [contra, torsion_of_zero] at h,
exact bot_ne_top.symm h, },
{ rw [mem_torsion_of_iff, smul_eq_zero] at hr,
tauto, },
end
/-- See also `complete_lattice.independent.linear_independent` which provides the same conclusion
but requires the stronger hypothesis `no_zero_smul_divisors R M`. -/
lemma complete_lattice.independent.linear_independent' {ι R M : Type*} {v : ι → M}
[ring R] [add_comm_group M] [module R M]
(hv : complete_lattice.independent $ λ i, (R ∙ v i))
(h_ne_zero : ∀ i, ideal.torsion_of R M (v i) = ⊥) :
linear_independent R v :=
begin
refine linear_independent_iff_not_smul_mem_span.mpr (λ i r hi, _),
replace hv := complete_lattice.independent_def.mp hv i,
simp only [supr_subtype', ← submodule.span_range_eq_supr, disjoint_iff] at hv,
have : r • v i ∈ ⊥,
{ rw [← hv, submodule.mem_inf],
refine ⟨submodule.mem_span_singleton.mpr ⟨r, rfl⟩, _⟩,
convert hi,
ext,
simp, },
rw [← submodule.mem_bot R, ← h_ne_zero i],
simpa using this,
end
end torsion_of
section
variables (R M : Type*) [ring R] [add_comm_group M] [module R M]
/--The span of `x` in `M` is isomorphic to `R` quotiented by the torsion ideal of `x`.-/
noncomputable def quot_torsion_of_equiv_span_singleton (x : M) :
(R ⧸ torsion_of R M x) ≃ₗ[R] (R ∙ x) :=
(linear_map.to_span_singleton R M x).quot_ker_equiv_range.trans $
linear_equiv.of_eq _ _ (linear_map.span_singleton_eq_range R M x).symm
variables {R M}
@[simp] lemma quot_torsion_of_equiv_span_singleton_apply_mk (x : M) (a : R) :
quot_torsion_of_equiv_span_singleton R M x (submodule.quotient.mk a) =
a • ⟨x, submodule.mem_span_singleton_self x⟩ := rfl
end
end ideal
open_locale non_zero_divisors
section defs
variables (R M : Type*) [comm_semiring R] [add_comm_monoid M] [module R M]
namespace submodule
/-- The `a`-torsion submodule for `a` in `R`, containing all elements `x` of `M` such that
`a • x = 0`. -/
@[simps] def torsion_by (a : R) : submodule R M := (distrib_mul_action.to_linear_map R M a).ker
/-- The submodule containing all elements `x` of `M` such that `a • x = 0` for all `a` in `s`. -/
@[simps] def torsion_by_set (s : set R) : submodule R M := Inf (torsion_by R M '' s)
/-- The `S`-torsion submodule, containing all elements `x` of `M` such that `a • x = 0` for some
`a` in `S`. -/
@[simps] def torsion' (S : Type*)
[comm_monoid S] [distrib_mul_action S M] [smul_comm_class S R M] :
submodule R M :=
{ carrier := { x | ∃ a : S, a • x = 0 },
zero_mem' := ⟨1, smul_zero _⟩,
add_mem' := λ x y ⟨a, hx⟩ ⟨b, hy⟩,
⟨b * a,
by rw [smul_add, mul_smul, mul_comm, mul_smul, hx, hy, smul_zero, smul_zero, add_zero]⟩,
smul_mem' := λ a x ⟨b, h⟩, ⟨b, by rw [smul_comm, h, smul_zero]⟩ }
/-- The torsion submodule, containing all elements `x` of `M` such that `a • x = 0` for some
non-zero-divisor `a` in `R`. -/
@[reducible] def torsion := torsion' R M R⁰
end submodule
namespace module
/-- A `a`-torsion module is a module where every element is `a`-torsion. -/
@[reducible] def is_torsion_by (a : R) := ∀ ⦃x : M⦄, a • x = 0
/-- A module where every element is `a`-torsion for all `a` in `s`. -/
@[reducible] def is_torsion_by_set (s : set R) := ∀ ⦃x : M⦄ ⦃a : s⦄, (a : R) • x = 0
/-- A `S`-torsion module is a module where every element is `a`-torsion for some `a` in `S`. -/
@[reducible] def is_torsion' (S : Type*) [has_smul S M] := ∀ ⦃x : M⦄, ∃ a : S, a • x = 0
/-- A torsion module is a module where every element is `a`-torsion for some non-zero-divisor `a`.
-/
@[reducible] def is_torsion := ∀ ⦃x : M⦄, ∃ a : R⁰, a • x = 0
end module
end defs
variables {R M : Type*}
section
variables [comm_semiring R] [add_comm_monoid M] [module R M] (s : set R) (a : R)
namespace submodule
@[simp] lemma smul_torsion_by (x : torsion_by R M a) : a • x = 0 := subtype.ext x.prop
@[simp] lemma smul_coe_torsion_by (x : torsion_by R M a) : a • (x : M) = 0 := x.prop
@[simp] lemma mem_torsion_by_iff (x : M) : x ∈ torsion_by R M a ↔ a • x = 0 := iff.rfl
@[simp] lemma mem_torsion_by_set_iff (x : M) :
x ∈ torsion_by_set R M s ↔ ∀ a : s, (a : R) • x = 0 :=
begin
refine ⟨λ h ⟨a, ha⟩, mem_Inf.mp h _ (set.mem_image_of_mem _ ha), λ h, mem_Inf.mpr _⟩,
rintro _ ⟨a, ha, rfl⟩, exact h ⟨a, ha⟩
end
@[simp] lemma torsion_by_singleton_eq : torsion_by_set R M {a} = torsion_by R M a :=
begin
ext x,
simp only [mem_torsion_by_set_iff, set_coe.forall, subtype.coe_mk, set.mem_singleton_iff,
forall_eq, mem_torsion_by_iff]
end
lemma torsion_by_set_le_torsion_by_set_of_subset {s t : set R} (st : s ⊆ t) :
torsion_by_set R M t ≤ torsion_by_set R M s :=
Inf_le_Inf $ λ _ ⟨a, ha, h⟩, ⟨a, st ha, h⟩
/-- Torsion by a set is torsion by the ideal generated by it. -/
lemma torsion_by_set_eq_torsion_by_span :
torsion_by_set R M s = torsion_by_set R M (ideal.span s) :=
begin
refine le_antisymm (λ x hx, _) (torsion_by_set_le_torsion_by_set_of_subset subset_span),
rw mem_torsion_by_set_iff at hx ⊢,
suffices : ideal.span s ≤ ideal.torsion_of R M x,
{ rintro ⟨a, ha⟩, exact this ha },
rw ideal.span_le, exact λ a ha, hx ⟨a, ha⟩
end
lemma torsion_by_span_singleton_eq : torsion_by_set R M (R ∙ a) = torsion_by R M a :=
((torsion_by_set_eq_torsion_by_span _).symm.trans $ torsion_by_singleton_eq _)
lemma torsion_by_le_torsion_by_of_dvd (a b : R) (dvd : a ∣ b) :
torsion_by R M a ≤ torsion_by R M b :=
begin
rw [← torsion_by_span_singleton_eq, ← torsion_by_singleton_eq],
apply torsion_by_set_le_torsion_by_set_of_subset,
rintro c (rfl : c = b), exact ideal.mem_span_singleton.mpr dvd
end
@[simp] lemma torsion_by_one : torsion_by R M 1 = ⊥ :=
eq_bot_iff.mpr (λ _ h, by { rw [mem_torsion_by_iff, one_smul] at h, exact h })
@[simp] lemma torsion_by_univ : torsion_by_set R M set.univ = ⊥ :=
by { rw [eq_bot_iff, ← torsion_by_one, ← torsion_by_singleton_eq],
exact torsion_by_set_le_torsion_by_set_of_subset (λ _ _, trivial) }
end submodule
open submodule
namespace module
@[simp] lemma is_torsion_by_singleton_iff : is_torsion_by_set R M {a} ↔ is_torsion_by R M a :=
begin
refine ⟨λ h x, @h _ ⟨_, set.mem_singleton _⟩, λ h x, _⟩,
rintro ⟨b, rfl : b = a⟩, exact @h _
end
lemma is_torsion_by_set_iff_torsion_by_set_eq_top :
is_torsion_by_set R M s ↔ submodule.torsion_by_set R M s = ⊤ :=
⟨λ h, eq_top_iff.mpr (λ _ _, (mem_torsion_by_set_iff _ _).mpr $ @h _),
λ h x, by { rw [← mem_torsion_by_set_iff, h], trivial }⟩
/-- A `a`-torsion module is a module whose `a`-torsion submodule is the full space. -/
lemma is_torsion_by_iff_torsion_by_eq_top : is_torsion_by R M a ↔ torsion_by R M a = ⊤ :=
by rw [← torsion_by_singleton_eq, ← is_torsion_by_singleton_iff,
is_torsion_by_set_iff_torsion_by_set_eq_top]
lemma is_torsion_by_set_iff_is_torsion_by_span :
is_torsion_by_set R M s ↔ is_torsion_by_set R M (ideal.span s) :=
by rw [is_torsion_by_set_iff_torsion_by_set_eq_top, is_torsion_by_set_iff_torsion_by_set_eq_top,
torsion_by_set_eq_torsion_by_span]
lemma is_torsion_by_span_singleton_iff : is_torsion_by_set R M (R ∙ a) ↔ is_torsion_by R M a :=
((is_torsion_by_set_iff_is_torsion_by_span _).symm.trans $ is_torsion_by_singleton_iff _)
end module
namespace submodule
open module
lemma torsion_by_set_is_torsion_by_set : is_torsion_by_set R (torsion_by_set R M s) s :=
λ ⟨x, hx⟩ a, subtype.ext $ (mem_torsion_by_set_iff _ _).mp hx a
/-- The `a`-torsion submodule is a `a`-torsion module. -/
lemma torsion_by_is_torsion_by : is_torsion_by R (torsion_by R M a) a := λ _, smul_torsion_by _ _
@[simp] lemma torsion_by_torsion_by_eq_top : torsion_by R (torsion_by R M a) a = ⊤ :=
(is_torsion_by_iff_torsion_by_eq_top a).mp $ torsion_by_is_torsion_by a
@[simp] lemma torsion_by_set_torsion_by_set_eq_top :
torsion_by_set R (torsion_by_set R M s) s = ⊤ :=
(is_torsion_by_set_iff_torsion_by_set_eq_top s).mp $ torsion_by_set_is_torsion_by_set s
variables (R M)
lemma torsion_gc : @galois_connection (submodule R M) (ideal R)ᵒᵈ _ _
annihilator (λ I, torsion_by_set R M $ I.of_dual) :=
λ A I, ⟨λ h x hx, (mem_torsion_by_set_iff _ _).mpr $ λ ⟨a, ha⟩, mem_annihilator.mp (h ha) x hx,
λ h a ha, mem_annihilator.mpr $ λ x hx, (mem_torsion_by_set_iff _ _).mp (h hx) ⟨a, ha⟩⟩
variables {R M}
section coprime
open_locale big_operators
variables {ι : Type*} {p : ι → ideal R} {S : finset ι}
variables (hp : (S : set ι).pairwise $ λ i j, p i ⊔ p j = ⊤)
include hp
lemma supr_torsion_by_ideal_eq_torsion_by_infi :
(⨆ i ∈ S, torsion_by_set R M $ p i) = torsion_by_set R M ↑(⨅ i ∈ S, p i) :=
begin
cases S.eq_empty_or_nonempty with h h,
{ rw h, convert supr_emptyset, convert torsion_by_univ, convert top_coe, exact infi_emptyset },
apply le_antisymm,
{ apply supr_le _, intro i, apply supr_le _, intro is,
apply torsion_by_set_le_torsion_by_set_of_subset,
exact (infi_le (λ i, ⨅ (H : i ∈ S), p i) i).trans (infi_le _ is), },
{ intros x hx,
rw mem_supr_finset_iff_exists_sum,
obtain ⟨μ, hμ⟩ := (mem_supr_finset_iff_exists_sum _ _).mp
((ideal.eq_top_iff_one _).mp $ (ideal.supr_infi_eq_top_iff_pairwise h _).mpr hp),
refine ⟨λ i, ⟨(μ i : R) • x, _⟩, _⟩,
{ rw mem_torsion_by_set_iff at hx ⊢,
rintro ⟨a, ha⟩, rw smul_smul,
suffices : a * μ i ∈ ⨅ i ∈ S, p i, from hx ⟨_, this⟩,
rw mem_infi, intro j, rw mem_infi, intro hj,
by_cases ij : j = i,
{ rw ij, exact ideal.mul_mem_right _ _ ha },
{ have := coe_mem (μ i), simp only [mem_infi] at this,
exact ideal.mul_mem_left _ _ (this j hj ij) } },
{ simp_rw coe_mk, rw [← finset.sum_smul, hμ, one_smul] } }
end
lemma sup_indep_torsion_by_ideal : S.sup_indep (λ i, torsion_by_set R M $ p i) :=
λ T hT i hi hiT, begin
rw [disjoint_iff, finset.sup_eq_supr,
supr_torsion_by_ideal_eq_torsion_by_infi $ λ i hi j hj ij, hp (hT hi) (hT hj) ij],
have := @galois_connection.u_inf _ _ (order_dual.to_dual _) (order_dual.to_dual _) _ _ _ _
(torsion_gc R M), dsimp at this ⊢,
rw [← this, ideal.sup_infi_eq_top, top_coe, torsion_by_univ],
intros j hj, apply hp hi (hT hj), rintro rfl, exact hiT hj
end
omit hp
variables {q : ι → R} (hq : (S : set ι).pairwise $ is_coprime on q)
include hq
lemma supr_torsion_by_eq_torsion_by_prod :
(⨆ i ∈ S, torsion_by R M $ q i) = torsion_by R M (∏ i in S, q i) :=
begin
rw [← torsion_by_span_singleton_eq, ideal.submodule_span_eq,
← ideal.finset_inf_span_singleton _ _ hq, finset.inf_eq_infi,
← supr_torsion_by_ideal_eq_torsion_by_infi],
{ congr, ext : 1, congr, ext : 1, exact (torsion_by_span_singleton_eq _).symm },
{ exact λ i hi j hj ij, (ideal.sup_eq_top_iff_is_coprime _ _).mpr (hq hi hj ij), }
end
lemma sup_indep_torsion_by : S.sup_indep (λ i, torsion_by R M $ q i) :=
begin
convert sup_indep_torsion_by_ideal
(λ i hi j hj ij, (ideal.sup_eq_top_iff_is_coprime (q i) _).mpr $ hq hi hj ij),
ext : 1, exact (torsion_by_span_singleton_eq _).symm,
end
end coprime
end submodule
end
section needs_group
variables [comm_ring R] [add_comm_group M] [module R M]
namespace submodule
open_locale big_operators
variables {ι : Type*} [decidable_eq ι] {S : finset ι}
/--If the `p i` are pairwise coprime, a `⨅ i, p i`-torsion module is the internal direct sum of
its `p i`-torsion submodules.-/
lemma torsion_by_set_is_internal {p : ι → ideal R}
(hp : (S : set ι).pairwise $ λ i j, p i ⊔ p j = ⊤)
(hM : module.is_torsion_by_set R M (⨅ i ∈ S, p i : ideal R)) :
direct_sum.is_internal (λ i : S, torsion_by_set R M $ p i) :=
direct_sum.is_internal_submodule_of_independent_of_supr_eq_top
(complete_lattice.independent_iff_sup_indep.mpr $ sup_indep_torsion_by_ideal hp)
((supr_subtype'' ↑S $ λ i, torsion_by_set R M $ p i).trans $
(supr_torsion_by_ideal_eq_torsion_by_infi hp).trans $
(module.is_torsion_by_set_iff_torsion_by_set_eq_top _).mp hM)
/--If the `q i` are pairwise coprime, a `∏ i, q i`-torsion module is the internal direct sum of
its `q i`-torsion submodules.-/
lemma torsion_by_is_internal {q : ι → R} (hq : (S : set ι).pairwise $ is_coprime on q)
(hM : module.is_torsion_by R M $ ∏ i in S, q i) :
direct_sum.is_internal (λ i : S, torsion_by R M $ q i) :=
begin
rw [← module.is_torsion_by_span_singleton_iff, ideal.submodule_span_eq,
← ideal.finset_inf_span_singleton _ _ hq, finset.inf_eq_infi] at hM,
convert torsion_by_set_is_internal
(λ i hi j hj ij, (ideal.sup_eq_top_iff_is_coprime (q i) _).mpr $ hq hi hj ij) hM,
ext : 1, exact (torsion_by_span_singleton_eq _).symm,
end
end submodule
namespace module
variables {I : ideal R} (hM : is_torsion_by_set R M I)
include hM
/-- can't be an instance because hM can't be inferred -/
def is_torsion_by_set.has_smul : has_smul (R ⧸ I) M :=
{ smul := λ b x, quotient.lift_on' b (• x) $ λ b₁ b₂ h, begin
show b₁ • x = b₂ • x,
have : (-b₁ + b₂) • x = 0 := @hM x ⟨_, quotient_add_group.left_rel_apply.mp h⟩,
rw [add_smul, neg_smul, neg_add_eq_zero] at this,
exact this
end }
@[simp] lemma is_torsion_by_set.mk_smul (b : R) (x : M) :
by haveI := hM.has_smul; exact ideal.quotient.mk I b • x = b • x := rfl
/-- A `(R ⧸ I)`-module is a `R`-module which `is_torsion_by_set R M I`. -/
def is_torsion_by_set.module : module (R ⧸ I) M :=
@function.surjective.module_left _ _ _ _ _ _ _ hM.has_smul
_ ideal.quotient.mk_surjective (is_torsion_by_set.mk_smul hM)
instance is_torsion_by_set.is_scalar_tower {S : Type*} [has_smul S R] [has_smul S M]
[is_scalar_tower S R M] [is_scalar_tower S R R] :
@@is_scalar_tower S (R ⧸ I) M _ (is_torsion_by_set.module hM).to_has_smul _ :=
{ smul_assoc := λ b d x, quotient.induction_on' d $ λ c, (smul_assoc b c x : _) }
omit hM
instance : module (R ⧸ I) (M ⧸ I • (⊤ : submodule R M)) :=
is_torsion_by_set.module (λ x r, begin
induction x using quotient.induction_on,
refine (submodule.quotient.mk_eq_zero _).mpr (submodule.smul_mem_smul r.prop _),
trivial,
end)
end module
namespace submodule
instance (I : ideal R) : module (R ⧸ I) (torsion_by_set R M I) :=
module.is_torsion_by_set.module $ torsion_by_set_is_torsion_by_set I
@[simp] lemma torsion_by_set.mk_smul (I : ideal R) (b : R) (x : torsion_by_set R M I) :
ideal.quotient.mk I b • x = b • x := rfl
instance (I : ideal R) {S : Type*} [has_smul S R] [has_smul S M]
[is_scalar_tower S R M] [is_scalar_tower S R R] :
is_scalar_tower S (R ⧸ I) (torsion_by_set R M I) :=
infer_instance
/-- The `a`-torsion submodule as a `(R ⧸ R∙a)`-module. -/
instance (a : R) : module (R ⧸ R ∙ a) (torsion_by R M a) :=
module.is_torsion_by_set.module $
(module.is_torsion_by_span_singleton_iff a).mpr $ torsion_by_is_torsion_by a
@[simp] lemma torsion_by.mk_smul (a b : R) (x : torsion_by R M a) :
ideal.quotient.mk (R ∙ a) b • x = b • x := rfl
instance (a : R) {S : Type*} [has_smul S R] [has_smul S M]
[is_scalar_tower S R M] [is_scalar_tower S R R] :
is_scalar_tower S (R ⧸ R ∙ a) (torsion_by R M a) :=
infer_instance
end submodule
end needs_group
namespace submodule
section torsion'
open module
variables [comm_semiring R] [add_comm_monoid M] [module R M]
variables (S : Type*) [comm_monoid S] [distrib_mul_action S M] [smul_comm_class S R M]
@[simp] lemma mem_torsion'_iff (x : M) : x ∈ torsion' R M S ↔ ∃ a : S, a • x = 0 := iff.rfl
@[simp] lemma mem_torsion_iff (x : M) : x ∈ torsion R M ↔ ∃ a : R⁰, a • x = 0 := iff.rfl
@[simps] instance : has_smul S (torsion' R M S) :=
⟨λ s x, ⟨s • x, by { obtain ⟨x, a, h⟩ := x, use a, dsimp, rw [smul_comm, h, smul_zero] }⟩⟩
instance : distrib_mul_action S (torsion' R M S) := subtype.coe_injective.distrib_mul_action
((torsion' R M S).subtype).to_add_monoid_hom (λ (c : S) x, rfl)
instance : smul_comm_class S R (torsion' R M S) := ⟨λ s a x, subtype.ext $ smul_comm _ _ _⟩
/-- A `S`-torsion module is a module whose `S`-torsion submodule is the full space. -/
lemma is_torsion'_iff_torsion'_eq_top : is_torsion' M S ↔ torsion' R M S = ⊤ :=
⟨λ h, eq_top_iff.mpr (λ _ _, @h _), λ h x, by { rw [← @mem_torsion'_iff R, h], trivial }⟩
/-- The `S`-torsion submodule is a `S`-torsion module. -/
lemma torsion'_is_torsion' : is_torsion' (torsion' R M S) S := λ ⟨x, ⟨a, h⟩⟩, ⟨a, subtype.ext h⟩
@[simp] lemma torsion'_torsion'_eq_top : torsion' R (torsion' R M S) S = ⊤ :=
(is_torsion'_iff_torsion'_eq_top S).mp $ torsion'_is_torsion' S
/-- The torsion submodule of the torsion submodule (viewed as a module) is the full
torsion module. -/
@[simp] lemma torsion_torsion_eq_top : torsion R (torsion R M) = ⊤ := torsion'_torsion'_eq_top R⁰
/-- The torsion submodule is always a torsion module. -/
lemma torsion_is_torsion : module.is_torsion R (torsion R M) := torsion'_is_torsion' R⁰
end torsion'
section torsion
variables [comm_semiring R] [add_comm_monoid M] [module R M]
open_locale big_operators
lemma is_torsion_by_ideal_of_finite_of_is_torsion [module.finite R M] (hM : module.is_torsion R M) :
∃ I : ideal R, (I : set R) ∩ R⁰ ≠ ∅ ∧ module.is_torsion_by_set R M I :=
begin
cases (module.finite_def.mp infer_instance : (⊤ : submodule R M).fg) with S h,
refine ⟨∏ x in S, ideal.torsion_of R M x, _, _⟩,
{ rw set.ne_empty_iff_nonempty,
refine ⟨_, _, (∏ x in S, (@hM x).some : R⁰).2⟩,
rw [subtype.val_eq_coe, submonoid.coe_finset_prod],
apply ideal.prod_mem_prod,
exact λ x _, (@hM x).some_spec },
{ rw [module.is_torsion_by_set_iff_torsion_by_set_eq_top, eq_top_iff, ← h, span_le],
intros x hx, apply torsion_by_set_le_torsion_by_set_of_subset,
{ apply ideal.le_of_dvd, exact finset.dvd_prod_of_mem _ hx },
{ rw mem_torsion_by_set_iff, rintro ⟨a, ha⟩, exact ha } }
end
variables [no_zero_divisors R] [nontrivial R]
lemma coe_torsion_eq_annihilator_ne_bot :
(torsion R M : set M) = { x : M | (R ∙ x).annihilator ≠ ⊥ } :=
begin
ext x, simp_rw [submodule.ne_bot_iff, mem_annihilator, mem_span_singleton],
exact ⟨λ ⟨a, hax⟩, ⟨a, λ _ ⟨b, hb⟩, by rw [← hb, smul_comm, ← submonoid.smul_def, hax, smul_zero],
non_zero_divisors.coe_ne_zero _⟩,
λ ⟨a, hax, ha⟩, ⟨⟨_, mem_non_zero_divisors_of_ne_zero ha⟩, hax x ⟨1, one_smul _ _⟩⟩⟩
end
/-- A module over a domain has `no_zero_smul_divisors` iff its torsion submodule is trivial. -/
lemma no_zero_smul_divisors_iff_torsion_eq_bot :
no_zero_smul_divisors R M ↔ torsion R M = ⊥ :=
begin
split; intro h,
{ haveI : no_zero_smul_divisors R M := h,
rw eq_bot_iff, rintro x ⟨a, hax⟩,
change (a : R) • x = 0 at hax,
cases eq_zero_or_eq_zero_of_smul_eq_zero hax with h0 h0,
{ exfalso, exact non_zero_divisors.coe_ne_zero a h0 }, { exact h0 } },
{ exact { eq_zero_or_eq_zero_of_smul_eq_zero := λ a x hax, begin
by_cases ha : a = 0,
{ left, exact ha },
{ right, rw [← mem_bot _, ← h],
exact ⟨⟨a, mem_non_zero_divisors_of_ne_zero ha⟩, hax⟩ }
end } }
end
end torsion
namespace quotient_torsion
variables [comm_ring R] [add_comm_group M] [module R M]
/-- Quotienting by the torsion submodule gives a torsion-free module. -/
@[simp] lemma torsion_eq_bot : torsion R (M ⧸ torsion R M) = ⊥ :=
eq_bot_iff.mpr $ λ z, quotient.induction_on' z $ λ x ⟨a, hax⟩,
begin
rw [quotient.mk'_eq_mk, ← quotient.mk_smul, quotient.mk_eq_zero] at hax,
rw [mem_bot, quotient.mk'_eq_mk, quotient.mk_eq_zero],
cases hax with b h,
exact ⟨b * a, (mul_smul _ _ _).trans h⟩
end
instance no_zero_smul_divisors [is_domain R] : no_zero_smul_divisors R (M ⧸ torsion R M) :=
no_zero_smul_divisors_iff_torsion_eq_bot.mpr torsion_eq_bot
end quotient_torsion
section p_torsion
open module
section
variables [monoid R] [add_comm_monoid M] [distrib_mul_action R M]
lemma is_torsion'_powers_iff (p : R) :
is_torsion' M (submonoid.powers p) ↔ ∀ x : M, ∃ n : ℕ, p ^ n • x = 0 :=
⟨λ h x, let ⟨⟨a, ⟨n, rfl⟩⟩, hx⟩ := @h x in ⟨n, hx⟩,
λ h x, let ⟨n, hn⟩ := h x in ⟨⟨_, ⟨n, rfl⟩⟩, hn⟩⟩
/--In a `p ^ ∞`-torsion module (that is, a module where all elements are cancelled by scalar
multiplication by some power of `p`), the smallest `n` such that `p ^ n • x = 0`.-/
def p_order {p : R} (hM : is_torsion' M $ submonoid.powers p) (x : M)
[Π n : ℕ, decidable (p ^ n • x = 0)] :=
nat.find $ (is_torsion'_powers_iff p).mp hM x
@[simp] lemma pow_p_order_smul {p : R} (hM : is_torsion' M $ submonoid.powers p) (x : M)
[Π n : ℕ, decidable (p ^ n • x = 0)] : p ^ p_order hM x • x = 0 :=
nat.find_spec $ (is_torsion'_powers_iff p).mp hM x
end
variables [comm_semiring R] [add_comm_monoid M] [module R M] [Π x : M, decidable (x = 0)]
lemma exists_is_torsion_by {p : R} (hM : is_torsion' M $ submonoid.powers p)
(d : ℕ) (hd : d ≠ 0) (s : fin d → M) (hs : span R (set.range s) = ⊤) :
∃ j : fin d, module.is_torsion_by R M (p ^ p_order hM (s j)) :=
begin
let oj := list.argmax (λ i, p_order hM $ s i) (list.fin_range d),
have hoj : oj.is_some := (option.ne_none_iff_is_some.mp $
λ eq_none, hd $ list.fin_range_eq_nil.mp $ list.argmax_eq_none.mp eq_none),
use option.get hoj,
rw [is_torsion_by_iff_torsion_by_eq_top, eq_top_iff, ← hs, submodule.span_le,
set.range_subset_iff], intro i, change _ • _ = _,
have : p_order hM (s i) ≤ p_order hM (s $ option.get hoj) :=
list.le_of_mem_argmax (list.mem_fin_range i) (option.get_mem hoj),
rw [← nat.sub_add_cancel this, pow_add, mul_smul, pow_p_order_smul, smul_zero]
end
end p_torsion
end submodule
namespace ideal.quotient
open submodule
lemma torsion_by_eq_span_singleton {R : Type*} [comm_ring R] (a b : R) (ha : a ∈ R⁰) :
torsion_by R (R ⧸ R ∙ a * b) a = R ∙ (mk _ b) :=
begin
ext x, rw [mem_torsion_by_iff, mem_span_singleton],
obtain ⟨x, rfl⟩ := mk_surjective x, split; intro h,
{ rw [← mk_eq_mk, ← quotient.mk_smul, quotient.mk_eq_zero, mem_span_singleton] at h,
obtain ⟨c, h⟩ := h, rw [smul_eq_mul, smul_eq_mul, mul_comm, mul_assoc,
mul_cancel_left_mem_non_zero_divisor ha, mul_comm] at h,
use c, rw [← h, ← mk_eq_mk, ← quotient.mk_smul, smul_eq_mul, mk_eq_mk] },
{ obtain ⟨c, h⟩ := h,
rw [← h, smul_comm, ← mk_eq_mk, ← quotient.mk_smul,
(quotient.mk_eq_zero _).mpr $ mem_span_singleton_self _, smul_zero] }
end
end ideal.quotient
namespace add_monoid
theorem is_torsion_iff_is_torsion_nat [add_comm_monoid M] :
add_monoid.is_torsion M ↔ module.is_torsion ℕ M :=
begin
refine ⟨λ h x, _, λ h x, _⟩,
{ obtain ⟨n, h0, hn⟩ := (is_of_fin_add_order_iff_nsmul_eq_zero x).mp (h x),
exact ⟨⟨n, mem_non_zero_divisors_of_ne_zero $ ne_of_gt h0⟩, hn⟩ },
{ rw is_of_fin_add_order_iff_nsmul_eq_zero,
obtain ⟨n, hn⟩ := @h x,
refine ⟨n, nat.pos_of_ne_zero (non_zero_divisors.coe_ne_zero _), hn⟩ }
end
theorem is_torsion_iff_is_torsion_int [add_comm_group M] :
add_monoid.is_torsion M ↔ module.is_torsion ℤ M :=
begin
refine ⟨λ h x, _, λ h x, _⟩,
{ obtain ⟨n, h0, hn⟩ := (is_of_fin_add_order_iff_nsmul_eq_zero x).mp (h x),
exact ⟨⟨n, mem_non_zero_divisors_of_ne_zero $ ne_of_gt $ int.coe_nat_pos.mpr h0⟩,
(coe_nat_zsmul _ _).trans hn⟩ },
{ rw is_of_fin_add_order_iff_nsmul_eq_zero,
obtain ⟨n, hn⟩ := @h x,
exact exists_nsmul_eq_zero_of_zsmul_eq_zero (non_zero_divisors.coe_ne_zero n) hn }
end
end add_monoid
|
a85230016088845b9dc9fc3a859ecb40aaaa5b30 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/polynomial/iterated_deriv_auto.lean | f6953365b8e0eaf73269dc458153df7b8ecd86ba | [] | 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 | 3,786 | lean | /-
Copyright (c) 2020 Jujian Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jujian Zhang
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.polynomial.derivative
import Mathlib.logic.function.iterate
import Mathlib.data.finset.intervals
import Mathlib.tactic.ring
import Mathlib.tactic.linarith.default
import Mathlib.PostPort
universes u
namespace Mathlib
/-!
# Theory of iterated derivative
We define and prove some lemmas about iterated (formal) derivative for polynomials over a semiring.
-/
namespace polynomial
/-- `iterated_deriv f n` is the `n`-th formal derivative of the polynomial `f` -/
def iterated_deriv {R : Type u} [semiring R] (f : polynomial R) (n : ℕ) : polynomial R :=
nat.iterate (⇑derivative) n f
@[simp] theorem iterated_deriv_zero_right {R : Type u} [semiring R] (f : polynomial R) :
iterated_deriv f 0 = f :=
rfl
theorem iterated_deriv_succ {R : Type u} [semiring R] (f : polynomial R) (n : ℕ) :
iterated_deriv f (n + 1) = coe_fn derivative (iterated_deriv f n) :=
sorry
@[simp] theorem iterated_deriv_zero_left {R : Type u} [semiring R] (n : ℕ) :
iterated_deriv 0 n = 0 :=
sorry
@[simp] theorem iterated_deriv_add {R : Type u} [semiring R] (p : polynomial R) (q : polynomial R)
(n : ℕ) : iterated_deriv (p + q) n = iterated_deriv p n + iterated_deriv q n :=
sorry
@[simp] theorem iterated_deriv_smul {R : Type u} [semiring R] (r : R) (p : polynomial R) (n : ℕ) :
iterated_deriv (r • p) n = r • iterated_deriv p n :=
sorry
@[simp] theorem iterated_deriv_X_zero {R : Type u} [semiring R] : iterated_deriv X 0 = X := sorry
@[simp] theorem iterated_deriv_X_one {R : Type u} [semiring R] : iterated_deriv X 1 = 1 := sorry
@[simp] theorem iterated_deriv_X {R : Type u} [semiring R] (n : ℕ) (h : 1 < n) :
iterated_deriv X n = 0 :=
sorry
@[simp] theorem iterated_deriv_C_zero {R : Type u} [semiring R] (r : R) :
iterated_deriv (coe_fn C r) 0 = coe_fn C r :=
sorry
@[simp] theorem iterated_deriv_C {R : Type u} [semiring R] (r : R) (n : ℕ) (h : 0 < n) :
iterated_deriv (coe_fn C r) n = 0 :=
sorry
@[simp] theorem iterated_deriv_one_zero {R : Type u} [semiring R] : iterated_deriv 1 0 = 1 := sorry
@[simp] theorem iterated_deriv_one {R : Type u} [semiring R] (n : ℕ) :
0 < n → iterated_deriv 1 n = 0 :=
sorry
@[simp] theorem iterated_deriv_neg {R : Type u} [ring R] (p : polynomial R) (n : ℕ) :
iterated_deriv (-p) n = -iterated_deriv p n :=
sorry
@[simp] theorem iterated_deriv_sub {R : Type u} [ring R] (p : polynomial R) (q : polynomial R)
(n : ℕ) : iterated_deriv (p - q) n = iterated_deriv p n - iterated_deriv q n :=
sorry
theorem coeff_iterated_deriv_as_prod_Ico {R : Type u} [comm_semiring R] (f : polynomial R) (k : ℕ)
(m : ℕ) :
coeff (iterated_deriv f k) m =
(finset.prod (finset.Ico (Nat.succ m) (m + Nat.succ k)) fun (i : ℕ) => ↑i) *
coeff f (m + k) :=
sorry
theorem coeff_iterated_deriv_as_prod_range {R : Type u} [comm_semiring R] (f : polynomial R) (k : ℕ)
(m : ℕ) :
coeff (iterated_deriv f k) m =
coeff f (m + k) * finset.prod (finset.range k) fun (i : ℕ) => ↑(m + k - i) :=
sorry
theorem iterated_deriv_eq_zero_of_nat_degree_lt {R : Type u} [comm_semiring R] (f : polynomial R)
(n : ℕ) (h : nat_degree f < n) : iterated_deriv f n = 0 :=
sorry
theorem iterated_deriv_mul {R : Type u} [comm_semiring R] (p : polynomial R) (q : polynomial R)
(n : ℕ) :
iterated_deriv (p * q) n =
finset.sum (finset.range (Nat.succ n))
fun (k : ℕ) =>
coe_fn C ↑(nat.choose n k) * iterated_deriv p (n - k) * iterated_deriv q k :=
sorry
end Mathlib |
d4ca936196271d1f936188bc027f126be86c01b1 | 367134ba5a65885e863bdc4507601606690974c1 | /src/linear_algebra/std_basis.lean | 4c643cef9360936351c62862ebe2164328b8194a | [
"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 | 9,219 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import linear_algebra.basic
import linear_algebra.basis
import linear_algebra.pi
/-!
# The standard basis
This file defines the standard basis `std_basis R φ i b j`, which is `b` where `i = j` and `0`
elsewhere.
To give a concrete example, `std_basis R (λ (i : fin 3), R) i 1` gives the `i`th unit basis vector
in `R³`, and `pi.is_basis_fun` proves this is a basis over `fin 3 → R`.
## Main definitions
- `linear_map.std_basis R ϕ i b`: the `i`'th standard `R`-basis vector on `Π i, ϕ i`,
scaled by `b`.
## Main results
- `pi.is_basis_std_basis`: `std_basis` turns a component-wise basis into a basis on the product
type.
- `pi.is_basis_fun`: `std_basis R (λ _, R) i 1` is a basis for `n → R`.
-/
open function submodule
open_locale big_operators
open_locale big_operators
namespace linear_map
variables (R : Type*) {ι : Type*} [semiring R] (φ : ι → Type*)
[Π i, add_comm_monoid (φ i)] [Π i, semimodule R (φ i)] [decidable_eq ι]
/-- The standard basis of the product of `φ`. -/
def std_basis : Π (i : ι), φ i →ₗ[R] (Πi, φ i) := single
lemma std_basis_apply (i : ι) (b : φ i) : std_basis R φ i b = update 0 i b :=
rfl
lemma coe_std_basis (i : ι) : ⇑(std_basis R φ i) = pi.single i :=
funext $ std_basis_apply R φ i
@[simp] lemma std_basis_same (i : ι) (b : φ i) : std_basis R φ i b i = b :=
by rw [std_basis_apply, update_same]
lemma std_basis_ne (i j : ι) (h : j ≠ i) (b : φ i) : std_basis R φ i b j = 0 :=
by rw [std_basis_apply, update_noteq h]; refl
lemma std_basis_eq_pi_diag (i : ι) : std_basis R φ i = pi (diag i) :=
begin
ext x j,
convert (update_apply 0 x i j _).symm,
refl,
end
lemma ker_std_basis (i : ι) : ker (std_basis R φ i) = ⊥ :=
ker_eq_bot_of_injective $ assume f g hfg,
have std_basis R φ i f i = std_basis R φ i g i := hfg ▸ rfl,
by simpa only [std_basis_same]
lemma proj_comp_std_basis (i j : ι) : (proj i).comp (std_basis R φ j) = diag j i :=
by rw [std_basis_eq_pi_diag, proj_pi]
lemma proj_std_basis_same (i : ι) : (proj i).comp (std_basis R φ i) = id :=
by ext b; simp
lemma proj_std_basis_ne (i j : ι) (h : i ≠ j) : (proj i).comp (std_basis R φ j) = 0 :=
by ext b; simp [std_basis_ne R φ _ _ h]
lemma supr_range_std_basis_le_infi_ker_proj (I J : set ι) (h : disjoint I J) :
(⨆i∈I, range (std_basis R φ i)) ≤ (⨅i∈J, ker (proj i)) :=
begin
refine (supr_le $ assume i, supr_le $ assume hi, range_le_iff_comap.2 _),
simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi],
assume b hb j hj,
have : i ≠ j := assume eq, h ⟨hi, eq.symm ▸ hj⟩,
rw [proj_std_basis_ne R φ j i this.symm, zero_apply]
end
lemma infi_ker_proj_le_supr_range_std_basis {I : finset ι} {J : set ι} (hu : set.univ ⊆ ↑I ∪ J) :
(⨅ i∈J, ker (proj i)) ≤ (⨆i∈I, range (std_basis R φ i)) :=
submodule.le_def'.2
begin
assume b hb,
simp only [mem_infi, mem_ker, proj_apply] at hb,
rw ← show ∑ i in I, std_basis R φ i (b i) = b,
{ ext i,
rw [finset.sum_apply, ← std_basis_same R φ i (b i)],
refine finset.sum_eq_single i (assume j hjI ne, std_basis_ne _ _ _ _ ne.symm _) _,
assume hiI,
rw [std_basis_same],
exact hb _ ((hu trivial).resolve_left hiI) },
exact sum_mem _ (assume i hiI, mem_supr_of_mem i $ mem_supr_of_mem hiI $
(std_basis R φ i).mem_range_self (b i))
end
lemma supr_range_std_basis_eq_infi_ker_proj {I J : set ι}
(hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) (hI : set.finite I) :
(⨆i∈I, range (std_basis R φ i)) = (⨅i∈J, ker (proj i)) :=
begin
refine le_antisymm (supr_range_std_basis_le_infi_ker_proj _ _ _ _ hd) _,
have : set.univ ⊆ ↑hI.to_finset ∪ J, { rwa [hI.coe_to_finset] },
refine le_trans (infi_ker_proj_le_supr_range_std_basis R φ this) (supr_le_supr $ assume i, _),
rw [set.finite.mem_to_finset],
exact le_refl _
end
lemma supr_range_std_basis [fintype ι] : (⨆i:ι, range (std_basis R φ i)) = ⊤ :=
have (set.univ : set ι) ⊆ ↑(finset.univ : finset ι) ∪ ∅ := by rw [finset.coe_univ, set.union_empty],
begin
apply top_unique,
convert (infi_ker_proj_le_supr_range_std_basis R φ this),
exact infi_emptyset.symm,
exact (funext $ λi, (@supr_pos _ _ _ (λh, range (std_basis R φ i)) $ finset.mem_univ i).symm)
end
lemma disjoint_std_basis_std_basis (I J : set ι) (h : disjoint I J) :
disjoint (⨆i∈I, range (std_basis R φ i)) (⨆i∈J, range (std_basis R φ i)) :=
begin
refine disjoint.mono
(supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ disjoint_compl_right)
(supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ disjoint_compl_right) _,
simp only [disjoint, submodule.le_def', mem_infi, mem_inf, mem_ker, mem_bot, proj_apply,
funext_iff],
rintros b ⟨hI, hJ⟩ i,
classical,
by_cases hiI : i ∈ I,
{ by_cases hiJ : i ∈ J,
{ exact (h ⟨hiI, hiJ⟩).elim },
{ exact hJ i hiJ } },
{ exact hI i hiI }
end
lemma std_basis_eq_single {a : R} :
(λ (i : ι), (std_basis R (λ _ : ι, R) i) a) = λ (i : ι), (finsupp.single i a) :=
begin
ext i j,
rw [std_basis_apply, finsupp.single_apply],
split_ifs,
{ rw [h, function.update_same] },
{ rw [function.update_noteq (ne.symm h)], refl },
end
end linear_map
namespace pi
open linear_map
open set
variables {R : Type*}
section module
variables {η : Type*} {ιs : η → Type*} {Ms : η → Type*}
variables [ring R] [∀i, add_comm_group (Ms i)] [∀i, module R (Ms i)]
lemma linear_independent_std_basis [decidable_eq η]
(v : Πj, ιs j → (Ms j)) (hs : ∀i, linear_independent R (v i)) :
linear_independent R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (v ji.1 ji.2)) :=
begin
have hs' : ∀j : η, linear_independent R (λ i : ιs j, std_basis R Ms j (v j i)),
{ intro j,
exact (hs j).map' _ (ker_std_basis _ _ _) },
apply linear_independent_Union_finite hs',
{ assume j J _ hiJ,
simp [(set.Union.equations._eqn_1 _).symm, submodule.span_image, submodule.span_Union],
have h₀ : ∀ j, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))
≤ range (std_basis R Ms j),
{ intro j,
rw [span_le, linear_map.range_coe],
apply range_comp_subset_range },
have h₁ : span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))
≤ ⨆ i ∈ {j}, range (std_basis R Ms i),
{ rw @supr_singleton _ _ _ (λ i, linear_map.range (std_basis R (λ (j : η), Ms j) i)),
apply h₀ },
have h₂ : (⨆ j ∈ J, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))) ≤
⨆ j ∈ J, range (std_basis R (λ (j : η), Ms j) j) :=
supr_le_supr (λ i, supr_le_supr (λ H, h₀ i)),
have h₃ : disjoint (λ (i : η), i ∈ {j}) J,
{ convert set.disjoint_singleton_left.2 hiJ using 0 },
exact (disjoint_std_basis_std_basis _ _ _ _ h₃).mono h₁ h₂ }
end
variable [fintype η]
lemma is_basis_std_basis [decidable_eq η] (s : Πj, ιs j → (Ms j)) (hs : ∀j, is_basis R (s j)) :
is_basis R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (s ji.1 ji.2)) :=
begin
split,
{ apply linear_independent_std_basis _ (assume i, (hs i).1) },
have h₁ : Union (λ j, set.range (std_basis R Ms j ∘ s j))
⊆ range (λ (ji : Σ (j : η), ιs j), (std_basis R Ms (ji.fst)) (s (ji.fst) (ji.snd))),
{ apply Union_subset, intro i,
apply range_comp_subset_range (λ x : ιs i, (⟨i, x⟩ : Σ (j : η), ιs j))
(λ (ji : Σ (j : η), ιs j), std_basis R Ms (ji.fst) (s (ji.fst) (ji.snd))) },
have h₂ : ∀ i, span R (range (std_basis R Ms i ∘ s i)) = range (std_basis R Ms i),
{ intro i,
rw [set.range_comp, submodule.span_image, (assume i, (hs i).2), submodule.map_top] },
apply eq_top_mono,
apply span_mono h₁,
rw span_Union,
simp only [h₂],
apply supr_range_std_basis
end
section
variables (R η)
lemma is_basis_fun₀ [decidable_eq η] : is_basis R
(λ (ji : Σ (j : η), unit),
(std_basis R (λ (i : η), R) (ji.fst)) 1) :=
@is_basis_std_basis R η (λi:η, unit) (λi:η, R) _ _ _ _ _ (λ _ _, (1 : R))
(assume i, @is_basis_singleton_one _ _ _ _)
lemma is_basis_fun [decidable_eq η] : is_basis R (λ i, std_basis R (λi:η, R) i 1) :=
begin
apply (is_basis_fun₀ R η).comp (λ i, ⟨i, punit.star⟩),
apply bijective_iff_has_inverse.2,
use sigma.fst,
simp [function.left_inverse, function.right_inverse]
end
@[simp] lemma is_basis_fun_repr [decidable_eq η] (x : η → R) (i : η) :
(pi.is_basis_fun R η).repr x i = x i :=
begin
conv_rhs { rw ← (pi.is_basis_fun R η).total_repr x },
rw [finsupp.total_apply, finsupp.sum_fintype],
show (pi.is_basis_fun R η).repr x i =
(∑ j, λ i, (pi.is_basis_fun R η).repr x j • std_basis R (λ _, R) j 1 i) i,
rw [finset.sum_apply, finset.sum_eq_single i],
{ simp only [pi.smul_apply, smul_eq_mul, std_basis_same, mul_one] },
{ rintros b - hb, simp only [std_basis_ne _ _ _ _ hb.symm, smul_zero] },
{ intro,
have := finset.mem_univ i,
contradiction },
{ intros, apply zero_smul },
end
end
end module
end pi
|
f45065189cf17944b9c7de1691bb3663b9a049ee | 0c1546a496eccfb56620165cad015f88d56190c5 | /tests/lean/run/t2.lean | b5f2b34745b627bb0a2a2ed7316eb2d7f8268be0 | [
"Apache-2.0"
] | permissive | Solertis/lean | 491e0939957486f664498fbfb02546e042699958 | 84188c5aa1673fdf37a082b2de8562dddf53df3f | refs/heads/master | 1,610,174,257,606 | 1,486,263,620,000 | 1,486,263,620,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 183 | lean | universe l
universe u
print raw Type
print raw Type.{1}
print raw Type.{2}
print raw Type.{l+1}
print raw Type.{max l u 1}
print raw Type.{imax l+1 u 1}
print raw Type.{imax l+1 l u}
|
ec0f9b0176c22337b1fbd7985d853da3bd4423db | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Init/Control/Id.lean | ab1b4a1a15a7a9eb1d2d226933466bb9dccd0a78 | [
"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 | 561 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
The identity Monad.
-/
prelude
import Init.Core
universe u
def Id (type : Type u) : Type u := type
namespace Id
@[always_inline]
instance : Monad Id where
pure x := x
bind x f := f x
map f x := f x
def hasBind : Bind Id :=
inferInstance
@[always_inline, inline]
protected def run (x : Id α) : α := x
instance [OfNat α n] : OfNat (Id α) n :=
inferInstanceAs (OfNat α n)
end Id
|
5c05c9e2b0eea10234b57d7b6415aecd52422917 | 737dc4b96c97368cb66b925eeea3ab633ec3d702 | /stage0/src/Lean/Compiler/Util.lean | 6e193ee79fde62f62496ae74b2bbb5a943f5c8ef | [
"Apache-2.0"
] | permissive | Bioye97/lean4 | 1ace34638efd9913dc5991443777b01a08983289 | bc3900cbb9adda83eed7e6affeaade7cfd07716d | refs/heads/master | 1,690,589,820,211 | 1,631,051,000,000 | 1,631,067,598,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,798 | 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.Environment
namespace Lean.Compiler
def neutralExpr : Expr := mkConst `_neutral
def unreachableExpr : Expr := mkConst `_unreachable
def objectType : Expr := mkConst `_obj
def voidType : Expr := mkConst `_void
def mkLcProof (pred : Expr) := mkApp (mkConst `lcProof []) pred
namespace atMostOnce
structure AtMostOnceData where
found : Bool
result : Bool
def Visitor := AtMostOnceData → AtMostOnceData
@[inline] def seq (f g : Visitor) : Visitor := fun d =>
match f d with
| ⟨found, false⟩ => ⟨found, false⟩
| other => g other
instance : AndThen Visitor where
andThen a b := seq a (b ())
@[inline] def skip : Visitor := id
@[inline] def visitFVar (x y : Name) : Visitor
| d@{result := false, ..} => d
| {found := false, result := true} => {found := x == y, result := true}
| {found := true, result := true} => {found := true, result := x != y}
def visit (x : Name) : Expr → Visitor
| Expr.fvar y _ => visitFVar y x
| Expr.app f a _ => visit x a >> visit x f
| Expr.lam _ d b _ => visit x d >> visit x b
| Expr.forallE _ d b _ => visit x d >> visit x b
| Expr.letE _ t v b _ => visit x t >> visit x v >> visit x b
| Expr.mdata _ e _ => visit x e
| Expr.proj _ _ e _ => visit x e
| _ => skip
end atMostOnce
open atMostOnce (visit) in
/-- Return true iff the free variable with id `x` occurs at most once in `e` -/
@[export lean_at_most_once]
def atMostOnce (e : Expr) (x : Name) : Bool :=
let {result := result, ..} := visit x e {found := false, result := true}
result
/- Helper functions for creating auxiliary names used in compiler passes. -/
@[export lean_mk_eager_lambda_lifting_name]
def mkEagerLambdaLiftingName (n : Name) (idx : Nat) : Name :=
Name.mkStr n ("_elambda_" ++ toString idx)
@[export lean_is_eager_lambda_lifting_name]
def isEagerLambdaLiftingName : Name → Bool
| Name.str p s _ => "_elambda".isPrefixOf s || isEagerLambdaLiftingName p
| Name.num p _ _ => isEagerLambdaLiftingName p
| _ => false
/-- Return the name of new definitions in the a given declaration.
Here we consider only declarations we generate code for.
We use this definition to implement `add_and_compile`. -/
@[export lean_get_decl_names_for_code_gen]
private def getDeclNamesForCodeGen : Declaration → List Name
| Declaration.defnDecl { name := n, .. } => [n]
| Declaration.mutualDefnDecl defs => defs.map fun d => d.name
| Declaration.opaqueDecl { name := n, .. } => [n]
| Declaration.axiomDecl { name := n, .. } => [n] -- axiom may be tagged with `@[extern ...]`
| _ => []
def checkIsDefinition (env : Environment) (n : Name) : Except String Unit :=
match env.find? n with
| (some (ConstantInfo.defnInfo _)) => Except.ok ()
| (some (ConstantInfo.opaqueInfo _)) => Except.ok ()
| none => Except.error s!"unknow declaration '{n}'"
| _ => Except.error s!"declaration is not a definition '{n}'"
/--
We generate auxiliary unsafe definitions for regular recursive definitions.
The auxiliary unsafe definition has a clear runtime cost execution model.
This function returns the auxiliary unsafe definition name for the given name. -/
@[export lean_mk_unsafe_rec_name]
def mkUnsafeRecName (declName : Name) : Name :=
Name.mkStr declName "_unsafe_rec"
/-- Return `some _` if the given name was created using `mkUnsafeRecName` -/
@[export lean_is_unsafe_rec_name]
def isUnsafeRecName? : Name → Option Name
| Name.str n "_unsafe_rec" _ => some n
| _ => none
end Lean.Compiler
|
55cb920a3dd3aadf09a9c74f091b3dad170265b1 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/combinatorics/simple_graph/hasse.lean | 0a65ddf502722bc9e1510d20dcd8c940e6721ca6 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,864 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import combinatorics.simple_graph.prod
import data.fin.succ_pred
import order.succ_pred.relation
/-!
# The Hasse diagram as a graph
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the Hasse diagram of an order (graph of `covby`, the covering relation) and the
path graph on `n` vertices.
## Main declarations
* `simple_graph.hasse`: Hasse diagram of an order.
* `simple_graph.path_graph`: Path graph on `n` vertices.
-/
open order order_dual relation
namespace simple_graph
variables (α β : Type*)
section preorder
variables [preorder α] [preorder β]
/-- The Hasse diagram of an order as a simple graph. The graph of the covering relation. -/
def hasse : simple_graph α :=
{ adj := λ a b, a ⋖ b ∨ b ⋖ a,
symm := λ a b, or.symm,
loopless := λ a h, h.elim (irrefl _) (irrefl _) }
variables {α β} {a b : α}
@[simp] lemma hasse_adj : (hasse α).adj a b ↔ a ⋖ b ∨ b ⋖ a := iff.rfl
/-- `αᵒᵈ` and `α` have the same Hasse diagram. -/
def hasse_dual_iso : hasse αᵒᵈ ≃g hasse α :=
{ map_rel_iff' := λ a b, by simp [or_comm],
..of_dual }
@[simp] lemma hasse_dual_iso_apply (a : αᵒᵈ) : hasse_dual_iso a = of_dual a := rfl
@[simp] lemma hasse_dual_iso_symm_apply (a : α) : hasse_dual_iso.symm a = to_dual a := rfl
end preorder
section partial_order
variables [partial_order α] [partial_order β]
@[simp] lemma hasse_prod : hasse (α × β) = hasse α □ hasse β :=
by { ext x y, simp_rw [box_prod_adj, hasse_adj, prod.covby_iff, or_and_distrib_right,
@eq_comm _ y.1, @eq_comm _ y.2, or_or_or_comm] }
end partial_order
section linear_order
variables [linear_order α]
lemma hasse_preconnected_of_succ [succ_order α] [is_succ_archimedean α] : (hasse α).preconnected :=
λ a b, begin
rw reachable_iff_refl_trans_gen,
exact refl_trans_gen_of_succ _ (λ c hc, or.inl $ covby_succ_of_not_is_max hc.2.not_is_max)
(λ c hc, or.inr $ covby_succ_of_not_is_max hc.2.not_is_max),
end
lemma hasse_preconnected_of_pred [pred_order α] [is_pred_archimedean α] : (hasse α).preconnected :=
λ a b, begin
rw [reachable_iff_refl_trans_gen, ←refl_trans_gen_swap],
exact refl_trans_gen_of_pred _ (λ c hc, or.inl $ pred_covby_of_not_is_min hc.1.not_is_min)
(λ c hc, or.inr $ pred_covby_of_not_is_min hc.1.not_is_min),
end
end linear_order
/-- The path graph on `n` vertices. -/
def path_graph (n : ℕ) : simple_graph (fin n) := hasse _
lemma path_graph_preconnected (n : ℕ) : (path_graph n).preconnected := hasse_preconnected_of_succ _
lemma path_graph_connected (n : ℕ) : (path_graph (n + 1)).connected := ⟨path_graph_preconnected _⟩
end simple_graph
|
139f1db179e5193f6b33c77753f6dcc94205dd6e | ff5230333a701471f46c57e8c115a073ebaaa448 | /library/init/meta/converter/conv.lean | cd45a258d12918951eabc2bd9f9ba6097305b9f7 | [
"Apache-2.0"
] | permissive | stanford-cs242/lean | f81721d2b5d00bc175f2e58c57b710d465e6c858 | 7bd861261f4a37326dcf8d7a17f1f1f330e4548c | refs/heads/master | 1,600,957,431,849 | 1,576,465,093,000 | 1,576,465,093,000 | 225,779,423 | 0 | 3 | Apache-2.0 | 1,575,433,936,000 | 1,575,433,935,000 | null | UTF-8 | Lean | false | false | 4,377 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
Converter monad for building simplifiers.
-/
prelude
import init.meta.tactic init.meta.simp_tactic init.meta.interactive
import init.meta.congr_lemma init.meta.match_tactic
open tactic
universe u
/-- `conv α` is a tactic for discharging goals of the form `lhs ~ rhs` for some relation `~` (usually equality) and fixed lhs, rhs.
Known in the literature as a __conversion__ tactic.
So for example, if one had the lemma `p : x = y`, then the conversion for `p` would be one that solves `p`.
-/
meta def conv (α : Type u) :=
tactic α
meta instance : monad conv :=
by dunfold conv; apply_instance
meta instance : monad_fail conv :=
by dunfold conv; apply_instance
meta instance : alternative conv :=
by dunfold conv; apply_instance
namespace conv
/-- Applies the conversion `c`. Returns `(rhs,p)` where `p : r lhs rhs`. Throws away the return value of `c`.-/
meta def convert (c : conv unit) (lhs : expr) (rel : name := `eq) : tactic (expr × expr) :=
do lhs_type ← infer_type lhs,
rhs ← mk_meta_var lhs_type,
new_target ← mk_app rel [lhs, rhs],
new_g ← mk_meta_var new_target,
gs ← get_goals,
set_goals [new_g],
c,
try $ any_goals reflexivity,
n ← num_goals,
when (n ≠ 0) (fail "convert tactic failed, there are unsolved goals"),
set_goals gs,
rhs ← instantiate_mvars rhs,
new_g ← instantiate_mvars new_g,
return (rhs, new_g)
meta def lhs : conv expr :=
do (_, lhs, rhs) ← target_lhs_rhs,
return lhs
meta def rhs : conv expr :=
do (_, lhs, rhs) ← target_lhs_rhs,
return rhs
/-- `⊢ lhs = rhs` ~~> `⊢ lhs' = rhs` using `h : lhs = lhs'`. -/
meta def update_lhs (new_lhs : expr) (h : expr) : conv unit :=
do transitivity,
rhs >>= unify new_lhs,
exact h,
t ← target >>= instantiate_mvars,
change t
/-- Change `lhs` to something definitionally equal to it. -/
meta def change (new_lhs : expr) : conv unit :=
do (r, lhs, rhs) ← target_lhs_rhs,
new_target ← mk_app r [new_lhs, rhs],
tactic.change new_target
/-- Use reflexivity to prove. -/
meta def skip : conv unit :=
reflexivity
/-- Put LHS in WHNF. -/
meta def whnf : conv unit :=
lhs >>= tactic.whnf >>= change
/-- dsimp the LHS. -/
meta def dsimp (s : option simp_lemmas := none) (u : list name := []) (cfg : dsimp_config := {}) : conv unit :=
do s ← match s with
| some s := return s
| none := simp_lemmas.mk_default
end,
l ← lhs,
s.dsimplify u l cfg >>= change
private meta def congr_aux : list congr_arg_kind → list expr → tactic (list expr × list expr)
| [] [] := return ([], [])
| (k::ks) (a::as) := do
(gs, largs) ← congr_aux ks as,
match k with
-- parameter for the congruence lemma
| congr_arg_kind.fixed := return $ (gs, a::largs)
-- parameter which is a subsingleton
| congr_arg_kind.fixed_no_param := return $ (gs, largs)
| congr_arg_kind.eq := do
a_type ← infer_type a,
rhs ← mk_meta_var a_type,
g_type ← mk_app `eq [a, rhs],
g ← mk_meta_var g_type, -- proof that `a = rhs`
return (g::gs, a::rhs::g::largs)
| congr_arg_kind.cast := return $ (gs, a::largs)
| _ := fail "congr tactic failed, unsupported congruence lemma"
end
| ks as := fail "congr tactic failed, unsupported congruence lemma"
/-- Take the target equality `f x y = X` and try to apply the congruence lemma for `f` to it (namely `x = x' → y = y' → f x y = f x' y'`). -/
meta def congr : conv unit :=
do (r, lhs, rhs) ← target_lhs_rhs,
guard (r = `eq),
let fn := lhs.get_app_fn,
let args := lhs.get_app_args,
cgr_lemma ← mk_congr_lemma_simp fn (some args.length),
g::gs ← get_goals,
(new_gs, lemma_args) ← congr_aux cgr_lemma.arg_kinds args,
let g_val := cgr_lemma.proof.mk_app lemma_args,
unify g g_val,
set_goals $ new_gs ++ gs,
return ()
/-- Create a conversion from the function extensionality tactic.-/
meta def funext : conv unit :=
iterate $ do
(r, lhs, rhs) ← target_lhs_rhs,
guard (r = `eq),
(expr.lam n _ _ _) ← return lhs,
tactic.applyc `funext,
intro n,
return ()
end conv
|
1be53b012b3692ee470d328521f2a42c3d77e23e | bb31430994044506fa42fd667e2d556327e18dfe | /src/data/list/perm.lean | af5455996a7de2c7d2a85fbb863da5254ec212d2 | [
"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 | 54,774 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro
-/
import data.list.dedup
import data.list.permutation
import data.list.range
import data.nat.factorial.basic
/-!
# List Permutations
This file introduces the `list.perm` relation, which is true if two lists are permutations of one
another.
## Notation
The notation `~` is used for permutation equivalence.
-/
open_locale nat
universes uu vv
namespace list
variables {α : Type uu} {β : Type vv} {l₁ l₂ : list α}
/-- `perm l₁ l₂` or `l₁ ~ l₂` asserts that `l₁` and `l₂` are permutations
of each other. This is defined by induction using pairwise swaps. -/
inductive perm : list α → list α → Prop
| nil : perm [] []
| cons : Π (x : α) {l₁ l₂ : list α}, perm l₁ l₂ → perm (x::l₁) (x::l₂)
| swap : Π (x y : α) (l : list α), perm (y::x::l) (x::y::l)
| trans : Π {l₁ l₂ l₃ : list α}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃
open perm (swap)
infix (name := list.perm) ` ~ `:50 := perm
@[refl] protected theorem perm.refl : ∀ (l : list α), l ~ l
| [] := perm.nil
| (x::xs) := (perm.refl xs).cons x
@[symm] protected theorem perm.symm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₂ ~ l₁ :=
perm.rec_on p
perm.nil
(λ x l₁ l₂ p₁ r₁, r₁.cons x)
(λ x y l, swap y x l)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, r₂.trans r₁)
theorem perm_comm {l₁ l₂ : list α} : l₁ ~ l₂ ↔ l₂ ~ l₁ := ⟨perm.symm, perm.symm⟩
theorem perm.swap'
(x y : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : y::x::l₁ ~ x::y::l₂ :=
(swap _ _ _).trans ((p.cons _).cons _)
attribute [trans] perm.trans
theorem perm.eqv (α) : equivalence (@perm α) :=
mk_equivalence (@perm α) (@perm.refl α) (@perm.symm α) (@perm.trans α)
instance is_setoid (α) : setoid (list α) :=
setoid.mk (@perm α) (perm.eqv α)
theorem perm.subset {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ ⊆ l₂ :=
λ a, perm.rec_on p
(λ h, h)
(λ x l₁ l₂ p₁ r₁ i, or.elim i
(λ ax, by simp [ax])
(λ al₁, or.inr (r₁ al₁)))
(λ x y l ayxl, or.elim ayxl
(λ ay, by simp [ay])
(λ axl, or.elim axl
(λ ax, by simp [ax])
(λ al, or.inr (or.inr al))))
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ ainl₁, r₂ (r₁ ainl₁))
theorem perm.mem_iff {a : α} {l₁ l₂ : list α} (h : l₁ ~ l₂) : a ∈ l₁ ↔ a ∈ l₂ :=
iff.intro (λ m, h.subset m) (λ m, h.symm.subset m)
theorem perm.append_right {l₁ l₂ : list α} (t₁ : list α) (p : l₁ ~ l₂) : l₁++t₁ ~ l₂++t₁ :=
perm.rec_on p
(perm.refl ([] ++ t₁))
(λ x l₁ l₂ p₁ r₁, r₁.cons x)
(λ x y l, swap x y _)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, r₁.trans r₂)
theorem perm.append_left {t₁ t₂ : list α} : ∀ (l : list α), t₁ ~ t₂ → l++t₁ ~ l++t₂
| [] p := p
| (x::xs) p := (perm.append_left xs p).cons x
theorem perm.append {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁++t₁ ~ l₂++t₂ :=
(p₁.append_right t₁).trans (p₂.append_left l₂)
theorem perm.append_cons (a : α) {h₁ h₂ t₁ t₂ : list α}
(p₁ : h₁ ~ h₂) (p₂ : t₁ ~ t₂) : h₁ ++ a::t₁ ~ h₂ ++ a::t₂ :=
p₁.append (p₂.cons a)
@[simp] theorem perm_middle {a : α} : ∀ {l₁ l₂ : list α}, l₁++a::l₂ ~ a::(l₁++l₂)
| [] l₂ := perm.refl _
| (b::l₁) l₂ := ((@perm_middle l₁ l₂).cons _).trans (swap a b _)
@[simp] theorem perm_append_singleton (a : α) (l : list α) : l ++ [a] ~ a::l :=
perm_middle.trans $ by rw [append_nil]
theorem perm_append_comm : ∀ {l₁ l₂ : list α}, (l₁++l₂) ~ (l₂++l₁)
| [] l₂ := by simp
| (a::t) l₂ := (perm_append_comm.cons _).trans perm_middle.symm
theorem concat_perm (l : list α) (a : α) : concat l a ~ a :: l :=
by simp
theorem perm.length_eq {l₁ l₂ : list α} (p : l₁ ~ l₂) : length l₁ = length l₂ :=
perm.rec_on p
rfl
(λ x l₁ l₂ p r, by simp[r])
(λ x y l, by simp)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂)
theorem perm.eq_nil {l : list α} (p : l ~ []) : l = [] :=
eq_nil_of_length_eq_zero p.length_eq
theorem perm.nil_eq {l : list α} (p : [] ~ l) : [] = l :=
p.symm.eq_nil.symm
@[simp]
theorem perm_nil {l₁ : list α} : l₁ ~ [] ↔ l₁ = [] :=
⟨λ p, p.eq_nil, λ e, e ▸ perm.refl _⟩
@[simp]
theorem nil_perm {l₁ : list α} : [] ~ l₁ ↔ l₁ = [] :=
perm_comm.trans perm_nil
theorem not_perm_nil_cons (x : α) (l : list α) : ¬ [] ~ x::l
| p := by injection p.symm.eq_nil
@[simp] theorem reverse_perm : ∀ (l : list α), reverse l ~ l
| [] := perm.nil
| (a::l) := by { rw reverse_cons,
exact (perm_append_singleton _ _).trans ((reverse_perm l).cons a) }
theorem perm_cons_append_cons {l l₁ l₂ : list α} (a : α) (p : l ~ l₁++l₂) :
a::l ~ l₁++(a::l₂) :=
(p.cons a).trans perm_middle.symm
@[simp] theorem perm_repeat {a : α} {n : ℕ} {l : list α} : l ~ repeat a n ↔ l = repeat a n :=
⟨λ p, (eq_repeat.2
⟨p.length_eq.trans $ length_repeat _ _,
λ b m, eq_of_mem_repeat $ p.subset m⟩),
λ h, h ▸ perm.refl _⟩
@[simp] theorem repeat_perm {a : α} {n : ℕ} {l : list α} : repeat a n ~ l ↔ repeat a n = l :=
(perm_comm.trans perm_repeat).trans eq_comm
@[simp] theorem perm_singleton {a : α} {l : list α} : l ~ [a] ↔ l = [a] :=
@perm_repeat α a 1 l
@[simp] theorem singleton_perm {a : α} {l : list α} : [a] ~ l ↔ [a] = l :=
@repeat_perm α a 1 l
theorem perm.eq_singleton {a : α} {l : list α} (p : l ~ [a]) : l = [a] :=
perm_singleton.1 p
theorem perm.singleton_eq {a : α} {l : list α} (p : [a] ~ l) : [a] = l :=
p.symm.eq_singleton.symm
theorem singleton_perm_singleton {a b : α} : [a] ~ [b] ↔ a = b :=
by simp
theorem perm_cons_erase [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) :
l ~ a :: l.erase a :=
let ⟨l₁, l₂, _, e₁, e₂⟩ := exists_erase_eq h in
e₂.symm ▸ e₁.symm ▸ perm_middle
@[elab_as_eliminator] theorem perm_induction_on
{P : list α → list α → Prop} {l₁ l₂ : list α} (p : l₁ ~ l₂)
(h₁ : P [] [])
(h₂ : ∀ x l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (x::l₁) (x::l₂))
(h₃ : ∀ x y l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (y::x::l₁) (x::y::l₂))
(h₄ : ∀ l₁ l₂ l₃, l₁ ~ l₂ → l₂ ~ l₃ → P l₁ l₂ → P l₂ l₃ → P l₁ l₃) :
P l₁ l₂ :=
have P_refl : ∀ l, P l l, from
assume l,
list.rec_on l h₁ (λ x xs ih, h₂ x xs xs (perm.refl xs) ih),
perm.rec_on p h₁ h₂ (λ x y l, h₃ x y l l (perm.refl l) (P_refl l)) h₄
@[congr] theorem perm.filter_map (f : α → option β) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
filter_map f l₁ ~ filter_map f l₂ :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂,
{ simp },
{ simp only [filter_map], cases f x with a; simp [filter_map, IH, perm.cons] },
{ simp only [filter_map], cases f x with a; cases f y with b; simp [filter_map, swap] },
{ exact IH₁.trans IH₂ }
end
@[congr] theorem perm.map (f : α → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
map f l₁ ~ map f l₂ :=
filter_map_eq_map f ▸ p.filter_map _
theorem perm.pmap {p : α → Prop} (f : Π a, p a → β)
{l₁ l₂ : list α} (p : l₁ ~ l₂) {H₁ H₂} : pmap f l₁ H₁ ~ pmap f l₂ H₂ :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂,
{ simp },
{ simp [IH, perm.cons] },
{ simp [swap] },
{ refine IH₁.trans IH₂,
exact λ a m, H₂ a (p₂.subset m) }
end
theorem perm.filter (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} (s : l₁ ~ l₂) : filter p l₁ ~ filter p l₂ :=
by rw ← filter_map_eq_filter; apply s.filter_map _
theorem filter_append_perm (p : α → Prop) [decidable_pred p]
(l : list α) : filter p l ++ filter (λ x, ¬ p x) l ~ l :=
begin
induction l with x l ih,
{ refl },
{ by_cases h : p x,
{ simp only [h, filter_cons_of_pos, filter_cons_of_neg, not_true, not_false_iff, cons_append],
exact ih.cons x },
{ simp only [h, filter_cons_of_neg, not_false_iff, filter_cons_of_pos],
refine perm.trans _ (ih.cons x),
exact perm_append_comm.trans (perm_append_comm.cons _), } }
end
theorem exists_perm_sublist {l₁ l₂ l₂' : list α}
(s : l₁ <+ l₂) (p : l₂ ~ l₂') : ∃ l₁' ~ l₁, l₁' <+ l₂' :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂ generalizing l₁ s,
{ exact ⟨[], eq_nil_of_sublist_nil s ▸ perm.refl _, nil_sublist _⟩ },
{ cases s with _ _ _ s l₁ _ _ s,
{ exact let ⟨l₁', p', s'⟩ := IH s in ⟨l₁', p', s'.cons _ _ _⟩ },
{ exact let ⟨l₁', p', s'⟩ := IH s in ⟨x::l₁', p'.cons x, s'.cons2 _ _ _⟩ } },
{ cases s with _ _ _ s l₁ _ _ s; cases s with _ _ _ s l₁ _ _ s,
{ exact ⟨l₁, perm.refl _, (s.cons _ _ _).cons _ _ _⟩ },
{ exact ⟨x::l₁, perm.refl _, (s.cons _ _ _).cons2 _ _ _⟩ },
{ exact ⟨y::l₁, perm.refl _, (s.cons2 _ _ _).cons _ _ _⟩ },
{ exact ⟨x::y::l₁, perm.swap _ _ _, (s.cons2 _ _ _).cons2 _ _ _⟩ } },
{ exact let ⟨m₁, pm, sm⟩ := IH₁ s, ⟨r₁, pr, sr⟩ := IH₂ sm in
⟨r₁, pr.trans pm, sr⟩ }
end
theorem perm.sizeof_eq_sizeof [has_sizeof α] {l₁ l₂ : list α} (h : l₁ ~ l₂) :
l₁.sizeof = l₂.sizeof :=
begin
induction h with hd l₁ l₂ h₁₂ h_sz₁₂ a b l l₁ l₂ l₃ h₁₂ h₂₃ h_sz₁₂ h_sz₂₃,
{ refl },
{ simp only [list.sizeof, h_sz₁₂] },
{ simp only [list.sizeof, add_left_comm] },
{ simp only [h_sz₁₂, h_sz₂₃] }
end
section rel
open relator
variables {γ : Type*} {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
local infixr ` ∘r ` : 80 := relation.comp
lemma perm_comp_perm : (perm ∘r perm : list α → list α → Prop) = perm :=
begin
funext a c, apply propext,
split,
{ exact assume ⟨b, hab, hba⟩, perm.trans hab hba },
{ exact assume h, ⟨a, perm.refl a, h⟩ }
end
lemma perm_comp_forall₂ {l u v} (hlu : perm l u) (huv : forall₂ r u v) : (forall₂ r ∘r perm) l v :=
begin
induction hlu generalizing v,
case perm.nil { cases huv, exact ⟨[], forall₂.nil, perm.nil⟩ },
case perm.cons : a l u hlu ih
{ cases huv with _ b _ v hab huv',
rcases ih huv' with ⟨l₂, h₁₂, h₂₃⟩,
exact ⟨b::l₂, forall₂.cons hab h₁₂, h₂₃.cons _⟩ },
case perm.swap : a₁ a₂ l₁ l₂ h₂₃
{ cases h₂₃ with _ b₁ _ l₂ h₁ hr_₂₃,
cases hr_₂₃ with _ b₂ _ l₂ h₂ h₁₂,
exact ⟨b₂::b₁::l₂, forall₂.cons h₂ (forall₂.cons h₁ h₁₂), perm.swap _ _ _⟩ },
case perm.trans : la₁ la₂ la₃ _ _ ih₁ ih₂
{ rcases ih₂ huv with ⟨lb₂, hab₂, h₂₃⟩,
rcases ih₁ hab₂ with ⟨lb₁, hab₁, h₁₂⟩,
exact ⟨lb₁, hab₁, perm.trans h₁₂ h₂₃⟩ }
end
lemma forall₂_comp_perm_eq_perm_comp_forall₂ : forall₂ r ∘r perm = perm ∘r forall₂ r :=
begin
funext l₁ l₃, apply propext,
split,
{ assume h, rcases h with ⟨l₂, h₁₂, h₂₃⟩,
have : forall₂ (flip r) l₂ l₁, from h₁₂.flip ,
rcases perm_comp_forall₂ h₂₃.symm this with ⟨l', h₁, h₂⟩,
exact ⟨l', h₂.symm, h₁.flip⟩ },
{ exact assume ⟨l₂, h₁₂, h₂₃⟩, perm_comp_forall₂ h₁₂ h₂₃ }
end
lemma rel_perm_imp (hr : right_unique r) : (forall₂ r ⇒ forall₂ r ⇒ implies) perm perm :=
assume a b h₁ c d h₂ h,
have (flip (forall₂ r) ∘r (perm ∘r forall₂ r)) b d, from ⟨a, h₁, c, h, h₂⟩,
have ((flip (forall₂ r) ∘r forall₂ r) ∘r perm) b d,
by rwa [← forall₂_comp_perm_eq_perm_comp_forall₂, ← relation.comp_assoc] at this,
let ⟨b', ⟨c', hbc, hcb⟩, hbd⟩ := this in
have b' = b, from right_unique_forall₂' hr hcb hbc,
this ▸ hbd
lemma rel_perm (hr : bi_unique r) : (forall₂ r ⇒ forall₂ r ⇒ (↔)) perm perm :=
assume a b hab c d hcd, iff.intro
(rel_perm_imp hr.2 hab hcd)
(rel_perm_imp hr.left.flip hab.flip hcd.flip)
end rel
section subperm
/-- `subperm l₁ l₂`, denoted `l₁ <+~ l₂`, means that `l₁` is a sublist of
a permutation of `l₂`. This is an analogue of `l₁ ⊆ l₂` which respects
multiplicities of elements, and is used for the `≤` relation on multisets. -/
def subperm (l₁ l₂ : list α) : Prop := ∃ l ~ l₁, l <+ l₂
infix ` <+~ `:50 := subperm
theorem nil_subperm {l : list α} : [] <+~ l :=
⟨[], perm.nil, by simp⟩
theorem perm.subperm_left {l l₁ l₂ : list α} (p : l₁ ~ l₂) : l <+~ l₁ ↔ l <+~ l₂ :=
suffices ∀ {l₁ l₂ : list α}, l₁ ~ l₂ → l <+~ l₁ → l <+~ l₂,
from ⟨this p, this p.symm⟩,
λ l₁ l₂ p ⟨u, pu, su⟩,
let ⟨v, pv, sv⟩ := exists_perm_sublist su p in
⟨v, pv.trans pu, sv⟩
theorem perm.subperm_right {l₁ l₂ l : list α} (p : l₁ ~ l₂) : l₁ <+~ l ↔ l₂ <+~ l :=
⟨λ ⟨u, pu, su⟩, ⟨u, pu.trans p, su⟩,
λ ⟨u, pu, su⟩, ⟨u, pu.trans p.symm, su⟩⟩
theorem sublist.subperm {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁ <+~ l₂ :=
⟨l₁, perm.refl _, s⟩
theorem perm.subperm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ <+~ l₂ :=
⟨l₂, p.symm, sublist.refl _⟩
@[refl] theorem subperm.refl (l : list α) : l <+~ l := (perm.refl _).subperm
@[trans] theorem subperm.trans {l₁ l₂ l₃ : list α} : l₁ <+~ l₂ → l₂ <+~ l₃ → l₁ <+~ l₃
| s ⟨l₂', p₂, s₂⟩ :=
let ⟨l₁', p₁, s₁⟩ := p₂.subperm_left.2 s in ⟨l₁', p₁, s₁.trans s₂⟩
theorem subperm.length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ ≤ length l₂
| ⟨l, p, s⟩ := p.length_eq ▸ s.length_le
theorem subperm.perm_of_length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₂ ≤ length l₁ → l₁ ~ l₂
| ⟨l, p, s⟩ h := (s.eq_of_length_le $ p.symm.length_eq ▸ h) ▸ p.symm
theorem subperm.antisymm {l₁ l₂ : list α} (h₁ : l₁ <+~ l₂) (h₂ : l₂ <+~ l₁) : l₁ ~ l₂ :=
h₁.perm_of_length_le h₂.length_le
theorem subperm.subset {l₁ l₂ : list α} : l₁ <+~ l₂ → l₁ ⊆ l₂
| ⟨l, p, s⟩ := subset.trans p.symm.subset s.subset
lemma subperm.filter (p : α → Prop) [decidable_pred p]
⦃l l' : list α⦄ (h : l <+~ l') : filter p l <+~ filter p l' :=
begin
obtain ⟨xs, hp, h⟩ := h,
exact ⟨_, hp.filter p, h.filter p⟩
end
end subperm
theorem sublist.exists_perm_append : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → ∃ l, l₂ ~ l₁ ++ l
| ._ ._ sublist.slnil := ⟨nil, perm.refl _⟩
| ._ ._ (sublist.cons l₁ l₂ a s) :=
let ⟨l, p⟩ := sublist.exists_perm_append s in
⟨a::l, (p.cons a).trans perm_middle.symm⟩
| ._ ._ (sublist.cons2 l₁ l₂ a s) :=
let ⟨l, p⟩ := sublist.exists_perm_append s in
⟨l, p.cons a⟩
theorem perm.countp_eq (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} (s : l₁ ~ l₂) : countp p l₁ = countp p l₂ :=
by rw [countp_eq_length_filter, countp_eq_length_filter];
exact (s.filter _).length_eq
theorem subperm.countp_le (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} : l₁ <+~ l₂ → countp p l₁ ≤ countp p l₂
| ⟨l, p', s⟩ := p'.countp_eq p ▸ s.countp_le p
theorem perm.countp_congr (s : l₁ ~ l₂) {p p' : α → Prop} [decidable_pred p] [decidable_pred p']
(hp : ∀ x ∈ l₁, p x = p' x) : l₁.countp p = l₂.countp p' :=
begin
rw ← s.countp_eq p',
clear s,
induction l₁ with y s hs,
{ refl },
{ simp only [mem_cons_iff, forall_eq_or_imp] at hp,
simp only [countp_cons, hs hp.2, hp.1], },
end
theorem countp_eq_countp_filter_add
(l : list α) (p q : α → Prop) [decidable_pred p] [decidable_pred q] :
l.countp p = (l.filter q).countp p + (l.filter (λ a, ¬ q a)).countp p :=
by { rw [← countp_append], exact perm.countp_eq _ (filter_append_perm _ _).symm }
theorem perm.count_eq [decidable_eq α] {l₁ l₂ : list α}
(p : l₁ ~ l₂) (a) : count a l₁ = count a l₂ :=
p.countp_eq _
theorem subperm.count_le [decidable_eq α] {l₁ l₂ : list α}
(s : l₁ <+~ l₂) (a) : count a l₁ ≤ count a l₂ :=
s.countp_le _
theorem perm.foldl_eq' {f : β → α → β} {l₁ l₂ : list α} (p : l₁ ~ l₂) :
(∀ (x ∈ l₁) (y ∈ l₁) z, f (f z x) y = f (f z y) x) → ∀ b, foldl f b l₁ = foldl f b l₂ :=
perm_induction_on p
(λ H b, rfl)
(λ x t₁ t₂ p r H b, r (λ x hx y hy, H _ (or.inr hx) _ (or.inr hy)) _)
(λ x y t₁ t₂ p r H b,
begin
simp only [foldl],
rw [H x (or.inr $ or.inl rfl) y (or.inl rfl)],
exact r (λ x hx y hy, H _ (or.inr $ or.inr hx) _ (or.inr $ or.inr hy)) _
end)
(λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ H b, eq.trans (r₁ H b)
(r₂ (λ x hx y hy, H _ (p₁.symm.subset hx) _ (p₁.symm.subset hy)) b))
theorem perm.foldl_eq {f : β → α → β} {l₁ l₂ : list α} (rcomm : right_commutative f) (p : l₁ ~ l₂) :
∀ b, foldl f b l₁ = foldl f b l₂ :=
p.foldl_eq' $ λ x hx y hy z, rcomm z x y
theorem perm.foldr_eq {f : α → β → β} {l₁ l₂ : list α} (lcomm : left_commutative f) (p : l₁ ~ l₂) :
∀ b, foldr f b l₁ = foldr f b l₂ :=
perm_induction_on p
(λ b, rfl)
(λ x t₁ t₂ p r b, by simp; rw [r b])
(λ x y t₁ t₂ p r b, by simp; rw [lcomm, r b])
(λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ a, eq.trans (r₁ a) (r₂ a))
lemma perm.rec_heq {β : list α → Sort*} {f : Πa l, β l → β (a::l)} {b : β []} {l l' : list α}
(hl : perm l l')
(f_congr : ∀{a l l' b b'}, perm l l' → b == b' → f a l b == f a l' b')
(f_swap : ∀{a a' l b}, f a (a'::l) (f a' l b) == f a' (a::l) (f a l b)) :
@list.rec α β b f l == @list.rec α β b f l' :=
begin
induction hl,
case list.perm.nil { refl },
case list.perm.cons : a l l' h ih { exact f_congr h ih },
case list.perm.swap : a a' l { exact f_swap },
case list.perm.trans : l₁ l₂ l₃ h₁ h₂ ih₁ ih₂ { exact heq.trans ih₁ ih₂ }
end
section
variables {op : α → α → α} [is_associative α op] [is_commutative α op]
local notation (name := op) a ` * ` b := op a b
local notation (name := foldl) l ` <*> ` a := foldl op a l
lemma perm.fold_op_eq {l₁ l₂ : list α} {a : α} (h : l₁ ~ l₂) : l₁ <*> a = l₂ <*> a :=
h.foldl_eq (right_comm _ is_commutative.comm is_associative.assoc) _
end
section comm_monoid
/-- If elements of a list commute with each other, then their product does not
depend on the order of elements. -/
@[to_additive "If elements of a list additively commute with each other, then their sum does not
depend on the order of elements."]
lemma perm.prod_eq' [monoid α] {l₁ l₂ : list α} (h : l₁ ~ l₂) (hc : l₁.pairwise commute) :
l₁.prod = l₂.prod :=
h.foldl_eq' (pairwise.forall_of_forall (λ x y h z, (h z).symm) (λ x hx z, rfl) $
hc.imp $ λ x y h z, by simp only [mul_assoc, h.eq]) _
variable [comm_monoid α]
@[to_additive]
lemma perm.prod_eq {l₁ l₂ : list α} (h : perm l₁ l₂) : prod l₁ = prod l₂ :=
h.fold_op_eq
@[to_additive]
lemma prod_reverse (l : list α) : prod l.reverse = prod l :=
(reverse_perm l).prod_eq
end comm_monoid
theorem perm_inv_core {a : α} {l₁ l₂ r₁ r₂ : list α} : l₁++a::r₁ ~ l₂++a::r₂ → l₁++r₁ ~ l₂++r₂ :=
begin
generalize e₁ : l₁++a::r₁ = s₁, generalize e₂ : l₂++a::r₂ = s₂,
intro p, revert l₁ l₂ r₁ r₂ e₁ e₂,
refine perm_induction_on p _ (λ x t₁ t₂ p IH, _) (λ x y t₁ t₂ p IH, _)
(λ t₁ t₂ t₃ p₁ p₂ IH₁ IH₂, _); intros l₁ l₂ r₁ r₂ e₁ e₂,
{ apply (not_mem_nil a).elim, rw ← e₁, simp },
{ cases l₁ with y l₁; cases l₂ with z l₂;
dsimp at e₁ e₂; injections; subst x,
{ substs t₁ t₂, exact p },
{ substs z t₁ t₂, exact p.trans perm_middle },
{ substs y t₁ t₂, exact perm_middle.symm.trans p },
{ substs z t₁ t₂, exact (IH rfl rfl).cons y } },
{ rcases l₁ with _|⟨y, _|⟨z, l₁⟩⟩; rcases l₂ with _|⟨u, _|⟨v, l₂⟩⟩;
dsimp at e₁ e₂; injections; substs x y,
{ substs r₁ r₂, exact p.cons a },
{ substs r₁ r₂, exact p.cons u },
{ substs r₁ v t₂, exact (p.trans perm_middle).cons u },
{ substs r₁ r₂, exact p.cons y },
{ substs r₁ r₂ y u, exact p.cons a },
{ substs r₁ u v t₂, exact ((p.trans perm_middle).cons y).trans (swap _ _ _) },
{ substs r₂ z t₁, exact (perm_middle.symm.trans p).cons y },
{ substs r₂ y z t₁, exact (swap _ _ _).trans ((perm_middle.symm.trans p).cons u) },
{ substs u v t₁ t₂, exact (IH rfl rfl).swap' _ _ } },
{ substs t₁ t₃,
have : a ∈ t₂ := p₁.subset (by simp),
rcases mem_split this with ⟨l₂, r₂, e₂⟩,
subst t₂, exact (IH₁ rfl rfl).trans (IH₂ rfl rfl) }
end
theorem perm.cons_inv {a : α} {l₁ l₂ : list α} : a::l₁ ~ a::l₂ → l₁ ~ l₂ :=
@perm_inv_core _ _ [] [] _ _
@[simp] theorem perm_cons (a : α) {l₁ l₂ : list α} : a::l₁ ~ a::l₂ ↔ l₁ ~ l₂ :=
⟨perm.cons_inv, perm.cons a⟩
theorem perm_append_left_iff {l₁ l₂ : list α} : ∀ l, l++l₁ ~ l++l₂ ↔ l₁ ~ l₂
| [] := iff.rfl
| (a::l) := (perm_cons a).trans (perm_append_left_iff l)
theorem perm_append_right_iff {l₁ l₂ : list α} (l) : l₁++l ~ l₂++l ↔ l₁ ~ l₂ :=
⟨λ p, (perm_append_left_iff _).1 $ perm_append_comm.trans $ p.trans perm_append_comm,
perm.append_right _⟩
theorem perm_option_to_list {o₁ o₂ : option α} : o₁.to_list ~ o₂.to_list ↔ o₁ = o₂ :=
begin
refine ⟨λ p, _, λ e, e ▸ perm.refl _⟩,
cases o₁ with a; cases o₂ with b, {refl},
{ cases p.length_eq },
{ cases p.length_eq },
{ exact option.mem_to_list.1 (p.symm.subset $ by simp) }
end
theorem subperm_cons (a : α) {l₁ l₂ : list α} : a::l₁ <+~ a::l₂ ↔ l₁ <+~ l₂ :=
⟨λ ⟨l, p, s⟩, begin
cases s with _ _ _ s' u _ _ s',
{ exact (p.subperm_left.2 $ (sublist_cons _ _).subperm).trans s'.subperm },
{ exact ⟨u, p.cons_inv, s'⟩ }
end, λ ⟨l, p, s⟩, ⟨a::l, p.cons a, s.cons2 _ _ _⟩⟩
alias subperm_cons ↔ subperm.of_cons subperm.cons
attribute [protected] subperm.cons
theorem cons_subperm_of_mem {a : α} {l₁ l₂ : list α} (d₁ : nodup l₁) (h₁ : a ∉ l₁) (h₂ : a ∈ l₂)
(s : l₁ <+~ l₂) : a :: l₁ <+~ l₂ :=
begin
rcases s with ⟨l, p, s⟩,
induction s generalizing l₁,
case list.sublist.slnil { cases h₂ },
case list.sublist.cons : r₁ r₂ b s' ih
{ simp at h₂,
cases h₂ with e m,
{ subst b, exact ⟨a::r₁, p.cons a, s'.cons2 _ _ _⟩ },
{ rcases ih m d₁ h₁ p with ⟨t, p', s'⟩, exact ⟨t, p', s'.cons _ _ _⟩ } },
case list.sublist.cons2 : r₁ r₂ b s' ih
{ have bm : b ∈ l₁ := (p.subset $ mem_cons_self _ _),
have am : a ∈ r₂ := h₂.resolve_left (λ e, h₁ $ e.symm ▸ bm),
rcases mem_split bm with ⟨t₁, t₂, rfl⟩,
have st : t₁ ++ t₂ <+ t₁ ++ b :: t₂ := by simp,
rcases ih am (d₁.sublist st)
(mt (λ x, st.subset x) h₁)
(perm.cons_inv $ p.trans perm_middle) with ⟨t, p', s'⟩,
exact ⟨b::t, (p'.cons b).trans $ (swap _ _ _).trans (perm_middle.symm.cons a), s'.cons2 _ _ _⟩ }
end
theorem subperm_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+~ l++l₂ ↔ l₁ <+~ l₂
| [] := iff.rfl
| (a::l) := (subperm_cons a).trans (subperm_append_left l)
theorem subperm_append_right {l₁ l₂ : list α} (l) : l₁++l <+~ l₂++l ↔ l₁ <+~ l₂ :=
(perm_append_comm.subperm_left.trans perm_append_comm.subperm_right).trans (subperm_append_left l)
theorem subperm.exists_of_length_lt {l₁ l₂ : list α} :
l₁ <+~ l₂ → length l₁ < length l₂ → ∃ a, a :: l₁ <+~ l₂
| ⟨l, p, s⟩ h :=
suffices length l < length l₂ → ∃ (a : α), a :: l <+~ l₂, from
(this $ p.symm.length_eq ▸ h).imp (λ a, (p.cons a).subperm_right.1),
begin
clear subperm.exists_of_length_lt p h l₁, rename l₂ u,
induction s with l₁ l₂ a s IH _ _ b s IH; intro h,
{ cases h },
{ cases lt_or_eq_of_le (nat.le_of_lt_succ h : length l₁ ≤ length l₂) with h h,
{ exact (IH h).imp (λ a s, s.trans (sublist_cons _ _).subperm) },
{ exact ⟨a, s.eq_of_length h ▸ subperm.refl _⟩ } },
{ exact (IH $ nat.lt_of_succ_lt_succ h).imp
(λ a s, (swap _ _ _).subperm_right.1 $ (subperm_cons _).2 s) }
end
protected lemma nodup.subperm (d : nodup l₁) (H : l₁ ⊆ l₂) : l₁ <+~ l₂ :=
begin
induction d with a l₁' h d IH,
{ exact ⟨nil, perm.nil, nil_sublist _⟩ },
{ cases forall_mem_cons.1 H with H₁ H₂,
simp at h,
exact cons_subperm_of_mem d h H₁ (IH H₂) }
end
theorem perm_ext {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) :
l₁ ~ l₂ ↔ ∀a, a ∈ l₁ ↔ a ∈ l₂ :=
⟨λ p a, p.mem_iff, λ H, (d₁.subperm $ λ a, (H a).1).antisymm $ d₂.subperm $ λ a, (H a).2⟩
theorem nodup.sublist_ext {l₁ l₂ l : list α} (d : nodup l)
(s₁ : l₁ <+ l) (s₂ : l₂ <+ l) : l₁ ~ l₂ ↔ l₁ = l₂ :=
⟨λ h, begin
induction s₂ with l₂ l a s₂ IH l₂ l a s₂ IH generalizing l₁,
{ exact h.eq_nil },
{ simp at d,
cases s₁ with _ _ _ s₁ l₁ _ _ s₁,
{ exact IH d.2 s₁ h },
{ apply d.1.elim,
exact subperm.subset ⟨_, h.symm, s₂⟩ (mem_cons_self _ _) } },
{ simp at d,
cases s₁ with _ _ _ s₁ l₁ _ _ s₁,
{ apply d.1.elim,
exact subperm.subset ⟨_, h, s₁⟩ (mem_cons_self _ _) },
{ rw IH d.2 s₁ h.cons_inv } }
end, λ h, by rw h⟩
section
variable [decidable_eq α]
-- attribute [congr]
theorem perm.erase (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
l₁.erase a ~ l₂.erase a :=
if h₁ : a ∈ l₁ then
have h₂ : a ∈ l₂, from p.subset h₁,
perm.cons_inv $ (perm_cons_erase h₁).symm.trans $ p.trans (perm_cons_erase h₂)
else
have h₂ : a ∉ l₂, from mt p.mem_iff.2 h₁,
by rw [erase_of_not_mem h₁, erase_of_not_mem h₂]; exact p
theorem subperm_cons_erase (a : α) (l : list α) : l <+~ a :: l.erase a :=
begin
by_cases h : a ∈ l,
{ exact (perm_cons_erase h).subperm },
{ rw [erase_of_not_mem h],
exact (sublist_cons _ _).subperm }
end
theorem erase_subperm (a : α) (l : list α) : l.erase a <+~ l :=
(erase_sublist _ _).subperm
theorem subperm.erase {l₁ l₂ : list α} (a : α) (h : l₁ <+~ l₂) : l₁.erase a <+~ l₂.erase a :=
let ⟨l, hp, hs⟩ := h in ⟨l.erase a, hp.erase _, hs.erase _⟩
theorem perm.diff_right {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.diff t ~ l₂.diff t :=
by induction t generalizing l₁ l₂ h; simp [*, perm.erase]
theorem perm.diff_left (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l.diff t₁ = l.diff t₂ :=
by induction h generalizing l; simp [*, perm.erase, erase_comm]
<|> exact (ih_1 _).trans (ih_2 _)
theorem perm.diff {l₁ l₂ t₁ t₂ : list α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) :
l₁.diff t₁ ~ l₂.diff t₂ :=
ht.diff_left l₂ ▸ hl.diff_right _
theorem subperm.diff_right {l₁ l₂ : list α} (h : l₁ <+~ l₂) (t : list α) :
l₁.diff t <+~ l₂.diff t :=
by induction t generalizing l₁ l₂ h; simp [*, subperm.erase]
theorem erase_cons_subperm_cons_erase (a b : α) (l : list α) :
(a :: l).erase b <+~ a :: l.erase b :=
begin
by_cases h : a = b,
{ subst b,
rw [erase_cons_head],
apply subperm_cons_erase },
{ rw [erase_cons_tail _ h] }
end
theorem subperm_cons_diff {a : α} : ∀ {l₁ l₂ : list α}, (a :: l₁).diff l₂ <+~ a :: l₁.diff l₂
| l₁ [] := ⟨a::l₁, by simp⟩
| l₁ (b::l₂) :=
begin
simp only [diff_cons],
refine ((erase_cons_subperm_cons_erase a b l₁).diff_right l₂).trans _,
apply subperm_cons_diff
end
theorem subset_cons_diff {a : α} {l₁ l₂ : list α} : (a :: l₁).diff l₂ ⊆ a :: l₁.diff l₂ :=
subperm_cons_diff.subset
theorem perm.bag_inter_right {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) :
l₁.bag_inter t ~ l₂.bag_inter t :=
begin
induction h with x _ _ _ _ x y _ _ _ _ _ _ ih_1 ih_2 generalizing t, {simp},
{ by_cases x ∈ t; simp [*, perm.cons] },
{ by_cases x = y, {simp [h]},
by_cases xt : x ∈ t; by_cases yt : y ∈ t,
{ simp [xt, yt, mem_erase_of_ne h, mem_erase_of_ne (ne.symm h), erase_comm, swap] },
{ simp [xt, yt, mt mem_of_mem_erase, perm.cons] },
{ simp [xt, yt, mt mem_of_mem_erase, perm.cons] },
{ simp [xt, yt] } },
{ exact (ih_1 _).trans (ih_2 _) }
end
theorem perm.bag_inter_left (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) :
l.bag_inter t₁ = l.bag_inter t₂ :=
begin
induction l with a l IH generalizing t₁ t₂ p, {simp},
by_cases a ∈ t₁,
{ simp [h, p.subset h, IH (p.erase _)] },
{ simp [h, mt p.mem_iff.2 h, IH p] }
end
theorem perm.bag_inter {l₁ l₂ t₁ t₂ : list α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) :
l₁.bag_inter t₁ ~ l₂.bag_inter t₂ :=
ht.bag_inter_left l₂ ▸ hl.bag_inter_right _
theorem cons_perm_iff_perm_erase {a : α} {l₁ l₂ : list α} : a::l₁ ~ l₂ ↔ a ∈ l₂ ∧ l₁ ~ l₂.erase a :=
⟨λ h, have a ∈ l₂, from h.subset (mem_cons_self a l₁),
⟨this, (h.trans $ perm_cons_erase this).cons_inv⟩,
λ ⟨m, h⟩, (h.cons a).trans (perm_cons_erase m).symm⟩
theorem perm_iff_count {l₁ l₂ : list α} : l₁ ~ l₂ ↔ ∀ a, count a l₁ = count a l₂ :=
⟨perm.count_eq, λ H, begin
induction l₁ with a l₁ IH generalizing l₂,
{ cases l₂ with b l₂, {refl},
specialize H b, simp at H, contradiction },
{ have : a ∈ l₂ := count_pos.1 (by rw ← H; simp; apply nat.succ_pos),
refine ((IH $ λ b, _).cons a).trans (perm_cons_erase this).symm,
specialize H b,
rw (perm_cons_erase this).count_eq at H,
by_cases b = a; simp [h] at H ⊢; assumption }
end⟩
lemma subperm.cons_right {α : Type*} {l l' : list α} (x : α) (h : l <+~ l') : l <+~ x :: l' :=
h.trans (sublist_cons x l').subperm
/-- The list version of `add_tsub_cancel_of_le` for multisets. -/
lemma subperm_append_diff_self_of_count_le {l₁ l₂ : list α}
(h : ∀ x ∈ l₁, count x l₁ ≤ count x l₂) : l₁ ++ l₂.diff l₁ ~ l₂ :=
begin
induction l₁ with hd tl IH generalizing l₂,
{ simp },
{ have : hd ∈ l₂,
{ rw ←count_pos,
exact lt_of_lt_of_le (count_pos.mpr (mem_cons_self _ _)) (h hd (mem_cons_self _ _)) },
replace this : l₂ ~ hd :: l₂.erase hd := perm_cons_erase this,
refine perm.trans _ this.symm,
rw [cons_append, diff_cons, perm_cons],
refine IH (λ x hx, _),
specialize h x (mem_cons_of_mem _ hx),
rw (perm_iff_count.mp this) at h,
by_cases hx : x = hd,
{ subst hd,
simpa [nat.succ_le_succ_iff] using h },
{ simpa [hx] using h } },
end
/-- The list version of `multiset.le_iff_count`. -/
lemma subperm_ext_iff {l₁ l₂ : list α} :
l₁ <+~ l₂ ↔ ∀ x ∈ l₁, count x l₁ ≤ count x l₂ :=
begin
refine ⟨λ h x hx, subperm.count_le h x, λ h, _⟩,
suffices : l₁ <+~ (l₂.diff l₁ ++ l₁),
{ refine this.trans (perm.subperm _),
exact perm_append_comm.trans (subperm_append_diff_self_of_count_le h) },
convert (subperm_append_right _).mpr nil_subperm using 1
end
instance decidable_subperm : decidable_rel ((<+~) : list α → list α → Prop) :=
λ l₁ l₂, decidable_of_iff _ list.subperm_ext_iff.symm
@[simp] lemma subperm_singleton_iff {α} {l : list α} {a : α} : [a] <+~ l ↔ a ∈ l :=
⟨λ ⟨s, hla, h⟩, by rwa [perm_singleton.mp hla, singleton_sublist] at h,
λ h, ⟨[a], perm.refl _, singleton_sublist.mpr h⟩⟩
lemma subperm.cons_left {l₁ l₂ : list α} (h : l₁ <+~ l₂)
(x : α) (hx : count x l₁ < count x l₂) :
x :: l₁ <+~ l₂ :=
begin
rw subperm_ext_iff at h ⊢,
intros y hy,
by_cases hy' : y = x,
{ subst x,
simpa using nat.succ_le_of_lt hx },
{ rw count_cons_of_ne hy',
refine h y _,
simpa [hy'] using hy }
end
instance decidable_perm : ∀ (l₁ l₂ : list α), decidable (l₁ ~ l₂)
| [] [] := is_true $ perm.refl _
| [] (b::l₂) := is_false $ λ h, by have := h.nil_eq; contradiction
| (a::l₁) l₂ := by haveI := decidable_perm l₁ (l₂.erase a);
exact decidable_of_iff' _ cons_perm_iff_perm_erase
-- @[congr]
theorem perm.dedup {l₁ l₂ : list α} (p : l₁ ~ l₂) :
dedup l₁ ~ dedup l₂ :=
perm_iff_count.2 $ λ a,
if h : a ∈ l₁
then by simp [nodup_dedup, h, p.subset h]
else by simp [h, mt p.mem_iff.2 h]
-- attribute [congr]
theorem perm.insert (a : α)
{l₁ l₂ : list α} (p : l₁ ~ l₂) : insert a l₁ ~ insert a l₂ :=
if h : a ∈ l₁
then by simpa [h, p.subset h] using p
else by simpa [h, mt p.mem_iff.2 h] using p.cons a
theorem perm_insert_swap (x y : α) (l : list α) :
insert x (insert y l) ~ insert y (insert x l) :=
begin
by_cases xl : x ∈ l; by_cases yl : y ∈ l; simp [xl, yl],
by_cases xy : x = y, { simp [xy] },
simp [not_mem_cons_of_ne_of_not_mem xy xl,
not_mem_cons_of_ne_of_not_mem (ne.symm xy) yl],
constructor
end
theorem perm_insert_nth {α} (x : α) (l : list α) {n} (h : n ≤ l.length) :
insert_nth n x l ~ x :: l :=
begin
induction l generalizing n,
{ cases n, refl, cases h },
cases n,
{ simp [insert_nth] },
{ simp only [insert_nth, modify_nth_tail],
transitivity,
{ apply perm.cons, apply l_ih,
apply nat.le_of_succ_le_succ h },
{ apply perm.swap } }
end
theorem perm.union_right {l₁ l₂ : list α} (t₁ : list α) (h : l₁ ~ l₂) : l₁ ∪ t₁ ~ l₂ ∪ t₁ :=
begin
induction h with a _ _ _ ih _ _ _ _ _ _ _ _ ih_1 ih_2; try {simp},
{ exact ih.insert a },
{ apply perm_insert_swap },
{ exact ih_1.trans ih_2 }
end
theorem perm.union_left (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l ∪ t₁ ~ l ∪ t₂ :=
by induction l; simp [*, perm.insert]
-- @[congr]
theorem perm.union {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∪ t₁ ~ l₂ ∪ t₂ :=
(p₁.union_right t₁).trans (p₂.union_left l₂)
theorem perm.inter_right {l₁ l₂ : list α} (t₁ : list α) : l₁ ~ l₂ → l₁ ∩ t₁ ~ l₂ ∩ t₁ :=
perm.filter _
theorem perm.inter_left (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l ∩ t₁ = l ∩ t₂ :=
filter_congr' (λ a _, p.mem_iff)
-- @[congr]
theorem perm.inter {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∩ t₁ ~ l₂ ∩ t₂ :=
p₂.inter_left l₂ ▸ p₁.inter_right t₁
theorem perm.inter_append {l t₁ t₂ : list α} (h : disjoint t₁ t₂) :
l ∩ (t₁ ++ t₂) ~ l ∩ t₁ ++ l ∩ t₂ :=
begin
induction l,
case list.nil
{ simp },
case list.cons : x xs l_ih
{ by_cases h₁ : x ∈ t₁,
{ have h₂ : x ∉ t₂ := h h₁,
simp * },
by_cases h₂ : x ∈ t₂,
{ simp only [*, inter_cons_of_not_mem, false_or, mem_append, inter_cons_of_mem, not_false_iff],
transitivity,
{ apply perm.cons _ l_ih, },
change [x] ++ xs ∩ t₁ ++ xs ∩ t₂ ~ xs ∩ t₁ ++ ([x] ++ xs ∩ t₂),
rw [← list.append_assoc],
solve_by_elim [perm.append_right, perm_append_comm] },
{ simp * } },
end
end
theorem perm.pairwise_iff {R : α → α → Prop} (S : symmetric R) :
∀ {l₁ l₂ : list α} (p : l₁ ~ l₂), pairwise R l₁ ↔ pairwise R l₂ :=
suffices ∀ {l₁ l₂}, l₁ ~ l₂ → pairwise R l₁ → pairwise R l₂, from λ l₁ l₂ p, ⟨this p, this p.symm⟩,
λ l₁ l₂ p d, begin
induction d with a l₁ h d IH generalizing l₂,
{ rw ← p.nil_eq, constructor },
{ have : a ∈ l₂ := p.subset (mem_cons_self _ _),
rcases mem_split this with ⟨s₂, t₂, rfl⟩,
have p' := (p.trans perm_middle).cons_inv,
refine (pairwise_middle S).2 (pairwise_cons.2 ⟨λ b m, _, IH _ p'⟩),
exact h _ (p'.symm.subset m) }
end
lemma pairwise.perm {R : α → α → Prop} {l l' : list α} (hR : l.pairwise R)
(hl : l ~ l') (hsymm : symmetric R) : l'.pairwise R :=
(hl.pairwise_iff hsymm).mp hR
lemma perm.pairwise {R : α → α → Prop} {l l' : list α}
(hl : l ~ l') (hR : l.pairwise R) (hsymm : symmetric R) : l'.pairwise R :=
hR.perm hl hsymm
theorem perm.nodup_iff {l₁ l₂ : list α} : l₁ ~ l₂ → (nodup l₁ ↔ nodup l₂) :=
perm.pairwise_iff $ @ne.symm α
theorem perm.join {l₁ l₂ : list (list α)} (h : l₁ ~ l₂) : l₁.join ~ l₂.join :=
perm.rec_on h
(perm.refl _)
(λ x xs₁ xs₂ hxs ih, ih.append_left x)
(λ x₁ x₂ xs, by simpa only [join, append_assoc] using perm_append_comm.append_right _)
(λ xs₁ xs₂ xs₃ h₁₂ h₂₃, perm.trans)
theorem perm.bind_right {l₁ l₂ : list α} (f : α → list β) (p : l₁ ~ l₂) :
l₁.bind f ~ l₂.bind f :=
(p.map _).join
lemma perm.join_congr :
∀ {l₁ l₂ : list (list α)} (h : list.forall₂ (~) l₁ l₂), l₁.join ~ l₂.join
| _ _ forall₂.nil := perm.refl _
| (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := h₁.append (perm.join_congr h₂)
theorem perm.bind_left (l : list α) {f g : α → list β} (h : ∀ a ∈ l, f a ~ g a) :
l.bind f ~ l.bind g :=
perm.join_congr $
by rwa [list.forall₂_map_right_iff,list.forall₂_map_left_iff, list.forall₂_same]
theorem bind_append_perm (l : list α) (f g : α → list β) :
l.bind f ++ l.bind g ~ l.bind (λ x, f x ++ g x) :=
begin
induction l with a l IH; simp,
refine (perm.trans _ (IH.append_left _)).append_left _,
rw [← append_assoc, ← append_assoc],
exact perm_append_comm.append_right _
end
theorem map_append_bind_perm (l : list α) (f : α → β) (g : α → list β) :
l.map f ++ l.bind g ~ l.bind (λ x, f x :: g x) :=
by simpa [←map_eq_bind] using bind_append_perm l (λ x, [f x]) g
theorem perm.product_right {l₁ l₂ : list α} (t₁ : list β) (p : l₁ ~ l₂) :
product l₁ t₁ ~ product l₂ t₁ :=
p.bind_right _
theorem perm.product_left (l : list α) {t₁ t₂ : list β} (p : t₁ ~ t₂) :
product l t₁ ~ product l t₂ :=
perm.bind_left _ $ λ a ha, p.map _
@[congr] theorem perm.product {l₁ l₂ : list α} {t₁ t₂ : list β}
(p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : product l₁ t₁ ~ product l₂ t₂ :=
(p₁.product_right t₁).trans (p₂.product_left l₂)
theorem perm_lookmap (f : α → option α) {l₁ l₂ : list α}
(H : pairwise (λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d) l₁)
(p : l₁ ~ l₂) : lookmap f l₁ ~ lookmap f l₂ :=
begin
let F := λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d,
change pairwise F l₁ at H,
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ cases h : f a,
{ simp [h], exact IH (pairwise_cons.1 H).2 },
{ simp [lookmap_cons_some _ _ h, p] } },
{ cases h₁ : f a with c; cases h₂ : f b with d,
{ simp [h₁, h₂], apply swap },
{ simp [h₁, lookmap_cons_some _ _ h₂], apply swap },
{ simp [lookmap_cons_some _ _ h₁, h₂], apply swap },
{ simp [lookmap_cons_some _ _ h₁, lookmap_cons_some _ _ h₂],
rcases (pairwise_cons.1 H).1 _ (or.inl rfl) _ h₂ _ h₁ with ⟨rfl, rfl⟩,
refl } },
{ refine (IH₁ H).trans (IH₂ ((p₁.pairwise_iff _).1 H)),
exact λ a b h c h₁ d h₂, (h d h₂ c h₁).imp eq.symm eq.symm }
end
theorem perm.erasep (f : α → Prop) [decidable_pred f] {l₁ l₂ : list α}
(H : pairwise (λ a b, f a → f b → false) l₁)
(p : l₁ ~ l₂) : erasep f l₁ ~ erasep f l₂ :=
begin
let F := λ a b, f a → f b → false,
change pairwise F l₁ at H,
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ by_cases h : f a,
{ simp [h, p] },
{ simp [h], exact IH (pairwise_cons.1 H).2 } },
{ by_cases h₁ : f a; by_cases h₂ : f b; simp [h₁, h₂],
{ cases (pairwise_cons.1 H).1 _ (or.inl rfl) h₂ h₁ },
{ apply swap } },
{ refine (IH₁ H).trans (IH₂ ((p₁.pairwise_iff _).1 H)),
exact λ a b h h₁ h₂, h h₂ h₁ }
end
lemma perm.take_inter {α} [decidable_eq α] {xs ys : list α} (n : ℕ)
(h : xs ~ ys) (h' : ys.nodup) :
xs.take n ~ ys.inter (xs.take n) :=
begin
simp only [list.inter] at *,
induction h generalizing n,
case list.perm.nil : n
{ simp only [not_mem_nil, filter_false, take_nil] },
case list.perm.cons : h_x h_l₁ h_l₂ h_a h_ih n
{ cases n; simp only [mem_cons_iff, true_or, eq_self_iff_true, filter_cons_of_pos,
perm_cons, take, not_mem_nil, filter_false],
cases h' with _ _ h₁ h₂,
convert h_ih h₂ n using 1,
apply filter_congr',
introv h, simp only [(h₁ x h).symm, false_or], },
case list.perm.swap : h_x h_y h_l n
{ cases h' with _ _ h₁ h₂,
cases h₂ with _ _ h₂ h₃,
have := h₁ _ (or.inl rfl),
cases n; simp only [mem_cons_iff, not_mem_nil, filter_false, take],
cases n; simp only [mem_cons_iff, false_or, true_or, filter, *, nat.nat_zero_eq_zero, if_true,
not_mem_nil, eq_self_iff_true, or_false, if_false, perm_cons, take],
{ rw filter_eq_nil.2, intros, solve_by_elim [ne.symm], },
{ convert perm.swap _ _ _, rw @filter_congr' _ _ (∈ take n h_l),
{ clear h₁, induction n generalizing h_l, { simp },
cases h_l; simp only [mem_cons_iff, true_or, eq_self_iff_true, filter_cons_of_pos,
true_and, take, not_mem_nil, filter_false, take_nil],
cases h₃ with _ _ h₃ h₄,
rwa [@filter_congr' _ _ (∈ take n_n h_l_tl), n_ih],
{ introv h, apply h₂ _ (or.inr h), },
{ introv h, simp only [(h₃ x h).symm, false_or], }, },
{ introv h, simp only [(h₂ x h).symm, (h₁ x (or.inr h)).symm, false_or], } } },
case list.perm.trans : h_l₁ h_l₂ h_l₃ h₀ h₁ h_ih₀ h_ih₁ n
{ transitivity,
{ apply h_ih₀, rwa h₁.nodup_iff },
{ apply perm.filter _ h₁, } },
end
lemma perm.drop_inter {α} [decidable_eq α] {xs ys : list α} (n : ℕ)
(h : xs ~ ys) (h' : ys.nodup) :
xs.drop n ~ ys.inter (xs.drop n) :=
begin
by_cases h'' : n ≤ xs.length,
{ let n' := xs.length - n,
have h₀ : n = xs.length - n',
{ dsimp [n'], rwa tsub_tsub_cancel_of_le, } ,
have h₁ : n' ≤ xs.length,
{ apply tsub_le_self },
have h₂ : xs.drop n = (xs.reverse.take n').reverse,
{ rw [reverse_take _ h₁, h₀, reverse_reverse], },
rw [h₂],
apply (reverse_perm _).trans,
rw inter_reverse,
apply perm.take_inter _ _ h',
apply (reverse_perm _).trans; assumption, },
{ have : drop n xs = [],
{ apply eq_nil_of_length_eq_zero,
rw [length_drop, tsub_eq_zero_iff_le],
apply le_of_not_ge h'' },
simp [this, list.inter], }
end
lemma perm.slice_inter {α} [decidable_eq α] {xs ys : list α} (n m : ℕ)
(h : xs ~ ys) (h' : ys.nodup) :
list.slice n m xs ~ ys ∩ (list.slice n m xs) :=
begin
simp only [slice_eq],
have : n ≤ n + m := nat.le_add_right _ _,
have := h.nodup_iff.2 h',
apply perm.trans _ (perm.inter_append _).symm;
solve_by_elim [perm.append, perm.drop_inter, perm.take_inter, disjoint_take_drop, h, h']
{ max_depth := 7 },
end
/- enumerating permutations -/
section permutations
theorem perm_of_mem_permutations_aux :
∀ {ts is l : list α}, l ∈ permutations_aux ts is → l ~ ts ++ is :=
begin
refine permutations_aux.rec (by simp) _,
introv IH1 IH2 m,
rw [permutations_aux_cons, permutations, mem_foldr_permutations_aux2] at m,
rcases m with m | ⟨l₁, l₂, m, _, e⟩,
{ exact (IH1 m).trans perm_middle },
{ subst e,
have p : l₁ ++ l₂ ~ is,
{ simp [permutations] at m,
cases m with e m, {simp [e]},
exact is.append_nil ▸ IH2 m },
exact ((perm_middle.trans (p.cons _)).append_right _).trans (perm_append_comm.cons _) }
end
theorem perm_of_mem_permutations {l₁ l₂ : list α}
(h : l₁ ∈ permutations l₂) : l₁ ~ l₂ :=
(eq_or_mem_of_mem_cons h).elim (λ e, e ▸ perm.refl _)
(λ m, append_nil l₂ ▸ perm_of_mem_permutations_aux m)
theorem length_permutations_aux : ∀ ts is : list α,
length (permutations_aux ts is) + is.length! = (length ts + length is)! :=
begin
refine permutations_aux.rec (by simp) _,
intros t ts is IH1 IH2,
have IH2 : length (permutations_aux is nil) + 1 = is.length!,
{ simpa using IH2 },
simp [-add_comm, nat.factorial, nat.add_succ, mul_comm] at IH1,
rw [permutations_aux_cons,
length_foldr_permutations_aux2' _ _ _ _ _
(λ l m, (perm_of_mem_permutations m).length_eq),
permutations, length, length, IH2,
nat.succ_add, nat.factorial_succ, mul_comm (nat.succ _), ← IH1,
add_comm (_*_), add_assoc, nat.mul_succ, mul_comm]
end
theorem length_permutations (l : list α) : length (permutations l) = (length l)! :=
length_permutations_aux l []
theorem mem_permutations_of_perm_lemma {is l : list α}
(H : l ~ [] ++ is → (∃ ts' ~ [], l = ts' ++ is) ∨ l ∈ permutations_aux is [])
: l ~ is → l ∈ permutations is :=
by simpa [permutations, perm_nil] using H
theorem mem_permutations_aux_of_perm :
∀ {ts is l : list α}, l ~ is ++ ts → (∃ is' ~ is, l = is' ++ ts) ∨ l ∈ permutations_aux ts is :=
begin
refine permutations_aux.rec (by simp) _,
intros t ts is IH1 IH2 l p,
rw [permutations_aux_cons, mem_foldr_permutations_aux2],
rcases IH1 (p.trans perm_middle) with ⟨is', p', e⟩ | m,
{ clear p, subst e,
rcases mem_split (p'.symm.subset (mem_cons_self _ _)) with ⟨l₁, l₂, e⟩,
subst is',
have p := (perm_middle.symm.trans p').cons_inv,
cases l₂ with a l₂',
{ exact or.inl ⟨l₁, by simpa using p⟩ },
{ exact or.inr (or.inr ⟨l₁, a::l₂',
mem_permutations_of_perm_lemma IH2 p, by simp⟩) } },
{ exact or.inr (or.inl m) }
end
@[simp] theorem mem_permutations {s t : list α} : s ∈ permutations t ↔ s ~ t :=
⟨perm_of_mem_permutations, mem_permutations_of_perm_lemma mem_permutations_aux_of_perm⟩
theorem perm_permutations'_aux_comm (a b : α) (l : list α) :
(permutations'_aux a l).bind (permutations'_aux b) ~
(permutations'_aux b l).bind (permutations'_aux a) :=
begin
induction l with c l ih, {simp [swap]},
simp [permutations'_aux], apply perm.swap',
have : ∀ a b,
(map (cons c) (permutations'_aux a l)).bind (permutations'_aux b) ~
map (cons b ∘ cons c) (permutations'_aux a l) ++
map (cons c) ((permutations'_aux a l).bind (permutations'_aux b)),
{ intros,
simp only [map_bind, permutations'_aux],
refine (bind_append_perm _ (λ x, [_]) _).symm.trans _,
rw [← map_eq_bind, ← bind_map] },
refine (((this _ _).append_left _).trans _).trans ((this _ _).append_left _).symm,
rw [← append_assoc, ← append_assoc],
exact perm_append_comm.append (ih.map _),
end
theorem perm.permutations' {s t : list α} (p : s ~ t) :
permutations' s ~ permutations' t :=
begin
induction p with a s t p IH a b l s t u p₁ p₂ IH₁ IH₂, {simp},
{ simp only [permutations'], exact IH.bind_right _ },
{ simp only [permutations'],
rw [bind_assoc, bind_assoc],
apply perm.bind_left,
intros l' hl',
apply perm_permutations'_aux_comm },
{ exact IH₁.trans IH₂ }
end
theorem permutations_perm_permutations' (ts : list α) : ts.permutations ~ ts.permutations' :=
begin
obtain ⟨n, h⟩ : ∃ n, length ts < n := ⟨_, nat.lt_succ_self _⟩,
induction n with n IH generalizing ts, {cases h},
refine list.reverse_rec_on ts (λ h, _) (λ ts t _ h, _) h, {simp [permutations]},
rw [← concat_eq_append, length_concat, nat.succ_lt_succ_iff] at h,
have IH₂ := (IH ts.reverse (by rwa [length_reverse])).trans (reverse_perm _).permutations',
simp only [permutations_append, foldr_permutations_aux2,
permutations_aux_nil, permutations_aux_cons, append_nil],
refine (perm_append_comm.trans ((IH₂.bind_right _).append ((IH _ h).map _))).trans
(perm.trans _ perm_append_comm.permutations'),
rw [map_eq_bind, singleton_append, permutations'],
convert bind_append_perm _ _ _, funext ys,
rw [permutations'_aux_eq_permutations_aux2, permutations_aux2_append]
end
@[simp] theorem mem_permutations' {s t : list α} : s ∈ permutations' t ↔ s ~ t :=
(permutations_perm_permutations' _).symm.mem_iff.trans mem_permutations
theorem perm.permutations {s t : list α} (h : s ~ t) : permutations s ~ permutations t :=
(permutations_perm_permutations' _).trans $ h.permutations'.trans
(permutations_perm_permutations' _).symm
@[simp] theorem perm_permutations_iff {s t : list α} : permutations s ~ permutations t ↔ s ~ t :=
⟨λ h, mem_permutations.1 $ h.mem_iff.1 $ mem_permutations.2 (perm.refl _), perm.permutations⟩
@[simp] theorem perm_permutations'_iff {s t : list α} : permutations' s ~ permutations' t ↔ s ~ t :=
⟨λ h, mem_permutations'.1 $ h.mem_iff.1 $ mem_permutations'.2 (perm.refl _), perm.permutations'⟩
lemma nth_le_permutations'_aux (s : list α) (x : α) (n : ℕ)
(hn : n < length (permutations'_aux x s)) :
(permutations'_aux x s).nth_le n hn = s.insert_nth n x :=
begin
induction s with y s IH generalizing n,
{ simp only [length, permutations'_aux, nat.lt_one_iff] at hn,
simp [hn] },
{ cases n,
{ simp },
{ simpa using IH _ _ } }
end
lemma count_permutations'_aux_self [decidable_eq α] (l : list α) (x : α) :
count (x :: l) (permutations'_aux x l) = length (take_while ((=) x) l) + 1 :=
begin
induction l with y l IH generalizing x,
{ simp [take_while], },
{ rw [permutations'_aux, count_cons_self],
by_cases hx : x = y,
{ subst hx,
simpa [take_while, nat.succ_inj'] using IH _ },
{ rw take_while,
rw if_neg hx,
cases permutations'_aux x l with a as,
{ simp },
{ rw [count_eq_zero_of_not_mem, length, zero_add],
simp [hx, ne.symm hx] } } }
end
@[simp] lemma length_permutations'_aux (s : list α) (x : α) :
length (permutations'_aux x s) = length s + 1 :=
begin
induction s with y s IH,
{ simp },
{ simpa using IH }
end
@[simp] lemma permutations'_aux_nth_le_zero (s : list α) (x : α)
(hn : 0 < length (permutations'_aux x s) := by simp) :
(permutations'_aux x s).nth_le 0 hn = x :: s :=
nth_le_permutations'_aux _ _ _ _
lemma injective_permutations'_aux (x : α) : function.injective (permutations'_aux x) :=
begin
intros s t h,
apply insert_nth_injective s.length x,
have hl : s.length = t.length := by simpa using congr_arg length h,
rw [←nth_le_permutations'_aux s x s.length (by simp),
←nth_le_permutations'_aux t x s.length (by simp [hl])],
simp [h, hl]
end
lemma nodup_permutations'_aux_of_not_mem (s : list α) (x : α) (hx : x ∉ s) :
nodup (permutations'_aux x s) :=
begin
induction s with y s IH,
{ simp },
{ simp only [not_or_distrib, mem_cons_iff] at hx,
simp only [not_and, exists_eq_right_right, mem_map, permutations'_aux, nodup_cons],
refine ⟨λ _, ne.symm hx.left, _⟩,
rw nodup_map_iff,
{ exact IH hx.right },
{ simp } }
end
lemma nodup_permutations'_aux_iff {s : list α} {x : α} :
nodup (permutations'_aux x s) ↔ x ∉ s :=
begin
refine ⟨λ h, _, nodup_permutations'_aux_of_not_mem _ _⟩,
intro H,
obtain ⟨k, hk, hk'⟩ := nth_le_of_mem H,
rw nodup_iff_nth_le_inj at h,
suffices : k = k + 1,
{ simpa using this },
refine h k (k + 1) _ _ _,
{ simpa [nat.lt_succ_iff] using hk.le },
{ simpa using hk },
rw [nth_le_permutations'_aux, nth_le_permutations'_aux],
have hl : length (insert_nth k x s) = length (insert_nth (k + 1) x s),
{ rw [length_insert_nth _ _ hk.le, length_insert_nth _ _ (nat.succ_le_of_lt hk)] },
refine ext_le hl (λ n hn hn', _),
rcases lt_trichotomy n k with H|rfl|H,
{ rw [nth_le_insert_nth_of_lt _ _ _ _ H (H.trans hk),
nth_le_insert_nth_of_lt _ _ _ _ (H.trans (nat.lt_succ_self _))] },
{ rw [nth_le_insert_nth_self _ _ _ hk.le,
nth_le_insert_nth_of_lt _ _ _ _ (nat.lt_succ_self _) hk, hk'] },
{ rcases (nat.succ_le_of_lt H).eq_or_lt with rfl|H',
{ rw [nth_le_insert_nth_self _ _ _ (nat.succ_le_of_lt hk)],
convert hk' using 1,
convert nth_le_insert_nth_add_succ _ _ _ 0 _,
simpa using hk },
{ obtain ⟨m, rfl⟩ := nat.exists_eq_add_of_lt H',
rw [length_insert_nth _ _ hk.le, nat.succ_lt_succ_iff, nat.succ_add] at hn,
rw nth_le_insert_nth_add_succ,
convert nth_le_insert_nth_add_succ s x k m.succ _ using 2,
{ simp [nat.add_succ, nat.succ_add] },
{ simp [add_left_comm, add_comm] },
{ simpa [nat.add_succ] using hn },
{ simpa [nat.succ_add] using hn } } }
end
lemma nodup_permutations (s : list α) (hs : nodup s) :
nodup s.permutations :=
begin
rw (permutations_perm_permutations' s).nodup_iff,
induction hs with x l h h' IH,
{ simp },
{ rw [permutations'],
rw nodup_bind,
split,
{ intros ys hy,
rw mem_permutations' at hy,
rw [nodup_permutations'_aux_iff, hy.mem_iff],
exact λ H, h x H rfl },
{ refine IH.pairwise_of_forall_ne (λ as ha bs hb H, _),
rw disjoint_iff_ne,
rintro a ha' b hb' rfl,
obtain ⟨n, hn, hn'⟩ := nth_le_of_mem ha',
obtain ⟨m, hm, hm'⟩ := nth_le_of_mem hb',
rw mem_permutations' at ha hb,
have hl : as.length = bs.length := (ha.trans hb.symm).length_eq,
simp only [nat.lt_succ_iff, length_permutations'_aux] at hn hm,
rw nth_le_permutations'_aux at hn' hm',
have hx : nth_le (insert_nth n x as) m
(by rwa [length_insert_nth _ _ hn, nat.lt_succ_iff, hl]) = x,
{ simp [hn', ←hm', hm] },
have hx' : nth_le (insert_nth m x bs) n
(by rwa [length_insert_nth _ _ hm, nat.lt_succ_iff, ←hl]) = x,
{ simp [hm', ←hn', hn] },
rcases lt_trichotomy n m with ht|ht|ht,
{ suffices : x ∈ bs,
{ exact h x (hb.subset this) rfl },
rw [←hx', nth_le_insert_nth_of_lt _ _ _ _ ht (ht.trans_le hm)],
exact nth_le_mem _ _ _ },
{ simp only [ht] at hm' hn',
rw ←hm' at hn',
exact H (insert_nth_injective _ _ hn') },
{ suffices : x ∈ as,
{ exact h x (ha.subset this) rfl },
rw [←hx, nth_le_insert_nth_of_lt _ _ _ _ ht (ht.trans_le hn)],
exact nth_le_mem _ _ _ } } }
end
-- TODO: `nodup s.permutations ↔ nodup s`
-- TODO: `count s s.permutations = (zip_with count s s.tails).prod`
end permutations
end list
|
6cf867efe6b37b93061430b0db9a6711242486f7 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/analysis/complex/liouville.lean | 133d8fa3ea95b294d7ec38f1b4692a3f58069a2a | [
"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 | 5,722 | lean | /-
Copyright (c) 2022 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import analysis.complex.cauchy_integral
import analysis.calculus.fderiv_analytic
import analysis.normed_space.completion
/-!
# Liouville's theorem
In this file we prove Liouville's theorem: if `f : E → F` is complex differentiable on the whole
space and its range is bounded, then the function is a constant. Various versions of this theorem
are formalized in `differentiable.apply_eq_apply_of_bounded`,
`differentiable.exists_const_forall_eq_of_bounded`, and
`differentiable.exists_eq_const_of_bounded`.
The proof is based on the Cauchy integral formula for the derivative of an analytic function, see
`complex.deriv_eq_smul_circle_integral`.
-/
open topological_space metric set filter asymptotics function measure_theory
open_locale topological_space filter nnreal real
universes u v
variables {E : Type u} [normed_add_comm_group E] [normed_space ℂ E]
{F : Type v} [normed_add_comm_group F] [normed_space ℂ F]
local postfix `̂`:100 := uniform_space.completion
namespace complex
/-- If `f` is complex differentiable on an open disc with center `c` and radius `R > 0` and is
continuous on its closure, then `f' c` can be represented as an integral over the corresponding
circle.
TODO: add a version for `w ∈ metric.ball c R`.
TODO: add a version for higher derivatives. -/
lemma deriv_eq_smul_circle_integral [complete_space F] {R : ℝ} {c : ℂ} {f : ℂ → F} (hR : 0 < R)
(hf : diff_cont_on_cl ℂ f (ball c R)) :
deriv f c = (2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - c) ^ (-2 : ℤ) • f z :=
begin
lift R to ℝ≥0 using hR.le,
refine (hf.has_fpower_series_on_ball hR).has_fpower_series_at.deriv.trans _,
simp only [cauchy_power_series_apply, one_div, zpow_neg, pow_one, smul_smul, zpow_two, mul_inv]
end
lemma norm_deriv_le_aux [complete_space F] {c : ℂ} {R C : ℝ} {f : ℂ → F} (hR : 0 < R)
(hf : diff_cont_on_cl ℂ f (ball c R)) (hC : ∀ z ∈ sphere c R, ∥f z∥ ≤ C) :
∥deriv f c∥ ≤ C / R :=
begin
have : ∀ z ∈ sphere c R, ∥(z - c) ^ (-2 : ℤ) • f z∥ ≤ C / (R * R),
from λ z (hz : abs (z - c) = R), by simpa [-mul_inv_rev, norm_smul, hz, zpow_two,
←div_eq_inv_mul] using (div_le_div_right (mul_pos hR hR)).2 (hC z hz),
calc ∥deriv f c∥ = ∥(2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - c) ^ (-2 : ℤ) • f z∥ :
congr_arg norm (deriv_eq_smul_circle_integral hR hf)
... ≤ R * (C / (R * R)) :
circle_integral.norm_two_pi_I_inv_smul_integral_le_of_norm_le_const hR.le this
... = C / R : by rw [mul_div_left_comm, div_self_mul_self', div_eq_mul_inv]
end
/-- If `f` is complex differentiable on an open disc of radius `R > 0`, is continuous on its
closure, and its values on the boundary circle of this disc are bounded from above by `C`, then the
norm of its derivative at the center is at most `C / R`. -/
lemma norm_deriv_le_of_forall_mem_sphere_norm_le {c : ℂ} {R C : ℝ} {f : ℂ → F} (hR : 0 < R)
(hd : diff_cont_on_cl ℂ f (ball c R)) (hC : ∀ z ∈ sphere c R, ∥f z∥ ≤ C) :
∥deriv f c∥ ≤ C / R :=
begin
set e : F →L[ℂ] F̂ := uniform_space.completion.to_complL,
have : has_deriv_at (e ∘ f) (e (deriv f c)) c,
from e.has_fderiv_at.comp_has_deriv_at c
(hd.differentiable_at is_open_ball $ mem_ball_self hR).has_deriv_at,
calc ∥deriv f c∥ = ∥deriv (e ∘ f) c∥ :
by { rw this.deriv, exact (uniform_space.completion.norm_coe _).symm }
... ≤ C / R :
norm_deriv_le_aux hR (e.differentiable.comp_diff_cont_on_cl hd)
(λ z hz, (uniform_space.completion.norm_coe _).trans_le (hC z hz))
end
/-- An auxiliary lemma for Liouville's theorem `differentiable.apply_eq_apply_of_bounded`. -/
lemma liouville_theorem_aux {f : ℂ → F} (hf : differentiable ℂ f)
(hb : bounded (range f)) (z w : ℂ) : f z = f w :=
begin
suffices : ∀ c, deriv f c = 0, from is_const_of_deriv_eq_zero hf this z w,
clear z w, intro c,
obtain ⟨C, C₀, hC⟩ : ∃ C > (0 : ℝ), ∀ z, ∥f z∥ ≤ C,
{ rcases bounded_iff_forall_norm_le.1 hb with ⟨C, hC⟩,
exact ⟨max C 1, lt_max_iff.2 (or.inr zero_lt_one),
λ z, (hC (f z) (mem_range_self _)).trans (le_max_left _ _)⟩ },
refine norm_le_zero_iff.1 (le_of_forall_le_of_dense $ λ ε ε₀, _),
calc ∥deriv f c∥ ≤ C / (C / ε) :
norm_deriv_le_of_forall_mem_sphere_norm_le (div_pos C₀ ε₀) hf.diff_cont_on_cl (λ z _, hC z)
... = ε : div_div_cancel' C₀.lt.ne'
end
end complex
namespace differentiable
open complex
/-- **Liouville's theorem**: a complex differentiable bounded function `f : E → F` is a constant. -/
lemma apply_eq_apply_of_bounded {f : E → F} (hf : differentiable ℂ f) (hb : bounded (range f))
(z w : E) : f z = f w :=
begin
set g : ℂ → F := f ∘ (λ t : ℂ, t • (w - z) + z),
suffices : g 0 = g 1, by simpa [g],
apply liouville_theorem_aux,
exacts [hf.comp ((differentiable_id.smul_const (w - z)).add_const z),
hb.mono (range_comp_subset_range _ _)]
end
/-- **Liouville's theorem**: a complex differentiable bounded function is a constant. -/
lemma exists_const_forall_eq_of_bounded {f : E → F} (hf : differentiable ℂ f)
(hb : bounded (range f)) : ∃ c, ∀ z, f z = c :=
⟨f 0, λ z, hf.apply_eq_apply_of_bounded hb _ _⟩
/-- **Liouville's theorem**: a complex differentiable bounded function is a constant. -/
lemma exists_eq_const_of_bounded {f : E → F} (hf : differentiable ℂ f)
(hb : bounded (range f)) : ∃ c, f = const E c :=
(hf.exists_const_forall_eq_of_bounded hb).imp $ λ c, funext
end differentiable
|
1a5c36f293bb305ef315f808560c03f0b0a49344 | 8cb37a089cdb4af3af9d8bf1002b417e407a8e9e | /library/init/control/monad.lean | ced07732bc540ed18d0d0fd7967e971cc1b79a3e | [
"Apache-2.0"
] | permissive | kbuzzard/lean | ae3c3db4bb462d750dbf7419b28bafb3ec983ef7 | ed1788fd674bb8991acffc8fca585ec746711928 | refs/heads/master | 1,620,983,366,617 | 1,618,937,600,000 | 1,618,937,600,000 | 359,886,396 | 1 | 0 | Apache-2.0 | 1,618,936,987,000 | 1,618,936,987,000 | null | UTF-8 | Lean | false | false | 1,051 | lean | /-
Copyright (c) Luke Nelson and Jared Roesch. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Luke Nelson, Jared Roesch, Sebastian Ullrich
-/
prelude
import init.control.applicative
universes u v
open function
class has_bind (m : Type u → Type v) :=
(bind : Π {α β : Type u}, m α → (α → m β) → m β)
export has_bind (bind)
@[inline] def has_bind.and_then {α β : Type u} {m : Type u → Type v} [has_bind m] (x : m α) (y : m β) : m β :=
do x, y
infixl ` >>= `:55 := bind
infixl ` >> `:55 := has_bind.and_then
class monad (m : Type u → Type v) extends applicative m, has_bind m : Type (max (u+1) v) :=
(map := λ α β f x, x >>= pure ∘ f)
(seq := λ α β f x, f >>= (<$> x))
@[reducible, inline] def return {m : Type u → Type v} [monad m] {α : Type u} : α → m α :=
pure
/- Identical to has_bind.and_then, but it is not inlined. -/
def has_bind.seq {α β : Type u} {m : Type u → Type v} [has_bind m] (x : m α) (y : m β) : m β :=
do x, y
|
097eac2dbe67f286a5ebbf28ede497fb7bb35de2 | d7189ea2ef694124821b033e533f18905b5e87ef | /galois/rat.lean | 0b0ec6535bc1f58d11e9ad231885b28d6c5681d9 | [
"Apache-2.0"
] | permissive | digama0/lean-protocol-support | eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59 | cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda | refs/heads/master | 1,625,421,450,627 | 1,506,035,462,000 | 1,506,035,462,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 444 | lean | import data.rat
import galois.nat.div_lemmas
namespace rat
def of_nat.f (n : ℕ) (rec : Π(m:ℕ), m < n → ℚ) : ℚ :=
if pr : n > 0 then
let pr2 : 1 < 2 := dec_trivial in
if n = 1 then
1
else if (n % 2) = 0 then
bit0 (rec (n / 2) (nat.div_lt_self pr pr2))
else
bit1 (rec (n / 2) (nat.div_lt_self pr pr2))
else
0
def of_nat (n : ℕ) : ℚ := @nat.strong_rec_on (λx, ℚ) n @of_nat.f
end rat
|
d74acfeea90487ca2f4fbe4ef980f56b5dacc661 | bf532e3e865883a676110e756f800e0ddeb465be | /number_theory/dioph.lean | c3e509d98a6a01740dda7d9633730082aa5f3635 | [
"Apache-2.0"
] | permissive | aqjune/mathlib | da42a97d9e6670d2efaa7d2aa53ed3585dafc289 | f7977ff5a6bcf7e5c54eec908364ceb40dafc795 | refs/heads/master | 1,631,213,225,595 | 1,521,089,840,000 | 1,521,089,840,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 36,080 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import number_theory.pell data.set data.pfun
universe u
open nat function
namespace int
lemma eq_nat_abs_iff_mul (x n) : nat_abs x = n ↔ (x - n) * (x + n) = 0 :=
begin
refine iff.trans _ mul_eq_zero.symm,
refine iff.trans _ (or_congr sub_eq_zero add_eq_zero_iff_eq_neg).symm,
exact ⟨λe, by rw ← e; apply nat_abs_eq,
λo, by cases o; subst x; simp [nat_abs_of_nat]⟩
end
end int
/-- An alternate definition of `fin n` defined as an inductive type
instead of a subtype of `nat`. This is useful for its induction
principle and different definitional equalities. -/
inductive fin2 : ℕ → Type
| fz {n} : fin2 (succ n)
| fs {n} : fin2 n → fin2 (succ n)
namespace fin2
@[elab_as_eliminator]
protected def cases' {n} {C : fin2 (succ n) → Sort u} (H1 : C fz) (H2 : Π n, C (fs n)) :
Π (i : fin2 (succ n)), C i
| fz := H1
| (fs n) := H2 n
def elim0 {C : fin2 0 → Sort u} : Π (i : fin2 0), C i.
/-- convert a `fin2` into a `nat` -/
def to_nat : Π {n}, fin2 n → ℕ
| ._ (@fz n) := 0
| ._ (@fs n i) := succ (to_nat i)
/-- convert a `nat` into a `fin2` if it is in range -/
def opt_of_nat : Π {n} (k : ℕ), option (fin2 n)
| 0 _ := none
| (succ n) 0 := some fz
| (succ n) (succ k) := fs <$> @opt_of_nat n k
/-- `i + k : fin2 (n + k)` when `i : fin2 n` and `k : ℕ` -/
def add {n} (i : fin2 n) : Π k, fin2 (n + k)
| 0 := i
| (succ k) := fs (add k)
/-- `left k` is the embedding `fin2 n → fin2 (k + n)` -/
def left (k) : Π {n}, fin2 n → fin2 (k + n)
| ._ (@fz n) := fz
| ._ (@fs n i) := fs (left i)
/-- `insert_perm a` is a permutation of `fin2 n` with the following properties:
* `insert_perm a i = i+1` if `i < a`
* `insert_perm a a = 0`
* `insert_perm a i = i` if `i > a` -/
def insert_perm : Π {n}, fin2 n → fin2 n → fin2 n
| ._ (@fz n) (@fz ._) := fz
| ._ (@fz n) (@fs ._ j) := fs j
| ._ (@fs (succ n) i) (@fz ._) := fs fz
| ._ (@fs (succ n) i) (@fs ._ j) := match insert_perm i j with fz := fz | fs k := fs (fs k) end
/-- `remap_left f k : fin2 (m + k) → fin2 (n + k)` applies the function
`f : fin2 m → fin2 n` to inputs less than `m`, and leaves the right part
on the right (that is, `remap_left f k (m + i) = n + i`). -/
def remap_left {m n} (f : fin2 m → fin2 n) : Π k, fin2 (m + k) → fin2 (n + k)
| 0 i := f i
| (succ k) (@fz ._) := fz
| (succ k) (@fs ._ i) := fs (remap_left _ i)
/-- This is a simple type class inference prover for proof obligations
of the form `m < n` where `m n : ℕ`. -/
class is_lt (m n : ℕ) := (h : m < n)
instance is_lt.zero (n) : is_lt 0 (succ n) := ⟨succ_pos _⟩
instance is_lt.succ (m n) [l : is_lt m n] : is_lt (succ m) (succ n) := ⟨succ_lt_succ l.h⟩
/-- Use type class inference to infer the boundedness proof, so that we
can directly convert a `nat` into a `fin2 n`. This supports
notation like `&1 : fin 3`. -/
def of_nat' : Π {n} m [is_lt m n], fin2 n
| 0 m ⟨h⟩ := absurd h (not_lt_zero _)
| (succ n) 0 ⟨h⟩ := fz
| (succ n) (succ m) ⟨h⟩ := fs (@of_nat' n m ⟨lt_of_succ_lt_succ h⟩)
local prefix `&`:max := of_nat'
end fin2
open fin2
/-- Alternate definition of `vector` based on `fin2`. -/
def vector3 (α : Type u) (n : ℕ) : Type u := fin2 n → α
namespace vector3
/-- The empty vector -/
@[pattern] def nil {α} : vector3 α 0.
/-- The vector cons operation -/
@[pattern] def cons {α} {n} (a : α) (v : vector3 α n) : vector3 α (succ n) :=
λi, by {refine i.cases' _ _, exact a, exact v}
notation a :: b := cons a b
notation `[` l:(foldr `, ` (h t, cons h t) nil `]`) := l
@[simp] theorem cons_fz {α} {n} (a : α) (v : vector3 α n) : (a :: v) fz = a := rfl
@[simp] theorem cons_fs {α} {n} (a : α) (v : vector3 α n) (i) : (a :: v) (fs i) = v i := rfl
/-- Get the `i`th element of a vector -/
@[reducible] def nth {α} {n} (i : fin2 n) (v : vector3 α n) : α := v i
/-- Construct a vector from a function on `fin2`. -/
@[reducible] def of_fn {α} {n} (f : fin2 n → α) : vector3 α n := f
/-- Get the head of a nonempty vector. -/
def head {α} {n} (v : vector3 α (succ n)) : α := v fz
/-- Get the tail of a nonempty vector. -/
def tail {α} {n} (v : vector3 α (succ n)) : vector3 α n := λi, v (fs i)
theorem eq_nil {α} (v : vector3 α 0) : v = [] :=
funext $ λi, match i with end
theorem cons_head_tail {α} {n} (v : vector3 α (succ n)) : head v :: tail v = v :=
funext $ λi, fin2.cases' rfl (λ_, rfl) i
def nil_elim {α} {C : vector3 α 0 → Sort u} (H : C []) (v : vector3 α 0) : C v :=
by rw eq_nil v; apply H
def cons_elim {α n} {C : vector3 α (succ n) → Sort u} (H : Π (a : α) (t : vector3 α n), C (a :: t))
(v : vector3 α (succ n)) : C v :=
by rw ← (cons_head_tail v); apply H
@[simp] theorem cons_elim_cons {α n C H a t} : @cons_elim α n C H (a :: t) = H a t := rfl
@[elab_as_eliminator]
protected def rec_on {α} {C : Π {n}, vector3 α n → Sort u} {n} (v : vector3 α n)
(H0 : C [])
(Hs : Π {n} (a) (w : vector3 α n), C w → C (a :: w)) : C v :=
nat.rec_on n
(λv, v.nil_elim H0)
(λn IH v, v.cons_elim (λa t, Hs _ _ (IH _))) v
@[simp] theorem rec_on_nil {α C H0 Hs} : @vector3.rec_on α @C 0 [] H0 @Hs = H0 :=
rfl
@[simp] theorem rec_on_cons {α C H0 Hs n a v} :
@vector3.rec_on α @C (succ n) (a :: v) H0 @Hs = Hs a v (@vector3.rec_on α @C n v H0 @Hs) :=
rfl
/-- Append two vectors -/
def append {α} {m} (v : vector3 α m) {n} (w : vector3 α n) : vector3 α (n+m) :=
nat.rec_on m (λ_, w) (λm IH v, v.cons_elim $ λa t, @fin2.cases' (n+m) (λ_, α) a (IH t)) v
infix ` +-+ `:65 := append
@[simp] theorem append_nil {α} {n} (w : vector3 α n) : [] +-+ w = w := rfl
@[simp] theorem append_cons {α} (a : α) {m} (v : vector3 α m) {n} (w : vector3 α n) :
(a::v) +-+ w = a :: (v +-+ w) := rfl
@[simp] theorem append_left {α} : ∀ {m} (i : fin2 m) (v : vector3 α m) {n} (w : vector3 α n),
(v +-+ w) (left n i) = v i
| ._ (@fz m) v n w := v.cons_elim (λa t, by simp [*, left])
| ._ (@fs m i) v n w := v.cons_elim (λa t, by simp [*, left])
@[simp] theorem append_add {α} : ∀ {m} (v : vector3 α m) {n} (w : vector3 α n) (i : fin2 n),
(v +-+ w) (add i m) = w i
| 0 v n w i := rfl
| (succ m) v n w i := v.cons_elim (λa t, by simp [*, add])
/-- Insert `a` into `v` at index `i`. -/
def insert {α} (a : α) {n} (v : vector3 α n) (i : fin2 (succ n)) : vector3 α (succ n) :=
λj, (a :: v) (insert_perm i j)
@[simp] theorem insert_fz {α} (a : α) {n} (v : vector3 α n) : insert a v fz = a :: v :=
by refine funext (λj, j.cases' _ _); intros; refl
@[simp] theorem insert_fs {α} (a : α) {n} (b : α) (v : vector3 α n) (i : fin2 (succ n)) :
insert a (b :: v) (fs i) = b :: insert a v i :=
funext $ λj, by {
refine j.cases' _ (λj, _); simp [insert, insert_perm],
refine fin2.cases' _ _ (insert_perm i j); simp [insert_perm] }
theorem append_insert {α} (a : α) {k} (t : vector3 α k) {n} (v : vector3 α n) (i : fin2 (succ n)) (e : succ n + k = succ (n + k)) :
insert a (t +-+ v) (eq.rec_on e (i.add k)) = eq.rec_on e (t +-+ insert a v i) :=
begin
refine vector3.rec_on t (λe, _) (λk b t IH e, _) e, refl,
have e' := succ_add n k,
change insert a (b :: (t +-+ v)) (eq.rec_on (congr_arg succ e') (fs (add i k)))
= eq.rec_on (congr_arg succ e') (b :: (t +-+ insert a v i)),
rw ← (eq.drec_on e' rfl : fs (eq.rec_on e' (i.add k) : fin2 (succ (n + k))) = eq.rec_on (congr_arg succ e') (fs (i.add k))),
simp, rw IH, exact eq.drec_on e' rfl
end
end vector3
open vector3
/-- "Curried" exists, i.e. ∃ x1 ... xn, f [x1, ..., xn] -/
def vector_ex {α} : Π k, (vector3 α k → Prop) → Prop
| 0 f := f []
| (succ k) f := ∃x : α, vector_ex k (λv, f (x :: v))
/-- "Curried" forall, i.e. ∀ x1 ... xn, f [x1, ..., xn] -/
def vector_all {α} : Π k, (vector3 α k → Prop) → Prop
| 0 f := f []
| (succ k) f := ∀x : α, vector_all k (λv, f (x :: v))
theorem exists_vector_zero {α} (f : vector3 α 0 → Prop) : Exists f ↔ f [] :=
⟨λ⟨v, fv⟩, by rw ← (eq_nil v); exact fv, λf0, ⟨[], f0⟩⟩
theorem exists_vector_succ {α n} (f : vector3 α (succ n) → Prop) : Exists f ↔ ∃x v, f (x :: v) :=
⟨λ⟨v, fv⟩, ⟨_, _, by rw cons_head_tail v; exact fv⟩, λ⟨x, v, fxv⟩, ⟨_, fxv⟩⟩
theorem vector_ex_iff_exists {α} : ∀ {n} (f : vector3 α n → Prop), vector_ex n f ↔ Exists f
| 0 f := (exists_vector_zero f).symm
| (succ n) f := iff.trans (exists_congr (λx, vector_ex_iff_exists _)) (exists_vector_succ f).symm
theorem vector_all_iff_forall {α} : ∀ {n} (f : vector3 α n → Prop), vector_all n f ↔ ∀ v, f v
| 0 f := ⟨λf0 v, v.nil_elim f0, λal, al []⟩
| (succ n) f := (forall_congr (λx, vector_all_iff_forall (λv, f (x :: v)))).trans
⟨λal v, v.cons_elim al, λal x v, al (x::v)⟩
/-- `vector_allp p v` is equivalent to `∀ i, p (v i)`, but unfolds directly to a conjunction,
i.e. `vector_allp p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/
def vector_allp {α} (p : α → Prop) {n} (v : vector3 α n) : Prop :=
vector3.rec_on v true (λn a v IH, @vector3.rec_on _ (λn v, Prop) _ v (p a) (λn b v' _, p a ∧ IH))
@[simp] theorem vector_allp_nil {α} (p : α → Prop) : vector_allp p [] = true := rfl
@[simp] theorem vector_allp_singleton {α} (p : α → Prop) (x : α) : vector_allp p [x] = p x := rfl
@[simp] theorem vector_allp_cons {α} (p : α → Prop) {n} (x : α) (v : vector3 α n) :
vector_allp p (x :: v) ↔ p x ∧ vector_allp p v :=
vector3.rec_on v (and_true _).symm (λn a v IH, iff.rfl)
theorem vector_allp_iff_forall {α} (p : α → Prop) {n} (v : vector3 α n) : vector_allp p v ↔ ∀ i, p (v i) :=
begin refine v.rec_on _ _,
{ exact ⟨λ_, fin2.elim0, λ_, trivial⟩ },
{ simp, refine λn a v IH, (and_congr_right (λ_, IH)).trans
⟨λ⟨pa, h⟩ i, by {refine i.cases' _ _, exacts [pa, h]}, λh, ⟨_, λi, _⟩⟩,
{ have h0 := h fz, simp at h0, exact h0 },
{ have hs := h (fs i), simp at hs, exact hs } }
end
theorem vector_allp.imp {α} {p q : α → Prop} (h : ∀ x, p x → q x)
{n} {v : vector3 α n} (al : vector_allp p v) : vector_allp q v :=
(vector_allp_iff_forall _ _).2 (λi, h _ $ (vector_allp_iff_forall _ _).1 al _)
/-- `list_all p l` is equivalent to `∀ a ∈ l, p a`, but unfolds directly to a conjunction,
i.e. `list_all p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/
@[simp] def list_all {α} (p : α → Prop) : list α → Prop
| [] := true
| (x :: []) := p x
| (x :: l) := p x ∧ list_all l
@[simp] theorem list_all_cons {α} (p : α → Prop) (x : α) : ∀ (l : list α), list_all p (x :: l) ↔ p x ∧ list_all p l
| [] := (and_true _).symm
| (x :: l) := iff.rfl
theorem list_all_iff_forall {α} (p : α → Prop) : ∀ (l : list α), list_all p l ↔ ∀ x ∈ l, p x
| [] := (iff_true_intro $ list.ball_nil _).symm
| (x :: l) := by rw [list.ball_cons, ← list_all_iff_forall l]; simp
theorem list_all.imp {α} {p q : α → Prop} (h : ∀ x, p x → q x) : ∀ {l : list α}, list_all p l → list_all q l
| [] := id
| (x :: l) := by simpa using and.imp (h x) list_all.imp
@[simp] theorem list_all_map {α β} {p : β → Prop} (f : α → β) {l : list α} : list_all p (l.map f) ↔ list_all (p ∘ f) l :=
by induction l; simp *
theorem list_all_congr {α} {p q : α → Prop} (h : ∀ x, p x ↔ q x) {l : list α} : list_all p l ↔ list_all q l :=
⟨list_all.imp (λx, (h x).1), list_all.imp (λx, (h x).2)⟩
instance decidable_list_all {α} (p : α → Prop) [decidable_pred p] (l : list α) : decidable (list_all p l) :=
decidable_of_decidable_of_iff (by apply_instance) (list_all_iff_forall _ _).symm
/- poly -/
/-- A predicate asserting that a function is a multivariate integer polynomial.
(We are being a bit lazy here by allowing many representations for multiplication,
rather than only allowing monomials and addition, but the definition is equivalent
and this is easier to use.) -/
inductive is_poly {α} : ((α → ℕ) → ℤ) → Prop
| proj : ∀ i, is_poly (λx : α → ℕ, x i)
| const : Π (n : ℤ), is_poly (λx : α → ℕ, n)
| sub : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λx, f x - g x)
| mul : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λx, f x * g x)
/-- The type of multivariate integer polynomials -/
def poly (α : Type u) := {f : (α → ℕ) → ℤ // is_poly f}
namespace poly
section
parameter {α : Type u}
instance : has_coe_to_fun (poly α) := ⟨_, λ f, f.1⟩
/-- The underlying function of a `poly` is a polynomial -/
def isp (f : poly α) : is_poly f := f.2
/-- Extensionality for `poly α` -/
def ext {f g : poly α} (e : ∀x, f x = g x) : f = g :=
subtype.eq (funext e)
/-- Construct a `poly` given an extensionally equivalent `poly`. -/
def subst (f : poly α) (g : (α → ℕ) → ℤ) (e : ∀x, f x = g x) : poly α :=
⟨g, by rw ← (funext e : coe_fn f = g); exact f.isp⟩
@[simp] theorem subst_eval (f g e x) : subst f g e x = g x := rfl
/-- The `i`th projection function, `x_i`. -/
def proj (i) : poly α := ⟨_, is_poly.proj i⟩
@[simp] theorem proj_eval (i x) : proj i x = x i := rfl
/-- The constant function with value `n : ℤ`. -/
def const (n) : poly α := ⟨_, is_poly.const n⟩
@[simp] theorem const_eval (n x) : const n x = n := rfl
/-- The zero polynomial -/
def zero : poly α := const 0
instance : has_zero (poly α) := ⟨poly.zero⟩
@[simp] theorem zero_eval (x) : (0 : poly α) x = 0 := rfl
/-- The zero polynomial -/
def one : poly α := const 1
instance : has_one (poly α) := ⟨poly.one⟩
@[simp] theorem one_eval (x) : (1 : poly α) x = 1 := rfl
/-- Subtraction of polynomials -/
def sub : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ :=
⟨_, is_poly.sub pf pg⟩
instance : has_sub (poly α) := ⟨poly.sub⟩
@[simp] theorem sub_eval : Π (f g x), (f - g : poly α) x = f x - g x
| ⟨f, pf⟩ ⟨g, pg⟩ x := rfl
/-- Negation of a polynomial -/
def neg (f : poly α) : poly α := 0 - f
instance : has_neg (poly α) := ⟨poly.neg⟩
@[simp] theorem neg_eval (f x) : (-f : poly α) x = -f x :=
show (0-f) x = _, by simp
/-- Addition of polynomials -/
def add : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ :=
subst (⟨f, pf⟩ - -⟨g, pg⟩) _
(λx, show f x - (0 - g x) = f x + g x, by simp)
instance : has_add (poly α) := ⟨poly.add⟩
@[simp] theorem add_eval : Π (f g x), (f + g : poly α) x = f x + g x
| ⟨f, pf⟩ ⟨g, pg⟩ x := rfl
/-- Multiplication of polynomials -/
def mul : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ :=
⟨_, is_poly.mul pf pg⟩
instance : has_mul (poly α) := ⟨poly.mul⟩
@[simp] theorem mul_eval : Π (f g x), (f * g : poly α) x = f x * g x
| ⟨f, pf⟩ ⟨g, pg⟩ x := rfl
instance : comm_ring (poly α) := by refine
{ add := (+),
zero := 0,
neg := has_neg.neg,
mul := (*),
one := 1, .. }; {intros, exact ext (λx, by simp [mul_add, mul_left_comm, mul_comm])}
def induction {C : poly α → Prop}
(H1 : ∀i, C (proj i)) (H2 : ∀n, C (const n))
(H3 : ∀f g, C f → C g → C (f - g))
(H4 : ∀f g, C f → C g → C (f * g)) (f : poly α) : C f :=
begin
cases f with f pf,
induction pf with i n f g pf pg ihf ihg f g pf pg ihf ihg,
apply H1, apply H2, apply H3 _ _ ihf ihg, apply H4 _ _ ihf ihg
end
/-- The sum of squares of a list of polynomials. This is relevant for
Diophantine equations, because it means that a list of equations
can be encoded as a single equation: `x = 0 ∧ y = 0 ∧ z = 0` is
equivalent to `x^2 + y^2 + z^2 = 0`. -/
def sumsq : list (poly α) → poly α
| [] := 0
| (p::ps) := p*p + sumsq ps
theorem sumsq_nonneg (x) : ∀ l, 0 ≤ sumsq l x
| [] := le_refl 0
| (p::ps) := by rw sumsq; simp [-add_comm];
exact add_nonneg (mul_self_nonneg _) (sumsq_nonneg ps)
theorem sumsq_eq_zero (x) : ∀ l, sumsq l x = 0 ↔ list_all (λa : poly α, a x = 0) l
| [] := eq_self_iff_true _
| (p::ps) := by rw [list_all_cons, ← sumsq_eq_zero ps]; rw sumsq; simp [-add_comm]; exact
⟨λ(h : p x * p x + sumsq ps x = 0),
have p x = 0, from eq_zero_of_mul_self_eq_zero $ le_antisymm
(by rw ← h; have t := add_le_add_left (sumsq_nonneg x ps) (p x * p x); rwa [add_zero] at t)
(mul_self_nonneg _),
⟨this, by simp [this] at h; exact h⟩,
λ⟨h1, h2⟩, by rw [h1, h2]; refl⟩
end
/-- Map the index set of variables, replacing `x_i` with `x_(f i)`. -/
def remap {α β} (f : α → β) (g : poly α) : poly β :=
⟨λv, g $ v ∘ f, g.induction
(λi, by simp; apply is_poly.proj)
(λn, by simp; apply is_poly.const)
(λf g pf pg, by simp; apply is_poly.sub pf pg)
(λf g pf pg, by simp; apply is_poly.mul pf pg)⟩
@[simp] theorem remap_eval {α β} (f : α → β) (g : poly α) (v) : remap f g v = g (v ∘ f) := rfl
end poly
namespace sum
/-- combine two functions into a function on the disjoint union -/
def join {α β γ} (f : α → γ) (g : β → γ) : α ⊕ β → γ :=
by {refine sum.rec _ _, exacts [f, g]}
end sum
local infixr ` ⊗ `:65 := sum.join
open sum
namespace option
/-- Functions from `option` can be combined similarly to `vector.cons` -/
def cons {α β} (a : β) (v : α → β) : option α → β :=
by {refine option.rec _ _, exacts [a, v]}
notation a :: b := cons a b
@[simp] theorem cons_head_tail {α β} (v : option α → β) : v none :: v ∘ some = v :=
funext $ λo, by cases o; refl
end option
/- dioph -/
/-- A set `S ⊆ ℕ^α` is diophantine if there exists a polynomial on
`α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. -/
def dioph {α : Type u} (S : set (α → ℕ)) : Prop :=
∃ {β : Type u} (p : poly (α ⊕ β)), ∀ (v : α → ℕ), S v ↔ ∃t, p (v ⊗ t) = 0
namespace dioph
section
variables {α β γ : Type u}
theorem ext {S S' : set (α → ℕ)} (d : dioph S) (H : ∀v, S v ↔ S' v) : dioph S' :=
eq.rec d $ show S = S', from set.ext H
theorem of_no_dummies (S : set (α → ℕ)) (p : poly α) (h : ∀ (v : α → ℕ), S v ↔ p v = 0) : dioph S :=
⟨ulift empty, p.remap inl, λv, (h v).trans
⟨λh, ⟨λt, empty.rec _ t.down, by simp; rw [
show (v ⊗ λt:ulift empty, empty.rec _ t.down) ∘ inl = v, from rfl, h]⟩,
λ⟨t, ht⟩, by simp at ht; rwa [show (v ⊗ t) ∘ inl = v, from rfl] at ht⟩⟩
lemma inject_dummies_lem (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x)
(p : poly (α ⊕ β)) (v : α → ℕ) : (∃t, p (v ⊗ t) = 0) ↔
(∃t, p.remap (inl ⊗ (inr ∘ f)) (v ⊗ t) = 0) :=
begin
simp, refine ⟨λt, _, λt, _⟩; cases t with t ht,
{ have : (v ⊗ (0 :: t) ∘ g) ∘ (inl ⊗ inr ∘ f) = v ⊗ t :=
funext (λs, by cases s with a b; dsimp [join, (∘)]; try {rw inv}; refl),
exact ⟨(0 :: t) ∘ g, by rwa this⟩ },
{ have : v ⊗ t ∘ f = (v ⊗ t) ∘ (inl ⊗ inr ∘ f) :=
funext (λs, by cases s with a b; refl),
exact ⟨t ∘ f, by rwa this⟩ }
end
theorem inject_dummies {S : set (α → ℕ)} (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x)
(p : poly (α ⊕ β)) (h : ∀ (v : α → ℕ), S v ↔ ∃t, p (v ⊗ t) = 0) :
∃ q : poly (α ⊕ γ), ∀ (v : α → ℕ), S v ↔ ∃t, q (v ⊗ t) = 0 :=
⟨p.remap (inl ⊗ (inr ∘ f)), λv, (h v).trans $ inject_dummies_lem f g inv _ _⟩
theorem reindex_dioph {S : set (α → ℕ)} : Π (d : dioph S) (f : α → β), dioph (λv, S (v ∘ f))
| ⟨γ, p, pe⟩ f := ⟨γ, p.remap ((inl ∘ f) ⊗ inr), λv, (pe _).trans $ exists_congr $ λt,
suffices v ∘ f ⊗ t = (v ⊗ t) ∘ (inl ∘ f ⊗ inr), by simp [this],
funext $ λs, by cases s with a b; refl⟩
theorem dioph_list_all (l) (d : list_all dioph l) : dioph (λv, list_all (λS : set (α → ℕ), S v) l) :=
suffices ∃ β (pl : list (poly (α ⊕ β))), ∀ v, list_all (λS : set _, S v) l ↔ ∃t, list_all (λp : poly (α ⊕ β), p (v ⊗ t) = 0) pl,
from let ⟨β, pl, h⟩ := this in ⟨β, poly.sumsq pl, λv, (h v).trans $ exists_congr $ λt, (poly.sumsq_eq_zero _ _).symm⟩,
begin
induction l with S l IH,
exact ⟨ulift empty, [], λv, by simp; exact ⟨λ⟨t⟩, empty.rec _ t, trivial⟩⟩,
simp at d,
exact let ⟨⟨β, p, pe⟩, dl⟩ := d, ⟨γ, pl, ple⟩ := IH dl in
⟨β ⊕ γ, p.remap (inl ⊗ inr ∘ inl) :: pl.map (λq, q.remap (inl ⊗ (inr ∘ inr))), λv,
by simp; exact iff.trans (and_congr (pe v) (ple v))
⟨λ⟨⟨m, hm⟩, ⟨n, hn⟩⟩,
⟨m ⊗ n, by rw [
show (v ⊗ m ⊗ n) ∘ (inl ⊗ inr ∘ inl) = v ⊗ m,
from funext $ λs, by cases s with a b; refl]; exact hm,
by { refine list_all.imp (λq hq, _) hn, dsimp [(∘)],
rw [show (λ (x : α ⊕ γ), (v ⊗ m ⊗ n) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ n,
from funext $ λs, by cases s with a b; refl]; exact hq }⟩,
λ⟨t, hl, hr⟩,
⟨⟨t ∘ inl, by rwa [
show (v ⊗ t) ∘ (inl ⊗ inr ∘ inl) = v ⊗ t ∘ inl,
from funext $ λs, by cases s with a b; refl] at hl⟩,
⟨t ∘ inr, by {
refine list_all.imp (λq hq, _) hr, dsimp [(∘)] at hq,
rwa [show (λ (x : α ⊕ γ), (v ⊗ t) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ t ∘ inr,
from funext $ λs, by cases s with a b; refl] at hq }⟩⟩⟩⟩
end
theorem and_dioph {S S' : set (α → ℕ)} (d : dioph S) (d' : dioph S') : dioph (λv, S v ∧ S' v) :=
dioph_list_all [S, S'] ⟨d, d'⟩
theorem or_dioph {S S' : set (α → ℕ)} : ∀ (d : dioph S) (d' : dioph S'), dioph (λv, S v ∨ S' v)
| ⟨β, p, pe⟩ ⟨γ, q, qe⟩ := ⟨β ⊕ γ, p.remap (inl ⊗ inr ∘ inl) * q.remap (inl ⊗ inr ∘ inr), λv,
begin
refine iff.trans (or_congr ((pe v).trans _) ((qe v).trans _)) (exists_or_distrib.symm.trans (exists_congr $ λt,
(@mul_eq_zero_iff_eq_zero_or_eq_zero _ _ (p ((v ⊗ t) ∘ (inl ⊗ inr ∘ inl))) (q ((v ⊗ t) ∘ (inl ⊗ inr ∘ inr)))).symm)),
exact inject_dummies_lem _ (some ⊗ (λ_, none)) (λx, rfl) _ _,
exact inject_dummies_lem _ ((λ_, none) ⊗ some) (λx, rfl) _ _,
end⟩
/-- A partial function is Diophantine if its graph is Diophantine. -/
def dioph_pfun (f : (α → ℕ) →. ℕ) := dioph (λv : option α → ℕ, f.graph (v ∘ some, v none))
/-- A function is Diophantine if its graph is Diophantine. -/
def dioph_fn (f : (α → ℕ) → ℕ) := dioph (λv : option α → ℕ, f (v ∘ some) = v none)
theorem reindex_dioph_fn {f : (α → ℕ) → ℕ} (d : dioph_fn f) (g : α → β) : dioph_fn (λv, f (v ∘ g)) :=
reindex_dioph d (has_map.map g)
theorem ex_dioph {S : set (α ⊕ β → ℕ)} : dioph S → dioph (λv, ∃x, S (v ⊗ x))
| ⟨γ, p, pe⟩ := ⟨β ⊕ γ, p.remap ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr), λv,
⟨λ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x ⊗ t, by simp; rw [
show (v ⊗ x ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ x) ⊗ t,
from funext $ λs, by cases s with a b; try {cases a}; refl]; exact ht⟩,
λ⟨t, ht⟩, ⟨t ∘ inl, (pe _).2 ⟨t ∘ inr, by simp at ht; rwa [
show (v ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ t ∘ inl) ⊗ t ∘ inr,
from funext $ λs, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩
theorem ex1_dioph {S : set (option α → ℕ)} : dioph S → dioph (λv, ∃x, S (x :: v))
| ⟨β, p, pe⟩ := ⟨option β, p.remap (inr none :: inl ⊗ inr ∘ some), λv,
⟨λ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x :: t, by simp; rw [
show (v ⊗ x :: t) ∘ (inr none :: inl ⊗ inr ∘ some) = x :: v ⊗ t,
from funext $ λs, by cases s with a b; try {cases a}; refl]; exact ht⟩,
λ⟨t, ht⟩, ⟨t none, (pe _).2 ⟨t ∘ some, by simp at ht; rwa [
show (v ⊗ t) ∘ (inr none :: inl ⊗ inr ∘ some) = t none :: v ⊗ t ∘ some,
from funext $ λs, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩
theorem dom_dioph {f : (α → ℕ) →. ℕ} (d : dioph_pfun f) : dioph f.dom :=
cast (congr_arg dioph $ set.ext $ λv, (pfun.dom_iff_graph _ _).symm) (ex1_dioph d)
theorem dioph_fn_iff_pfun (f : (α → ℕ) → ℕ) : dioph_fn f = @dioph_pfun α f :=
by refine congr_arg dioph (set.ext $ λv, _); exact pfun.lift_graph.symm
theorem abs_poly_dioph (p : poly α) : dioph_fn (λv, (p v).nat_abs) :=
by refine of_no_dummies _ ((p.remap some - poly.proj none) * (p.remap some + poly.proj none)) (λv, _);
apply int.eq_nat_abs_iff_mul
theorem proj_dioph (i : α) : dioph_fn (λv, v i) :=
abs_poly_dioph (poly.proj i)
theorem dioph_pfun_comp1 {S : set (option α → ℕ)} (d : dioph S) {f} (df : dioph_pfun f) :
dioph (λv : α → ℕ, ∃ h : f.dom v, S (f.fn v h :: v)) :=
ext (ex1_dioph (and_dioph d df)) $ λv,
⟨λ⟨x, hS, (h: Exists _)⟩, by
rw [show (x :: v) ∘ some = v, from funext $ λs, rfl] at h;
cases h with hf h; refine ⟨hf, _⟩; rw [pfun.fn, h]; exact hS,
λ⟨x, hS⟩, ⟨f.fn v x, hS, show Exists _,
by rw [show (f.fn v x :: v) ∘ some = v, from funext $ λs, rfl]; exact ⟨x, rfl⟩⟩⟩
theorem dioph_fn_comp1 {S : set (option α → ℕ)} (d : dioph S) {f : (α → ℕ) → ℕ} (df : dioph_fn f) :
dioph (λv : α → ℕ, S (f v :: v)) :=
ext (dioph_pfun_comp1 d (cast (dioph_fn_iff_pfun f) df)) $ λv,
⟨λ⟨_, h⟩, h, λh, ⟨trivial, h⟩⟩
end
section
variables {α β γ : Type}
theorem dioph_fn_vec_comp1 {n} {S : set (vector3 ℕ (succ n))} (d : dioph S) {f : (vector3 ℕ n) → ℕ} (df : dioph_fn f) :
dioph (λv : vector3 ℕ n, S (cons (f v) v)) :=
ext (dioph_fn_comp1 (reindex_dioph d (none :: some)) df) $ λv, by rw [
show option.cons (f v) v ∘ (cons none some) = f v :: v,
from funext $ λs, by cases s with a b; refl]
theorem vec_ex1_dioph (n) {S : set (vector3 ℕ (succ n))} (d : dioph S) : dioph (λv : vector3 ℕ n, ∃x, S (x :: v)) :=
ext (ex1_dioph $ reindex_dioph d (none :: some)) $ λv, exists_congr $ λx, by rw [
show (option.cons x v) ∘ (cons none some) = x :: v,
from funext $ λs, by cases s with a b; refl]
theorem dioph_fn_vec {n} (f : vector3 ℕ n → ℕ) : dioph_fn f ↔ dioph (λv : vector3 ℕ (succ n), f (v ∘ fs) = v fz) :=
⟨λh, reindex_dioph h (fz :: fs), λh, reindex_dioph h (none :: some)⟩
theorem dioph_pfun_vec {n} (f : vector3 ℕ n →. ℕ) : dioph_pfun f ↔ dioph (λv : vector3 ℕ (succ n), f.graph (v ∘ fs, v fz)) :=
⟨λh, reindex_dioph h (fz :: fs), λh, reindex_dioph h (none :: some)⟩
theorem dioph_fn_compn {α : Type} : ∀ {n} {S : set (α ⊕ fin2 n → ℕ)} (d : dioph S) {f : vector3 ((α → ℕ) → ℕ) n} (df : vector_allp dioph_fn f),
dioph (λv : α → ℕ, S (v ⊗ λi, f i v))
| 0 S d f := λdf, ext (reindex_dioph d (id ⊗ fin2.elim0)) $ λv,
by refine eq.to_iff (congr_arg S $ funext $ λs, _); {cases s with a b, refl, cases b}
| (succ n) S d f := f.cons_elim $ λf fl, by simp; exact λ df dfl,
have dioph (λv, S (v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr)),
from ext (dioph_fn_comp1 (reindex_dioph d (some ∘ inl ⊗ none :: some ∘ inr)) (reindex_dioph_fn df inl)) $
λv, by {refine eq.to_iff (congr_arg S $ funext $ λs, _); cases s with a b, refl, cases b; refl},
have dioph (λv, S (v ⊗ f v :: λ (i : fin2 n), fl i v)),
from @dioph_fn_compn n (λv, S (v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr)) this _ dfl,
ext this $ λv, by rw [
show cons (f v) (λ (i : fin2 n), fl i v) = λ (i : fin2 (succ n)), (f :: fl) i v,
from funext $ λs, by cases s with a b; refl]
theorem dioph_comp {n} {S : set (vector3 ℕ n)} (d : dioph S)
(f : vector3 ((α → ℕ) → ℕ) n) (df : vector_allp dioph_fn f) : dioph (λv, S (λi, f i v)) :=
dioph_fn_compn (reindex_dioph d inr) df
theorem dioph_fn_comp {n} {f : vector3 ℕ n → ℕ} (df : dioph_fn f)
(g : vector3 ((α → ℕ) → ℕ) n) (dg : vector_allp dioph_fn g) : dioph_fn (λv, f (λi, g i v)) :=
dioph_comp ((dioph_fn_vec _).1 df) ((λv, v none) :: λi v, g i (v ∘ some)) $
by simp; exact ⟨proj_dioph none, (vector_allp_iff_forall _ _).2 $ λi,
reindex_dioph_fn ((vector_allp_iff_forall _ _).1 dg _) _⟩
local notation x ` D∧ `:35 y := and_dioph x y
local notation x ` D∨ `:35 y := or_dioph x y
local notation `D∃`:30 := vec_ex1_dioph
local prefix `&`:max := of_nat'
theorem proj_dioph_of_nat {n : ℕ} (m : ℕ) [is_lt m n] : dioph_fn (λv : vector3 ℕ n, v &m) :=
proj_dioph &m
local prefix `D&`:100 := proj_dioph_of_nat
theorem const_dioph (n : ℕ) : dioph_fn (const (α → ℕ) n) :=
abs_poly_dioph (poly.const n)
local prefix `D.`:100 := const_dioph
variables {f g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g)
include df dg
theorem dioph_comp2 {S : ℕ → ℕ → Prop} (d : dioph (λv:vector3 ℕ 2, S (v &0) (v &1))) :
dioph (λv, S (f v) (g v)) :=
dioph_comp d [f, g] (by exact ⟨df, dg⟩)
theorem dioph_fn_comp2 {h : ℕ → ℕ → ℕ} (d : dioph_fn (λv:vector3 ℕ 2, h (v &0) (v &1))) :
dioph_fn (λv, h (f v) (g v)) :=
dioph_fn_comp d [f, g] (by exact ⟨df, dg⟩)
theorem eq_dioph : dioph (λv, f v = g v) :=
dioph_comp2 df dg $ of_no_dummies _ (poly.proj &0 - poly.proj &1)
(λv, (int.coe_nat_eq_coe_nat_iff _ _).symm.trans
⟨@sub_eq_zero_of_eq ℤ _ (v &0) (v &1), eq_of_sub_eq_zero⟩)
local infix ` D= `:50 := eq_dioph
theorem add_dioph : dioph_fn (λv, f v + g v) :=
dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 + poly.proj &1)
local infix ` D+ `:80 := add_dioph
theorem mul_dioph : dioph_fn (λv, f v * g v) :=
dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 * poly.proj &1)
local infix ` D* `:90 := mul_dioph
theorem le_dioph : dioph (λv, f v ≤ g v) :=
dioph_comp2 df dg $ ext (D∃2 $ D&1 D+ D&0 D= D&2) (λv, ⟨λ⟨x, hx⟩, le.intro hx, le.dest⟩)
local infix ` D≤ `:50 := le_dioph
theorem lt_dioph : dioph (λv, f v < g v) := df D+ (D. 1) D≤ dg
local infix ` D< `:50 := lt_dioph
theorem ne_dioph : dioph (λv, f v ≠ g v) :=
ext (df D< dg D∨ dg D< df) $ λv, ne_iff_lt_or_gt.symm
local infix ` D≠ `:50 := ne_dioph
theorem sub_dioph : dioph_fn (λv, f v - g v) :=
dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $
ext (D&1 D= D&0 D+ D&2 D∨ D&1 D≤ D&2 D∧ D&0 D= D.0) $ (vector_all_iff_forall _).1 $ λx y z,
show (y = x + z ∨ y ≤ z ∧ x = 0) ↔ y - z = x, from
⟨λo, begin
rcases o with ae | ⟨yz, x0⟩,
{ rw [ae, nat.add_sub_cancel] },
{ rw [x0, nat.sub_eq_zero_of_le yz] }
end, λh, begin
subst x,
cases le_total y z with yz zy,
{ exact or.inr ⟨yz, nat.sub_eq_zero_of_le yz⟩ },
{ exact or.inl (nat.sub_add_cancel zy).symm },
end⟩
local infix ` D- `:80 := sub_dioph
theorem dvd_dioph : dioph (λv, f v ∣ g v) :=
dioph_comp (D∃2 $ D&2 D= D&1 D* D&0) [f, g] (by exact ⟨df, dg⟩)
local infix ` D∣ `:50 := dvd_dioph
theorem mod_dioph : dioph_fn (λv, f v % g v) :=
have dioph (λv : vector3 ℕ 3, (v &2 = 0 ∨ v &0 < v &2) ∧ ∃ (x : ℕ), v &0 + v &2 * x = v &1),
from (D&2 D= D.0 D∨ D&0 D< D&2) D∧ (D∃3 $ D&1 D+ D&3 D* D&0 D= D&2),
dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λz x y,
show ((y = 0 ∨ z < y) ∧ ∃ c, z + y * c = x) ↔ x % y = z, from
⟨λ⟨h, c, hc⟩, begin rw ← hc; simp; cases h with x0 hl, rw [x0, mod_zero], exact mod_eq_of_lt hl end,
λe, by rw ← e; exact ⟨or_iff_not_imp_left.2 $ λh, mod_lt _ (nat.pos_of_ne_zero h), x / y, mod_add_div _ _⟩⟩
local infix ` D% `:80 := mod_dioph
theorem modeq_dioph {h : (α → ℕ) → ℕ} (dh : dioph_fn h) : dioph (λv, f v ≡ g v [MOD h v]) :=
df D% dh D= dg D% dh
local notation `D≡` := modeq_dioph
theorem div_dioph : dioph_fn (λv, f v / g v) :=
have dioph (λv : vector3 ℕ 3, v &2 = 0 ∧ v &0 = 0 ∨ v &0 * v &2 ≤ v &1 ∧ v &1 < (v &0 + 1) * v &2),
from (D&2 D= D.0 D∧ D&0 D= D.0) D∨ D&0 D* D&2 D≤ D&1 D∧ D&1 D< (D&0 D+ D.1) D* D&2,
dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λz x y,
show y = 0 ∧ z = 0 ∨ z * y ≤ x ∧ x < (z + 1) * y ↔ x / y = z,
by refine iff.trans _ eq_comm; exact y.eq_zero_or_pos.elim
(λy0, by rw [y0, nat.div_zero]; exact
⟨λo, (o.resolve_right $ λ⟨_, h2⟩, not_lt_zero _ h2).right, λz0, or.inl ⟨rfl, z0⟩⟩)
(λypos, iff.trans ⟨λo, o.resolve_left $ λ⟨h1, _⟩, ne_of_gt ypos h1, or.inr⟩
(le_antisymm_iff.trans $ and_congr (nat.le_div_iff_mul_le _ _ ypos) $
iff.trans ⟨lt_succ_of_le, le_of_lt_succ⟩ (div_lt_iff_lt_mul _ _ ypos)).symm)
local infix ` D/ `:80 := div_dioph
omit df dg
open pell
theorem pell_dioph : dioph (λv:vector3 ℕ 4, ∃ h : v &0 > 1,
xn h (v &1) = v &2 ∧ yn h (v &1) = v &3) :=
have dioph {v : vector3 ℕ 4 |
v &0 > 1 ∧ v &1 ≤ v &3 ∧
(v &2 = 1 ∧ v &3 = 0 ∨
∃ (u w s t b : ℕ),
v &2 * v &2 - (v &0 * v &0 - 1) * v &3 * v &3 = 1 ∧
u * u - (v &0 * v &0 - 1) * w * w = 1 ∧
s * s - (b * b - 1) * t * t = 1 ∧
b > 1 ∧ (b ≡ 1 [MOD 4 * v &3]) ∧ (b ≡ v &0 [MOD u]) ∧
w > 0 ∧ v &3 * v &3 ∣ w ∧
(s ≡ v &2 [MOD u]) ∧
(t ≡ v &1 [MOD 4 * v &3]))}, from
D.1 D< D&0 D∧ D&1 D≤ D&3 D∧
((D&2 D= D.1 D∧ D&3 D= D.0) D∨
(D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $
D&7 D* D&7 D- (D&5 D* D&5 D- D.1) D* D&8 D* D&8 D= D.1 D∧
D&4 D* D&4 D- (D&5 D* D&5 D- D.1) D* D&3 D* D&3 D= D.1 D∧
D&2 D* D&2 D- (D&0 D* D&0 D- D.1) D* D&1 D* D&1 D= D.1 D∧
D.1 D< D&0 D∧ (D≡ (D&0) (D.1) (D.4 D* D&8)) D∧ (D≡ (D&0) (D&5) D&4) D∧
D.0 D< D&3 D∧ D&8 D* D&8 D∣ D&3 D∧
(D≡ (D&2) (D&7) D&4) D∧
(D≡ (D&1) (D&6) (D.4 D* D&8)))),
dioph.ext this $ λv, matiyasevic.symm
theorem xn_dioph : dioph_pfun (λv:vector3 ℕ 2, ⟨v &0 > 1, λh, xn h (v &1)⟩) :=
have dioph (λv:vector3 ℕ 3, ∃ y, ∃ h : v &1 > 1, xn h (v &2) = v &0 ∧ yn h (v &2) = y), from
let D_pell := @reindex_dioph _ (fin2 4) _ pell_dioph [&2, &3, &1, &0] in D∃3 D_pell,
(dioph_pfun_vec _).2 $ dioph.ext this $ λv, ⟨λ⟨y, h, xe, ye⟩, ⟨h, xe⟩, λ⟨h, xe⟩, ⟨_, h, xe, rfl⟩⟩
include df dg
theorem pow_dioph : dioph_fn (λv, f v ^ g v) :=
have dioph {v : vector3 ℕ 3 |
v &2 = 0 ∧ v &0 = 1 ∨ v &2 > 0 ∧
(v &1 = 0 ∧ v &0 = 0 ∨ v &1 > 0 ∧
∃ (w a t z x y : ℕ),
(∃ (a1 : a > 1), xn a1 (v &2) = x ∧ yn a1 (v &2) = y) ∧
(x ≡ y * (a - v &1) + v &0 [MOD t]) ∧
2 * a * v &1 = t + (v &1 * v &1 + 1) ∧
v &0 < t ∧ v &1 ≤ w ∧ v &2 ≤ w ∧
a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)}, from
let D_pell := @reindex_dioph _ (fin2 9) _ pell_dioph [&4, &8, &1, &0] in
(D&2 D= D.0 D∧ D&0 D= D.1) D∨ (D.0 D< D&2 D∧
((D&1 D= D.0 D∧ D&0 D= D.0) D∨ (D.0 D< D&1 D∧
(D∃3 $ D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $ D_pell D∧
(D≡ (D&1) (D&0 D* (D&4 D- D&7) D+ D&6) (D&3)) D∧
D.2 D* D&4 D* D&7 D= D&3 D+ (D&7 D* D&7 D+ D.1) D∧
D&6 D< D&3 D∧ D&7 D≤ D&5 D∧ D&8 D≤ D&5 D∧
D&4 D* D&4 D- ((D&5 D+ D.1) D* (D&5 D+ D.1) D- D.1) D* (D&5 D* D&2) D* (D&5 D* D&2) D= D.1)))),
dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ dioph.ext this $ λv, iff.symm $
eq_pow_of_pell.trans $ or_congr iff.rfl $ and_congr iff.rfl $ or_congr iff.rfl $ and_congr iff.rfl $
⟨λ⟨w, a, t, z, a1, h⟩, ⟨w, a, t, z, _, _, ⟨a1, rfl, rfl⟩, h⟩,
λ⟨w, a, t, z, ._, ._, ⟨a1, rfl, rfl⟩, h⟩, ⟨w, a, t, z, a1, h⟩⟩
end
end dioph
|
55d1f4e202313041e7e44dd8ef6a097ff3308603 | 86f6f4f8d827a196a32bfc646234b73328aeb306 | /examples/basics/unnamed_1976.lean | a20ff1f9a2a2b9aad15a02655230acd404cc2a90 | [] | no_license | jamescheuk91/mathematics_in_lean | 09f1f87d2b0dce53464ff0cbe592c568ff59cf5e | 4452499264e2975bca2f42565c0925506ba5dda3 | refs/heads/master | 1,679,716,410,967 | 1,613,957,947,000 | 1,613,957,947,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 199 | lean | import algebra.ordered_ring
variables {R : Type*} [ordered_ring R]
variables a b c : R
#check (add_le_add_left : a ≤ b → ∀ c, c + a ≤ c + b)
#check (mul_pos : 0 < a → 0 < b → 0 < a * b) |
7bc7177a2d17a8eb3a84f3d5b8b83ce5c6551abe | 592ee40978ac7604005a4e0d35bbc4b467389241 | /Library/generated/mathscheme-lean/AdditiveUnaryAntiDistribution.lean | a7354f3ee21ea413ea9dbbbfc4f538b89716fac3 | [] | no_license | ysharoda/Deriving-Definitions | 3e149e6641fae440badd35ac110a0bd705a49ad2 | dfecb27572022de3d4aa702cae8db19957523a59 | refs/heads/master | 1,679,127,857,700 | 1,615,939,007,000 | 1,615,939,007,000 | 229,785,731 | 4 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,600 | lean | import init.data.nat.basic
import init.data.fin.basic
import data.vector
import .Prelude
open Staged
open nat
open fin
open vector
section AdditiveUnaryAntiDistribution
structure AdditiveUnaryAntiDistribution (A : Type) : Type :=
(prim : (A → A))
(plus : (A → (A → A)))
(antidis_prim_plus : (∀ {x y : A} , (prim (plus x y)) = (plus (prim y) (prim x))))
open AdditiveUnaryAntiDistribution
structure Sig (AS : Type) : Type :=
(primS : (AS → AS))
(plusS : (AS → (AS → AS)))
structure Product (A : Type) : Type :=
(primP : ((Prod A A) → (Prod A A)))
(plusP : ((Prod A A) → ((Prod A A) → (Prod A A))))
(antidis_prim_plusP : (∀ {xP yP : (Prod A A)} , (primP (plusP xP yP)) = (plusP (primP yP) (primP xP))))
structure Hom {A1 : Type} {A2 : Type} (Ad1 : (AdditiveUnaryAntiDistribution A1)) (Ad2 : (AdditiveUnaryAntiDistribution A2)) : Type :=
(hom : (A1 → A2))
(pres_prim : (∀ {x1 : A1} , (hom ((prim Ad1) x1)) = ((prim Ad2) (hom x1))))
(pres_plus : (∀ {x1 x2 : A1} , (hom ((plus Ad1) x1 x2)) = ((plus Ad2) (hom x1) (hom x2))))
structure RelInterp {A1 : Type} {A2 : Type} (Ad1 : (AdditiveUnaryAntiDistribution A1)) (Ad2 : (AdditiveUnaryAntiDistribution A2)) : Type 1 :=
(interp : (A1 → (A2 → Type)))
(interp_prim : (∀ {x1 : A1} {y1 : A2} , ((interp x1 y1) → (interp ((prim Ad1) x1) ((prim Ad2) y1)))))
(interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus Ad1) x1 x2) ((plus Ad2) y1 y2))))))
inductive AdditiveUnaryAntiDistributionTerm : Type
| primL : (AdditiveUnaryAntiDistributionTerm → AdditiveUnaryAntiDistributionTerm)
| plusL : (AdditiveUnaryAntiDistributionTerm → (AdditiveUnaryAntiDistributionTerm → AdditiveUnaryAntiDistributionTerm))
open AdditiveUnaryAntiDistributionTerm
inductive ClAdditiveUnaryAntiDistributionTerm (A : Type) : Type
| sing : (A → ClAdditiveUnaryAntiDistributionTerm)
| primCl : (ClAdditiveUnaryAntiDistributionTerm → ClAdditiveUnaryAntiDistributionTerm)
| plusCl : (ClAdditiveUnaryAntiDistributionTerm → (ClAdditiveUnaryAntiDistributionTerm → ClAdditiveUnaryAntiDistributionTerm))
open ClAdditiveUnaryAntiDistributionTerm
inductive OpAdditiveUnaryAntiDistributionTerm (n : ℕ) : Type
| v : ((fin n) → OpAdditiveUnaryAntiDistributionTerm)
| primOL : (OpAdditiveUnaryAntiDistributionTerm → OpAdditiveUnaryAntiDistributionTerm)
| plusOL : (OpAdditiveUnaryAntiDistributionTerm → (OpAdditiveUnaryAntiDistributionTerm → OpAdditiveUnaryAntiDistributionTerm))
open OpAdditiveUnaryAntiDistributionTerm
inductive OpAdditiveUnaryAntiDistributionTerm2 (n : ℕ) (A : Type) : Type
| v2 : ((fin n) → OpAdditiveUnaryAntiDistributionTerm2)
| sing2 : (A → OpAdditiveUnaryAntiDistributionTerm2)
| primOL2 : (OpAdditiveUnaryAntiDistributionTerm2 → OpAdditiveUnaryAntiDistributionTerm2)
| plusOL2 : (OpAdditiveUnaryAntiDistributionTerm2 → (OpAdditiveUnaryAntiDistributionTerm2 → OpAdditiveUnaryAntiDistributionTerm2))
open OpAdditiveUnaryAntiDistributionTerm2
def simplifyCl {A : Type} : ((ClAdditiveUnaryAntiDistributionTerm A) → (ClAdditiveUnaryAntiDistributionTerm A))
| (plusCl (primCl y) (primCl x)) := (primCl (plusCl x y))
| (primCl x1) := (primCl (simplifyCl x1))
| (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2))
| (sing x1) := (sing x1)
def simplifyOpB {n : ℕ} : ((OpAdditiveUnaryAntiDistributionTerm n) → (OpAdditiveUnaryAntiDistributionTerm n))
| (plusOL (primOL y) (primOL x)) := (primOL (plusOL x y))
| (primOL x1) := (primOL (simplifyOpB x1))
| (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2))
| (v x1) := (v x1)
def simplifyOp {n : ℕ} {A : Type} : ((OpAdditiveUnaryAntiDistributionTerm2 n A) → (OpAdditiveUnaryAntiDistributionTerm2 n A))
| (plusOL2 (primOL2 y) (primOL2 x)) := (primOL2 (plusOL2 x y))
| (primOL2 x1) := (primOL2 (simplifyOp x1))
| (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2))
| (v2 x1) := (v2 x1)
| (sing2 x1) := (sing2 x1)
def evalB {A : Type} : ((AdditiveUnaryAntiDistribution A) → (AdditiveUnaryAntiDistributionTerm → A))
| Ad (primL x1) := ((prim Ad) (evalB Ad x1))
| Ad (plusL x1 x2) := ((plus Ad) (evalB Ad x1) (evalB Ad x2))
def evalCl {A : Type} : ((AdditiveUnaryAntiDistribution A) → ((ClAdditiveUnaryAntiDistributionTerm A) → A))
| Ad (sing x1) := x1
| Ad (primCl x1) := ((prim Ad) (evalCl Ad x1))
| Ad (plusCl x1 x2) := ((plus Ad) (evalCl Ad x1) (evalCl Ad x2))
def evalOpB {A : Type} {n : ℕ} : ((AdditiveUnaryAntiDistribution A) → ((vector A n) → ((OpAdditiveUnaryAntiDistributionTerm n) → A)))
| Ad vars (v x1) := (nth vars x1)
| Ad vars (primOL x1) := ((prim Ad) (evalOpB Ad vars x1))
| Ad vars (plusOL x1 x2) := ((plus Ad) (evalOpB Ad vars x1) (evalOpB Ad vars x2))
def evalOp {A : Type} {n : ℕ} : ((AdditiveUnaryAntiDistribution A) → ((vector A n) → ((OpAdditiveUnaryAntiDistributionTerm2 n A) → A)))
| Ad vars (v2 x1) := (nth vars x1)
| Ad vars (sing2 x1) := x1
| Ad vars (primOL2 x1) := ((prim Ad) (evalOp Ad vars x1))
| Ad vars (plusOL2 x1 x2) := ((plus Ad) (evalOp Ad vars x1) (evalOp Ad vars x2))
def inductionB {P : (AdditiveUnaryAntiDistributionTerm → Type)} : ((∀ (x1 : AdditiveUnaryAntiDistributionTerm) , ((P x1) → (P (primL x1)))) → ((∀ (x1 x2 : AdditiveUnaryAntiDistributionTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → (∀ (x : AdditiveUnaryAntiDistributionTerm) , (P x))))
| ppriml pplusl (primL x1) := (ppriml _ (inductionB ppriml pplusl x1))
| ppriml pplusl (plusL x1 x2) := (pplusl _ _ (inductionB ppriml pplusl x1) (inductionB ppriml pplusl x2))
def inductionCl {A : Type} {P : ((ClAdditiveUnaryAntiDistributionTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 : (ClAdditiveUnaryAntiDistributionTerm A)) , ((P x1) → (P (primCl x1)))) → ((∀ (x1 x2 : (ClAdditiveUnaryAntiDistributionTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → (∀ (x : (ClAdditiveUnaryAntiDistributionTerm A)) , (P x)))))
| psing pprimcl ppluscl (sing x1) := (psing x1)
| psing pprimcl ppluscl (primCl x1) := (pprimcl _ (inductionCl psing pprimcl ppluscl x1))
| psing pprimcl ppluscl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing pprimcl ppluscl x1) (inductionCl psing pprimcl ppluscl x2))
def inductionOpB {n : ℕ} {P : ((OpAdditiveUnaryAntiDistributionTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 : (OpAdditiveUnaryAntiDistributionTerm n)) , ((P x1) → (P (primOL x1)))) → ((∀ (x1 x2 : (OpAdditiveUnaryAntiDistributionTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → (∀ (x : (OpAdditiveUnaryAntiDistributionTerm n)) , (P x)))))
| pv pprimol pplusol (v x1) := (pv x1)
| pv pprimol pplusol (primOL x1) := (pprimol _ (inductionOpB pv pprimol pplusol x1))
| pv pprimol pplusol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv pprimol pplusol x1) (inductionOpB pv pprimol pplusol x2))
def inductionOp {n : ℕ} {A : Type} {P : ((OpAdditiveUnaryAntiDistributionTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 : (OpAdditiveUnaryAntiDistributionTerm2 n A)) , ((P x1) → (P (primOL2 x1)))) → ((∀ (x1 x2 : (OpAdditiveUnaryAntiDistributionTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → (∀ (x : (OpAdditiveUnaryAntiDistributionTerm2 n A)) , (P x))))))
| pv2 psing2 pprimol2 pplusol2 (v2 x1) := (pv2 x1)
| pv2 psing2 pprimol2 pplusol2 (sing2 x1) := (psing2 x1)
| pv2 psing2 pprimol2 pplusol2 (primOL2 x1) := (pprimol2 _ (inductionOp pv2 psing2 pprimol2 pplusol2 x1))
| pv2 psing2 pprimol2 pplusol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 pprimol2 pplusol2 x1) (inductionOp pv2 psing2 pprimol2 pplusol2 x2))
def stageB : (AdditiveUnaryAntiDistributionTerm → (Staged AdditiveUnaryAntiDistributionTerm))
| (primL x1) := (stage1 primL (codeLift1 primL) (stageB x1))
| (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2))
def stageCl {A : Type} : ((ClAdditiveUnaryAntiDistributionTerm A) → (Staged (ClAdditiveUnaryAntiDistributionTerm A)))
| (sing x1) := (Now (sing x1))
| (primCl x1) := (stage1 primCl (codeLift1 primCl) (stageCl x1))
| (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2))
def stageOpB {n : ℕ} : ((OpAdditiveUnaryAntiDistributionTerm n) → (Staged (OpAdditiveUnaryAntiDistributionTerm n)))
| (v x1) := (const (code (v x1)))
| (primOL x1) := (stage1 primOL (codeLift1 primOL) (stageOpB x1))
| (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2))
def stageOp {n : ℕ} {A : Type} : ((OpAdditiveUnaryAntiDistributionTerm2 n A) → (Staged (OpAdditiveUnaryAntiDistributionTerm2 n A)))
| (sing2 x1) := (Now (sing2 x1))
| (v2 x1) := (const (code (v2 x1)))
| (primOL2 x1) := (stage1 primOL2 (codeLift1 primOL2) (stageOp x1))
| (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2))
structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type :=
(primT : ((Repr A) → (Repr A)))
(plusT : ((Repr A) → ((Repr A) → (Repr A))))
end AdditiveUnaryAntiDistribution |
2dc99b23f3cd6ab3074b8032b5db5dbecf36d4d1 | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /tests/lean/run/monadCache.lean | 75568cf19fb40b8a81a8b0109401f159e0f082ef | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,282 | lean | import Lean
open Lean
def mkTower : Nat → Expr
| 0 => mkConst `a
| n+1 => mkApp2 (mkConst `f) (mkTower n) (mkTower n)
partial def depth : Expr → MonadCacheT Expr Nat CoreM Nat
| e =>
checkCache e fun e =>
match e with
| Expr.const c [] _ => pure 1
| Expr.app f a _ => do d₁ ← depth f; d₂ ← depth a; pure $ Nat.max d₁ d₂ + 1
| _ => pure 0
#eval (depth (mkTower 100)).run
partial def visit : Expr → MonadCacheT Expr Expr CoreM Expr
| e =>
checkCache e fun e =>
match e with
| Expr.const `a [] _ => pure $ mkConst `b
| Expr.app f a _ => e.updateApp! <$> visit f <*> visit a
| _ => pure e
#eval (visit (mkTower 4)).run
#eval do e ← (visit (mkTower 100)).run; (depth e).run
partial def visitNoCache : Expr → CoreM Expr
| e =>
match e with
| Expr.const `a [] _ => pure $ mkConst `b
| Expr.app f a _ => e.updateApp! <$> visitNoCache f <*> visitNoCache a
| _ => pure e
-- The following is super slow
-- #eval do e ← visitNoCache (mkTower 30); (depth e).run
def displayConsts (e : Expr) : CoreM Unit :=
e.forEach fun e => match e with
| Expr.const c _ _ => do IO.println c
| _ => pure ()
#eval do e ← (visit (mkTower 100)).run; displayConsts e
|
31559b577fc60f92b9a6dd247004750a036ca4cc | d5b53bc87e7f4dda87570c8ef6ee4b4de685f315 | /src/cochain.lean | 5d05a86dc9a47d91217a53984c73a73214e1f41b | [] | no_license | Shenyang1995/M4R | 3bec366fba7262ed29d7f64b4ba7cc978494c022 | a6a3399c4d1935b39a22f64c30f293ef2a32fdeb | refs/heads/master | 1,597,008,096,640 | 1,591,722,931,000 | 1,591,722,931,000 | 214,177,424 | 5 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 19,695 | lean | import algebra.group -- for is_add_group_hom
import group_theory.subgroup -- for kernels
import algebra.module
import tactic.linarith
import tactic.omega
import tactic.fin_cases
import add_group_hom.basic
import algebra.pi_instances
import G_module.basic
def cochain(n:ℕ)(G : Type*) [group G] (M : Type*) [add_comm_group M] [G_module G M] :=
(fin n → G) → M
def F{n:ℕ}(j:ℕ) {G : Type*}[group G](g:fin (n+1)→ G):fin n→ G
:= λ k, if k.val < j then g ⟨k.val, lt_trans k.2 $ lt_add_one _⟩ else
if k.val=j then g ⟨k.val, lt_trans k.2 $ lt_add_one _⟩ *g ⟨k.val+1, add_lt_add_right k.2 1⟩
else g ⟨k.val+1, add_lt_add_right k.2 1⟩
def XYZ (n : ℕ): fin n → fin (n + 1) := coe
example : XYZ 3 ⟨2,by linarith⟩ = ⟨2, by linarith⟩ := rfl
--set_option pp.all true
theorem degenerate{n:ℕ}{j:ℕ}{k:ℕ}{G : Type*}[group G](h:j≤ k)(g:fin (n+2)→ G):
F j (F (k+1) g) = F k (F j g):=
begin
unfold F,
funext t,
cases t with t ht,
-- I got this line by typing "dsimp"
show ite (t < j) (ite (t < k + 1) (g ⟨t, _⟩) (ite (t = k + 1) (g ⟨t, _⟩ * g ⟨t + 1, _⟩) (g ⟨t + 1, _⟩)))
(ite (t = j)
(ite (t < k + 1) (g ⟨t, _⟩) (ite (t = k + 1) (g ⟨t, _⟩ * g ⟨t + 1, _⟩) (g ⟨t + 1, _⟩)) *
ite (t + 1 < k + 1) (g ⟨t + 1, _⟩)
(ite (t + 1 = k + 1) (g ⟨t + 1, _⟩ * g ⟨t + 1 + 1, _⟩) (g ⟨t + 1 + 1, _⟩)))
(ite (t + 1 < k + 1) (g ⟨t + 1, _⟩)
(ite (t + 1 = k + 1) (g ⟨t + 1, _⟩ * g ⟨t + 1 + 1, _⟩) (g ⟨t + 1 + 1, _⟩)))) =
ite (t < k) (ite (t < j) (g ⟨t, _⟩) (ite (t = j) (g ⟨t, _⟩ * g ⟨t + 1, _⟩) (g ⟨t + 1, _⟩)))
(ite (t = k)
(ite (t < j) (g ⟨t, _⟩) (ite (t = j) (g ⟨t, _⟩ * g ⟨t + 1, _⟩) (g ⟨t + 1, _⟩)) *
ite (t + 1 < j) (g ⟨t + 1, _⟩)
(ite (t + 1 = j) (g ⟨t + 1, _⟩ * g ⟨t + 1 + 1, _⟩) (g ⟨t + 1 + 1, _⟩)))
(ite (t + 1 < j) (g ⟨t + 1, _⟩)
(ite (t + 1 = j) (g ⟨t + 1, _⟩ * g ⟨t + 1 + 1, _⟩) (g ⟨t + 1 + 1, _⟩)))),
by_cases h1 : t < j,
{ rw if_pos h1,
rw if_pos (lt_trans h1 (nat.lt_succ_of_le h)),
--rw if_pos (show t < k, from lt_of_lt_of_le h1 h),
rw if_pos (lt_of_lt_of_le h1 h),
rw if_pos h1
},
rw if_neg h1,
by_cases h2:t=j,
{ rw if_pos (h2),
cases h2,
rw if_pos (nat.lt_succ_of_le h),
rw le_iff_eq_or_lt at h,
cases h,
{cases h,
rw if_neg (lt_irrefl (j+1)),
rw if_pos (rfl),
rw if_neg (lt_irrefl j),
rw if_pos (rfl),
rw if_neg (lt_irrefl j),
rw if_pos (rfl),
rw if_neg (show ¬ (j+1<j), from mt (le_of_lt) (nat.not_succ_le_self j) ),
rw if_neg (show ¬ (j+1=j), from mt (le_of_eq) (nat.not_succ_le_self j) ),
rw mul_assoc,
},
{rw if_pos (nat.succ_lt_succ h),
rw if_pos h,
rw if_neg (lt_irrefl j),
rw if_pos rfl,
},
},
rw if_neg h2,
by_cases h3 : t < k,
{ rw if_pos (nat.lt_succ_iff.2 h3),
rw if_pos h3,
rw if_neg h1,
rw if_neg h2,
},
rw if_neg (mt nat.lt_succ_iff.1 h3),
by_cases h4 : t = k,
{ cases h4,
rw if_pos rfl,
rw if_neg (lt_irrefl k),
rw if_pos rfl,
rw if_neg h1,
rw if_neg h2,
rw if_neg (not_lt_of_le (le_trans h (nat.le_succ k))),
rw if_neg (ne_of_gt (nat.succ_le_succ h) : ¬ (k + 1 = j)),
},
rw if_neg (mt (nat.succ_inj) h4),
rw if_neg h3,
rw if_neg h4,
have h5: ¬ t+1<j, by linarith,
rw if_neg h5,
have h6: ¬ t+1=j, by linarith,
rw if_neg h6,
-- no goal!
end
--example (j : ℕ) : ¬ (j+1<j) := mt (le_of_lt) (nat.not_succ_le_self j)
theorem neg_one_power(n:ℕ )(G : Type*) [group G] (M : Type*) [add_comm_group M] [G_module G M]
: ∀ m : M, ((-1:ℤ)^n + (-1:ℤ)^(n+1)) • m = 0 :=
begin
intro m,
induction n with h hd,
norm_num,
rw nat.succ_eq_add_one,
rw pow_add (-1:ℤ ) h 1,
rw pow_add (-1:ℤ ) h (1+1),
norm_num,
end
--open_locale add_group
theorem neg_degenerate (n:ℕ)(j:ℕ)(k:ℕ)(G : Type*)[group G](g:fin (n+2)→ G)(h:j≤ k) (M : Type*) [add_comm_group M] [G_module G M](v:cochain n G M)
: (-1:ℤ)^(j+k+1) • (v (F j (F (k+1) g))) + (-1:ℤ)^(j+k)• (v (F k (F j g)))=0:=
begin
rw degenerate h,
--show gsmul ((-1) ^ n) (v (F k (F j g))) + gsmul ((-1) ^ (n + 1)) (v (F k (F j g))) = 0,
rw <-add_smul,
--show ((-1 : ℤ) ^ n + (-1) ^ (n + 1)) • (v (F k (F j g))) = 0,
rw add_comm,
rw neg_one_power (j+k) G M,
end
open finset
def finset.sum_smul2 {α : Type*} {R : Type*} [semiring R] {M : Type*} [add_comm_monoid M]
[semimodule R M] (s : finset α) (r : R) (f : α → M) :
finset.sum s (λ (x : α), (r • (f x))) = r • (finset.sum s f) :=
by haveI := classical.dec_eq α; exact
finset.induction_on s (by simp) (by simp [_root_.smul_add] {contextual := tt})
theorem pow_add'(a : ℤ ) (m n : ℕ): a ^ m * a ^ n=a ^ (m + n) :=
begin
rw pow_add,
end
--theorem double_sum_zero (n':ℕ)(G : Type*)[group G](g:fin (n'+3)→ G)(M : Type*) [add_comm_group M] [G_module G M](v:cochain (n'+1) G M):
--(range (n'+1)).sum(λ i, (-1:ℤ)^(i+1)• (range i).sum(λ j, (-1:ℤ )^(j+1)• (v (F j (F i g))))) =0:=
--begin
--simp only [(finset.sum_smul' _ _ _).symm, smul_smul, pow_add],
--norm_num,
--simp only [pow_add'],
----simp only [degenerate2],
--sorry
--end
theorem degenerate2{n:ℕ}{j:ℕ}{k:ℕ}{G : Type*}[group G](h:j≤ k)(g:fin (n+2)→ G):
F k (F j g)=F j (F (k+1) g) :=
begin
rw degenerate,
exact h,
end
def F2{n:ℕ}{G : Type*}[group G](g:fin (n+2)→ G){M : Type*} [add_comm_group M] [G_module G M](v:cochain n G M): ℕ × ℕ → M:=
λ j, (-1:ℤ)^(j.1+j.2)• v (F (j.2) (F (j.1) g))
theorem F2_degenerate {n:ℕ}{j:ℕ}{k:ℕ}(h:j≤ k){G : Type*}[group G](g:fin (n+2)→ G){M : Type*} [add_comm_group M] [G_module G M](v:cochain n G M):
F2 g v (k+1, j)+F2 g v (j, k)=0:=
begin
unfold F2,
norm_num,
rw degenerate,
rw <-add_smul,
rw <-add_assoc,
rw neg_one_power (j+k) G M,
exact h,
end
def invo : ℕ × ℕ → ℕ × ℕ :=
λ jk, if jk.1 ≤ jk.2 then ⟨jk.2 + 1, jk.1⟩ else ⟨jk.2, jk.1 - 1⟩
lemma invo_def1 {jk : ℕ × ℕ} (h : jk.1 ≤ jk.2) :
invo jk = ⟨jk.2 + 1, jk.1⟩ := if_pos h
lemma invo_ineq1 {jk : ℕ × ℕ}
(h : jk.1 ≤ jk.2) :
¬(invo jk).1 ≤ (invo jk).2 :=
begin
unfold invo,
rw if_pos h,
exact not_le.2 (nat.lt_succ_of_le h),
end
lemma invo_ineq2 {jk : ℕ × ℕ}
(h : ¬jk.1 ≤ jk.2) :
(invo jk).1 ≤ (invo jk).2 :=
begin
unfold invo,
rw if_neg h,
rw not_le at h,
exact nat.pred_le_pred h,
end
lemma invo_aux {j k : ℕ} (h : ¬j ≤ k) : j - 1 + 1 = j :=
nat.succ_pred_eq_of_pos $ lt_of_le_of_lt (zero_le _) (lt_of_not_ge h)
lemma invo_invo (jk : ℕ × ℕ) : invo (invo jk) = jk :=
begin
unfold invo,
split_ifs,
{ exfalso, linarith},
{ ext, refl, simp},
{ ext, dsimp, exact invo_aux h, refl},
{ exfalso,
rw not_le at h_1,
rw nat.lt_iff_add_one_le at h_1,
rw invo_aux h at h_1,
linarith,}
end
--example (n:ℕ )(x:ℕ){G : Type*}[group G](g:fin (n+2)→ G)(M : Type*) [add_comm_group M] [G_module G M](v:cochain n G M):F2 g v(x,x)=v (F (x) (F (x) g)):=rfl
--#print prod
--#check finset.product
--#check finset.range
theorem double_sum_zero1 (n':ℕ)(G : Type*)[group G](g:fin (n'+3)→ G)(M : Type*) [add_comm_group M] [G_module G M](v:cochain (n'+1) G M):
(range (n'+3)).sum(λ i, (range (n'+2)).sum(λ j, (F2 g v (i,j)))) =0:=
begin
rw <-sum_product,
apply sum_involution (λ jk h, invo jk),
{ intros jk hjk,
let j := jk.1,
let k := jk.2,
-- do we need these next three lines?
--cases mem_product.1 hjk with hj hk,
--replace hj : j < n' + 1 := mem_range.1 hj,
--replace hk : k < n' := mem_range.1 hk,
by_cases hin : j ≤ k,
{ rw add_comm,
convert F2_degenerate hin g v,
exact invo_def1 hin},
{ convert F2_degenerate (invo_ineq2 hin) g v,
unfold invo,
rw if_neg hin,
ext,
exact (invo_aux hin).symm,
refl,
}
},
{ intros jk hjk _ h,
dsimp at h,
by_cases hin : jk.1 ≤ jk.2,
{ apply invo_ineq1 hin,
rwa h},
{ have h2 := invo_ineq2 hin,
apply hin,
rwa h at h2}},
{ intros jk hjk,
dsimp,
exact invo_invo jk, },
{ intros jk hjk,
dsimp,
unfold invo,
let j := jk.1,
let k := jk.2,
-- do we need these next three lines?
cases mem_product.1 hjk with hj hk,
replace hj : j < n' + 3 := mem_range.1 hj,
replace hk : k < n'+ 2 := mem_range.1 hk,
rw finset.mem_product,
split_ifs,
split,
show k+1∈ range(n'+3),
rw mem_range,
linarith,
show j∈ range(n'+2),
rw mem_range,
exact lt_of_le_of_lt h hk,
split,
show k∈ range(n'+3),
rw mem_range,
linarith,
show j-1∈ range(n'+2),
rw mem_range,
rw nat.sub_lt_left_iff_lt_add,
linarith,
rw not_le at h,
exact nat.one_le_of_lt h,}
end
--#check @finset.product
--#check @finset.sum_bij
--#check @finset.sum_bind
--#check @finset.sum
--#check finset.bind
--example (a b:ℤ )(M : Type*) [add_comm_group M](c:M):(a+b) • c=a• c+b• c :=begin library_search end
--example (a b:ℕ) :(-a:ℤ ) + (-b:ℤ )=-(a+b) := begin library_search end
--#example (n:ℕ ): (-1:ℤ)^n + (-1:ℤ)^(n+1)=0 := begin library_search end
--funext t,
--conv begin
-- to_lhs,
-- simp only [F],
--end,
--split_ifs;try {refl}; try {rw (show (↑t : fin(n + 1)).val = t.val, by refl) at *}; try {exfalso;linarith};
--rw (show (↑t : fin(n + 1)).val = t.val, by refl) at *,
--change t.val < k + 1 at h_2,
--unfold F,
--{split_ifs;try {rw (show (↑t : fin(n + 1)).val = t.val, by refl) at *}; try {exfalso;linarith}; try {refl}; try {simp only [mul_assoc]}; try {finish}},
--{split_ifs;try {rw (show (↑t : fin(n + 1)).val = t.val, by refl) at *}; try {exfalso;linarith}; try {refl}; try {simp only [mul_assoc]}; try {finish}},
--{split_ifs;try {rw (show (↑t : fin(n + 1)).val = t.val, by refl) at *}; try {exfalso;linarith}; try {refl}; try {simp only [mul_assoc]}; try {finish}},
--{split_ifs;try {rw (show (↑t : fin(n + 1)).val = t.val, by refl) at *}; try {exfalso;linarith}; try {refl}; try {simp only [mul_assoc]}; try {finish}},
--{split_ifs;try {rw (show (↑t : fin(n + 1)).val = t.val, by refl) at *}; try {exfalso;linarith}; try {refl}; try {simp only [mul_assoc]}; try {finish}},
--swap,
--{split_ifs;try {rw (show (↑t : fin(n + 1)).val = t.val, by refl) at *}; try {exfalso;linarith}; try {refl}; try {simp only [mul_assoc]}; try {finish}},
--{split_ifs;try {rw (show (↑t : fin(n + 1)).val = t.val, by refl) at *}; try {exfalso;linarith}; try {refl}; try {simp only [mul_assoc]}; try {finish}},
--split_ifs; try {refl}; try {rw (show (t : fin(n + 1)).val = t.val, by refl) at *},
--{split_ifs;try {rw (show (↑t : fin(n + 1)).val = t.val, by refl) at *}; try {exfalso;linarith}; try {refl}; try {simp only [mul_assoc]}; try {finish}},
--end
def F_first{n:ℕ} {G : Type*}[group G](g:fin (n+1)→ G):fin n→ G
:= λ k, g ⟨k.val+1, add_lt_add_right k.2 1⟩
def d.to_fun {n:ℕ}{G : Type*} [group G] {M : Type*} [add_comm_group M] [G_module G M]
(φ: cochain n G M): (cochain (n+1) G M):= λ(gi: fin (n+1) → G),
gi ⟨0, (by simp)⟩ • φ (λ i, gi ⟨i.val + 1, add_lt_add_right i.2 1⟩)
+(range (n+1)).sum(λ j,(-1:ℤ )^(j+1)• φ (F j gi))
example (G : Type*) [group G] (M : Type*) [add_comm_group M] [G_module G M]
(φ : cochain 1 G M) (hφ : d.to_fun φ = (λ i, 0)) (g h : G) : φ (λ _, g * h) = φ (λ _, g) + g • φ (λ _, h) :=
begin
unfold d.to_fun at hφ,
let glist : fin 2 → G := λ i, if i.val = 0 then g else if i.val = 1 then h else 1,
have h2 : (λ (gi : fin (1 + 1) → G),
gi ⟨0, _⟩ • φ (λ (i : fin 1), gi ⟨i.val + 1, _⟩) +
finset.sum (finset.range (1 + 1)) (λ (j : ℕ), (-1: ℤ) ^ (j + 1) • φ (F j gi))) glist = 0,
rw hφ,
dsimp at h2,
change g • φ (λ (i : fin 1), glist ⟨i.val + 1, _⟩) +
finset.sum (finset.range (1 + 1)) (λ (j : ℕ), (-1 : ℤ) ^ (j + 1) • φ (F j glist)) =
0 at h2,
rw finset.sum_range_succ at h2,
rw finset.sum_range_succ at h2,
rw finset.sum_range_zero at h2,
have H : (-1 : ℤ) ^ (1 + 1) = 1,
norm_num,
rw H at h2,
rw one_smul at h2,
rw ←add_assoc at h2,
rw add_zero at h2,
clear H,
have H : (-1 : ℤ) ^ (0 + 1) = -1,
norm_num,
rw H at h2,
rw neg_one_smul at h2,
clear H,
rw add_neg_eq_zero at h2,
rw eq_comm at h2,
rw add_comm at h2,
convert h2,
{
ext,
cases x with x hx,
cases (nat.sub_eq_zero_of_le hx),
refl,
},
{ ext,
cases x with x hx,
cases (nat.sub_eq_zero_of_le hx),
refl,
},
{ ext,
cases x with x hx,
cases (nat.sub_eq_zero_of_le hx),
refl,
}
end
--theorem lt_succ_self{n j:ℕ }{H:j=nat.succ n}:n<j:=begin rw H, exact nat.lt_succ_self n,end
theorem add_one_finset{n:ℕ }{n'=nat.succ n}{j:fin n }:j.1+1<n'+1:=begin
have h2: n<n',
rw H,
exact nat.lt_succ_self n,
--rw H, exact lt_add_one n,
--have h3: j.val<n',
--exact lt.trans j.is_lt h2,
norm_num,
exact lt.trans j.is_lt h2,
end
--example {a b c d:ℕ }{h1:a<c}{h2:b<d} : (a+b) < (c+b) := begin library_search end
theorem F_0_0(n':ℕ){G : Type*}[group G](g:fin (n'+1+1+1)→ G):F 0 g ⟨0, nat.succ_pos (n'+1)⟩ = g⟨ 0, nat.succ_pos (n'+1+1) ⟩ *g⟨ 1,nat.lt_of_sub_eq_succ rfl⟩ :=
begin
refl,
end
theorem F_0_j{n':ℕ}{j:fin (n'+1)}{G : Type*}[group G](g:fin (n'+1+1+1)→ G):F 0 g⟨ j.val+1,nat.lt_succ_iff.mpr j.is_lt
--norm_num,
--have h3:1<2,
--exact nat.lt_succ_self 1,
--exact add_lt_add (lt.trans j.is_lt h2) h3,
--end
⟩ =g⟨ j.val+2, add_lt_add_right j.is_lt 2⟩:=
begin
refl,
end
theorem F_x_0(n' x:ℕ)(h:x>0){G : Type*}[group G](g:fin (n'+1+1+1)→ G):F x g ⟨0, nat.succ_pos (n'+1)⟩ = g⟨ 0, nat.succ_pos (n'+1+1) ⟩:=
begin
unfold F,
rw if_pos h,
end
theorem F_x_j(n' x:ℕ){G : Type*}[group G](g:fin (n'+1+1+1)→ G):F x (λ (j:fin (n'+1+1)), g ⟨j.val+1, nat.lt_succ_iff.mpr j.is_lt,⟩ )
= λ (j:fin (n'+1)), F (x+1) g⟨j.1+1, nat.lt_succ_iff.mpr j.is_lt,⟩:=
begin
unfold F,
funext,
split_ifs,
{refl},
{exfalso,linarith},
{exfalso,linarith},
{exfalso,linarith},
{refl},
{have h5: k.val+1=x+1,
rw h_1,
contradiction,
},
{exfalso,linarith},
{have h5: k.val=x,
exact nat.succ_inj h_3,
contradiction},
{refl},
end
--example {n m:ℕ }(h:n+1=m+1):n=m:=by library_search
theorem sum_range_first{β : Type*} [_inst_1 : add_comm_monoid β] (f : ℕ → β) (n': ℕ):
sum (range (n'+1)) f = f 0 + sum (range n') (λ i, f (i+1)):=
begin
--induction n' with d hd,
--{refl},
--rw sum_range_suc
rw sum_range_succ',
rw add_comm,
end
theorem sum_add_eq_add_sum {β : Type*} [_inst_1 : add_comm_monoid β] (f g: ℕ → β) (n: ℕ): sum (range n) (λ x, f x+g x)=sum (range n) f+sum(range n) g:=
begin
exact sum_add_distrib,
end
--#check @finset.sum_range_succ'
theorem d_square_zero{n:ℕ}{G : Type*} [group G] {M : Type*} [add_comm_group M] [G_module G M]
(φ: cochain n G M):d.to_fun (d.to_fun φ )=λ(gi: fin (n+2) → G), 0:=
begin
unfold d.to_fun,
funext,
dsimp,
norm_num,
cases n with n',
{ norm_num,
rw sum_range_succ,
rw sum_range_succ,
rw sum_range_zero,
norm_num,
unfold F,
split_ifs,
cases h_1,
{ clear h h_1,
let f : fin 0 → G := λ ⟨i, hi⟩, false.elim (by cases hi),
have hf0 : ∀ f' : fin 0 → G, f' = f,
intro f',
ext i,
cases i.2,
have hf1 : ∀ f' : fin 0 → G, φ f' = φ f,
intro f', rw hf0 f',
conv begin
to_lhs,
congr,
rw hf1,
skip,
congr,
rw hf1,
skip,
congr,
rw hf1,
skip,
congr,
rw hf1,
skip,
congr,
rw hf1,
skip,
congr,
skip,
rw hf1,
end,
simp,
},
cases h_1,
cases h_1,
cases h_2,
dsimp at h, exfalso, apply h, norm_num,
},
-- cases n with 0 n',
rw ←double_sum_zero1 n' G gi _ φ,
unfold F2,
dsimp,
simp only [smul_add],
rw sum_add_eq_add_sum,
rw sum_range_succ' _ (n'+2),
rw F_0_0,
simp only [F_0_j],
rw [zero_add, pow_one, neg_one_smul],
rw <-sub_eq_add_neg,
rw sub_add_eq_add_sub,
apply add_eq_of_eq_sub',
convert sub_add_cancel _ _,
show _ = sum (range (n' + 2))
((λ (x : ℕ),
(-(1 : ℤ )) ^ (x + 1 + 1) • F (x + 1) gi ⟨0, _⟩ • φ (λ (i : fin (nat.succ n')), F (x + 1) gi ⟨i.val + 1, _⟩)))+_,
simp only [F_x_0 _ _ (nat.succ_pos _)],
simp only [(F_x_j n' _ gi).symm],
rw sub_eq_add_neg,
convert add_comm _ _,
{
simp only [(pow_add' _ _ _).symm, nat.succ_eq_add_one],
simp only [(G_module.G_sum_smul _ _ _).symm],
norm_num,
simp only [G_module.neg_one_pow_mul_comm],
},
{
simp only [(finset.sum_smul2 _ _ _).symm],
simp only [nat.succ_eq_add_one, smul_smul,pow_add'],
simp only [(add_assoc _ _ _).symm,(pow_add' _ _ _).symm],
norm_num,
},
end
--#check neg_one_pow_eq_pow_mod_two
variables (n : ℕ) (G : Type*) [group G] (M : Type*) [add_comm_group M] [G_module G M]
instance: add_comm_group (cochain n G M):=
by unfold cochain; apply_instance
lemma sum_cochain {x y :cochain n G M}{F: fin n → G}: (x+y)(F)=x(F)+y(F):=
begin
refl,
end
lemma zero_cochain {v :cochain n G M}: v=0 → ∀ {F: fin n → G}, v(F)=(0:M):=
begin
intros,
exact congr_fun a F,
end
lemma G_module.zero{G : Type*} [group G] {M : Type*} [add_comm_group M]
[G_module G M]
:∀ g : G, g• (0:M) = 0:= begin
intros,
have h: g• (0:M)+g• (0:M)=g• ((0:M)+(0:M)),
rw G_module.linear,
rw add_zero at h,
exact add_left_eq_self.mp h,
end
lemma G_module.neg_one_linear (G : Type*) [group G] {M : Type*} [add_comm_group M]
[G_module G M] (n:ℕ )(m l: M):(-1:ℤ )^(n+1) • (m+l) = (-1:ℤ )^(n+1) • m + (-1:ℤ )^(n+1) • l:=
begin
induction n with d hd,
norm_num,
rw nat.succ_eq_add_one,
rw pow_add,
norm_num,
rw hd,
norm_num,
end
lemma G_module.neg_one_linear_applied {G : Type*}[group G] {M : Type*} [add_comm_group M]
[G_module G M] (i:ℕ )(gi:fin(n+1)→ G)(x y: cochain n G M): (-1:ℤ )^(i+1) • (x(F i gi)+y(F i gi)) = (-1:ℤ )^(i+1) • x(F i gi) + (-1:ℤ )^(i+1) • y(F i gi):=
begin
--have h:(-1:ℤ )^(n+1) • (m+l) = (-1:ℤ )^(n+1) • m + (-1:ℤ )^(n+1) • l,
--exact G_module.neg_one_linear G n m l,
simp only [G_module.neg_one_linear G _ (x(F i gi)) _],
end
def d : add_group_hom (cochain n G M) (cochain (n + 1) G M) :=
{ to_fun := d.to_fun,
map_zero' := begin
unfold d.to_fun,
funext,
have h1: (0:cochain n G M)=0, refl,
have h2: (0:cochain (n+1) G M)=0, refl,
simp only [zero_cochain n G M h1],
rw zero_cochain (n+1) G M h2,
norm_num,
rw G_module.zero,
end,
map_add' := begin
unfold d.to_fun,
intros,
funext,
simp only [sum_cochain, G_module.linear, G_module.neg_one_linear_applied, sum_add_distrib],
rw [add_left_comm, <-add_assoc, add_left_comm, <-add_assoc,add_assoc],
end }
theorem d_square_zero2 :d (n + 1) G M ∘ d n G M = 0 :=
begin
funext,
--dsimp,
show d.to_fun (d.to_fun x) gi=0,
rw d_square_zero x,
end
theorem range_d_sub_ker_d : add_group_hom.range (d n G M) ⊆ add_group_hom.ker (d (n + 1) G M) :=
begin
rintros _ ⟨a, ha, rfl⟩,
show d n G M a ∈ add_group_hom.ker (d (n + 1) G M),
rw add_group_hom.mem_ker,
exact d_square_zero a,
end
example {β : Type*} [_inst_1 : add_comm_monoid β] (f g: ℕ → β)(i:ℕ ) : f i+ g i=((λ (j:ℕ), f j) + λ (j:ℕ ), g j ) i:=rfl
example {β : Type*} [_inst_1 : add_comm_monoid β]{a b c d:β }:a+b+(c+d)=a+c+(b+d):=
begin
rw add_left_comm,
rw <-add_assoc,
rw add_left_comm,
rw <-add_assoc,
rw add_assoc,
end |
1b1b8a08f0d72c081af3d3c8814b271fda5496b5 | 36938939954e91f23dec66a02728db08a7acfcf9 | /lean/deps/typed_smt2/src/galois/smt2/symbol.lean | 443b59283f12a779f8d76fe1cc3c4bfdd93b4a96 | [
"Apache-2.0"
] | permissive | 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 | 12,674 | lean | import galois.algebra.order
import galois.category.except
import galois.data.buffer
import galois.data.fin
import galois.data.sigma
import galois.logic
meta def exact_trivial_tac : tactic unit := `[exact trivial]
open galois
-- Defines the SMT symbol type
namespace smt2
------------------------------------------------------------------------
-- reserved_words
/--
This is the list of reserved words in SMTLIB.
TODO: Add all commands in Section 3.9
-/
def reserved_words : list string :=
[ "BINARY"
, "DECIMAL"
, "HEXADECIMAL"
, "NUMERAL"
, "STRING"
, "_"
, "!"
, "as"
, "let"
, "exists"
, "forall"
, "match"
, "par"
, "assert"
, "check-sat"
, "declare-const"
, "declare-fun"
, "define-fun"
]
--- Reserved words as a list of character buffers.
def reserved_words_buffer : list char_buffer := reserved_words.map string.to_char_buffer
structure reserved_word :=
(buffer : char_buffer)
(proof : buffer ∈ reserved_words_buffer)
--- Predicate that holds if buffer is a reserved word.
def is_reserved_word (b:char_buffer) : Prop :=
b ∈ reserved_words_buffer
namespace is_reserved_word
local attribute [reducible] is_reserved_word
instance decidable : decidable_pred is_reserved_word := by apply_instance
end is_reserved_word
namespace reserved_word
protected def of_buffer (b:char_buffer) (p:is_reserved_word b) : reserved_word := ⟨b, p⟩
protected def repr (w:reserved_word) : string := w.buffer.to_string
instance has_repr : has_repr reserved_word := ⟨reserved_word.repr⟩
/--
Construct a reserved word from a character buffer using the decidability of reserved word membership.
-/
def of_string (s:string) (p:as_true (s ∈ reserved_words) . exact_trivial_tac) : reserved_word :=
let q : s.to_char_buffer ∈ reserved_words_buffer :=
begin
simp [reserved_words_buffer],
apply (Exists.intro s),
simp [of_as_true p],
end in
⟨s.to_char_buffer, q⟩
end reserved_word
------------------------------------------------------------------------
-- is_printable
/-- Predicate that holds if character is considered an SMTLIB printable character. -/
def is_printable (c:char) : Prop := 0x20 ≤ c.val ∧ c.val ≠ 127
namespace is_printable
local attribute [reducible] is_printable
instance decidable_is_printable (c:char) : decidable (is_printable c) := by apply_instance
end is_printable
theorem alpha_is_printable {c:char} : c.is_alpha → is_printable c :=
begin
unfold char.is_alpha, unfold is_printable,
intro isa,
cases isa;
{
simp [char.is_upper, char.is_lower] at isa,
apply and.intro,
{ transitivity, tactic.swap, exact isa.left, exact dec_trivial, },
{ intro eq,
simp [eq] at isa,
exact of_as_false isa trivial,
}
},
end
theorem digit_is_printable {c:char} : c.is_digit → is_printable c :=
begin
unfold char.is_digit, unfold is_printable,
intro isd,
apply and.intro,
{ transitivity, tactic.swap, exact isd.left, exact dec_trivial, },
{ intro eq,
simp [eq] at isd,
exact of_as_false isd trivial,
},
end
------------------------------------------------------------------------
-- is_legal
/-- Legal characters are either printable characters or whitespace. -/
def is_legal (c:char) : Prop := is_printable c ∨ c ∈ ['\t', '\n', '\x0d']
namespace is_legal
local attribute [reducible] is_legal
instance is_legal_decidable (c:char) : decidable (is_legal c) := by apply_instance
end is_legal
------------------------------------------------------------------------
-- symbol
namespace symbol
/-- Check character is allowed in a symbol. -/
def is_symbol_char (c:char) : Prop := is_legal c ∧ c ∉ ['|', '\\']
namespace is_symbol_char
local attribute [reducible] is_symbol_char
instance decidable : decidable_pred is_symbol_char := by apply_instance
end is_symbol_char
/-- A simple symbol character is a quoted symbol. -/
theorem digit_is_symbol_char {c:char}
: char.is_digit c → is_symbol_char c :=
begin
intro h,
unfold is_symbol_char,
unfold is_legal,
apply and.intro,
exact or.inl (digit_is_printable h),
{ intro p, simp at p,
cases p; simp only [p] at h; exact (of_as_false h trivial),
},
end
/-- Check all characters in buffer can appear in quoted symbols. -/
def is_symbol (b:char_buffer) : Prop
:= ∀(i: fin b.size), is_symbol_char (b.read i)
namespace is_symbol
local attribute [reducible] is_symbol
instance decidable : decidable_pred is_symbol := by apply_instance
end is_symbol
end symbol
/-- A symbol is used to identify function or sort names. -/
structure symbol :=
(to_char_buffer : char_buffer)
(valid : symbol.is_symbol to_char_buffer)
namespace symbol
instance decidable_eq : decidable_eq symbol := by tactic.mk_dec_eq_instance
--- Reflexive lexicographic ordering of symbols.
protected def le (x y : symbol) : Prop := x.to_char_buffer ≤ y.to_char_buffer
instance : has_le symbol := ⟨symbol.le⟩
instance decidable_le
: Π(x y : symbol), decidable (x ≤ y)
| ⟨m,a⟩ ⟨n,b⟩ :=
begin
simp [has_le.le, symbol.le],
apply_instance,
end
--- Strict lexicographic ordering of symbols.
protected def lt (x y : symbol) : Prop := x.to_char_buffer < y.to_char_buffer
instance : has_lt symbol := ⟨symbol.lt⟩
instance decidable_lt
: Π(x y : symbol), decidable (x < y)
| ⟨m,a⟩ ⟨n,b⟩ :=
begin
simp [has_lt.lt, symbol.lt],
apply_instance,
end
/- Sizeof always returns a number greater than 0. -/
theorem sizeof_gt0 (s:symbol) : symbol.sizeof s > 0 :=
begin
cases s,
dsimp [symbol.sizeof],
exact dec_trivial,
end
section simple_symbols
/-- Symbol characters allowed in simple symbols -/
def simple_char_symbols : list char :=
['~', '!', '@', '$', '%', '^', '&', '*', '_', '-', '+', '=', '<', '>', '.', '?', '/' ]
/-- Predicate that checks if character is allowed in a simple symbol. -/
inductive is_simple_symbol_char (c:char) : Prop
| is_alpha : char.is_alpha c → is_simple_symbol_char
| is_digit : char.is_digit c → is_simple_symbol_char
| is_other : c ∈ simple_char_symbols → is_simple_symbol_char
-- Show is_simple_symbol_char is decidable.
open is_simple_symbol_char
open decidable
instance is_simple_symbol_char.decidable : decidable_pred is_simple_symbol_char
| c :=
if f : c.is_alpha then
is_true (is_alpha f)
else if g : c.is_digit then
is_true (is_digit g)
else if h : c ∈ simple_char_symbols then
is_true (is_other h)
else
is_false begin intro p, cases p; contradiction, end
/-- A simple symbol character is a quoted symbol. -/
theorem is_simple_symbol_char.is_symbol_char {c:char}
: is_simple_symbol_char c → is_symbol_char c :=
begin
intro h,
cases h,
case is_simple_symbol_char.is_alpha : h {
unfold is_symbol_char,
unfold is_legal,
apply and.intro,
exact or.inl (alpha_is_printable h),
{ intro p, simp at p,
cases p; simp only [p] at h; exact (of_as_false h trivial),
},
},
case is_simple_symbol_char.is_digit : h {
exact digit_is_symbol_char h,
},
case is_simple_symbol_char.is_other : h {
simp [simple_char_symbols] at h,
-- Try all characters and show they are allowed.
iterate { cases h, simp only [h], exact (of_as_true trivial), },
},
end
/-- Return true if this is a valid simple symbol. -/
def is_simple_symbol (b:char_buffer) : Prop
:= b ≠ buffer.nil
∧ ¬(is_reserved_word b)
∧ ∀(i: fin b.size),
let c := b.read i
in is_simple_symbol_char c ∧ (i.val = 0 → ¬(c.is_digit))
local attribute [reducible] is_simple_symbol
instance is_simple_symbol.decidable : decidable_pred is_simple_symbol := by apply_instance
end simple_symbols
------------------------------------------------------------------------
-- repr
section repr
/-- Render a symbol as a simple symbol is possible and quoted symbol otherwise. -/
protected
def repr (s:symbol) : string :=
if is_simple_symbol s.to_char_buffer then
s.to_char_buffer.to_string
else
"|" ++ s.to_char_buffer.to_string ++ "|"
instance : has_repr symbol := ⟨symbol.repr⟩
end repr
------------------------------------------------------------------------
-- Parsing
section parsing
theorem simple_symbol_is_symbol {b:char_buffer} : is_simple_symbol b → is_symbol b := do
begin
simp [is_simple_symbol, is_symbol],
intros is_not_nil is_not_reserved char_pred,
intro i,
let p : is_simple_symbol_char (buffer.read b i) := (char_pred i).left,
exact (is_simple_symbol_char.is_symbol_char p),
end
/--
A quoted symbol with the form "|???|" where '???' denotes
a list of legal characters '|' and '\\'.
-/
def is_quoted_symbol (b:char_buffer) : Prop
:= b.size ≥ 2
∧ ∀(i: fin b.size),
if i.val = 0 ∨ i.val = b.size - 1 then
b.read i = '|'
else
is_symbol_char (b.read i)
theorem is_quoted_symbol.size_ok {b:char_buffer} : is_quoted_symbol b → 1 ≤ b.size - 1 :=
begin
intro is_sym,
apply nat.le_sub_right_of_add_le,
dsimp [nat.add_succ],
dsimp [is_quoted_symbol] at is_sym,
exact is_sym.left,
end
theorem is_quoted_symbol.symbol_ok {b:char_buffer} (is_sym:is_quoted_symbol b)
: is_symbol (buffer.slice b 1 (b.size - 1) (is_quoted_symbol.size_ok is_sym)) :=
begin
dsimp [is_symbol],
intro i,
cases i with i i_lt,
simp only [buffer.read_slice],
--simp [buffer.size_slice] at i_lt,
have i_p_1 : 1 + i < b.size := buffer.slice_index_bound ⟨i, i_lt⟩,
-- Introduce forall constraint
have q := is_sym.right ⟨1 + i, i_p_1⟩,
have pr : ¬(1 + i = 0) := begin simp only [nat.succ_add], contradiction, end,
have min_le : buffer.size b - 1 ≤ buffer.size b := by apply nat.sub_le_self,
have sz_pos : b.size > 0 :=
calc b.size ≥ 2 : is_sym.left
... > 0 : of_as_true trivial,
have qr : ¬(1 + i= buffer.size b - 1),
{ intro q,
simp [buffer.size_slice, min_eq_left min_le] at i_lt,
simp only [nat.lt_sub_left_iff_add_lt, q] at i_lt,
simp [nat.succ_add, nat.sub_succ, nat.succ_pred_eq_of_pos sz_pos, lt_irrefl] at i_lt,
exact i_lt,
},
simp only [fin.val, pr, qr, false_or, if_false] at q,
exact q,
end
local attribute [reducible] is_quoted_symbol
instance is_quoted_symbol.decidable : decidable_pred is_quoted_symbol := by apply_instance
/- This parses the string as a symbol -/
protected
def parse (s:string) : except string symbol := do
let b := s.to_char_buffer,
if pr:is_quoted_symbol b then
pure ⟨ buffer.slice b 1 (b.size - 1) (is_quoted_symbol.size_ok pr)
, is_quoted_symbol.symbol_ok pr
⟩
else if p:is_simple_symbol b then
pure ⟨b, simple_symbol_is_symbol p⟩
else
throw "Invalid symbol"
end parsing
-- meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α
/- Return the value given a proof the result is ok -/
def is_ok_value : Π{e:except string symbol}, except.is_ok e → string
| (except.error l) p := false.elim p
| (except.ok r) p := r.to_char_buffer.to_string
/- Construct a symbol from a string literal. -/
def of_string (nm:string) (p : (symbol.parse nm).is_ok . exact_trivial_tac) : symbol := p.value
axiom by_reflection (α:Prop) : α
/- This generate a symbol from a string using a tactic that runs in the VM. -/
meta def vm_string_tac (s:string) : tactic unit := do
match symbol.parse s with
| (except.error e) :=
tactic.fail e
| (except.ok sym) :=
let r : expr := sym.to_char_buffer.to_string.reflect in
tactic.exact `(smt2.symbol.mk (string.to_char_buffer %%r) (by_reflection _))
end
theorem is_symbol_append {x y : char_buffer}
: is_symbol x → is_symbol y → is_symbol (x ++ y) :=
begin
unfold is_symbol,
intros p q i,
simp only [buffer.read_append],
apply (dite (i.val < buffer.size x)),
{ intro i_lt,
simp [i_lt],
exact (p _),
},
{ intro i_ge,
simp [i_ge],
exact (q _),
}
end
protected def append : symbol → symbol → symbol
| ⟨x,p⟩ ⟨y,q⟩ := ⟨x ++ y, is_symbol_append p q⟩
instance : has_append symbol := ⟨symbol.append⟩
theorem is_symbol_nat (v : ℕ) : is_symbol (string.to_char_buffer (repr v)) :=
begin
unfold is_symbol,
intro i_fin,
cases i_fin with i i_lt,
simp only [buffer.read_to_nth_le],
simp only [repr, has_repr.repr, nat.repr],
simp only [buffer.to_char_buffer_as_string],
simp only [buffer.to_list_to_buffer],
simp only [list.nth_le_reverse_simp],
simp only [list.nth_le_map],
apply digit_is_symbol_char,
apply char.digit_char_is_digit,
exact (nat.nth_to_digits_is_lt (of_as_true trivial) _),
end
/- Construct a symbol from a string literal. -/
def of_nat (v : ℕ) : symbol := ⟨string.to_char_buffer (repr v), is_symbol_nat v⟩
end symbol
end smt2
|
7664c811d2b2800619b039db85e33d298ffd450b | c9ba4946202cfd1e2586e71960dfed00503dcdf4 | /src/meta_k/symbol_schemas.lean | c4875eefbcad0c40d2fc2dabc2bc320233198eb2 | [] | no_license | ammkrn/learning_semantics_of_k | f55f669b369e32ef8407c16521b21ac5c106dc4d | c1487b538e1decc0f1fd389cd36bc36d2da012ab | refs/heads/master | 1,588,081,593,954 | 1,552,449,093,000 | 1,552,449,093,000 | 175,315,800 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 752 | lean | import .meta_sort
import .meta_symbol
import .meta_pattern
import .sort_schemas
-- nil{s} ∈ Σ *, List{S}
def List_nil : #Sort → #Symbol
| s := #symbol "nil" [s] [] (List s)
def List_cons : #Sort → #Symbol
| s := #symbol "cons" [s] [s, List s] (List s)
def List_append : #Sort → #Symbol
| s := ⟨ "append", [s], [List s, List s], (List s) ⟩
--| s := #symbol "append" [s] [List s, List s] (List s)
def empty_map : #Sort → #Sort → #Symbol
| s s' := ⟨ "empty_map", [s, s'], [], (Map s s') ⟩
def bind_map : #Sort → #Sort → #Symbol
| s s' := ⟨ "bind_map", [s, s'], [s, s', Map s s'], (Map s s') ⟩
def merge_map : #Sort → #Sort → #Symbol
| s s' := ⟨ "merge_map", [s, s'], [s, s', Map s s', Map s s'], (Map s s') ⟩
|
15c657cf2f483ca77e90b65734fd236dfee75b21 | 5ec8f5218a7c8e87dd0d70dc6b715b36d61a8d61 | /ctypes.lean | 2fa9af937e61b6f81698bb99b843b3e734b68838 | [] | no_license | mbrodersen/kremlin | f9f2f9dd77b9744fe0ffd5f70d9fa0f1f8bd8cec | d4665929ce9012e93a0b05fc7063b96256bab86f | refs/heads/master | 1,624,057,268,130 | 1,496,957,084,000 | 1,496,957,084,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 35,155 | lean | import .ast .errors .linking
/- Type expressions for the Compcert C and Clight languages -/
namespace ctypes
open ast maps errors linking
open ast.external_function ast.memory_chunk
/- Compcert C types are similar to those of C. They include numeric types,
pointers, arrays, function types, and composite types (struct and
union). Numeric types (integers and floats) fully specify the
bit size of the type. An integer type is a pair of a signed/unsigned
flag and a bit size: 8, 16, or 32 bits, or the special [IBool] size
standing for the C99 [_Bool] type. 64-bit integers are treated separately. -/
inductive signedness : Type
| Signed : signedness
| Unsigned : signedness
open signedness
inductive intsize : Type
| I8 : intsize
| I16 : intsize
| I32 : intsize
| IBool : intsize
open intsize
/- Float types come in two sizes: 32 bits (single precision)
and 64-bit (double precision). -/
inductive floatsize : Type
| F32 : floatsize
| F64 : floatsize
open floatsize
/- Every type carries a set of attributes. Currently, only two
attributes are modeled: [volatile] and [_Alignas(n)] (from ISO C 2011). -/
structure attr : Type :=
(attr_volatile : bool)
(attr_alignas : option ℕ) /- log2 of required alignment -/
instance attr_eq : decidable_eq attr := by tactic.mk_dec_eq_instance
def noattr : attr := { attr_volatile := false, attr_alignas := none }
/- The syntax of type expressions. some points to note:
- Array types [Tarray n] carry the size [n] of the array.
Arrays with unknown sizes are represented by pointer types.
- Function types [Tfunction targs tres] specify the number and types
of the function arguments (list [targs]), and the type of the
function result ([tres]). Variadic functions and old-style unprototyped
functions are not supported.
-/
inductive type : Type
| Tvoid : type /- the [void] type -/
| Tint : intsize → signedness → attr → type /- integer types -/
| Tlong : signedness → attr → type /- 64-bit integer types -/
| Tfloat : floatsize → attr → type /- floating-point types -/
| Tpointer : type → attr → type /- pointer types ([*ty]) -/
| Tarray : type → ℕ → attr → type /- array types ([ty[len]]) -/
| Tfunction : list type → type → calling_convention → type /- function types -/
| Tstruct : ident → attr → type /- struct types -/
| Tunion : ident → attr → type /- union types -/
export type
instance intsize_eq : decidable_eq intsize := by tactic.mk_dec_eq_instance
instance type_eq : decidable_eq type := sorry' --by tactic.mk_dec_eq_instance
/- Extract the attributes of a type. -/
def attr_of_type : type → attr
| Tvoid := noattr
| (Tint sz si a) := a
| (Tlong si a) := a
| (Tfloat sz a) := a
| (Tpointer elt a) := a
| (Tarray elt sz a) := a
| (Tfunction args res cc) := noattr
| (Tstruct id a) := a
| (Tunion id a) := a
/- Change the top-level attributes of a type -/
def change_attributes (f : attr → attr) : type → type
| (Tint sz si a) := Tint sz si (f a)
| (Tlong si a) := Tlong si (f a)
| (Tfloat sz a) := Tfloat sz (f a)
| (Tpointer elt a) := Tpointer elt (f a)
| (Tarray elt sz a) := Tarray elt sz (f a)
| (Tstruct id a) := Tstruct id (f a)
| (Tunion id a) := Tunion id (f a)
| ty := ty
/- Erase the top-level attributes of a type -/
def remove_attributes (ty : type) : type :=
change_attributes (λ_, noattr) ty
/- Add extra attributes to the top-level attributes of a type -/
def attr_union (a1 a2 : attr) : attr :=
{ attr_volatile := a1.attr_volatile || a2.attr_volatile,
attr_alignas :=
match a1.attr_alignas, a2.attr_alignas with
| none, al := al
| al, none := al
| some n1, some n2 := some (max n1 n2)
end }
def merge_attributes (ty : type) (a : attr) : type :=
change_attributes (attr_union a) ty
/- Syntax for [struct] and [union] definitions. [struct] and [union]
are collectively called "composites". Each compilation unit
comes with a list of top-level definitions of composites. -/
inductive struct_or_union : Type | struct | union
instance struct_or_union_eq : decidable_eq struct_or_union := by tactic.mk_dec_eq_instance
def members : Type := list (ident × type).
instance : has_mem (ident × type) members := ⟨@has_mem.mem _ (list _) _⟩
structure composite_definition : Type :=
(id : ident) (su : struct_or_union) (m : members) (a : attr)
def name_composite_def : composite_definition → ident :=
composite_definition.id
instance composite_def_eq : decidable_eq composite_definition := by tactic.mk_dec_eq_instance
/- For type-checking, compilation and semantics purposes, the composite
definitions are collected in the following [composite_env] environment.
The [composite] record contains additional information compared with
the [composite_definition], such as size and alignment information. -/
structure composite : Type :=
(co_su : struct_or_union)
(co_members : members)
(co_attr : attr)
(co_sizeof : ℕ)
(co_alignof : ℕ)
(co_rank : ℕ)
(co_alignof_two_p : ∃ n, co_alignof = 2^n)
(co_sizeof_alignof : co_alignof ∣ co_sizeof)
open composite
def composite_env : Type := PTree composite
/- * Operations over types -/
/- ** Conversions -/
def type_int32s := Tint I32 Signed noattr
def type_bool := Tint IBool Signed noattr
/- The usual unary conversion. Promotes small integer types to [signed int32]
and degrades array types and function types to pointer types.
Attributes are erased. -/
def typeconv (ty : type) : type :=
match ty with
| Tint I8 _ _ := Tint I32 Signed noattr
| Tint I16 _ _ := Tint I32 Signed noattr
| Tint IBool _ _ := Tint I32 Signed noattr
| Tarray t sz a := Tpointer t noattr
| Tfunction _ _ _ := Tpointer ty noattr
| _ := remove_attributes ty
end
/- Default conversion for arguments to an unprototyped or variadic function.
Like [typeconv] but also converts single floats to double floats. -/
def default_argument_conversion (ty : type) : type :=
match ty with
| Tint I8 _ _ := Tint I32 Signed noattr
| Tint I16 _ _ := Tint I32 Signed noattr
| Tint IBool _ _ := Tint I32 Signed noattr
| Tfloat _ _ := Tfloat F64 noattr
| Tarray t sz a := Tpointer t noattr
| Tfunction _ _ _ := Tpointer ty noattr
| _ := remove_attributes ty
end
/- ** Complete types -/
/- A type is complete if it fully describes an object.
All struct and union names appearing in the type must be defined,
unless they occur under a pointer or function type. [void] and
function types are incomplete types. -/
def complete_type (env : composite_env) : type → bool
| Tvoid := ff
| (Tint _ _ _) := tt
| (Tlong _ _) := tt
| (Tfloat _ _) := tt
| (Tpointer _ _) := tt
| (Tarray t' _ _) := complete_type t'
| (Tfunction _ _ _) := ff
| (Tstruct id _) := (env^!id).is_some
| (Tunion id _) := (env^!id).is_some
def complete_or_function_type (env : composite_env) : type → bool
| (Tfunction _ _ _) := true
| t := complete_type env t
/- ** Alignment of a type -/
/- Adjust the natural alignment [al] based on the attributes [a] attached
to the type. If an "alignas" attribute is given, use it as alignment
in preference to [al]. -/
def align_attr (a : attr) (al : ℕ) : ℕ :=
match a.attr_alignas with
| some l := 2^l
| none := al
end
/- In the ISO C standard, alignment is defined only for complete
types. However, it is convenient that [alignof] is a total
function. For incomplete types, it returns 1. -/
def alignof_inner (env : composite_env) : type → ℕ
| Tvoid := 1
| (Tint I8 _ _) := 1
| (Tint I16 _ _) := 2
| (Tint I32 _ _) := 4
| (Tint IBool _ _) := 1
| (Tlong _ _) := archi.align_int64
| (Tfloat F32 _) := 4
| (Tfloat F64 _) := archi.align_float64
| (Tpointer _ _) := if archi.ptr64 then 8 else 4
| (Tarray t' _ _) := align_attr (attr_of_type t') (alignof_inner t')
| (Tfunction _ _ _) := 1
| (Tstruct id _) := match env^!id with some co := co_alignof co | none := 1 end
| (Tunion id _) := match env^!id with some co := co_alignof co | none := 1 end
def alignof (env : composite_env) (t : type) : ℕ :=
align_attr (attr_of_type t) (alignof_inner env t)
theorem align_attr_two_p (al a) :
(∃ n, al = 2^n) →
(∃ n, align_attr a al = 2^n) := sorry'
theorem alignof_two_p (env t) : ∃ n, alignof env t = 2^n := sorry'
theorem alignof_pos (env t) : alignof env t > 0 := sorry'
/- ** Size of a type -/
/- In the ISO C standard, size is defined only for complete
types. However, it is convenient that [sizeof] is a total
function. For [void] and function types, we follow GCC and define
their size to be 1. For undefined structures and unions, the size is
arbitrarily taken to be 0.
-/
def sizeof (env: composite_env) : type → ℕ
| Tvoid := 1
| (Tint I8 _ _) := 1
| (Tint I16 _ _) := 2
| (Tint I32 _ _) := 4
| (Tint IBool _ _) := 1
| (Tlong _ _) := 8
| (Tfloat F32 _) := 4
| (Tfloat F64 _) := 8
| (Tpointer _ _) := if archi.ptr64 then 8 else 4
| (Tarray t' n _) := sizeof t' * n
| (Tfunction _ _ _) := 1
| (Tstruct id _) := match env^!id with some co := co_sizeof co | none := 0 end
| (Tunion id _) := match env^!id with some co := co_sizeof co | none := 0 end
lemma sizeof_pos (env t) : sizeof env t >= 0 := sorry'
/- The size of a type is an integral multiple of its alignment,
unless the alignment was artificially increased with the [__Alignas]
attribute. -/
def naturally_aligned : type → Prop
| (Tarray t' _ a) := attr.attr_alignas a = none ∧ naturally_aligned t'
| t := attr.attr_alignas (attr_of_type t) = none
lemma sizeof_alignof_compat (env t) (h : naturally_aligned t) :
alignof env t ∣ sizeof env t := sorry'
/- ** Size and alignment for composite definitions -/
/- The alignment for a structure or union is the max of the alignment
of its members. -/
def alignof_composite (env : composite_env) : members → ℕ
| [] := 1
| ((id, t) :: m') := max (alignof env t) (alignof_composite m')
/- The size of a structure corresponds to its layout: fields are
laid out consecutively, and padding is inserted to align
each field to the alignment for its type. -/
def sizeof_struct (env : composite_env) : ℕ → members → ℕ
| cur [] := cur
| cur ((id, t) :: m') := sizeof_struct (align cur (alignof env t) + sizeof env t) m'
/- The size of an union is the max of the sizes of its members. -/
def sizeof_union (env : composite_env) : members → ℕ
| [] := 0
| ((id, t) :: m') := max (sizeof env t) (sizeof_union m')
lemma alignof_composite_two_p (env m) : ∃ n, alignof_composite env m = 2^n := sorry'
lemma alignof_composite_pos (env m a) : align_attr a (alignof_composite env m) > 0 := sorry'
lemma sizeof_struct_incr (env m cur) : cur ≤ sizeof_struct env cur m := sorry'
lemma sizeof_union_pos (env m) : 0 ≤ sizeof_union env m := sorry'
/- ** Byte offset for a field of a structure -/
/- [field_offset env id fld] returns the byte offset for field [id]
in a structure whose members are [fld]. Fields are laid out
consecutively, and padding is inserted to align each field to the
alignment for its type. -/
def field_offset_rec (env : composite_env) (id : ident) : members → ℕ → res ℕ
| [] pos := error [MSG "Unknown field ", CTX id]
| ((id', t) :: fld') pos :=
if id = id'
then OK (align pos (alignof env t))
else field_offset_rec fld' (align pos (alignof env t) + sizeof env t)
def field_offset (env : composite_env) (id : ident) (fld : members) : res ℕ :=
field_offset_rec env id fld 0
def field_type (id : ident) : members → res type
| [] := error [MSG "Unknown field ", CTX id]
| ((id', t) :: fld') := if id = id' then OK t else field_type fld'
/- some sanity checks about field offsets. First, field offsets are
within the range of acceptable offsets. -/
theorem field_offset_rec_in_range (env id ofs ty fld pos) :
field_offset_rec env id fld pos = OK ofs → field_type id fld = OK ty →
pos ≤ ofs ∧ ofs + sizeof env ty ≤ sizeof_struct env pos fld := sorry'
lemma field_offset_in_range (env fld id ofs ty) :
field_offset env id fld = OK ofs → field_type id fld = OK ty →
0 ≤ ofs ∧ ofs + sizeof env ty ≤ sizeof_struct env 0 fld := sorry'
/- Second, two distinct fields do not overlap -/
lemma field_offset_no_overlap (env id1 ofs1 ty1 id2 ofs2 ty2 fld) :
field_offset env id1 fld = OK ofs1 → field_type id1 fld = OK ty1 →
field_offset env id2 fld = OK ofs2 → field_type id2 fld = OK ty2 →
id1 ≠ id2 → ofs1 + sizeof env ty1 ≤ ofs2 ∨ ofs2 + sizeof env ty2 ≤ ofs1 := sorry'
/- Third, if a struct is a prefix of another, the offsets of common fields
are the same. -/
lemma field_offset_prefix (env id ofs fld2 fld1) :
field_offset env id fld1 = OK ofs →
field_offset env id (fld1 ++ fld2 : list _) = OK ofs := sorry'
/- Fourth, the position of each field respects its alignment. -/
lemma field_offset_aligned (env id fld ofs ty) :
field_offset env id fld = OK ofs → field_type id fld = OK ty →
↑(alignof env ty) ∣ ofs := sorry'
/- ** Access modes -/
/- The [access_mode] function describes how a l-value of the given
type must be accessed:
- [By_value ch]: access by value, i.e. by loading from the address
of the l-value using the memory chunk [ch];
- [By_reference]: access by reference, i.e. by just returning
the address of the l-value (used for arrays and functions);
- [By_copy]: access is by reference, assignment is by copy
(used for [struct] and [union] types)
- [By_nothing]: no access is possible, e.g. for the [void] type.
-/
inductive mode : Type
| By_value : memory_chunk → mode
| By_reference : mode
| By_copy : mode
| By_nothing : mode
open mode ast.memory_chunk
def access_mode : type → mode
| (Tint I8 Signed _) := By_value Mint8signed
| (Tint I8 Unsigned _) := By_value Mint8unsigned
| (Tint I16 Signed _) := By_value Mint16signed
| (Tint I16 Unsigned _) := By_value Mint16unsigned
| (Tint I32 _ _) := By_value Mint32
| (Tint IBool _ _) := By_value Mint8unsigned
| (Tlong _ _) := By_value Mint64
| (Tfloat F32 _) := By_value Mfloat32
| (Tfloat F64 _) := By_value Mfloat64
| (Tvoid) := By_nothing
| (Tpointer _ _) := By_value Mptr
| (Tarray _ _ _) := By_reference
| (Tfunction _ _ _) := By_reference
| (Tstruct _ _) := By_copy
| (Tunion _ _) := By_copy
/- For the purposes of the semantics and the compiler, a type denotes
a volatile access if it carries the [volatile] attribute and it is
accessed by value. -/
def type_is_volatile (ty: type) : bool :=
match access_mode ty with
| By_value _ := attr.attr_volatile (attr_of_type ty)
| _ := false
end.
/- ** Alignment for block copy operations -/
/- A variant of [alignof] for use in block copy operations.
Block copy operations do not support alignments greater than 8,
and require the size to be an integral multiple of the alignment. -/
def alignof_blockcopy (env : composite_env) : type → ℤ
| Tvoid := 1
| (Tint I8 _ _) := 1
| (Tint I16 _ _) := 2
| (Tint I32 _ _) := 4
| (Tint IBool _ _) := 1
| (Tlong _ _) := 8
| (Tfloat F32 _) := 4
| (Tfloat F64 _) := 8
| (Tpointer _ _) := if archi.ptr64 then 8 else 4
| (Tarray t' _ _) := alignof_blockcopy t'
| (Tfunction _ _ _) := 1
| (Tstruct id _ ) := match env^!id with some co := min 8 (co_alignof co) | none := 1 end
| (Tunion id _) := match env^!id with some co := min 8 (co_alignof co) | none := 1 end
lemma alignof_blockcopy_1248 (env ty) :
let a := alignof_blockcopy env ty in
a = 1 ∨ a = 2 ∨ a = 4 ∨ a = 8 := sorry'
lemma alignof_blockcopy_pos (env ty) : alignof_blockcopy env ty > 0 := sorry'
lemma sizeof_alignof_blockcopy_compat (env ty) :
alignof_blockcopy env ty ∣ sizeof env ty := sorry'
/- Type ranks -/
/- The rank of a type is a nonnegative integer that measures the direct nesting
of arrays, struct and union types. It does not take into account indirect
nesting such as a struct type that appears under a pointer or function type.
Type ranks ensure that type expressions (ignoring pointer and function types)
have an inductive structure. -/
def rank_type (ce : composite_env) : type → nat
| (Tarray t' _ _) := rank_type t' + 1
| (Tstruct id _) :=
match ce^!id with
| none := 0
| some co := co_rank co + 1
end
| (Tunion id _) :=
match ce^!id with
| none := 0
| some co := co_rank co + 1
end
| _ := 0
def rank_members (ce : composite_env) : members → nat
| [] := 0
| ((id, t) :: m) := max (rank_type ce t) (rank_members m)
/- ** C types and back-end types -/
/- Extracting a type list from a function parameter declaration. -/
def type_of_params : list (ident × type) → list type
| [] := []
| ((id, ty) :: rem) := ty :: type_of_params rem
/- Translating C types to Cminor types and function signatures. -/
def typ_of_type : type → ast.typ
| Tvoid := ast.typ.Tint
| (Tint _ _ _) := ast.typ.Tint
| (Tlong _ _) := ast.typ.Tlong
| (Tfloat F32 _) := ast.typ.Tsingle
| (Tfloat F64 _) := ast.typ.Tfloat
| (Tpointer _ _) := ast.typ.Tptr
| (Tarray _ _ _) := ast.typ.Tptr
| (Tfunction _ _ _) := ast.typ.Tptr
| (Tstruct _ _) := ast.typ.Tptr
| (Tunion _ _) := ast.typ.Tptr
def opttyp_of_type (t : type) : option ast.typ :=
if t = Tvoid then none else some (typ_of_type t)
def typlist_of_typelist (l : list type) : list ast.typ := l.map typ_of_type
def signature_of_type (args : list type) (res : type) (cc : calling_convention) : signature :=
signature.mk (args.map typ_of_type) (opttyp_of_type res) cc
/- * Construction of the composite environment -/
def sizeof_composite (env : composite_env) : struct_or_union → members → ℕ
| struct_or_union.struct := sizeof_struct env 0
| struct_or_union.union := sizeof_union env
lemma sizeof_composite_pos (env su m) : 0 ≤ sizeof_composite env su m := sorry'
def complete_members (env : composite_env) : members → bool
| [] := true
| ((id, t) :: m') := complete_type env t && complete_members m'
lemma complete_member (env) (id : ident) (t m) :
(id, t) ∈ m →
complete_members env m = true →
complete_type env t = true := sorry'
/- Convert a composite def to its internal representation.
The size and alignment of the composite are determined at this time.
The alignment takes into account the [__Alignas] attributes
associated with the def. The size is rounded up to a multiple
of the alignment.
The conversion fails if a type of a member is not complete. This rules
out incorrect recursive definitions such as
<<
struct s { int x; struct s next; }
>>
Here, when we process the def of [struct s], the identifier [s]
is not bound yet in the composite environment, hence field [next]
has an incomplete type. However, recursions that go through a pointer type
are correctly handled:
<<
struct s { int x; struct s * next; }
>>
Here, [next] has a pointer type, which is always complete, even though
[s] is not yet bound to a composite.
-/
def composite_of_def (env : composite_env) (id : ident) (su : struct_or_union)
(m : members) (a : attr) : res composite :=
match env^!id, complete_members env m with
| some _, _ :=
error [MSG "Multiple definitions of struct or union ", CTX id]
| none, ff :=
error [MSG "Incomplete struct or union ", CTX id]
| none, tt :=
let al := align_attr a (alignof_composite env m) in
OK { co_su := su,
co_members := m,
co_attr := a,
co_sizeof := align (sizeof_composite env su m) al,
co_alignof := al,
co_rank := rank_members env m,
co_alignof_two_p := sorry',
co_sizeof_alignof := sorry' }
end
/- The composite environment for a program is obtained by entering
its composite definitions in sequence. The definitions are assumed
to be listed in dependency order: the def of a composite
must precede all uses of this composite, unless the use is under
a pointer or function type. -/
def add_composite_definitions : composite_env →
list composite_definition → res composite_env
| env [] := OK env
| env (⟨id, su, m, a⟩ :: defs) :=
do co ← composite_of_def env id su m a,
add_composite_definitions (PTree.set id co env) defs
def build_composite_env (defs: list composite_definition) :=
add_composite_definitions (∅ : PTree _) defs.
/- Stability properties for alignments, sizes, and ranks. If the type is
complete in a composite environment [env], its size, alignment, and rank
are unchanged if we add more definitions to [env]. -/
section stability
variables env env': composite_env
variable h : ∀ id co, (env^!id) = some co → (env'^!id) = some co
lemma alignof_stable (t) : complete_type env t →
alignof env' t = alignof env t := sorry'
lemma sizeof_stable (t) : complete_type env t →
sizeof env' t = sizeof env t := sorry'
lemma complete_type_stable (t) : complete_type env t →
complete_type env' t := sorry'
lemma rank_type_stable (t) : complete_type env t →
rank_type env' t = rank_type env t := sorry'
lemma alignof_composite_stable (m) : complete_members env m →
alignof_composite env' m = alignof_composite env m := sorry'
lemma sizeof_struct_stable (m pos) : complete_members env m →
sizeof_struct env' pos m = sizeof_struct env pos m := sorry'
lemma sizeof_union_stable (m) : complete_members env m →
sizeof_union env' m = sizeof_union env m := sorry'
lemma sizeof_composite_stable (su m) : complete_members env m →
sizeof_composite env' su m = sizeof_composite env su m := sorry'
lemma complete_members_stable (m) : complete_members env m →
complete_members env' m := sorry'
lemma rank_members_stable (m) : complete_members env m →
rank_members env' m = rank_members env m := sorry'
end stability
lemma add_composite_definitions_incr (id co defs env1 env2) :
add_composite_definitions env1 defs = OK env2 →
(env1^!id) = some co → (env2^!id) = some co := sorry'
/- It follows that the sizes and alignments contained in the composite
environment produced by [build_composite_env] are consistent with
the sizes and alignments of the members of the composite types. -/
structure composite_consistent (env : composite_env) (co : composite) : Prop :=
(co_consistent_complete :
complete_members env (co_members co))
(co_consistent_alignof :
co_alignof co = align_attr (co_attr co) (alignof_composite env (co_members co)))
(co_consistent_sizeof:
co_sizeof co = align (sizeof_composite env (co_su co) (co_members co)) (co_alignof co))
(co_consistent_rank:
co_rank co = rank_members env (co_members co))
def composite_env_consistent (env: composite_env) : Prop :=
∀ id co, (env^!id) = some co → composite_consistent env co
lemma composite_consistent_stable (env env': composite_env)
(ext : ∀ id co, (env^!id) = some co → (env'^!id) = some co)
(co) : composite_consistent env co → composite_consistent env' co := sorry'
lemma composite_of_def_consistent (env id su m a co) :
composite_of_def env id su m a = OK co →
composite_consistent env co := sorry'
theorem build_composite_env_consistent (defs env) :
build_composite_env defs = OK env → composite_env_consistent env := sorry'
/- Moreover, every composite def is reflected in the composite environment. -/
theorem build_composite_env_charact (id su m a defs env) :
build_composite_env defs = OK env →
composite_definition.mk id su m a ∈ defs →
∃ co, (env^!id) = some co ∧ co_members co = m ∧
co_attr co = a ∧ co_su co = su := sorry'
theorem build_composite_env_domain (env defs id co) :
build_composite_env defs = OK env →
(env^!id) = some co →
composite_definition.mk id (co_su co) (co_members co) (co_attr co) ∈ defs := sorry'
/- As a corollay, in a consistent environment, the rank of a composite type
is strictly greater than the ranks of its member types. -/
theorem rank_type_members (ce id t m) : (id, t) ∈ m →
rank_type ce t ≤ rank_members ce m := sorry'
lemma rank_struct_member (ce id a co id1 t1) :
composite_env_consistent ce →
(ce^!id) = some co →
(id1, t1) ∈ co_members co →
rank_type ce t1 < rank_type ce (Tstruct id a) := sorry'
lemma rank_union_member (ce id a co id1 t1) :
composite_env_consistent ce →
(ce^!id) = some co →
(id1, t1) ∈ co_members co →
rank_type ce t1 < rank_type ce (Tunion id a) := sorry'
/- * Programs and compilation units -/
/- The definitions in this section are parameterized over a type [F] of
internal function definitions, so that they apply both to CompCert C and to Clight. -/
section programs
/- Functions can either be defined ([Internal]) or declared as
external functions ([External]). -/
inductive fundef (F : Type) : Type
| Internal : F → fundef
| External {} : external_function → list type → type → calling_convention → fundef
/- A program, or compilation unit, is composed of:
- a list of definitions of functions and global variables;
- the names of functions and global variables that are public (not static);
- the name of the function that acts as entry point ("main" function).
- a list of definitions for structure and union names
- the corresponding composite environment
- a proof that this environment is consistent with the definitions. -/
structure program (F : Type) : Type :=
(defs: list (ident × globdef (fundef F) type))
(public: list ident)
(main: ident)
(types: list composite_definition)
(comp_env: composite_env)
(comp_env_eq: build_composite_env types = OK comp_env)
def program_of_program {F} (p : program F) : ast.program (fundef F) type :=
{ defs := p.defs,
public := p.public,
main := p.main }
instance {F} : has_coe (program F) (ast.program (fundef F) type) := ⟨program_of_program⟩
def make_program {F} (types: list composite_definition)
(defs: list (ident × globdef (fundef F) type))
(public: list ident)
(main: ident) : res (program F) :=
match _, rfl : ∀ r, build_composite_env types = r → _ with
| error e, h := error e
| OK ce, h :=
OK { defs := defs,
public := public,
main := main,
types := types,
comp_env := ce,
comp_env_eq := h }
end
end programs
open fundef
/- * Separate compilation and linking -/
/- ** Linking types -/
instance linker_types : linker type :=
{ link := λ t1 t2, if t1 = t2 then some t1 else none,
linkorder := (=),
linkorder_refl := eq.refl,
linkorder_trans := @eq.trans _,
link_linkorder := λt1 t2 t3, begin
by_cases (t1 = t2) with h1; intro h2; simp [h1] at h2,
{ injection h2, exact ⟨h1.trans h, h⟩ },
{ contradiction } end }
/- ** Linking composite definitions -/
def check_compat_composite (l : list composite_definition) (cd : composite_definition) : bool :=
l.all (λ cd', if name_composite_def cd' = name_composite_def cd then cd = cd' else tt)
def filter_redefs (l1 l2 : list composite_definition) :=
let names1 := l1.map name_composite_def in
l2.filter (λ cd, name_composite_def cd ∉ names1)
def link_composite_defs (l1 l2 : list composite_definition) : option (list composite_definition) :=
if l1.all (check_compat_composite l2)
then some (l1 ++ filter_redefs l1 l2)
else none
lemma link_composite_def_inv {l1 l2 l} (h : link_composite_defs l1 l2 = some l) :
(∀ cd1 ∈ l1, ∀ cd2 ∈ l2, name_composite_def cd2 = name_composite_def cd1 → cd2 = cd1)
∧ l = l1 ++ filter_redefs l1 l2
∧ (∀ {x}, x ∈ l ↔ x ∈ l1 ∨ x ∈ l2) := sorry'
instance Linker_composite_defs : linker (list composite_definition) :=
{ link := link_composite_defs,
linkorder := (⊆),
linkorder_refl := list.subset.refl,
linkorder_trans := @list.subset.trans _,
link_linkorder := λl1 l2 l h,
let ⟨_, _, C⟩ := link_composite_def_inv h in
⟨λx h, C.2 (or.inl h), λx h, C.2 (or.inr h)⟩ }
/- Connections with [build_composite_env]. -/
lemma add_composite_definitions_append (l1 l2 env env'') :
add_composite_definitions env (l1 ++ l2) = OK env'' ↔
∃ env', add_composite_definitions env l1 = OK env' ∧
add_composite_definitions env' l2 = OK env'' := sorry'
lemma composite_of_def_eq (env id co) :
composite_consistent env co →
(env^!id) = none →
composite_of_def env id (co_su co) (co_members co) (co_attr co) = OK co := sorry'
lemma composite_consistent_unique {env co1 co2} :
composite_consistent env co1 →
composite_consistent env co2 →
co_su co1 = co_su co2 →
co_members co1 = co_members co2 →
co_attr co1 = co_attr co2 →
co1 = co2 := sorry'
lemma composite_of_def_stable {env env'}
(ext : ∀ id co, (env^!id) = some co → (env'^!id) = some co)
{id su m a co}
(hn : (env'^!id) = none)
(ce : composite_of_def env id su m a = OK co) :
composite_of_def env' id su m a = OK co := sorry'
def link_add_composite_definitions {l0 env0}
(hl0 : build_composite_env l0 = OK env0) :
∀ {l env1 env1' env2}
(acd : add_composite_definitions env1 l = OK env1')
(agree1 : ∀ id co, (env1^!id) = some co → (env2^!id) = some co)
(agree0 : ∀ id co, (env0^!id) = some co → (env2^!id) = some co)
(agree2 : ∀ id : ident, (env2^!id) = if id ∈ l0.map name_composite_def then env0^!id else env1^!id)
(uniq : ∀ cd1 ∈ l0, ∀ cd2 ∈ l, name_composite_def cd2 = name_composite_def cd1 → cd2 = cd1),
{env2' // add_composite_definitions env2 (filter_redefs l0 l) = OK env2' ∧
(∀ (id : ident) co, (env1'^!id) = some co → (env2'^!id) = some co) ∧
(∀ (id : ident) co, (env0^!id) = some co → (env2'^!id) = some co)} :=
begin
dsimp [filter_redefs], intro l, induction l with co l IH; intros,
{ note : OK env1 = OK env1' := acd, injection this with this,
rw -this, exact ⟨env2, rfl, agree1, agree0⟩ },
cases co with id su m a,
simp [add_composite_definitions] at acd,
revert acd,
ginduction composite_of_def env1 id su m a with h co; intro,
{ by_cases name_composite_def ⟨id, su, m, a⟩ ∉ list.map name_composite_def l0 with hel;
simp [hel, list.filter, add_composite_definitions];
simp [name_composite_def] at hel,
{ note i2 := agree2 id,
simp [name_composite_def, hel] at i2,
exact let ⟨env2', _⟩ := @IH _ _ (PTree.set id co env2) acd sorry' sorry' sorry' sorry' in
⟨env2', sorry'⟩
},
{ note i2 := agree2 id,
simp [name_composite_def, decidable.by_contradiction hel] at i2,
exact let ⟨env2', _⟩ := @IH _ _ env2 acd sorry' sorry' sorry' sorry' in
⟨env2', sorry'⟩ } },
{ note := (acd : error _ = OK _), contradiction }
end
def link_build_composite_env {l1 l2 l env1 env2}
(hl1 : build_composite_env l1 = OK env1)
(hl2 : build_composite_env l2 = OK env2)
(hl : link l1 l2 = some l) :
{env // build_composite_env l = OK env ∧
(∀ (id : ident) co, (env1^!id) = some co → (env^!id) = some co) ∧
(∀ (id : ident) co, (env2^!id) = some co → (env^!id) = some co)} :=
let ⟨A, B, C⟩ := link_composite_def_inv hl in
let ⟨env, P, Q, R⟩ := begin
apply link_add_composite_definitions,
{ exact hl1 },
{ exact hl2 },
{ intros, rw PTree.gempty at a, contradiction },
{ intros, assumption },
{ intros,
by_cases (id ∈ list.map name_composite_def l1) with hel; simp [hel],
{ rw PTree.gempty, exact sorry' } },
{ assumption }
end in
⟨env, sorry', R, Q⟩
/- ** Linking function definitions -/
def link_fundef {F : Type} : fundef F → fundef F → option (fundef F)
| (Internal _) (Internal _) := none
| (External ef1 targs1 tres1 cc1) (External ef2 targs2 tres2 cc2) :=
if ef1 = ef2 ∧ targs1 = targs2 ∧ tres1 = tres2 ∧ cc1 = cc2
then some (External ef1 targs1 tres1 cc1)
else none
| (Internal f) (External (EF_external id sg) targs tres cc) := some (Internal f)
| (Internal f) (External _ targs tres cc) := none
| (External (EF_external id sg) targs tres cc) (Internal f) := some (Internal f)
| (External _ targs tres cc) (Internal f) := none
inductive linkorder_fundef {F : Type} : fundef F → fundef F → Prop
| refl (fd) : linkorder_fundef fd fd
| ext_int (f id sg targs tres cc) :
linkorder_fundef (External (EF_external id sg) targs tres cc) (Internal f)
instance Linker_fundef (F: Type) : linker (fundef F) :=
{ link := link_fundef,
linkorder := linkorder_fundef,
linkorder_refl := linkorder_fundef.refl,
linkorder_trans := λ x y z h1 h2, begin
induction h1, exact h2,
revert h2, generalize2 (Internal f) If hif, intro h2,
induction h2,
{ rw -hif, apply linkorder_fundef.ext_int },
{ contradiction }
end,
link_linkorder := sorry' }
theorem link_fundef_either {F : Type} {f1 f2 f : fundef F} : link f1 f2 = some f → f = f1 ∨ f = f2 := sorry'
/- ** Linking programs -/
def lift_option {A : Type} : Π (opt : option A), psum { x // opt = some x } (opt = none)
| (some x) := psum.inl ⟨x, rfl⟩
| none := psum.inr rfl
def link_program {F} (p1 p2 : program F) : option (program F) :=
match link (program_of_program p1) (program_of_program p2) with
| none := none
| some p :=
match _, rfl : ∀ o, link p1.types p2.types = o → _ with
| none, _ := none
| some typs, EQ :=
let ⟨env, P, Q⟩ := link_build_composite_env p1.comp_env_eq p2.comp_env_eq EQ in
some { defs := p.defs,
public := p.public,
main := p.main,
types := typs,
comp_env := env,
comp_env_eq := P }
end
end
def linkorder_program {F} (p1 p2: program F) : Prop :=
linkorder (program_of_program p1) (program_of_program p2)
∧ ∀ id co, (p1.comp_env^!id) = some co → (p2.comp_env^!id) = some co
instance linker_program (F) : linker (program F) :=
{ link := link_program,
linkorder := linkorder_program,
linkorder_refl := λx, ⟨@linker.linkorder_refl _ _ _, λid co h, h⟩,
linkorder_trans := λx y z ⟨p1, a1⟩ ⟨p2, a2⟩, ⟨linker.linkorder_trans p1 p2,
λid co, a2 id co ∘ a1 id co⟩,
link_linkorder := sorry' }
/- ** Commutation between linking and program transformations -/
section link_match_program
parameters {F G : Type}.
parameter match_fundef : fundef F → fundef G → Prop
variable link_match_fundef : ∀ {f1 tf1 f2 tf2 f},
link f1 f2 = some f →
match_fundef f1 tf1 → match_fundef f2 tf2 →
∃ tf, link tf1 tf2 = some tf ∧ match_fundef f tf.
def match_program (p : program F) (tp : program G) : Prop :=
@linking.match_program _ type _ type _ _ (λctx f tf, match_fundef f tf) eq p tp ∧
tp.types = p.types
theorem link_match_program {p1 p2 tp1 tp2 p} :
link p1 p2 = some p → match_program p1 tp1 → match_program p2 tp2 →
∃ tp, link tp1 tp2 = some tp ∧ match_program p tp := sorry'
end link_match_program
end ctypes
|
541e30d7931c1236863137097711e0c98ff2bfa9 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/data/list/min_max.lean | 80ad729868cd7e0076a67e89cd80f6090ff1fe97 | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 5,680 | lean | /-
Copyright (c) 2019 Minchao Wu. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Minchao Wu
-/
import data.list algebra.order_functions
namespace list
universes u
variables {α : Type u} [inhabited α] [decidable_linear_order α]
@[simp] def maximum (l : list α) : α := l.foldl max l.head
@[simp] def minimum (l : list α) : α := l.foldl min l.head
def maximum_aux (l : list α) : α := l.foldr max l.head
def minimum_aux (l : list α) : α := l.foldr min l.head
@[simp] def maximum_singleton {a : α} : maximum [a] = a := by simp
@[simp] def minimum_singleton {a : α} : minimum [a] = a := by simp
theorem le_of_foldr_max : Π {a b : α} {l}, a ∈ l → a ≤ foldr max b l
| a b [] h := absurd h $ not_mem_nil _
| a b (hd::tl) h :=
begin
cases h,
{ simp [h, le_refl] },
{ simp [le_max_right_of_le, le_of_foldr_max h] }
end
theorem le_of_foldr_min : Π {a b : α} {l}, a ∈ l → foldr min b l ≤ a
| a b [] h := absurd h $ not_mem_nil _
| a b (hd::tl) h :=
begin
cases h,
{ simp [h, le_refl] },
{ simp [min_le_left_of_le, le_of_foldr_min h] }
end
theorem le_of_foldl_max {a b : α} {l} (h : a ∈ l) : a ≤ foldl max b l :=
by { rw foldl_eq_foldr max_comm max_assoc, apply le_of_foldr_max h }
theorem le_of_foldl_min {a b : α} {l} (h : a ∈ l) : foldl min b l ≤ a :=
by { rw foldl_eq_foldr min_comm min_assoc, apply le_of_foldr_min h }
theorem mem_foldr_max : Π {a : α} {l}, foldr max a l ∈ a :: l
| a [] := by simp
| a (hd::tl) :=
begin
simp only [foldr_cons],
cases (@max_choice _ _ hd (foldr max a tl)),
{ simp [h] },
{ rw h,
have hmem := @mem_foldr_max a tl,
cases hmem, { simp [hmem] }, { right, right, exact hmem } }
end
theorem mem_foldr_min : Π {a : α} {l}, foldr min a l ∈ a :: l
| a [] := by simp
| a (hd::tl) :=
begin
simp only [foldr_cons],
cases (@min_choice _ _ hd (foldr min a tl)),
{ simp [h] },
{ rw h,
have hmem := @mem_foldr_min a tl,
cases hmem, { simp [hmem] }, { right, right, exact hmem } }
end
theorem mem_foldl_max {a : α} {l} : foldl max a l ∈ a :: l :=
by { rw foldl_eq_foldr max_comm max_assoc, apply mem_foldr_max }
theorem mem_foldl_min {a : α} {l} : foldl min a l ∈ a :: l :=
by { rw foldl_eq_foldr min_comm min_assoc, apply mem_foldr_min }
theorem mem_maximum_aux : Π {l : list α}, l ≠ [] → maximum_aux l ∈ l
| [] h := by contradiction
| (hd::tl) h :=
begin
dsimp [maximum_aux],
have hc := @max_choice _ _ hd (foldr max hd tl),
cases hc, { simp [hc] }, { simp [hc, mem_foldr_max] }
end
theorem mem_minimum_aux : Π {l : list α}, l ≠ [] → minimum_aux l ∈ l
| [] h := by contradiction
| (hd::tl) h :=
begin
dsimp [minimum_aux],
have hc := @min_choice _ _ hd (foldr min hd tl),
cases hc, { simp [hc] }, { simp [hc, mem_foldr_min] }
end
theorem maximum_mem {l : list α} (h : l ≠ []) : maximum l ∈ l :=
by { dsimp, rw foldl_eq_foldr max_comm max_assoc, apply mem_maximum_aux h }
theorem minimum_mem {l : list α} (h : l ≠ []) : minimum l ∈ l :=
by { dsimp, rw foldl_eq_foldr min_comm min_assoc, apply mem_minimum_aux h }
theorem le_maximum_aux_of_mem : Π {a : α} {l}, a ∈ l → a ≤ maximum_aux l
| a [] h := absurd h $ not_mem_nil _
| a (hd::tl) h :=
begin
cases h,
{ rw h, apply le_of_foldr_max, simp },
{ dsimp [maximum_aux], apply le_max_right_of_le, apply le_of_foldr_max h }
end
theorem le_minimum_aux_of_mem : Π {a : α} {l}, a ∈ l → minimum_aux l ≤ a
| a [] h := absurd h $ not_mem_nil _
| a (hd::tl) h :=
begin
cases h,
{ rw h, apply le_of_foldr_min, simp },
{ dsimp [minimum_aux], apply min_le_right_of_le, apply le_of_foldr_min h }
end
theorem le_maximum_of_mem {a : α} {l} (h : a ∈ l) : a ≤ maximum l :=
by { dsimp, rw foldl_eq_foldr max_comm max_assoc, apply le_maximum_aux_of_mem h }
theorem le_minimum_of_mem {a : α} {l} (h : a ∈ l) : minimum l ≤ a :=
by { dsimp, rw foldl_eq_foldr min_comm min_assoc, apply le_minimum_aux_of_mem h }
def maximum_aux_cons : Π {a : α} {l}, l ≠ [] → maximum_aux (a :: l) = max a (maximum_aux l)
| a [] h := by contradiction
| a (hd::tl) h :=
begin
apply le_antisymm,
{ have : a :: hd :: tl ≠ [], { simp [h] },
have hle := mem_maximum_aux this,
cases hle,
{ simp [hle, le_max_left] },
{ apply le_max_right_of_le, apply le_maximum_aux_of_mem, exact hle } },
{ have hc := @max_choice _ _ a (maximum_aux $ hd :: tl),
cases hc,
{ simp [hc, le_maximum_aux_of_mem] },
{ simp [hc, le_maximum_aux_of_mem, mem_maximum_aux h] } }
end
def minimum_aux_cons : Π {a : α} {l}, l ≠ [] → minimum_aux (a :: l) = min a (minimum_aux l)
| a [] h := by contradiction
| a (hd::tl) h :=
begin
apply le_antisymm,
{ have hc := @min_choice _ _ a (minimum_aux $ hd :: tl),
cases hc,
{ simp [hc, le_minimum_aux_of_mem] },
{ simp [hc, le_minimum_aux_of_mem, mem_minimum_aux h] } },
{ have : a :: hd :: tl ≠ [], { simp [h] },
have hle := mem_minimum_aux this,
cases hle,
{ simp [hle, min_le_left] },
{ apply min_le_right_of_le, apply le_minimum_aux_of_mem, exact hle } }
end
def maximum_cons {a : α} {l} (h : l ≠ []) : maximum (a :: l) = max a (maximum l) :=
begin
dsimp only [maximum],
repeat { rw foldl_eq_foldr max_comm max_assoc },
have := maximum_aux_cons h,
dsimp only [maximum_aux] at this,
exact this
end
def minimum_cons {a : α} {l} (h : l ≠ []) : minimum (a :: l) = min a (minimum l) :=
begin
dsimp only [minimum],
repeat { rw foldl_eq_foldr min_comm min_assoc },
have := minimum_aux_cons h,
dsimp only [minimum_aux] at this,
exact this
end
end list
|
35fdc32374caf3a9500dba897c9d81396329343b | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/polynomial/laurent.lean | 11243e114a4aeee0a24ed38a39bf74d02187a3e9 | [
"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 | 20,057 | lean | /-
Copyright (c) 2022 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import data.polynomial.algebra_map
import ring_theory.localization.basic
/-! # Laurent polynomials
We introduce Laurent polynomials over a semiring `R`. Mathematically, they are expressions of the
form
$$
\sum_{i \in \mathbb{Z}} a_i T ^ i
$$
where the sum extends over a finite subset of `ℤ`. Thus, negative exponents are allowed. The
coefficients come from the semiring `R` and the variable `T` commutes with everything.
Since we are going to convert back and forth between polynomials and Laurent polynomials, we
decided to maintain some distinction by using the symbol `T`, rather than `X`, as the variable for
Laurent polynomials
## Notation
The symbol `R[T;T⁻¹]` stands for `laurent_polynomial R`. We also define
* `C : R →+* R[T;T⁻¹]` the inclusion of constant polynomials, analogous to the one for `R[X]`;
* `T : ℤ → R[T;T⁻¹]` the sequence of powers of the variable `T`.
## Implementation notes
We define Laurent polynomials as `add_monoid_algebra R ℤ`.
Thus, they are essentially `finsupp`s `ℤ →₀ R`.
This choice differs from the current irreducible design of `polynomial`, that instead shields away
the implementation via `finsupp`s. It is closer to the original definition of polynomials.
As a consequence, `laurent_polynomial` plays well with polynomials, but there is a little roughness
in establishing the API, since the `finsupp` implementation of `R[X]` is well-shielded.
Unlike the case of polynomials, I felt that the exponent notation was not too easy to use, as only
natural exponents would be allowed. Moreover, in the end, it seems likely that we should aim to
perform computations on exponents in `ℤ` anyway and separating this via the symbol `T` seems
convenient.
I made a *heavy* use of `simp` lemmas, aiming to bring Laurent polynomials to the form `C a * T n`.
Any comments or suggestions for improvements is greatly appreciated!
## Future work
Lots is missing!
-- (Riccardo) add inclusion into Laurent series.
-- (Riccardo) giving a morphism (as `R`-alg, so in the commutative case)
from `R[T,T⁻¹]` to `S` is the same as choosing a unit of `S`.
-- A "better" definition of `trunc` would be as an `R`-linear map. This works:
-- ```
-- def trunc : R[T;T⁻¹] →[R] R[X] :=
-- begin
-- refine (_ : add_monoid_algebra R ℕ →[R] R[X]).comp _,
-- { exact ⟨(to_finsupp_iso R).symm, by simp⟩ },
-- { refine ⟨λ r, comap_domain _ r (set.inj_on_of_injective (λ a b ab, int.of_nat.inj ab) _), _⟩,
-- exact λ r f, comap_domain_smul _ _ _ }
-- end
-- ```
-- but it would make sense to bundle the maps better, for a smoother user experience.
-- I (DT) did not have the strength to embark on this (possibly short!) journey, after getting to
-- this stage of the Laurent process!
-- This would likely involve adding a `comap_domain` analogue of
-- `add_monoid_algebra.map_domain_alg_hom` and an `R`-linear version of
-- `polynomial.to_finsupp_iso`.
-- Add `degree, int_degree, int_trailing_degree, leading_coeff, trailing_coeff,...`.
-/
open_locale polynomial big_operators
open polynomial add_monoid_algebra finsupp
noncomputable theory
variables {R : Type*}
/-- The semiring of Laurent polynomials with coefficients in the semiring `R`.
We denote it by `R[T;T⁻¹]`.
The ring homomorphism `C : R →+* R[T;T⁻¹]` includes `R` as the constant polynomials. -/
abbreviation laurent_polynomial (R : Type*) [semiring R] := add_monoid_algebra R ℤ
local notation R`[T;T⁻¹]`:9000 := laurent_polynomial R
/-- The ring homomorphism, taking a polynomial with coefficients in `R` to a Laurent polynomial
with coefficients in `R`. -/
def polynomial.to_laurent [semiring R] : R[X] →+* R[T;T⁻¹] :=
(map_domain_ring_hom R int.of_nat_hom).comp (to_finsupp_iso R)
/-- This is not a simp lemma, as it is usually preferable to use the lemmas about `C` and `X`
instead. -/
lemma polynomial.to_laurent_apply [semiring R] (p : R[X]) :
p.to_laurent = p.to_finsupp.map_domain coe := rfl
/-- The `R`-algebra map, taking a polynomial with coefficients in `R` to a Laurent polynomial
with coefficients in `R`. -/
def polynomial.to_laurent_alg [comm_semiring R] :
R[X] →ₐ[R] R[T;T⁻¹] :=
begin
refine alg_hom.comp _ (to_finsupp_iso_alg R).to_alg_hom,
exact (map_domain_alg_hom R R int.of_nat_hom),
end
@[simp]
lemma polynomial.to_laurent_alg_apply [comm_semiring R] (f : R[X]) :
f.to_laurent_alg = f.to_laurent := rfl
namespace laurent_polynomial
section semiring
variables [semiring R]
lemma single_zero_one_eq_one : (single 0 1 : R[T;T⁻¹]) = (1 : R[T;T⁻¹]) := rfl
/-! ### The functions `C` and `T`. -/
/-- The ring homomorphism `C`, including `R` into the ring of Laurent polynomials over `R` as
the constant Laurent polynomials. -/
def C : R →+* R[T;T⁻¹] :=
single_zero_ring_hom
lemma algebra_map_apply {R A : Type*} [comm_semiring R] [semiring A] [algebra R A] (r : R) :
algebra_map R (laurent_polynomial A) r = C (algebra_map R A r) :=
rfl
/--
When we have `[comm_semiring R]`, the function `C` is the same as `algebra_map R R[T;T⁻¹]`.
(But note that `C` is defined when `R` is not necessarily commutative, in which case
`algebra_map` is not available.)
-/
lemma C_eq_algebra_map {R : Type*} [comm_semiring R] (r : R) :
C r = algebra_map R R[T;T⁻¹] r :=
rfl
lemma single_eq_C (r : R) : single 0 r = C r := rfl
/-- The function `n ↦ T ^ n`, implemented as a sequence `ℤ → R[T;T⁻¹]`.
Using directly `T ^ n` does not work, since we want the exponents to be of Type `ℤ` and there
is no `ℤ`-power defined on `R[T;T⁻¹]`. Using that `T` is a unit introduces extra coercions.
For these reasons, the definition of `T` is as a sequence. -/
def T (n : ℤ) : R[T;T⁻¹] := single n 1
@[simp]
lemma T_zero : (T 0 : R[T;T⁻¹]) = 1 := rfl
lemma T_add (m n : ℤ) : (T (m + n) : R[T;T⁻¹]) = T m * T n :=
by { convert single_mul_single.symm, simp [T] }
lemma T_sub (m n : ℤ) : (T (m - n) : R[T;T⁻¹]) = T m * T (-n) :=
by rw [← T_add, sub_eq_add_neg]
@[simp]
lemma T_pow (m : ℤ) (n : ℕ) : (T m ^ n : R[T;T⁻¹]) = T (n * m) :=
by rw [T, T, single_pow n, one_pow, nsmul_eq_mul]
/-- The `simp` version of `mul_assoc`, in the presence of `T`'s. -/
@[simp]
lemma mul_T_assoc (f : R[T;T⁻¹]) (m n : ℤ) : f * T m * T n = f * T (m + n) :=
by simp [← T_add, mul_assoc]
@[simp]
lemma single_eq_C_mul_T (r : R) (n : ℤ) :
(single n r : R[T;T⁻¹]) = (C r * T n : R[T;T⁻¹]) :=
by convert single_mul_single.symm; simp
-- This lemma locks in the right changes and is what Lean proved directly.
-- The actual `simp`-normal form of a Laurent monomial is `C a * T n`, whenever it can be reached.
@[simp]
lemma _root_.polynomial.to_laurent_C_mul_T (n : ℕ) (r : R) :
((polynomial.monomial n r).to_laurent : R[T;T⁻¹]) = C r * T n :=
show map_domain coe (monomial n r).to_finsupp = (C r * T n : R[T;T⁻¹]),
by rw [to_finsupp_monomial, map_domain_single, single_eq_C_mul_T]
@[simp]
lemma _root_.polynomial.to_laurent_C (r : R) : (polynomial.C r).to_laurent = C r :=
begin
convert polynomial.to_laurent_C_mul_T 0 r,
simp only [int.coe_nat_zero, T_zero, mul_one],
end
@[simp]
lemma _root_.polynomial.to_laurent_X : (polynomial.X.to_laurent : R[T;T⁻¹]) = T 1 :=
begin
have : (polynomial.X : R[X]) = monomial 1 1,
{ simp [← C_mul_X_pow_eq_monomial] },
simp [this, polynomial.to_laurent_C_mul_T],
end
@[simp] lemma _root_.polynomial.to_laurent_one : (polynomial.to_laurent : R[X] → R[T;T⁻¹]) 1 = 1 :=
map_one polynomial.to_laurent
@[simp]
lemma _root_.polynomial.to_laurent_C_mul_eq (r : R) (f : R[X]) :
(polynomial.C r * f).to_laurent = C r * f.to_laurent :=
by simp only [_root_.map_mul, polynomial.to_laurent_C]
@[simp]
lemma _root_.polynomial.to_laurent_X_pow (n : ℕ) : (X ^ n : R[X]).to_laurent = T n :=
by simp only [map_pow, polynomial.to_laurent_X, T_pow, mul_one]
@[simp]
lemma _root_.polynomial.to_laurent_C_mul_X_pow (n : ℕ) (r : R) :
(polynomial.C r * X ^ n).to_laurent = C r * T n :=
by simp only [_root_.map_mul, polynomial.to_laurent_C, polynomial.to_laurent_X_pow]
instance invertible_T (n : ℤ) : invertible (T n : R[T;T⁻¹]) :=
{ inv_of := T (- n),
inv_of_mul_self := by rw [← T_add, add_left_neg, T_zero],
mul_inv_of_self := by rw [← T_add, add_right_neg, T_zero] }
@[simp]
lemma inv_of_T (n : ℤ) : ⅟ (T n : R[T;T⁻¹]) = T (- n) := rfl
lemma is_unit_T (n : ℤ) : is_unit (T n : R[T;T⁻¹]) :=
is_unit_of_invertible _
@[elab_as_eliminator] protected lemma induction_on {M : R[T;T⁻¹] → Prop} (p : R[T;T⁻¹])
(h_C : ∀ a, M (C a))
(h_add : ∀ {p q}, M p → M q → M (p + q))
(h_C_mul_T : ∀ (n : ℕ) (a : R), M (C a * T n) → M (C a * T (n + 1)))
(h_C_mul_T_Z : ∀ (n : ℕ) (a : R), M (C a * T (- n)) → M (C a * T (- n - 1))) :
M p :=
begin
have A : ∀ {n : ℤ} {a : R}, M (C a * T n),
{ assume n a,
apply n.induction_on,
{ simpa only [T_zero, mul_one] using h_C a },
{ exact λ m, h_C_mul_T m a },
{ exact λ m, h_C_mul_T_Z m a } },
have B : ∀ (s : finset ℤ), M (s.sum (λ (n : ℤ), C (p.to_fun n) * T n)),
{ apply finset.induction,
{ convert h_C 0, simp only [finset.sum_empty, _root_.map_zero] },
{ assume n s ns ih, rw finset.sum_insert ns, exact h_add A ih } },
convert B p.support,
ext a,
simp_rw [← single_eq_C_mul_T, finset.sum_apply', single_apply, finset.sum_ite_eq'],
split_ifs with h h,
{ refl },
{ exact finsupp.not_mem_support_iff.mp h }
end
/-- To prove something about Laurent polynomials, it suffices to show that
* the condition is closed under taking sums, and
* it holds for monomials.
-/
@[elab_as_eliminator] protected lemma induction_on' {M : R[T;T⁻¹] → Prop} (p : R[T;T⁻¹])
(h_add : ∀p q, M p → M q → M (p + q))
(h_C_mul_T : ∀(n : ℤ) (a : R), M (C a * T n)) :
M p :=
begin
refine p.induction_on (λ a, _) h_add _ _;
try { exact λ n f _, h_C_mul_T _ f },
convert h_C_mul_T 0 a,
exact (mul_one _).symm,
end
lemma commute_T (n : ℤ) (f : R[T;T⁻¹]) : commute (T n) f :=
f.induction_on' (λ p q Tp Tq, commute.add_right Tp Tq) $ λ m a,
show T n * _ = _, by
{ rw [T, T, ← single_eq_C, single_mul_single, single_mul_single, single_mul_single],
simp [add_comm] }
@[simp]
lemma T_mul (n : ℤ) (f : R[T;T⁻¹]) : T n * f = f * T n :=
(commute_T n f).eq
/-- `trunc : R[T;T⁻¹] →+ R[X]` maps a Laurent polynomial `f` to the polynomial whose terms of
nonnegative degree coincide with the ones of `f`. The terms of negative degree of `f` "vanish".
`trunc` is a left-inverse to `polynomial.to_laurent`. -/
def trunc : R[T;T⁻¹] →+ R[X] :=
((to_finsupp_iso R).symm.to_add_monoid_hom).comp $
comap_domain.add_monoid_hom $ λ a b, int.of_nat.inj
@[simp]
lemma trunc_C_mul_T (n : ℤ) (r : R) : trunc (C r * T n) = ite (0 ≤ n) (monomial n.to_nat r) 0 :=
begin
apply (to_finsupp_iso R).injective,
rw [← single_eq_C_mul_T, trunc, add_monoid_hom.coe_comp, function.comp_app,
comap_domain.add_monoid_hom_apply, to_finsupp_iso_apply],
by_cases n0 : 0 ≤ n,
{ lift n to ℕ using n0,
erw [comap_domain_single, to_finsupp_iso_symm_apply],
simp only [int.coe_nat_nonneg, int.to_nat_coe_nat, if_true, to_finsupp_iso_apply,
to_finsupp_monomial] },
{ lift (- n) to ℕ using (neg_pos.mpr (not_le.mp n0)).le with m,
rw [to_finsupp_iso_apply, to_finsupp_inj, if_neg n0],
erw to_finsupp_iso_symm_apply,
ext a,
have := ((not_le.mp n0).trans_le (int.coe_zero_le a)).ne',
simp only [coeff, comap_domain_apply, int.of_nat_eq_coe, coeff_zero, single_apply_eq_zero, this,
is_empty.forall_iff] }
end
@[simp] lemma left_inverse_trunc_to_laurent :
function.left_inverse (trunc : R[T;T⁻¹] → R[X]) polynomial.to_laurent :=
begin
refine λ f, f.induction_on' _ _,
{ exact λ f g hf hg, by simp only [hf, hg, _root_.map_add] },
{ exact λ n r, by simp only [polynomial.to_laurent_C_mul_T, trunc_C_mul_T, int.coe_nat_nonneg,
int.to_nat_coe_nat, if_true] }
end
@[simp] lemma _root_.polynomial.trunc_to_laurent (f : R[X]) : trunc f.to_laurent = f :=
left_inverse_trunc_to_laurent _
lemma _root_.polynomial.to_laurent_injective :
function.injective (polynomial.to_laurent : R[X] → R[T;T⁻¹]) :=
left_inverse_trunc_to_laurent.injective
@[simp] lemma _root_.polynomial.to_laurent_inj (f g : R[X]) :
f.to_laurent = g.to_laurent ↔ f = g :=
⟨λ h, polynomial.to_laurent_injective h, congr_arg _⟩
lemma _root_.polynomial.to_laurent_ne_zero {f : R[X]} :
f ≠ 0 ↔ f.to_laurent ≠ 0 :=
(map_ne_zero_iff _ (by exact polynomial.to_laurent_injective)).symm
lemma exists_T_pow (f : R[T;T⁻¹]) :
∃ (n : ℕ) (f' : R[X]), f'.to_laurent = f * T n :=
begin
apply f.induction_on' _ (λ n a, _); clear f,
{ rintros f g ⟨m, fn, hf⟩ ⟨n, gn, hg⟩,
refine ⟨m + n, fn * X ^ n + gn * X ^ m, _⟩,
simp only [hf, hg, add_mul, add_comm (n : ℤ), map_add, map_mul, polynomial.to_laurent_X_pow,
mul_T_assoc, int.coe_nat_add] },
{ cases n with n n,
{ exact ⟨0, polynomial.C a * X ^ n, by simp⟩ },
{ refine ⟨n + 1, polynomial.C a, _⟩,
simp only [int.neg_succ_of_nat_eq, polynomial.to_laurent_C, int.coe_nat_succ, mul_T_assoc,
add_left_neg, T_zero, mul_one] } }
end
/-- This is a version of `exists_T_pow` stated as an induction principle. -/
@[elab_as_eliminator] lemma induction_on_mul_T {Q : R[T;T⁻¹] → Prop} (f : R[T;T⁻¹])
(Qf : ∀ {f : R[X]} {n : ℕ}, Q (f.to_laurent * T (- n))) :
Q f :=
begin
rcases f.exists_T_pow with ⟨n, f', hf⟩,
rw [← mul_one f, ← T_zero, ← nat.cast_zero, ← nat.sub_self n, nat.cast_sub rfl.le, T_sub,
← mul_assoc, ← hf],
exact Qf,
end
/-- Suppose that `Q` is a statement about Laurent polynomials such that
* `Q` is true on *ordinary* polynomials;
* `Q (f * T)` implies `Q f`;
it follow that `Q` is true on all Laurent polynomials. -/
lemma reduce_to_polynomial_of_mul_T (f : R[T;T⁻¹]) {Q : R[T;T⁻¹] → Prop}
(Qf : ∀ (f : R[X]), Q f.to_laurent)
(QT : ∀ f, Q (f * T 1) → Q f) :
Q f :=
begin
induction f using laurent_polynomial.induction_on_mul_T with f n,
induction n with n hn,
{ simpa only [int.coe_nat_zero, neg_zero, T_zero, mul_one] using Qf _ },
{ convert QT _ _,
simpa using hn }
end
section support
lemma support_C_mul_T (a : R) (n : ℤ) : (C a * T n).support ⊆ {n} :=
by simpa only [← single_eq_C_mul_T] using support_single_subset
lemma support_C_mul_T_of_ne_zero {a : R} (a0 : a ≠ 0) (n : ℤ) : (C a * T n).support = {n} :=
begin
rw ← single_eq_C_mul_T,
exact support_single_ne_zero _ a0,
end
/-- The support of a polynomial `f` is a finset in `ℕ`. The lemma `to_laurent_support f`
shows that the support of `f.to_laurent` is the same finset, but viewed in `ℤ` under the natural
inclusion `ℕ ↪ ℤ`. -/
lemma to_laurent_support (f : R[X]) :
f.to_laurent.support = f.support.map nat.cast_embedding :=
begin
generalize' hd : f.support = s,
revert f,
refine finset.induction_on s _ _; clear s,
{ simp only [polynomial.support_eq_empty, map_zero, finsupp.support_zero, eq_self_iff_true,
implies_true_iff, finset.map_empty] {contextual := tt} },
{ intros a s as hf f fs,
have : (erase a f).to_laurent.support = s.map nat.cast_embedding := hf (f.erase a) (by simp only
[fs, finset.erase_eq_of_not_mem as, polynomial.support_erase, finset.erase_insert_eq_erase]),
rw [← monomial_add_erase f a, finset.map_insert, ← this, map_add,
polynomial.to_laurent_C_mul_T, support_add_eq, finset.insert_eq],
{ congr,
exact support_C_mul_T_of_ne_zero (polynomial.mem_support_iff.mp (by simp [fs])) _ },
{ rw this,
exact disjoint.mono_left (support_C_mul_T _ _) (by simpa) } }
end
end support
section degrees
/-- The degree of a Laurent polynomial takes values in `with_bot ℤ`.
If `f : R[T;T⁻¹]` is a Laurent polynomial, then `f.degree` is the maximum of its support of `f`,
or `⊥`, if `f = 0`. -/
def degree (f : R[T;T⁻¹]) : with_bot ℤ := f.support.max
@[simp] lemma degree_zero : degree (0 : R[T;T⁻¹]) = ⊥ := rfl
@[simp] lemma degree_eq_bot_iff {f : R[T;T⁻¹]} : f.degree = ⊥ ↔ f = 0 :=
begin
refine ⟨λ h, _, λ h, by rw [h, degree_zero]⟩,
rw [degree, finset.max_eq_sup_with_bot] at h,
ext n,
refine not_not.mp (λ f0, _),
simp_rw [finset.sup_eq_bot_iff, finsupp.mem_support_iff, ne.def, with_bot.coe_ne_bot] at h,
exact h n f0,
end
section exact_degrees
open_locale classical
@[simp] lemma degree_C_mul_T (n : ℤ) (a : R) (a0 : a ≠ 0) : (C a * T n).degree = n :=
begin
rw degree,
convert finset.max_singleton,
refine support_eq_singleton.mpr _,
simp only [← single_eq_C_mul_T, single_eq_same, a0, ne.def, not_false_iff, eq_self_iff_true,
and_self],
end
lemma degree_C_mul_T_ite (n : ℤ) (a : R) : (C a * T n).degree = ite (a = 0) ⊥ n :=
by split_ifs with h h;
simp only [h, map_zero, zero_mul, degree_zero, degree_C_mul_T, ne.def, not_false_iff]
@[simp] lemma degree_T [nontrivial R] (n : ℤ) : (T n : R[T;T⁻¹]).degree = n :=
begin
rw [← one_mul (T n), ← map_one C],
exact degree_C_mul_T n 1 (one_ne_zero : (1 : R) ≠ 0),
end
lemma degree_C {a : R} (a0 : a ≠ 0) : (C a).degree = 0 :=
begin
rw [← mul_one (C a), ← T_zero],
exact degree_C_mul_T 0 a a0
end
lemma degree_C_ite (a : R) : (C a).degree = ite (a = 0) ⊥ 0 :=
by split_ifs with h h;
simp only [h, map_zero, degree_zero, degree_C, ne.def, not_false_iff]
end exact_degrees
section degree_bounds
lemma degree_C_mul_T_le (n : ℤ) (a : R) : (C a * T n).degree ≤ n :=
begin
by_cases a0 : a = 0,
{ simp only [a0, map_zero, zero_mul, degree_zero, bot_le] },
{ exact (degree_C_mul_T n a a0).le }
end
lemma degree_T_le (n : ℤ) : (T n : R[T;T⁻¹]).degree ≤ n :=
(le_of_eq (by rw [map_one, one_mul])).trans (degree_C_mul_T_le n (1 : R))
lemma degree_C_le (a : R) : (C a).degree ≤ 0 :=
(le_of_eq (by rw [T_zero, mul_one])).trans (degree_C_mul_T_le 0 a)
end degree_bounds
end degrees
instance : module R[X] R[T;T⁻¹] :=
module.comp_hom _ polynomial.to_laurent
instance (R : Type*) [semiring R] : is_scalar_tower R[X] R[X] R[T;T⁻¹] :=
{ smul_assoc := λ x y z, by simp only [has_smul.smul, has_smul.comp.smul, map_mul, mul_assoc] }
end semiring
section comm_semiring
variable [comm_semiring R]
instance algebra_polynomial (R : Type*) [comm_semiring R] : algebra R[X] R[T;T⁻¹] :=
{ commutes' := λ f l, by simp [mul_comm],
smul_def' := λ f l, rfl,
.. polynomial.to_laurent }
lemma algebra_map_X_pow (n : ℕ) : algebra_map R[X] R[T;T⁻¹] (X ^ n) = T n :=
polynomial.to_laurent_X_pow n
@[simp]
lemma algebra_map_eq_to_laurent (f : R[X]) : algebra_map R[X] R[T;T⁻¹] f = f.to_laurent :=
rfl
lemma is_localization : is_localization (submonoid.closure ({X} : set R[X])) R[T;T⁻¹] :=
{ map_units := λ t, begin
cases t with t ht,
rcases submonoid.mem_closure_singleton.mp ht with ⟨n, rfl⟩,
simp only [is_unit_T n, set_like.coe_mk, algebra_map_eq_to_laurent, polynomial.to_laurent_X_pow]
end,
surj := λ f, begin
induction f using laurent_polynomial.induction_on_mul_T with f n,
have := (submonoid.closure ({X} : set R[X])).pow_mem submonoid.mem_closure_singleton_self n,
refine ⟨(f, ⟨_, this⟩), _⟩,
simp only [set_like.coe_mk, algebra_map_eq_to_laurent, polynomial.to_laurent_X_pow, mul_T_assoc,
add_left_neg, T_zero, mul_one],
end,
eq_iff_exists := λ f g, begin
rw [algebra_map_eq_to_laurent, algebra_map_eq_to_laurent, polynomial.to_laurent_inj],
refine ⟨_, _⟩,
{ rintro rfl,
exact ⟨1, rfl⟩ },
{ rintro ⟨⟨h, hX⟩, h⟩,
rcases submonoid.mem_closure_singleton.mp hX with ⟨n, rfl⟩,
exact mul_X_pow_injective n (by simpa only [X_pow_mul] using h) }
end }
end comm_semiring
end laurent_polynomial
|
5f7ad5a47f35b58522739c033b671a49e83dda05 | 2a70b774d16dbdf5a533432ee0ebab6838df0948 | /_target/deps/mathlib/src/category_theory/equivalence.lean | 858c18457e203ef601e8fc90b0bc2a25b9e7b9b3 | [
"Apache-2.0"
] | permissive | hjvromen/lewis | 40b035973df7c77ebf927afab7878c76d05ff758 | 105b675f73630f028ad5d890897a51b3c1146fb0 | refs/heads/master | 1,677,944,636,343 | 1,676,555,301,000 | 1,676,555,301,000 | 327,553,599 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,324 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn
-/
import category_theory.fully_faithful
import category_theory.whiskering
import category_theory.essential_image
import tactic.slice
/-!
# Equivalence of categories
An equivalence of categories `C` and `D` is a pair of functors `F : C ⥤ D` and `G : D ⥤ C` such
that `η : 𝟭 C ≅ F ⋙ G` and `ε : G ⋙ F ≅ 𝟭 D`. In many situations, equivalences are a better
notion of "sameness" of categories than the stricter isomorphims of categories.
Recall that one way to express that two functors `F : C ⥤ D` and `G : D ⥤ C` are adjoint is using
two natural transformations `η : 𝟭 C ⟶ F ⋙ G` and `ε : G ⋙ F ⟶ 𝟭 D`, called the unit and the
counit, such that the compositions `F ⟶ FGF ⟶ F` and `G ⟶ GFG ⟶ G` are the identity. Unfortunately,
it is not the case that the natural isomorphisms `η` and `ε` in the definition of an equivalence
automatically give an adjunction. However, it is true that
* if one of the two compositions is the identity, then so is the other, and
* given an equivalence of categories, it is always possible to refine `η` in such a way that the
identities are satisfied.
For this reason, in mathlib we define an equivalence to be a "half-adjoint equivalence", which is
a tuple `(F, G, η, ε)` as in the first paragraph such that the composite `F ⟶ FGF ⟶ F` is the
identity. By the remark above, this already implies that the tuple is an "adjoint equivalence",
i.e., that the composite `G ⟶ GFG ⟶ G` is also the identity.
We also define essentially surjective functors and show that a functor is an equivalence if and only
if it is full, faithful and essentially surjective.
## Main definitions
* `equivalence`: bundled (half-)adjoint equivalences of categories
* `is_equivalence`: type class on a functor `F` containing the data of the inverse `G` as well as
the natural isomorphisms `η` and `ε`.
* `ess_surj`: type class on a functor `F` containing the data of the preimages and the isomorphisms
`F.obj (preimage d) ≅ d`.
## Main results
* `equivalence.mk`: upgrade an equivalence to a (half-)adjoint equivalence
* `equivalence_of_fully_faithfully_ess_surj`: a fully faithful essentially surjective functor is an
equivalence.
## Notations
We write `C ≌ D` (`\backcong`, not to be confused with `≅`/`\cong`) for a bundled equivalence.
-/
namespace category_theory
open category_theory.functor nat_iso category
universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation
/-- We define an equivalence as a (half)-adjoint equivalence, a pair of functors with
a unit and counit which are natural isomorphisms and the triangle law `Fη ≫ εF = 1`, or in other
words the composite `F ⟶ FGF ⟶ F` is the identity.
In `unit_inverse_comp`, we show that this is actually an adjoint equivalence, i.e., that the
composite `G ⟶ GFG ⟶ G` is also the identity.
The triangle equation is written as a family of equalities between morphisms, it is more
complicated if we write it as an equality of natural transformations, because then we would have
to insert natural transformations like `F ⟶ F1`.
See https://stacks.math.columbia.edu/tag/001J
-/
structure equivalence (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] :=
mk' ::
(functor : C ⥤ D)
(inverse : D ⥤ C)
(unit_iso : 𝟭 C ≅ functor ⋙ inverse)
(counit_iso : inverse ⋙ functor ≅ 𝟭 D)
(functor_unit_iso_comp' : ∀(X : C), functor.map ((unit_iso.hom : 𝟭 C ⟶ functor ⋙ inverse).app X) ≫
counit_iso.hom.app (functor.obj X) = 𝟙 (functor.obj X) . obviously)
restate_axiom equivalence.functor_unit_iso_comp'
infixr ` ≌ `:10 := equivalence
variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D]
namespace equivalence
/-- The unit of an equivalence of categories. -/
abbreviation unit (e : C ≌ D) : 𝟭 C ⟶ e.functor ⋙ e.inverse := e.unit_iso.hom
/-- The counit of an equivalence of categories. -/
abbreviation counit (e : C ≌ D) : e.inverse ⋙ e.functor ⟶ 𝟭 D := e.counit_iso.hom
/-- The inverse of the unit of an equivalence of categories. -/
abbreviation unit_inv (e : C ≌ D) : e.functor ⋙ e.inverse ⟶ 𝟭 C := e.unit_iso.inv
/-- The inverse of the counit of an equivalence of categories. -/
abbreviation counit_inv (e : C ≌ D) : 𝟭 D ⟶ e.inverse ⋙ e.functor := e.counit_iso.inv
/- While these abbreviations are convenient, they also cause some trouble,
preventing structure projections from unfolding. -/
@[simp] lemma equivalence_mk'_unit (functor inverse unit_iso counit_iso f) :
(⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).unit = unit_iso.hom := rfl
@[simp] lemma equivalence_mk'_counit (functor inverse unit_iso counit_iso f) :
(⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).counit = counit_iso.hom := rfl
@[simp] lemma equivalence_mk'_unit_inv (functor inverse unit_iso counit_iso f) :
(⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).unit_inv = unit_iso.inv := rfl
@[simp] lemma equivalence_mk'_counit_inv (functor inverse unit_iso counit_iso f) :
(⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).counit_inv = counit_iso.inv := rfl
@[simp] lemma functor_unit_comp (e : C ≌ D) (X : C) :
e.functor.map (e.unit.app X) ≫ e.counit.app (e.functor.obj X) = 𝟙 (e.functor.obj X) :=
e.functor_unit_iso_comp X
@[simp] lemma counit_inv_functor_comp (e : C ≌ D) (X : C) :
e.counit_inv.app (e.functor.obj X) ≫ e.functor.map (e.unit_inv.app X) = 𝟙 (e.functor.obj X) :=
begin
erw [iso.inv_eq_inv
(e.functor.map_iso (e.unit_iso.app X) ≪≫ e.counit_iso.app (e.functor.obj X)) (iso.refl _)],
exact e.functor_unit_comp X
end
lemma counit_inv_app_functor (e : C ≌ D) (X : C) :
e.counit_inv.app (e.functor.obj X) = e.functor.map (e.unit.app X) :=
by { symmetry, erw [←iso.comp_hom_eq_id (e.counit_iso.app _), functor_unit_comp], refl }
lemma counit_app_functor (e : C ≌ D) (X : C) :
e.counit.app (e.functor.obj X) = e.functor.map (e.unit_inv.app X) :=
by { erw [←iso.hom_comp_eq_id (e.functor.map_iso (e.unit_iso.app X)), functor_unit_comp], refl }
/-- The other triangle equality. The proof follows the following proof in Globular:
http://globular.science/1905.001 -/
@[simp] lemma unit_inverse_comp (e : C ≌ D) (Y : D) :
e.unit.app (e.inverse.obj Y) ≫ e.inverse.map (e.counit.app Y) = 𝟙 (e.inverse.obj Y) :=
begin
rw [←id_comp (e.inverse.map _), ←map_id e.inverse, ←counit_inv_functor_comp, map_comp,
←iso.hom_inv_id_assoc (e.unit_iso.app _) (e.inverse.map (e.functor.map _)),
app_hom, app_inv],
slice_lhs 2 3 { erw [e.unit.naturality] },
slice_lhs 1 2 { erw [e.unit.naturality] },
slice_lhs 4 4
{ rw [←iso.hom_inv_id_assoc (e.inverse.map_iso (e.counit_iso.app _)) (e.unit_inv.app _)] },
slice_lhs 3 4 { erw [←map_comp e.inverse, e.counit.naturality],
erw [(e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp],
slice_lhs 2 3 { erw [←map_comp e.inverse, e.counit_iso.inv.naturality, map_comp] },
slice_lhs 3 4 { erw [e.unit_inv.naturality] },
slice_lhs 4 5 { erw [←map_comp (e.functor ⋙ e.inverse), (e.unit_iso.app _).hom_inv_id, map_id] },
erw [id_comp],
slice_lhs 3 4 { erw [←e.unit_inv.naturality] },
slice_lhs 2 3 { erw [←map_comp e.inverse, ←e.counit_iso.inv.naturality,
(e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp, (e.unit_iso.app _).hom_inv_id], refl
end
@[simp] lemma inverse_counit_inv_comp (e : C ≌ D) (Y : D) :
e.inverse.map (e.counit_inv.app Y) ≫ e.unit_inv.app (e.inverse.obj Y) = 𝟙 (e.inverse.obj Y) :=
begin
erw [iso.inv_eq_inv
(e.unit_iso.app (e.inverse.obj Y) ≪≫ e.inverse.map_iso (e.counit_iso.app Y)) (iso.refl _)],
exact e.unit_inverse_comp Y
end
lemma unit_app_inverse (e : C ≌ D) (Y : D) :
e.unit.app (e.inverse.obj Y) = e.inverse.map (e.counit_inv.app Y) :=
by { erw [←iso.comp_hom_eq_id (e.inverse.map_iso (e.counit_iso.app Y)), unit_inverse_comp], refl }
lemma unit_inv_app_inverse (e : C ≌ D) (Y : D) :
e.unit_inv.app (e.inverse.obj Y) = e.inverse.map (e.counit.app Y) :=
by { symmetry, erw [←iso.hom_comp_eq_id (e.unit_iso.app _), unit_inverse_comp], refl }
@[simp] lemma fun_inv_map (e : C ≌ D) (X Y : D) (f : X ⟶ Y) :
e.functor.map (e.inverse.map f) = e.counit.app X ≫ f ≫ e.counit_inv.app Y :=
(nat_iso.naturality_2 (e.counit_iso) f).symm
@[simp] lemma inv_fun_map (e : C ≌ D) (X Y : C) (f : X ⟶ Y) :
e.inverse.map (e.functor.map f) = e.unit_inv.app X ≫ f ≫ e.unit.app Y :=
(nat_iso.naturality_1 (e.unit_iso) f).symm
section
-- In this section we convert an arbitrary equivalence to a half-adjoint equivalence.
variables {F : C ⥤ D} {G : D ⥤ C} (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D)
/-- If `η : 𝟭 C ≅ F ⋙ G` is part of a (not necessarily half-adjoint) equivalence, we can upgrade it
to a refined natural isomorphism `adjointify_η η : 𝟭 C ≅ F ⋙ G` which exhibits the properties
required for a half-adjoint equivalence. See `equivalence.mk`. -/
def adjointify_η : 𝟭 C ≅ F ⋙ G :=
calc
𝟭 C ≅ F ⋙ G : η
... ≅ F ⋙ (𝟭 D ⋙ G) : iso_whisker_left F (left_unitor G).symm
... ≅ F ⋙ ((G ⋙ F) ⋙ G) : iso_whisker_left F (iso_whisker_right ε.symm G)
... ≅ F ⋙ (G ⋙ (F ⋙ G)) : iso_whisker_left F (associator G F G)
... ≅ (F ⋙ G) ⋙ (F ⋙ G) : (associator F G (F ⋙ G)).symm
... ≅ 𝟭 C ⋙ (F ⋙ G) : iso_whisker_right η.symm (F ⋙ G)
... ≅ F ⋙ G : left_unitor (F ⋙ G)
lemma adjointify_η_ε (X : C) :
F.map ((adjointify_η η ε).hom.app X) ≫ ε.hom.app (F.obj X) = 𝟙 (F.obj X) :=
begin
dsimp [adjointify_η], simp,
have := ε.hom.naturality (F.map (η.inv.app X)), dsimp at this, rw [this], clear this,
rw [←assoc _ _ (F.map _)],
have := ε.hom.naturality (ε.inv.app $ F.obj X), dsimp at this, rw [this], clear this,
have := (ε.app $ F.obj X).hom_inv_id, dsimp at this, rw [this], clear this,
rw [id_comp], have := (F.map_iso $ η.app X).hom_inv_id, dsimp at this, rw [this]
end
end
/-- Every equivalence of categories consisting of functors `F` and `G` such that `F ⋙ G` and
`G ⋙ F` are naturally isomorphic to identity functors can be transformed into a half-adjoint
equivalence without changing `F` or `G`. -/
protected definition mk (F : C ⥤ D) (G : D ⥤ C)
(η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : C ≌ D :=
⟨F, G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩
/-- Equivalence of categories is reflexive. -/
@[refl, simps] def refl : C ≌ C :=
⟨𝟭 C, 𝟭 C, iso.refl _, iso.refl _, λ X, category.id_comp _⟩
instance : inhabited (C ≌ C) :=
⟨refl⟩
/-- Equivalence of categories is symmetric. -/
@[symm, simps] def symm (e : C ≌ D) : D ≌ C :=
⟨e.inverse, e.functor, e.counit_iso.symm, e.unit_iso.symm, e.inverse_counit_inv_comp⟩
variables {E : Type u₃} [category.{v₃} E]
/-- Equivalence of categories is transitive. -/
@[trans, simps] def trans (e : C ≌ D) (f : D ≌ E) : C ≌ E :=
{ functor := e.functor ⋙ f.functor,
inverse := f.inverse ⋙ e.inverse,
unit_iso :=
begin
refine iso.trans e.unit_iso _,
exact iso_whisker_left e.functor (iso_whisker_right f.unit_iso e.inverse) ,
end,
counit_iso :=
begin
refine iso.trans _ f.counit_iso,
exact iso_whisker_left f.inverse (iso_whisker_right e.counit_iso f.functor)
end,
-- We wouldn't have needed to give this proof if we'd used `equivalence.mk`,
-- but we choose to avoid using that here, for the sake of good structure projection `simp` lemmas.
functor_unit_iso_comp' := λ X,
begin
dsimp,
rw [← f.functor.map_comp_assoc, e.functor.map_comp, ←counit_inv_app_functor, fun_inv_map,
iso.inv_hom_id_app_assoc, assoc, iso.inv_hom_id_app, counit_app_functor, ← functor.map_comp],
erw [comp_id, iso.hom_inv_id_app, functor.map_id],
end }
/-- Composing a functor with both functors of an equivalence yields a naturally isomorphic functor. -/
def fun_inv_id_assoc (e : C ≌ D) (F : C ⥤ E) : e.functor ⋙ e.inverse ⋙ F ≅ F :=
(functor.associator _ _ _).symm ≪≫ iso_whisker_right e.unit_iso.symm F ≪≫ F.left_unitor
@[simp] lemma fun_inv_id_assoc_hom_app (e : C ≌ D) (F : C ⥤ E) (X : C) :
(fun_inv_id_assoc e F).hom.app X = F.map (e.unit_inv.app X) :=
by { dsimp [fun_inv_id_assoc], tidy }
@[simp] lemma fun_inv_id_assoc_inv_app (e : C ≌ D) (F : C ⥤ E) (X : C) :
(fun_inv_id_assoc e F).inv.app X = F.map (e.unit.app X) :=
by { dsimp [fun_inv_id_assoc], tidy }
/-- Composing a functor with both functors of an equivalence yields a naturally isomorphic functor. -/
def inv_fun_id_assoc (e : C ≌ D) (F : D ⥤ E) : e.inverse ⋙ e.functor ⋙ F ≅ F :=
(functor.associator _ _ _).symm ≪≫ iso_whisker_right e.counit_iso F ≪≫ F.left_unitor
@[simp] lemma inv_fun_id_assoc_hom_app (e : C ≌ D) (F : D ⥤ E) (X : D) :
(inv_fun_id_assoc e F).hom.app X = F.map (e.counit.app X) :=
by { dsimp [inv_fun_id_assoc], tidy }
@[simp] lemma inv_fun_id_assoc_inv_app (e : C ≌ D) (F : D ⥤ E) (X : D) :
(inv_fun_id_assoc e F).inv.app X = F.map (e.counit_inv.app X) :=
by { dsimp [inv_fun_id_assoc], tidy }
/-- If `C` is equivalent to `D`, then `C ⥤ E` is equivalent to `D ⥤ E`. -/
@[simps functor inverse unit_iso counit_iso]
def congr_left (e : C ≌ D) : (C ⥤ E) ≌ (D ⥤ E) :=
equivalence.mk
((whiskering_left _ _ _).obj e.inverse)
((whiskering_left _ _ _).obj e.functor)
(nat_iso.of_components (λ F, (e.fun_inv_id_assoc F).symm) (by tidy))
(nat_iso.of_components (λ F, e.inv_fun_id_assoc F) (by tidy))
/-- If `C` is equivalent to `D`, then `E ⥤ C` is equivalent to `E ⥤ D`. -/
@[simps functor inverse unit_iso counit_iso]
def congr_right (e : C ≌ D) : (E ⥤ C) ≌ (E ⥤ D) :=
equivalence.mk
((whiskering_right _ _ _).obj e.functor)
((whiskering_right _ _ _).obj e.inverse)
(nat_iso.of_components
(λ F, F.right_unitor.symm ≪≫ iso_whisker_left F e.unit_iso ≪≫ functor.associator _ _ _)
(by tidy))
(nat_iso.of_components
(λ F, functor.associator _ _ _ ≪≫ iso_whisker_left F e.counit_iso ≪≫ F.right_unitor)
(by tidy))
section cancellation_lemmas
variables (e : C ≌ D)
-- We need special forms of `cancel_nat_iso_hom_right(_assoc)` and `cancel_nat_iso_inv_right(_assoc)`
-- for units and counits, because neither `simp` or `rw` will apply those lemmas in this
-- setting without providing `e.unit_iso` (or similar) as an explicit argument.
-- We also provide the lemmas for length four compositions, since they're occasionally useful.
-- (e.g. in proving that equivalences take monos to monos)
@[simp] lemma cancel_unit_right {X Y : C}
(f f' : X ⟶ Y) :
f ≫ e.unit.app Y = f' ≫ e.unit.app Y ↔ f = f' :=
by simp only [cancel_mono]
@[simp] lemma cancel_unit_inv_right {X Y : C}
(f f' : X ⟶ e.inverse.obj (e.functor.obj Y)) :
f ≫ e.unit_inv.app Y = f' ≫ e.unit_inv.app Y ↔ f = f' :=
by simp only [cancel_mono]
@[simp] lemma cancel_counit_right {X Y : D}
(f f' : X ⟶ e.functor.obj (e.inverse.obj Y)) :
f ≫ e.counit.app Y = f' ≫ e.counit.app Y ↔ f = f' :=
by simp only [cancel_mono]
@[simp] lemma cancel_counit_inv_right {X Y : D}
(f f' : X ⟶ Y) :
f ≫ e.counit_inv.app Y = f' ≫ e.counit_inv.app Y ↔ f = f' :=
by simp only [cancel_mono]
@[simp] lemma cancel_unit_right_assoc {W X X' Y : C}
(f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) :
f ≫ g ≫ e.unit.app Y = f' ≫ g' ≫ e.unit.app Y ↔ f ≫ g = f' ≫ g' :=
by simp only [←category.assoc, cancel_mono]
@[simp] lemma cancel_counit_inv_right_assoc {W X X' Y : D}
(f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) :
f ≫ g ≫ e.counit_inv.app Y = f' ≫ g' ≫ e.counit_inv.app Y ↔ f ≫ g = f' ≫ g' :=
by simp only [←category.assoc, cancel_mono]
@[simp] lemma cancel_unit_right_assoc' {W X X' Y Y' Z : C}
(f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) (f' : W ⟶ X') (g' : X' ⟶ Y') (h' : Y' ⟶ Z) :
f ≫ g ≫ h ≫ e.unit.app Z = f' ≫ g' ≫ h' ≫ e.unit.app Z ↔ f ≫ g ≫ h = f' ≫ g' ≫ h' :=
by simp only [←category.assoc, cancel_mono]
@[simp] lemma cancel_counit_inv_right_assoc' {W X X' Y Y' Z : D}
(f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) (f' : W ⟶ X') (g' : X' ⟶ Y') (h' : Y' ⟶ Z) :
f ≫ g ≫ h ≫ e.counit_inv.app Z = f' ≫ g' ≫ h' ≫ e.counit_inv.app Z ↔ f ≫ g ≫ h = f' ≫ g' ≫ h' :=
by simp only [←category.assoc, cancel_mono]
end cancellation_lemmas
section
-- There's of course a monoid structure on `C ≌ C`,
-- but let's not encourage using it.
-- The power structure is nevertheless useful.
/-- Powers of an auto-equivalence. -/
def pow (e : C ≌ C) : ℤ → (C ≌ C)
| (int.of_nat 0) := equivalence.refl
| (int.of_nat 1) := e
| (int.of_nat (n+2)) := e.trans (pow (int.of_nat (n+1)))
| (int.neg_succ_of_nat 0) := e.symm
| (int.neg_succ_of_nat (n+1)) := e.symm.trans (pow (int.neg_succ_of_nat n))
instance : has_pow (C ≌ C) ℤ := ⟨pow⟩
@[simp] lemma pow_zero (e : C ≌ C) : e^(0 : ℤ) = equivalence.refl := rfl
@[simp] lemma pow_one (e : C ≌ C) : e^(1 : ℤ) = e := rfl
@[simp] lemma pow_minus_one (e : C ≌ C) : e^(-1 : ℤ) = e.symm := rfl
-- TODO as necessary, add the natural isomorphisms `(e^a).trans e^b ≅ e^(a+b)`.
-- At this point, we haven't even defined the category of equivalences.
end
end equivalence
/-- A functor that is part of a (half) adjoint equivalence -/
class is_equivalence (F : C ⥤ D) :=
mk' ::
(inverse : D ⥤ C)
(unit_iso : 𝟭 C ≅ F ⋙ inverse)
(counit_iso : inverse ⋙ F ≅ 𝟭 D)
(functor_unit_iso_comp' : ∀ (X : C), F.map ((unit_iso.hom : 𝟭 C ⟶ F ⋙ inverse).app X) ≫
counit_iso.hom.app (F.obj X) = 𝟙 (F.obj X) . obviously)
restate_axiom is_equivalence.functor_unit_iso_comp'
namespace is_equivalence
instance of_equivalence (F : C ≌ D) : is_equivalence F.functor :=
{ ..F }
instance of_equivalence_inverse (F : C ≌ D) : is_equivalence F.inverse :=
is_equivalence.of_equivalence F.symm
open equivalence
/-- To see that a functor is an equivalence, it suffices to provide an inverse functor `G` such that
`F ⋙ G` and `G ⋙ F` are naturally isomorphic to identity functors. -/
protected definition mk {F : C ⥤ D} (G : D ⥤ C)
(η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : is_equivalence F :=
⟨G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩
end is_equivalence
namespace functor
/-- Interpret a functor that is an equivalence as an equivalence. -/
def as_equivalence (F : C ⥤ D) [is_equivalence F] : C ≌ D :=
⟨F, is_equivalence.inverse F, is_equivalence.unit_iso, is_equivalence.counit_iso,
is_equivalence.functor_unit_iso_comp⟩
instance is_equivalence_refl : is_equivalence (𝟭 C) :=
is_equivalence.of_equivalence equivalence.refl
/-- The inverse functor of a functor that is an equivalence. -/
def inv (F : C ⥤ D) [is_equivalence F] : D ⥤ C :=
is_equivalence.inverse F
instance is_equivalence_inv (F : C ⥤ D) [is_equivalence F] : is_equivalence F.inv :=
is_equivalence.of_equivalence F.as_equivalence.symm
@[simp] lemma as_equivalence_functor (F : C ⥤ D) [is_equivalence F] :
F.as_equivalence.functor = F := rfl
@[simp] lemma as_equivalence_inverse (F : C ⥤ D) [is_equivalence F] :
F.as_equivalence.inverse = inv F := rfl
@[simp] lemma inv_inv (F : C ⥤ D) [is_equivalence F] :
inv (inv F) = F := rfl
/-- The composition of functor that is an equivalence with its inverse is naturally isomorphic to
the identity functor. -/
def fun_inv_id (F : C ⥤ D) [is_equivalence F] : F ⋙ F.inv ≅ 𝟭 C :=
is_equivalence.unit_iso.symm
/-- The composition of functor that is an equivalence with its inverse is naturally isomorphic to
the identity functor. -/
def inv_fun_id (F : C ⥤ D) [is_equivalence F] : F.inv ⋙ F ≅ 𝟭 D :=
is_equivalence.counit_iso
variables {E : Type u₃} [category.{v₃} E]
instance is_equivalence_trans (F : C ⥤ D) (G : D ⥤ E) [is_equivalence F] [is_equivalence G] :
is_equivalence (F ⋙ G) :=
is_equivalence.of_equivalence (equivalence.trans (as_equivalence F) (as_equivalence G))
end functor
namespace equivalence
@[simp]
lemma functor_inv (E : C ≌ D) : E.functor.inv = E.inverse := rfl
@[simp]
lemma inverse_inv (E : C ≌ D) : E.inverse.inv = E.functor := rfl
@[simp]
lemma functor_as_equivalence (E : C ≌ D) : E.functor.as_equivalence = E :=
by { cases E, congr, }
@[simp]
lemma inverse_as_equivalence (E : C ≌ D) : E.inverse.as_equivalence = E.symm :=
by { cases E, congr, }
end equivalence
namespace is_equivalence
@[simp] lemma fun_inv_map (F : C ⥤ D) [is_equivalence F] (X Y : D) (f : X ⟶ Y) :
F.map (F.inv.map f) = F.inv_fun_id.hom.app X ≫ f ≫ F.inv_fun_id.inv.app Y :=
begin
erw [nat_iso.naturality_2],
refl
end
@[simp] lemma inv_fun_map (F : C ⥤ D) [is_equivalence F] (X Y : C) (f : X ⟶ Y) :
F.inv.map (F.map f) = F.fun_inv_id.hom.app X ≫ f ≫ F.fun_inv_id.inv.app Y :=
begin
erw [nat_iso.naturality_2],
refl
end
-- We should probably restate many of the lemmas about `equivalence` for `is_equivalence`,
-- but these are the only ones I need for now.
@[simp] lemma functor_unit_comp (E : C ⥤ D) [is_equivalence E] (Y) :
E.map (E.fun_inv_id.inv.app Y) ≫ E.inv_fun_id.hom.app (E.obj Y) = 𝟙 _ :=
equivalence.functor_unit_comp E.as_equivalence Y
@[simp] lemma inv_fun_id_inv_comp (E : C ⥤ D) [is_equivalence E] (Y) :
E.inv_fun_id.inv.app (E.obj Y) ≫ E.map (E.fun_inv_id.hom.app Y) = 𝟙 _ :=
eq_of_inv_eq_inv (functor_unit_comp _ _)
end is_equivalence
namespace equivalence
/--
An equivalence is essentially surjective.
See https://stacks.math.columbia.edu/tag/02C3.
-/
lemma ess_surj_of_equivalence (F : C ⥤ D) [is_equivalence F] : ess_surj F :=
⟨λ Y, ⟨F.inv.obj Y, ⟨F.inv_fun_id.app Y⟩⟩⟩
/--
An equivalence is faithful.
See https://stacks.math.columbia.edu/tag/02C3.
-/
@[priority 100] -- see Note [lower instance priority]
instance faithful_of_equivalence (F : C ⥤ D) [is_equivalence F] : faithful F :=
{ map_injective' := λ X Y f g w,
begin
have p := congr_arg (@category_theory.functor.map _ _ _ _ F.inv _ _) w,
simpa only [cancel_epi, cancel_mono, is_equivalence.inv_fun_map] using p
end }.
/--
An equivalence is full.
See https://stacks.math.columbia.edu/tag/02C3.
-/
@[priority 100] -- see Note [lower instance priority]
instance full_of_equivalence (F : C ⥤ D) [is_equivalence F] : full F :=
{ preimage := λ X Y f, F.fun_inv_id.inv.app X ≫ F.inv.map f ≫ F.fun_inv_id.hom.app Y,
witness' := λ X Y f, F.inv.map_injective
(by simpa only [is_equivalence.inv_fun_map, assoc, iso.hom_inv_id_app_assoc, iso.hom_inv_id_app] using comp_id _) }
@[simps] private noncomputable def equivalence_inverse (F : C ⥤ D) [full F] [faithful F] [ess_surj F] : D ⥤ C :=
{ obj := λ X, F.obj_preimage X,
map := λ X Y f, F.preimage ((F.obj_obj_preimage_iso X).hom ≫ f ≫ (F.obj_obj_preimage_iso Y).inv),
map_id' := λ X, begin apply F.map_injective, tidy end,
map_comp' := λ X Y Z f g, by apply F.map_injective; simp }
/--
A functor which is full, faithful, and essentially surjective is an equivalence.
See https://stacks.math.columbia.edu/tag/02C3.
-/
noncomputable def equivalence_of_fully_faithfully_ess_surj
(F : C ⥤ D) [full F] [faithful F] [ess_surj F] : is_equivalence F :=
is_equivalence.mk (equivalence_inverse F)
(nat_iso.of_components
(λ X, (preimage_iso $ F.obj_obj_preimage_iso $ F.obj X).symm)
(λ X Y f, by { apply F.map_injective, obviously }))
(nat_iso.of_components F.obj_obj_preimage_iso (by tidy))
@[simp] lemma functor_map_inj_iff (e : C ≌ D) {X Y : C} (f g : X ⟶ Y) :
e.functor.map f = e.functor.map g ↔ f = g :=
⟨λ h, e.functor.map_injective h, λ h, h ▸ rfl⟩
@[simp] lemma inverse_map_inj_iff (e : C ≌ D) {X Y : D} (f g : X ⟶ Y) :
e.inverse.map f = e.inverse.map g ↔ f = g :=
functor_map_inj_iff e.symm f g
end equivalence
end category_theory
|
34d68ee3ef8902590908ae612dbf84560325b82b | c777c32c8e484e195053731103c5e52af26a25d1 | /src/analysis/calculus/darboux.lean | 1d25068eee2f2ff0bd87cf5cee10807e9f692222 | [
"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 | 4,810 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.calculus.local_extr
/-!
# Darboux's theorem
In this file we prove that the derivative of a differentiable function on an interval takes all
intermediate values. The proof is based on the
[Wikipedia](https://en.wikipedia.org/wiki/Darboux%27s_theorem_(analysis)) page about this theorem.
-/
open filter set
open_locale topology classical
variables {a b : ℝ} {f f' : ℝ → ℝ}
/-- **Darboux's theorem**: if `a ≤ b` and `f' a < m < f' b`, then `f' c = m` for some
`c ∈ [a, b]`. -/
theorem exists_has_deriv_within_at_eq_of_gt_of_lt
(hab : a ≤ b) (hf : ∀ x ∈ (Icc a b), has_deriv_within_at f (f' x) (Icc a b) x)
{m : ℝ} (hma : f' a < m) (hmb : m < f' b) :
m ∈ f' '' (Icc a b) :=
begin
have hab' : a < b,
{ refine lt_of_le_of_ne hab (λ hab', _),
subst b,
exact lt_asymm hma hmb },
set g : ℝ → ℝ := λ x, f x - m * x,
have hg : ∀ x ∈ Icc a b, has_deriv_within_at g (f' x - m) (Icc a b) x,
{ intros x hx,
simpa using (hf x hx).sub ((has_deriv_within_at_id x _).const_mul m) },
obtain ⟨c, cmem, hc⟩ : ∃ c ∈ Icc a b, is_min_on g (Icc a b) c,
from is_compact_Icc.exists_forall_le (nonempty_Icc.2 $ hab)
(λ x hx, (hg x hx).continuous_within_at),
have cmem' : c ∈ Ioo a b,
{ cases eq_or_lt_of_le cmem.1 with hac hac,
-- Show that `c` can't be equal to `a`
{ subst c,
refine absurd (sub_nonneg.1 $ nonneg_of_mul_nonneg_right _ (sub_pos.2 hab'))
(not_le_of_lt hma),
have : b - a ∈ pos_tangent_cone_at (Icc a b) a,
from mem_pos_tangent_cone_at_of_segment_subset (segment_eq_Icc hab ▸ subset.refl _),
simpa [-sub_nonneg, -continuous_linear_map.map_sub]
using hc.localize.has_fderiv_within_at_nonneg (hg a (left_mem_Icc.2 hab)) this },
cases eq_or_lt_of_le cmem.2 with hbc hbc,
-- Show that `c` can't be equal to `b`
{ subst c,
refine absurd (sub_nonpos.1 $ nonpos_of_mul_nonneg_right _ (sub_lt_zero.2 hab'))
(not_le_of_lt hmb),
have : a - b ∈ pos_tangent_cone_at (Icc a b) b,
from mem_pos_tangent_cone_at_of_segment_subset (by rw [segment_symm, segment_eq_Icc hab]),
simpa [-sub_nonneg, -continuous_linear_map.map_sub]
using hc.localize.has_fderiv_within_at_nonneg (hg b (right_mem_Icc.2 hab)) this },
exact ⟨hac, hbc⟩ },
use [c, cmem],
rw [← sub_eq_zero],
have : Icc a b ∈ 𝓝 c, by rwa [← mem_interior_iff_mem_nhds, interior_Icc],
exact (hc.is_local_min this).has_deriv_at_eq_zero ((hg c cmem).has_deriv_at this)
end
/-- **Darboux's theorem**: if `a ≤ b` and `f' a > m > f' b`, then `f' c = m` for some `c ∈ [a, b]`.
-/
theorem exists_has_deriv_within_at_eq_of_lt_of_gt
(hab : a ≤ b) (hf : ∀ x ∈ (Icc a b), has_deriv_within_at f (f' x) (Icc a b) x)
{m : ℝ} (hma : m < f' a) (hmb : f' b < m) :
m ∈ f' '' (Icc a b) :=
let ⟨c, cmem, hc⟩ := exists_has_deriv_within_at_eq_of_gt_of_lt hab (λ x hx, (hf x hx).neg)
(neg_lt_neg hma) (neg_lt_neg hmb)
in ⟨c, cmem, neg_injective hc⟩
/-- **Darboux's theorem**: the image of a convex set under `f'` is a convex set. -/
theorem convex_image_has_deriv_at {s : set ℝ} (hs : convex ℝ s)
(hf : ∀ x ∈ s, has_deriv_at f (f' x) x) :
convex ℝ (f' '' s) :=
begin
refine ord_connected.convex ⟨_⟩,
rintros _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ m ⟨hma, hmb⟩,
cases eq_or_lt_of_le hma with hma hma,
by exact hma ▸ mem_image_of_mem f' ha,
cases eq_or_lt_of_le hmb with hmb hmb,
by exact hmb.symm ▸ mem_image_of_mem f' hb,
cases le_total a b with hab hab,
{ have : Icc a b ⊆ s, from hs.ord_connected.out ha hb,
rcases exists_has_deriv_within_at_eq_of_gt_of_lt hab
(λ x hx, (hf x $ this hx).has_deriv_within_at) hma hmb
with ⟨c, cmem, hc⟩,
exact ⟨c, this cmem, hc⟩ },
{ have : Icc b a ⊆ s, from hs.ord_connected.out hb ha,
rcases exists_has_deriv_within_at_eq_of_lt_of_gt hab
(λ x hx, (hf x $ this hx).has_deriv_within_at) hmb hma
with ⟨c, cmem, hc⟩,
exact ⟨c, this cmem, hc⟩ }
end
/-- If the derivative of a function is never equal to `m`, then either
it is always greater than `m`, or it is always less than `m`. -/
theorem deriv_forall_lt_or_forall_gt_of_forall_ne {s : set ℝ} (hs : convex ℝ s)
(hf : ∀ x ∈ s, has_deriv_at f (f' x) x) {m : ℝ} (hf' : ∀ x ∈ s, f' x ≠ m) :
(∀ x ∈ s, f' x < m) ∨ (∀ x ∈ s, m < f' x) :=
begin
contrapose! hf',
rcases hf' with ⟨⟨b, hb, hmb⟩, ⟨a, ha, hma⟩⟩,
exact (convex_image_has_deriv_at hs hf).ord_connected.out (mem_image_of_mem f' ha)
(mem_image_of_mem f' hb) ⟨hma, hmb⟩
end
|
9ad8c672ae17b16a7d7aaf02bf57c5db613e6f08 | 5ca7b1b12d14c4742e29366312ba2c2ef8201b21 | /src/game/world8/level8.lean | 40f74fe8d24fbfa540f69662d06cb46029e2bb4a | [
"Apache-2.0"
] | permissive | MatthiasHu/natural_number_game | 2e464482ef3001863430b0336133b6697b275ba3 | 2d764f72669ae30861f6a1057fce0257f3e466c4 | refs/heads/master | 1,609,719,110,419 | 1,576,345,737,000 | 1,576,345,737,000 | 240,296,314 | 0 | 0 | Apache-2.0 | 1,581,608,357,000 | 1,581,608,356,000 | null | UTF-8 | Lean | false | false | 665 | lean | import game.world8.level7 -- hide
namespace mynat -- hide
/-
# Advanced Addition World
## Level 8: `eq_zero_of_add_right_eq_self`
The lemma you're about to prove will be useful when we want to prove that $\leq$ is antisymmetric.
There are some wrong paths that you can take with this one.
-/
/- Lemma
If $a$ and $b$ are natural numbers such that
$$ a + b = a, $$
then $b = 0$.
-/
lemma eq_zero_of_add_right_eq_self (a b : mynat) : a + b = a → b = 0 :=
begin [nat_num_game]
intro h,
induction a with a ha,
{
rw zero_add at h,
assumption
},
{ apply ha,
apply succ_inj,
rw succ_add at h,
assumption,
}
end
end mynat -- hide
|
85b99bfb7049d2b984b87ebac21fa198fa725bcc | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/run/vector.lean | c2d1ea2971cb6281c0f11c777fed5f889c16f869 | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,485 | lean | import logic data.nat.basic data.prod data.unit
open nat prod
inductive vector (A : Type) : nat → Type :=
vnil {} : vector A zero,
vcons : Π {n : nat}, A → vector A n → vector A (succ n)
namespace vector
print definition no_confusion
infixr `::` := vcons
theorem vcons.inj₁ {A : Type} {n : nat} (a₁ a₂ : A) (v₁ v₂ : vector A n) : vcons a₁ v₁ = vcons a₂ v₂ → a₁ = a₂ :=
begin
intro h, apply (no_confusion h), intros, assumption
end
theorem vcons.inj₂ {A : Type} {n : nat} (a₁ a₂ : A) (v₁ v₂ : vector A n) : vcons a₁ v₁ = vcons a₂ v₂ → v₁ = v₂ :=
begin
intro h, apply heq.to_eq, apply (no_confusion h), intros, eassumption,
end
section
universe variables l₁ l₂
variable {A : Type.{l₁}}
variable {C : Π (n : nat), vector A n → Type.{l₂+1}}
definition brec_on {n : nat} (v : vector A n) (H : Π (n : nat) (v : vector A n), @below A C n v → C n v) : C n v :=
have general : C n v × @below A C n v, from
rec_on v
(pair (H zero vnil unit.star) unit.star)
(λ (n₁ : nat) (a₁ : A) (v₁ : vector A n₁) (r₁ : C n₁ v₁ × @below A C n₁ v₁),
have b : @below A C _ (vcons a₁ v₁), from
r₁,
have c : C (succ n₁) (vcons a₁ v₁), from
H (succ n₁) (vcons a₁ v₁) b,
pair c b),
pr₁ general
end
check brec_on
definition bw := @below
definition sum {n : nat} (v : vector nat n) : nat :=
brec_on v (λ (n : nat) (v : vector nat n),
cases_on v
(λ (B : bw vnil), zero)
(λ (n₁ : nat) (a : nat) (v₁ : vector nat n₁) (B : bw (vcons a v₁)),
a + pr₁ B))
example : sum (10 :: 20 :: vnil) = 30 :=
rfl
definition addk {n : nat} (v : vector nat n) (k : nat) : vector nat n :=
brec_on v (λ (n : nat) (v : vector nat n),
cases_on v
(λ (B : bw vnil), vnil)
(λ (n₁ : nat) (a₁ : nat) (v₁ : vector nat n₁) (B : bw (vcons a₁ v₁)),
vcons (a₁+k) (pr₁ B)))
example : addk (1 :: 2 :: vnil) 3 = 4 :: 5 :: vnil :=
rfl
definition append.{l} {A : Type.{l+1}} {n m : nat} (w : vector A m) (v : vector A n) : vector A (n + m) :=
brec_on w (λ (n : nat) (w : vector A n),
cases_on w
(λ (B : bw vnil), v)
(λ (n₁ : nat) (a₁ : A) (v₁ : vector A n₁) (B : bw (vcons a₁ v₁)),
vcons a₁ (pr₁ B)))
example : append (1 :: 2 :: vnil) (3 :: vnil) = 1 :: 2 :: 3 :: vnil :=
rfl
definition head {A : Type} {n : nat} (v : vector A (succ n)) : A :=
cases_on v
(λ H : succ n = 0, nat.no_confusion H)
(λn' h t (H : succ n = succ n'), h)
rfl
definition tail {A : Type} {n : nat} (v : vector A (succ n)) : vector A n :=
@cases_on A (λn' v, succ n = n' → vector A (pred n')) (succ n) v
(λ H : succ n = 0, nat.no_confusion H)
(λ (n' : nat) (h : A) (t : vector A n') (H : succ n = succ n'),
t)
rfl
definition add {n : nat} (w v : vector nat n) : vector nat n :=
@brec_on nat (λ (n : nat) (v : vector nat n), vector nat n → vector nat n) n w
(λ (n : nat) (w : vector nat n),
cases_on w
(λ (B : bw vnil) (w : vector nat zero), vnil)
(λ (n₁ : nat) (a₁ : nat) (v₁ : vector nat n₁) (B : bw (vcons a₁ v₁)) (v : vector nat (succ n₁)),
vcons (a₁ + head v) (pr₁ B (tail v)))) v
example : add (1 :: 2 :: vnil) (3 :: 5 :: vnil) = 4 :: 7 :: vnil :=
rfl
end vector
|
e920f2e8eddb6c193f134abdb1cb59ecca31819d | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/special_functions/trigonometric/euler_sine_prod.lean | 955b1d130e7e2d19dfa2f08a52814ecb90ee2d58 | [
"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 | 16,048 | lean | /-
Copyright (c) 2023 David Loeffler. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Loeffler
-/
import analysis.special_functions.integrals
import measure_theory.integral.peak_function
/-! # Euler's infinite product for the sine function
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file proves the infinite product formula
$$ \sin \pi z = \pi z \prod_{n = 1}^\infty \left(1 - \frac{z ^ 2}{n ^ 2}\right) $$
for any real or complex `z`. Our proof closely follows the article
[Salwinski, *Euler's Sine Product Formula: An Elementary Proof*][salwinski2018]: the basic strategy
is to prove a recurrence relation for the integrals `∫ x in 0..π/2, cos 2 z x * cos x ^ (2 * n)`,
generalising the arguments used to prove Wallis' limit formula for `π`.
-/
open_locale real topology big_operators
open real set filter interval_integral measure_theory.measure_space
namespace euler_sine
section integral_recursion
/-! ## Recursion formula for the integral of `cos (2 * z * x) * cos x ^ n`
We evaluate the integral of `cos (2 * z * x) * cos x ^ n`, for any complex `z` and even integers
`n`, via repeated integration by parts. -/
variables {z : ℂ} {n : ℕ}
lemma antideriv_cos_comp_const_mul (hz : z ≠ 0) (x : ℝ) :
has_deriv_at (λ y:ℝ, complex.sin (2 * z * y) / (2 * z)) (complex.cos (2 * z * x)) x :=
begin
have a : has_deriv_at _ _ ↑x := has_deriv_at_mul_const _,
have b : has_deriv_at (λ (y : ℂ), complex.sin (y * (2 * z))) _ ↑x :=
has_deriv_at.comp x (complex.has_deriv_at_sin (x * (2 * z))) a,
convert (b.comp_of_real).div_const (2 * z),
{ ext1 x, rw mul_comm _ (2 * z) },
{ field_simp, rw mul_comm _ (2 * z) },
end
lemma antideriv_sin_comp_const_mul (hz : z ≠ 0) (x : ℝ) :
has_deriv_at (λ y:ℝ, -complex.cos (2 * z * y) / (2 * z)) (complex.sin (2 * z * x)) x :=
begin
have a : has_deriv_at _ _ ↑x := has_deriv_at_mul_const _,
have b : has_deriv_at (λ (y : ℂ), complex.cos (y * (2 * z))) _ ↑x :=
has_deriv_at.comp x (complex.has_deriv_at_cos (x * (2 * z))) a,
convert ((b.comp_of_real).div_const (2 * z)).neg,
{ ext1 x, rw mul_comm _ (2 * z), field_simp },
{ field_simp, rw mul_comm _ (2 * z) },
end
lemma integral_cos_mul_cos_pow_aux (hn : 2 ≤ n) (hz : z ≠ 0):
(∫ x:ℝ in 0..π/2, complex.cos (2 * z * x) * cos x ^ n) =
n / (2 * z) * ∫ x:ℝ in 0..π/2, complex.sin (2 * z * x) * sin x * cos x ^ (n - 1) :=
begin
have der1 : ∀ (x : ℝ), (x ∈ uIcc 0 (π/2)) → has_deriv_at (λ y, (↑(cos y)) ^ n : ℝ → ℂ)
(-n * sin x * cos x ^ (n - 1)) x,
{ intros x hx,
have b : has_deriv_at (λ y, ↑(cos y) : ℝ → ℂ) (-sin x) x,
by simpa using (has_deriv_at_cos x).of_real_comp,
convert has_deriv_at.comp x (has_deriv_at_pow _ _) b using 1,
ring, },
convert integral_mul_deriv_eq_deriv_mul der1 (λ x hx, antideriv_cos_comp_const_mul hz x) _ _,
{ ext1 x, rw mul_comm },
{ rw [complex.of_real_zero, mul_zero, complex.sin_zero, zero_div, mul_zero, sub_zero,
cos_pi_div_two, complex.of_real_zero, zero_pow (by positivity : 0 < n), zero_mul, zero_sub,
←integral_neg, ←integral_const_mul],
refine integral_congr (λ x hx, _),
field_simp, ring },
{ apply continuous.interval_integrable,
exact (continuous_const.mul (complex.continuous_of_real.comp continuous_sin)).mul
((complex.continuous_of_real.comp continuous_cos).pow (n - 1)) },
{ apply continuous.interval_integrable,
exact complex.continuous_cos.comp (continuous_const.mul complex.continuous_of_real) }
end
lemma integral_sin_mul_sin_mul_cos_pow_eq (hn : 2 ≤ n) (hz : z ≠ 0) :
∫ x:ℝ in 0..π/2, complex.sin (2 * z * x) * sin x * cos x ^ (n - 1) =
n / (2 * z) * (∫ x:ℝ in 0..π/2, complex.cos (2 * z * x) * cos x ^ n) -
(n - 1) / (2 * z) * (∫ x:ℝ in 0..π/2, complex.cos (2 * z * x) * cos x ^ (n - 2)) :=
begin
have der1 : ∀ (x : ℝ), (x ∈ uIcc 0 (π/2)) →
has_deriv_at (λ y, (sin y) * (cos y) ^ (n - 1) : ℝ → ℂ)
(cos x ^ n - (n - 1) * sin x ^ 2 * cos x ^ (n - 2)) x,
{ intros x hx,
have c := has_deriv_at.comp (x:ℂ) (has_deriv_at_pow (n - 1) _) (complex.has_deriv_at_cos x),
convert ((complex.has_deriv_at_sin x).mul c).comp_of_real using 1,
{ ext1 y, simp only [complex.of_real_sin, complex.of_real_cos] },
{ simp only [complex.of_real_cos, complex.of_real_sin],
rw [mul_neg, mul_neg, ←sub_eq_add_neg, function.comp_app],
congr' 1,
{ rw [←pow_succ, nat.sub_add_cancel (by linarith : 1 ≤ n)] },
{ have : ((n - 1 : ℕ) : ℂ) = (n:ℂ) - 1,
{ rw [nat.cast_sub (one_le_two.trans hn), nat.cast_one] },
rw [nat.sub_sub, this],
ring } } },
convert integral_mul_deriv_eq_deriv_mul der1 (λ x hx, antideriv_sin_comp_const_mul hz x) _ _
using 1,
{ refine integral_congr (λ x hx, _),
ring_nf },
{ -- now a tedious rearrangement of terms
-- gather into a single integral, and deal with continuity subgoals:
rw [sin_zero, cos_pi_div_two, complex.of_real_zero, zero_pow, zero_mul, mul_zero, zero_mul,
zero_mul, sub_zero, zero_sub, ←integral_neg, ←integral_const_mul, ←integral_const_mul,
←integral_sub],
rotate,
{ apply continuous.interval_integrable,
exact continuous_const.mul ((complex.continuous_cos.comp (continuous_const.mul
complex.continuous_of_real)).mul ((complex.continuous_of_real.comp
continuous_cos).pow n)) },
{ apply continuous.interval_integrable,
exact continuous_const.mul
((complex.continuous_cos.comp (continuous_const.mul complex.continuous_of_real)).mul
((complex.continuous_of_real.comp continuous_cos).pow (n - 2))), },
{ apply nat.sub_pos_of_lt, exact one_lt_two.trans_le hn },
refine integral_congr (λ x hx, _),
dsimp only,
-- get rid of real trig functions and divions by 2 * z:
rw [complex.of_real_cos, complex.of_real_sin, complex.sin_sq, ←mul_div_right_comm,
←mul_div_right_comm, ←sub_div, mul_div, ←neg_div],
congr' 1,
have : complex.cos ↑x ^ n = complex.cos ↑x ^ (n - 2) * complex.cos ↑x ^ 2,
{ conv_lhs { rw [←nat.sub_add_cancel hn, pow_add] } },
rw this,
ring },
{ apply continuous.interval_integrable,
exact ((complex.continuous_of_real.comp continuous_cos).pow n).sub
((continuous_const.mul ((complex.continuous_of_real.comp continuous_sin).pow 2)).mul
((complex.continuous_of_real.comp continuous_cos).pow (n - 2))) },
{ apply continuous.interval_integrable,
exact complex.continuous_sin.comp (continuous_const.mul complex.continuous_of_real) },
end
/-- Note this also holds for `z = 0`, but we do not need this case for `sin_pi_mul_eq`. -/
lemma integral_cos_mul_cos_pow (hn : 2 ≤ n) (hz : z ≠ 0) :
(1 - 4 * z ^ 2 / n ^ 2) * (∫ x:ℝ in 0..π/2, complex.cos (2 * z * x) * cos x ^ n) =
(n - 1 : ℂ) / n * ∫ x:ℝ in 0..π/2, complex.cos (2 * z * x) * cos x ^ (n - 2) :=
begin
have nne : (n : ℂ) ≠ 0,
{ contrapose! hn, rw nat.cast_eq_zero at hn, rw hn, exact zero_lt_two },
have := integral_cos_mul_cos_pow_aux hn hz,
rw [integral_sin_mul_sin_mul_cos_pow_eq hn hz, sub_eq_neg_add, mul_add, ←sub_eq_iff_eq_add]
at this,
convert congr_arg (λ u:ℂ, -u * (2 * z) ^ 2 / n ^ 2) this using 1;
{ field_simp, ring },
end
/-- Note this also holds for `z = 0`, but we do not need this case for `sin_pi_mul_eq`. -/
lemma integral_cos_mul_cos_pow_even (n : ℕ) (hz : z ≠ 0) :
(1 - z ^ 2 / (n + 1) ^ 2) * (∫ x:ℝ in 0..π/2, complex.cos (2 * z * x) * cos x ^ (2 * n + 2)) =
(2 * n + 1 : ℂ) / (2 * n + 2) * ∫ x:ℝ in 0..π/2, complex.cos (2 * z * x) * cos x ^ (2 * n) :=
begin
convert integral_cos_mul_cos_pow (by linarith : 2 ≤ 2 * n + 2) hz using 3,
{ simp only [nat.cast_add, nat.cast_mul, nat.cast_two],
nth_rewrite_rhs 2 ←mul_one (2:ℂ),
rw [←mul_add, mul_pow, ←div_div],
ring },
{ push_cast, ring },
{ push_cast, ring },
end
/-- Relate the integral `cos x ^ n` over `[0, π/2]` to the integral of `sin x ^ n` over `[0, π]`,
which is studied in `data.real.pi.wallis` and other places. -/
lemma integral_cos_pow_eq (n : ℕ) :
(∫ (x:ℝ) in 0..π/2, cos x ^ n) = 1 / 2 * (∫ (x:ℝ) in 0..π, (sin x) ^ n) :=
begin
rw [mul_comm (1/2 : ℝ), ←div_eq_iff (one_div_ne_zero (two_ne_zero' ℝ)), ←div_mul, div_one,
mul_two],
have L : interval_integrable _ volume 0 (π / 2) := (continuous_sin.pow n).interval_integrable _ _,
have R : interval_integrable _ volume (π / 2) π := (continuous_sin.pow n).interval_integrable _ _,
rw ←integral_add_adjacent_intervals L R,
congr' 1,
{ nth_rewrite 0 (by ring : 0 = π/2 - π/2),
nth_rewrite 2 (by ring : π/2 = π/2 - 0),
rw ←integral_comp_sub_left,
refine integral_congr (λ x _, _),
dsimp only,
rw cos_pi_div_two_sub },
{ nth_rewrite 2 (by ring : π = π/2 + π/2),
nth_rewrite 1 (by ring : π/2 = 0 + π/2),
rw ←integral_comp_add_right,
refine integral_congr (λ x _, _),
dsimp only,
rw sin_add_pi_div_two },
end
lemma integral_cos_pow_pos (n : ℕ) : 0 < (∫ (x:ℝ) in 0..π/2, cos x ^ n) :=
(integral_cos_pow_eq n).symm ▸ (mul_pos one_half_pos (integral_sin_pow_pos _))
/-- Finite form of Euler's sine product, with remainder term expressed as a ratio of cosine
integrals. -/
lemma sin_pi_mul_eq (z : ℂ) (n : ℕ) :
complex.sin (π * z) = π * z * (∏ j in finset.range n, (1 - z ^ 2 / (j + 1) ^ 2)) *
(∫ x in 0..π/2, complex.cos (2 * z * x) * cos x ^ (2 * n)) / ↑∫ x in 0..π/2, cos x ^ (2 * n) :=
begin
rcases eq_or_ne z 0 with rfl | hz,
{ simp },
induction n with n hn,
{ simp_rw [mul_zero, pow_zero, mul_one, finset.prod_range_zero, mul_one, integral_one, sub_zero],
rw [integral_cos_mul_complex (mul_ne_zero two_ne_zero hz), complex.of_real_zero, mul_zero,
complex.sin_zero, zero_div, sub_zero,
(by { push_cast, field_simp, ring } : 2 * z * ↑(π / 2) = π * z)],
field_simp [complex.of_real_ne_zero.mpr pi_pos.ne'],
ring },
{ rw [hn, finset.prod_range_succ],
set A := ∏ j in finset.range n, (1 - z ^ 2 / (j + 1) ^ 2),
set B := ∫ x:ℝ in 0..π/2, complex.cos (2 * z * x) * cos x ^ (2 * n),
set C := ∫ x:ℝ in 0..π/2, cos x ^ (2 * n),
have aux' : 2 * n.succ = 2 * n + 2,
{ rw [nat.succ_eq_add_one, mul_add, mul_one], },
have : ∫ x:ℝ in 0..π/2, cos x ^ (2 * n.succ) = (2 * (n:ℝ) + 1) / (2 * n + 2) * C,
{ rw integral_cos_pow_eq,
dsimp only [C],
rw [integral_cos_pow_eq, aux', integral_sin_pow, sin_zero, sin_pi, pow_succ, zero_mul,
zero_mul, zero_mul, sub_zero, zero_div, zero_add, ←mul_assoc, ←mul_assoc,
mul_comm (1 / 2 : ℝ) _, nat.cast_mul, nat.cast_bit0, nat.cast_one] },
rw this,
change ↑π * z * A * B / ↑C =
(↑π * z * (A * (1 - z ^ 2 / (↑n + 1) ^ 2)) *
∫ (x : ℝ) in 0..π / 2, complex.cos (2 * z * ↑x) * ↑(cos x) ^ (2 * n.succ)) /
↑((2 * ↑n + 1) / (2 * ↑n + 2) * C),
have : ↑π * z * (A * (1 - z ^ 2 / (↑n + 1) ^ 2)) *
∫ (x : ℝ) in 0..π / 2, complex.cos (2 * z * ↑x) * ↑(cos x) ^ (2 * n.succ)
= ↑π * z * A * ((1 - z ^ 2 / (↑n.succ) ^ 2) *
∫ (x : ℝ) in 0..π / 2, complex.cos (2 * z * ↑x) * ↑(cos x) ^ (2 * n.succ)),
{ nth_rewrite_rhs 0 nat.succ_eq_add_one,
rw nat.cast_add_one,
ring },
rw this,
suffices : (1 - z ^ 2 / ↑(n.succ) ^ 2) *
∫ (x : ℝ) in 0..π / 2, complex.cos (2 * z * ↑x) * ↑(cos x) ^ (2 * n.succ) =
(2 * n + 1) / (2 * n + 2) * B,
{ rw [this, complex.of_real_mul, complex.of_real_div],
have : (C:ℂ) ≠ 0 := complex.of_real_ne_zero.mpr (integral_cos_pow_pos _).ne',
have : 2 * (n:ℂ) + 1 ≠ 0,
{ convert (nat.cast_add_one_ne_zero (2 * n) : (↑(2 * n) + 1 : ℂ) ≠ 0),
simp },
have : 2 * (n:ℂ) + 2 ≠ 0,
{ convert (nat.cast_add_one_ne_zero (2 * n + 1) : (↑(2 * n + 1) + 1 : ℂ) ≠ 0) using 1,
push_cast, ring },
field_simp, ring },
convert integral_cos_mul_cos_pow_even n hz,
rw nat.cast_succ }
end
end integral_recursion
/-! ## Conclusion of the proof
The main theorem `complex.tendsto_euler_sin_prod`, and its real variant
`real.tendsto_euler_sin_prod`, now follow by combining `sin_pi_mul_eq` with a lemma
stating that the sequence of measures on `[0, π/2]` given by integration against `cos x ^ n`
(suitably normalised) tends to the Dirac measure at 0, as a special case of the general result
`tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_continuous_on`. -/
lemma tendsto_integral_cos_pow_mul_div {f : ℝ → ℂ} (hf : continuous_on f (Icc 0 (π/2))) :
tendsto (λ (n : ℕ), (∫ x:ℝ in 0..π/2, ↑(cos x) ^ n * f x) / ↑(∫ x:ℝ in 0..π/2, (cos x) ^ n))
at_top (𝓝 $ f 0) :=
begin
simp_rw [div_eq_inv_mul _ (coe _), ←complex.of_real_inv, integral_of_le (pi_div_two_pos.le),
←measure_theory.integral_Icc_eq_integral_Ioc, ←complex.of_real_pow, ←complex.real_smul],
have c_lt : ∀ (y : ℝ), y ∈ Icc 0 (π / 2) → y ≠ 0 → cos y < cos 0, from λ y hy hy',
cos_lt_cos_of_nonneg_of_le_pi_div_two (le_refl 0) hy.2 (lt_of_le_of_ne hy.1 hy'.symm),
have c_nonneg : ∀ (x : ℝ), x ∈ Icc 0 (π / 2) → 0 ≤ cos x, from λ x hx, cos_nonneg_of_mem_Icc
((Icc_subset_Icc_left (neg_nonpos_of_nonneg pi_div_two_pos.le)) hx),
have c_zero_pos : 0 < cos 0, by { rw cos_zero, exact zero_lt_one },
have zero_mem : (0:ℝ) ∈ closure (interior (Icc 0 (π / 2))),
{ rw [interior_Icc, closure_Ioo pi_div_two_pos.ne, left_mem_Icc],
exact pi_div_two_pos.le },
exact tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_continuous_on
is_compact_Icc continuous_on_cos c_lt c_nonneg c_zero_pos zero_mem hf
end
/-- Euler's infinite product formula for the complex sine function. -/
lemma _root_.complex.tendsto_euler_sin_prod (z : ℂ) :
tendsto (λ n:ℕ, ↑π * z * (∏ j in finset.range n, (1 - z ^ 2 / (j + 1) ^ 2)))
at_top (𝓝 $ complex.sin (π * z)) :=
begin
have A : tendsto (λ n:ℕ, ↑π * z * (∏ j in finset.range n, (1 - z ^ 2 / (j + 1) ^ 2)) *
(∫ x in 0..π / 2, complex.cos (2 * z * x) * cos x ^ (2 * n)) /
↑∫ x in 0..π / 2, cos x ^ (2 * n))
at_top (𝓝 $ _) := tendsto.congr (λ n, (sin_pi_mul_eq z n)) tendsto_const_nhds,
have : 𝓝 (complex.sin (π * z)) = 𝓝 (complex.sin (π * z) * 1) := by rw mul_one,
simp_rw [this, mul_div_assoc] at A,
convert (tendsto_mul_iff_of_ne_zero _ one_ne_zero).mp A,
suffices : tendsto (λ n:ℕ, (∫ x:ℝ in 0..π/2, complex.cos (2 * z * x) * cos x ^ n)
/ ↑(∫ x:ℝ in 0..π/2, cos x ^ n)) at_top (𝓝 1),
from this.comp (tendsto_id.const_mul_at_top' zero_lt_two),
have : continuous_on (λ x:ℝ, complex.cos (2 * z * x)) (Icc 0 (π/2)), from
(complex.continuous_cos.comp (continuous_const.mul complex.continuous_of_real)).continuous_on,
convert tendsto_integral_cos_pow_mul_div this,
{ ext1 n, congr' 2 with x:1, rw mul_comm },
{ rw [complex.of_real_zero, mul_zero, complex.cos_zero] },
end
/-- Euler's infinite product formula for the real sine function. -/
lemma _root_.real.tendsto_euler_sin_prod (x : ℝ) :
tendsto (λ n:ℕ, π * x * (∏ j in finset.range n, (1 - x ^ 2 / (j + 1) ^ 2)))
at_top (𝓝 $ sin (π * x)) :=
begin
convert (complex.continuous_re.tendsto _).comp (complex.tendsto_euler_sin_prod x),
{ ext1 n,
rw [function.comp_app, ←complex.of_real_mul, complex.of_real_mul_re],
suffices : ∏ (j : ℕ) in finset.range n, (1 - (x:ℂ) ^ 2 / (↑j + 1) ^ 2) =
↑∏ (j : ℕ) in finset.range n, (1 - x ^ 2 / (↑j + 1) ^ 2), by rw [this, complex.of_real_re],
rw complex.of_real_prod,
refine finset.prod_congr (by refl) (λ n hn, _),
norm_cast },
{ rw [←complex.of_real_mul, ←complex.of_real_sin, complex.of_real_re] }
end
end euler_sine
|
d733a39b33a102e0f5b18063bfc3f7df52daf547 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/n5.lean | 317c36c402662e48f4ac16c526e0dcf8a31a21b0 | [
"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 | 430 | lean | prelude
constant N : Type.{1}
constant f : N → N → N → N
constant g : N → N → N
constant h : N → N → N → N
constant s : N → N → N → N → N
precedence `*`:75
precedence `|`:75
notation a * b:prev | c:prev := f a b c
notation a * b := g a b
notation a * b * c:prev := h a b c
notation a * b | c * d:prev := s a b c d
constants a b c d e : N
check a * b
check a * b | d
check a * b * c
check a * b | d * e
|
6f7acea0aacdebe18999b72053111d4c6f5e80c0 | 4e3bf8e2b29061457a887ac8889e88fa5aa0e34c | /lean/love07_metaprogramming_exercise_solution.lean | 3ed654c0d6a0b0e79ed042fcfc3cb556a5cb901f | [] | no_license | mukeshtiwari/logical_verification_2019 | 9f964c067a71f65eb8884743273fbeef99e6503d | 16f62717f55ed5b7b87e03ae0134791a9bef9b9a | refs/heads/master | 1,619,158,844,208 | 1,585,139,500,000 | 1,585,139,500,000 | 249,906,380 | 0 | 0 | null | 1,585,118,728,000 | 1,585,118,727,000 | null | UTF-8 | Lean | false | false | 8,018 | lean | /- LoVe Exercise 7: Metaprogramming -/
import .lovelib
namespace LoVe
open expr
open tactic
/- Question 1: A Term Exploder -/
/- In this exercise, we develop a string format for the `expr` metatype. By
default, there is no `has_repr` instance to print a nice string. For
example: -/
#eval (expr.app (expr.var 0) (expr.var 1) : expr) -- result: `[external]`
#eval (`(λx : ℕ, x + x) : expr) -- result: `[external]`
/- 1.1. Define a metafunction `expr.repr` that converts an `expr` into a
`string`. It is acceptable to leave out some fields from the `expr`
constructors, such as the level `l` of a sort, the binder information `bi` of
a λ or Π binder, and the arguments of the `macro` constructor.
**Hint**: Use `name.to_string` to convert a name to a string, and `repr` for
other types that belong to the `has_repr` type class. -/
meta def expr.repr : expr → string
| (var n) := "(var " ++ repr n ++ ")"
| (sort l) := "sort"
| (const n ls) := "(const " ++ n.to_string ++ ")"
| (mvar n m t) :=
"(mvar " ++ name.to_string n ++ " " ++ name.to_string m ++ " " ++
expr.repr t ++ ")"
| (local_const n m bi t) :=
"(local_const " ++ name.to_string n ++ " " ++ name.to_string m ++ " " ++
expr.repr t ++ ")"
| (app e f) :=
"(app " ++ expr.repr e ++ " " ++ expr.repr f ++ ")"
| (lam n bi e t) :=
"(lam " ++ name.to_string n ++ " " ++ expr.repr e ++ " " ++ expr.repr t ++ ")"
| (pi n bi e t) :=
"(pi " ++ name.to_string n ++ " " ++ expr.repr e ++ " " ++ expr.repr t ++ ")"
| (elet n g e f) :=
"(elet " ++ name.to_string n ++ " " ++ expr.repr g ++ " " ++ expr.repr e ++
" " ++ expr.repr f ++ ")"
| (macro d args) := "macro"
/- We register `expr.repr` in the `has_repr` type class, so that we can use
`repr` without qualification in the future, and so that it is available to
`#eval`. We need the `meta` keyword in front of the command we enter. -/
meta instance : has_repr expr := ⟨expr.repr⟩
/- 1.2. Test your setup. -/
#eval (expr.app (expr.var 0) (expr.var 1) : expr)
#eval (`(λx : ℕ, x + x) : expr)
/- 1.3. Compare your answer with `expr.to_raw_fmt`. -/
#check expr.to_raw_fmt
/- Question 2: `destruct_and` on Steroids -/
/- Recall from the lecture that `destruct_and` fails on the following easy
goal: -/
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) :
b ∧ d :=
sorry
/- We will now address this by developing a new tactic called `destro_and`,
which applies both **des**truction and in**tro**duction rules for conjunction.
It will also go automatically through the hypotheses instead of taking an
argument. We will develop it in three steps. -/
/- 2.1. Develop a tactic `intro_ands` that replaces all goals of the form
`a ∧ b` with two new goals `a` and `b` systematically, until all top-level
conjunctions are gone.
For this, we can use tactics such as `repeat` (which repeatedly applies a tactic
on all goals until the tactic fails on each of the goal) and `applyc` (which can
be used to apply a rule, in connection with backtick quoting). -/
meta def intro_ands : tactic unit :=
repeat (applyc `and.intro)
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) :
b ∧ d :=
begin
intro_ands,
/- The proof state should be as follows:
2 goals
a b c d : Prop,
h : a ∧ (b ∧ c) ∧ d
⊢ b
a b c d : Prop,
h : a ∧ (b ∧ c) ∧ d
⊢ d -/
repeat { sorry }
end
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) :
b ∧ (a ∧ (c ∧ b)) :=
begin
intro_ands,
/- The proof state should be as follows:
4 goals
a b c d : Prop,
h : a ∧ (b ∧ c) ∧ d
⊢ b
a b c d : Prop,
h : a ∧ (b ∧ c) ∧ d
⊢ a
a b c d : Prop,
h : a ∧ (b ∧ c) ∧ d
⊢ c
a b c d : Prop,
h : a ∧ (b ∧ c) ∧ d
⊢ b -/
repeat { sorry }
end
/- 2.2. Develop a tactic `destruct_ands` that replaces hypotheses of the form
`h : a ∧ b` by two new hypotheses `h_left : a` and `h_right : b` systematically,
until all top-level conjunctions are gone.
Here is imperative-style pseudocode that you can follow:
1. Retrieve the list of hypotheses from the context. This is provided by the
metaconstant `local_context`.
2. Find the first hypothesis (= term) with a type (= proposition) of the form
`_ ∧ _`. Here, you can use the `list.mfirst` function, in conjunction with
pattern matching. You can use `infer_type` to query the type of a term.
3. Perform a case split on the first found hypothesis. This can be achieved
using the `cases` metafunction.
4. Go to step 1.
The above procedure might fail if there exists no hypotheses of the required
form. Make sure to handle this failure gracefully using `<|>`. -/
meta def destruct_ands : tactic unit :=
(do
hs ← local_context,
h ← list.mfirst (λh, do `(_ ∧ _) ← infer_type h, pure h) hs,
cases h,
destruct_ands)
<|> skip
-- alternative solution:
meta def destruct_ands_v2 : tactic unit :=
repeat (do
hs ← local_context,
h ← list.mfirst (λh, do `(_ ∧ _) ← infer_type h, pure h) hs,
cases h,
skip)
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) :
b ∧ d :=
begin
destruct_ands,
/- The proof state should be as follows:
a b c d : Prop,
h_left : a,
h_right_right : d,
h_right_left_left : b,
h_right_left_right : c
⊢ b ∧ d -/
sorry
end
/- 2.3. Finally, combine the two tactics developed above and the `assumption`
tactic to implement the desired `destro_and` tactic. -/
meta def destro_and : tactic unit :=
do
destruct_ands,
intro_ands,
all_goals assumption
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) :
b ∧ d :=
by destro_and
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) :
b ∧ (a ∧ (c ∧ b)) :=
by destro_and
/- Question 3 **optional**: A Theorem Finder -/
/- We will implement a function that allows us to find theorems by constants
appearing in their statements. So given a list of constant names, the function
will list all theorems in which all these constants appear.
You can use the following metaconstants:
* `declaration` contains all data (name, type, value) associated with a
declaration understood broadly (e.g., axiom, lemma, constant, etc.);
* `tactic.get_env` gives us access to the `environment`, a metatype thats lists
all `declaration`s (including all theorems);
* `environment.fold` allows us to walk through the environment and collect data;
* `expr.fold` allows us to walk through an expression and collect data. -/
/- 3.1 **optional**. Write a metafunction that checks whether an expression
contains a specific constant.
You can use `expr.fold` to walk through the expression, `||` and `ff` for
Booleans, and `expr.is_constant_of` to check whether an expression is a
constant. -/
meta def term_contains (e : expr) (nam : name) : bool :=
expr.fold e ff (λe' d c, c || expr.is_constant_of e' nam)
/- 3.2 **optional**. Write a metafunction that checks whether an expression
contains _all_ constants in a list.
You can use `list.band` (Boolean and). -/
meta def term_contains_all (nams : list name) (e : expr) : bool :=
list.band (list.map (term_contains e) nams)
/- 3.3 **optional**. Produce the list of all theorems that contain all constants
`nams` in their statement.
`environment.fold` allows you to walk over the list of declarations. With
`declaration.type`, you get the type of a theorem, and with
`declaration.to_name` you get the name. -/
meta def list_constants (nams : list name) (e : environment) : list name :=
environment.fold e [] (λdecl nams',
if term_contains_all nams decl.type then decl.to_name :: nams' else nams')
/- Finally, we develop a tactic that uses the above metafunctions to log all
found theorems: -/
meta def find_constants (nams : list name) : tactic unit :=
do
env ← get_env,
list.mmap' trace (list_constants nams env)
/- We test the solution. -/
run_cmd find_constants [] -- lists all theorems
run_cmd find_constants [`list.map, `function.comp]
end LoVe
|
54c3995f733036f4c22c7fa155e7a0fa88299dec | fecda8e6b848337561d6467a1e30cf23176d6ad0 | /src/data/mv_polynomial/variables.lean | 66aecf9f81781f72bb25f4257db8913f4ba04470 | [
"Apache-2.0"
] | permissive | spolu/mathlib | bacf18c3d2a561d00ecdc9413187729dd1f705ed | 480c92cdfe1cf3c2d083abded87e82162e8814f4 | refs/heads/master | 1,671,684,094,325 | 1,600,736,045,000 | 1,600,736,045,000 | 297,564,749 | 1 | 0 | null | 1,600,758,368,000 | 1,600,758,367,000 | null | UTF-8 | Lean | false | false | 19,370 | 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, Johan Commelin, Mario Carneiro
-/
import data.mv_polynomial.basic
import data.set.disjointed
/-!
# Degrees and variables of polynomials
This file establishes many results about the degree and variable sets of a multivariate polynomial.
The *variable set* of a polynomial $P \in R[X]$ is a `finset` containing each $x \in X$
that appears in a monomial in $P$.
The *degree set* of a polynomial $P \in R[X]$ is a `multiset` containing, for each $x$ in the
variable set, $n$ copies of $x$, where $n$ is the maximum number of copies of $x$ appearing in a
monomial of $P$.
## Main declarations
* `mv_polynomial.degrees p` : the multiset of variables representing the union of the multisets corresponding
to each non-zero monomial in `p`. For example if `7 ≠ 0` in `R` and `p = x²y+7y³` then
`degrees p = {x, x, y, y, y}`
* `mv_polynomial.vars p` : the finset of variables occurring in `p`. For example if `p = x⁴y+yz` then
`vars p = {x, y, z}`
* `mv_polynomial.degree_of n p : ℕ` -- the total degree of `p` with respect to the variable `n`. For example
if `p = x⁴y+yz` then `degree_of y p = 1`.
* `mv_polynomial.total_degree p : ℕ` -- the max of the sizes of the multisets `s` whose monomials `X^s` occur
in `p`. For example if `p = x⁴y+yz` then `total_degree p = 5`.
## Notation
As in other polynomial files we typically use the notation:
+ `σ : Type*` (indexing the variables)
+ `α : Type*` `[comm_semiring α]` (the coefficients)
+ `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set.
This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s`
+ `a : α`
+ `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians
+ `p : mv_polynomial σ α`
-/
noncomputable theory
open_locale classical big_operators
open set function finsupp add_monoid_algebra
open_locale big_operators
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
namespace mv_polynomial
variables {σ : Type*} {a a' a₁ a₂ : α} {e : ℕ} {n m : σ} {s : σ →₀ ℕ}
section comm_semiring
variables [comm_semiring α] {p q : mv_polynomial σ α}
section degrees
/-! ### `degrees` -/
/--
The maximal degrees of each variable in a multi-variable polynomial, expressed as a multiset.
(For example, `degrees (x^2 * y + y^3)` would be `{x, x, y, y, y}`.)
-/
def degrees (p : mv_polynomial σ α) : multiset σ :=
p.support.sup (λs:σ →₀ ℕ, s.to_multiset)
lemma degrees_monomial (s : σ →₀ ℕ) (a : α) : degrees (monomial s a) ≤ s.to_multiset :=
finset.sup_le $ assume t h,
begin
have := finsupp.support_single_subset h,
rw [finset.mem_singleton] at this,
rw this
end
lemma degrees_monomial_eq (s : σ →₀ ℕ) (a : α) (ha : a ≠ 0) :
degrees (monomial s a) = s.to_multiset :=
le_antisymm (degrees_monomial s a) $ finset.le_sup $
by rw [monomial, finsupp.support_single_ne_zero ha, finset.mem_singleton]
lemma degrees_C (a : α) : degrees (C a : mv_polynomial σ α) = 0 :=
multiset.le_zero.1 $ degrees_monomial _ _
lemma degrees_X (n : σ) : degrees (X n : mv_polynomial σ α) ≤ {n} :=
le_trans (degrees_monomial _ _) $ le_of_eq $ to_multiset_single _ _
lemma degrees_zero : degrees (0 : mv_polynomial σ α) = 0 :=
by { rw ← C_0, exact degrees_C 0 }
lemma degrees_one : degrees (1 : mv_polynomial σ α) = 0 := degrees_C 1
lemma degrees_add (p q : mv_polynomial σ α) : (p + q).degrees ≤ p.degrees ⊔ q.degrees :=
begin
refine finset.sup_le (assume b hb, _),
have := finsupp.support_add hb, rw finset.mem_union at this,
cases this,
{ exact le_sup_left_of_le (finset.le_sup this) },
{ exact le_sup_right_of_le (finset.le_sup this) },
end
lemma degrees_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ α) :
(∑ i in s, f i).degrees ≤ s.sup (λi, (f i).degrees) :=
begin
refine s.induction _ _,
{ simp only [finset.sum_empty, finset.sup_empty, degrees_zero], exact le_refl _ },
{ assume i s his ih,
rw [finset.sup_insert, finset.sum_insert his],
exact le_trans (degrees_add _ _) (sup_le_sup_left ih _) }
end
lemma degrees_mul (p q : mv_polynomial σ α) : (p * q).degrees ≤ p.degrees + q.degrees :=
begin
refine finset.sup_le (assume b hb, _),
have := support_mul p q hb,
simp only [finset.mem_bind, finset.mem_singleton] at this,
rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩,
rw [finsupp.to_multiset_add],
exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂)
end
lemma degrees_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ α) :
(∏ i in s, f i).degrees ≤ ∑ i in s, (f i).degrees :=
begin
refine s.induction _ _,
{ simp only [finset.prod_empty, finset.sum_empty, degrees_one] },
{ assume i s his ih,
rw [finset.prod_insert his, finset.sum_insert his],
exact le_trans (degrees_mul _ _) (add_le_add_left ih _) }
end
lemma degrees_pow (p : mv_polynomial σ α) :
∀(n : ℕ), (p^n).degrees ≤ n •ℕ p.degrees
| 0 := begin rw [pow_zero, degrees_one], exact multiset.zero_le _ end
| (n + 1) := le_trans (degrees_mul _ _) (add_le_add_left (degrees_pow n) _)
lemma mem_degrees {p : mv_polynomial σ α} {i : σ} :
i ∈ p.degrees ↔ ∃ d, p.coeff d ≠ 0 ∧ i ∈ d.support :=
by simp only [degrees, finset.mem_sup, ← finsupp.mem_support_iff, coeff,
finsupp.mem_to_multiset, exists_prop]
lemma le_degrees_add {p q : mv_polynomial σ α} (h : p.degrees.disjoint q.degrees) :
p.degrees ≤ (p + q).degrees :=
begin
apply finset.sup_le,
intros d hd,
rw multiset.disjoint_iff_ne at h,
rw multiset.le_iff_count,
intros i,
rw [degrees, multiset.count_sup],
simp only [finsupp.count_to_multiset],
by_cases h0 : d = 0,
{ simp only [h0, zero_le, finsupp.zero_apply], },
{ refine @finset.le_sup _ _ _ (p + q).support _ d _,
rw [finsupp.mem_support_iff, ← coeff, coeff_add],
suffices : q.coeff d = 0,
{ rwa [this, add_zero, coeff, ← finsupp.mem_support_iff], },
rw [← finsupp.support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty] at h0,
obtain ⟨j, hj⟩ := h0,
contrapose! h,
rw finsupp.mem_support_iff at hd,
refine ⟨j, _, j, _, rfl⟩,
all_goals { rw mem_degrees, refine ⟨d, _, hj⟩, assumption } }
end
lemma degrees_add_of_disjoint {p q : mv_polynomial σ α} (h : multiset.disjoint p.degrees q.degrees) :
(p + q).degrees = p.degrees ∪ q.degrees :=
begin
apply le_antisymm,
{ apply degrees_add },
{ apply multiset.union_le,
{ apply le_degrees_add h },
{ rw add_comm, apply le_degrees_add h.symm } }
end
lemma degrees_map [comm_semiring β] (p : mv_polynomial σ α) (f : α →+* β) :
(map f p).degrees ⊆ p.degrees :=
begin
dsimp only [degrees],
apply multiset.subset_of_le,
convert finset.sup_subset _ _,
apply mv_polynomial.support_map_subset
end
lemma degrees_map_of_injective [comm_semiring β] (p : mv_polynomial σ α)
{f : α →+* β} (hf : injective f) : (map f p).degrees = p.degrees :=
by simp only [degrees, mv_polynomial.support_map_of_injective _ hf]
end degrees
section vars
/-! ### `vars` -/
/-- `vars p` is the set of variables appearing in the polynomial `p` -/
def vars (p : mv_polynomial σ α) : finset σ := p.degrees.to_finset
@[simp] lemma vars_0 : (0 : mv_polynomial σ α).vars = ∅ :=
by rw [vars, degrees_zero, multiset.to_finset_zero]
@[simp] lemma vars_monomial (h : a ≠ 0) : (monomial s a).vars = s.support :=
by rw [vars, degrees_monomial_eq _ _ h, finsupp.to_finset_to_multiset]
@[simp] lemma vars_C : (C a : mv_polynomial σ α).vars = ∅ :=
by rw [vars, degrees_C, multiset.to_finset_zero]
@[simp] lemma vars_X (h : 0 ≠ (1 : α)) : (X n : mv_polynomial σ α).vars = {n} :=
by rw [X, vars_monomial h.symm, finsupp.support_single_ne_zero (one_ne_zero : 1 ≠ 0)]
lemma mem_vars (i : σ) :
i ∈ p.vars ↔ ∃ (d : σ →₀ ℕ) (H : d ∈ p.support), i ∈ d.support :=
by simp only [vars, multiset.mem_to_finset, mem_degrees, coeff, finsupp.mem_support_iff, exists_prop]
lemma mem_support_not_mem_vars_zero {f : mv_polynomial σ α} {x : σ →₀ ℕ} (H : x ∈ f.support) {v : σ} (h : v ∉ vars f) :
x v = 0 :=
begin
rw [vars, multiset.mem_to_finset] at h,
rw ←not_mem_support_iff,
contrapose! h,
unfold degrees,
rw (show f.support = insert x f.support, from eq.symm $ finset.insert_eq_of_mem H),
rw finset.sup_insert,
simp only [multiset.mem_union, multiset.sup_eq_union],
left,
rwa [←to_finset_to_multiset, multiset.mem_to_finset] at h,
end
lemma vars_add_subset (p q : mv_polynomial σ α) :
(p + q).vars ⊆ p.vars ∪ q.vars :=
begin
intros x hx,
simp only [vars, finset.mem_union, multiset.mem_to_finset] at hx ⊢,
simpa using multiset.mem_of_le (degrees_add _ _) hx,
end
lemma vars_add_of_disjoint (h : disjoint p.vars q.vars) :
(p + q).vars = p.vars ∪ q.vars :=
begin
apply finset.subset.antisymm (vars_add_subset p q),
intros x hx,
simp only [vars, multiset.disjoint_to_finset] at h hx ⊢,
rw [degrees_add_of_disjoint h, multiset.to_finset_union],
exact hx
end
section mul
lemma vars_mul (φ ψ : mv_polynomial σ α) : (φ * ψ).vars ⊆ φ.vars ∪ ψ.vars :=
begin
intro i,
simp only [mem_vars, finset.mem_union],
rintro ⟨d, hd, hi⟩,
rw [finsupp.mem_support_iff, ← coeff, coeff_mul] at hd,
contrapose! hd, cases hd,
rw finset.sum_eq_zero,
rintro ⟨d₁, d₂⟩ H,
rw finsupp.mem_antidiagonal_support at H,
subst H,
obtain H|H : i ∈ d₁.support ∨ i ∈ d₂.support,
{ simpa only [finset.mem_union] using finsupp.support_add hi, },
{ suffices : coeff d₁ φ = 0, by simp [this],
rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, },
{ suffices : coeff d₂ ψ = 0, by simp [this],
rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, },
end
@[simp] lemma vars_one : (1 : mv_polynomial σ α).vars = ∅ :=
vars_C
lemma vars_pow (φ : mv_polynomial σ α) (n : ℕ) : (φ ^ n).vars ⊆ φ.vars :=
begin
induction n with n ih,
{ simp },
{ rw pow_succ,
apply finset.subset.trans (vars_mul _ _),
exact finset.union_subset (finset.subset.refl _) ih }
end
/--
The variables of the product of a family of polynomials
are a subset of the union of the sets of variables of each polynomial.
-/
lemma vars_prod {ι : Type*} {s : finset ι} (f : ι → mv_polynomial σ α) :
(∏ i in s, f i).vars ⊆ s.bind (λ i, (f i).vars) :=
begin
apply s.induction_on,
{ simp },
{ intros a s hs hsub,
simp only [hs, finset.bind_insert, finset.prod_insert, not_false_iff],
apply finset.subset.trans (vars_mul _ _),
exact finset.union_subset_union (finset.subset.refl _) hsub }
end
section integral_domain
variables {A : Type*} [integral_domain A]
lemma vars_C_mul (a : A) (ha : a ≠ 0) (φ : mv_polynomial σ A) : (C a * φ).vars = φ.vars :=
begin
ext1 i,
simp only [mem_vars, exists_prop, finsupp.mem_support_iff],
apply exists_congr,
intro d,
apply and_congr _ iff.rfl,
rw [← coeff, ← coeff, coeff_C_mul, mul_ne_zero_iff, eq_true_intro ha, true_and],
end
end integral_domain
end mul
section sum
variables {ι : Type*} (t : finset ι) (φ : ι → mv_polynomial σ α)
lemma vars_sum_subset :
(∑ i in t, φ i).vars ⊆ finset.bind t (λ i, (φ i).vars) :=
begin
apply t.induction_on,
{ simp },
{ intros a s has hsum,
rw [finset.bind_insert, finset.sum_insert has],
refine finset.subset.trans (vars_add_subset _ _)
(finset.union_subset_union (finset.subset.refl _) _),
assumption }
end
lemma vars_sum_of_disjoint (h : pairwise $ disjoint on (λ i, (φ i).vars)) :
(∑ i in t, φ i).vars = finset.bind t (λ i, (φ i).vars) :=
begin
apply t.induction_on,
{ simp },
{ intros a s has hsum,
rw [finset.bind_insert, finset.sum_insert has, vars_add_of_disjoint, hsum],
unfold pairwise on_fun at h,
rw hsum,
simp only [finset.disjoint_iff_ne] at h ⊢,
intros v hv v2 hv2,
rw finset.mem_bind at hv2,
rcases hv2 with ⟨i, his, hi⟩,
refine h a i _ _ hv _ hi,
rintro rfl,
contradiction }
end
end sum
section map
variables [comm_semiring β] (f : α →+* β)
variable (p)
lemma vars_map : (map f p).vars ⊆ p.vars :=
by simp [vars, degrees_map]
variable {f}
lemma vars_map_of_injective (hf : injective f) :
(map f p).vars = p.vars :=
by simp [vars, degrees_map_of_injective _ hf]
lemma vars_monomial_single (i : σ) {e : ℕ} {r : α} (he : e ≠ 0) (hr : r ≠ 0) :
(monomial (finsupp.single i e) r).vars = {i} :=
by rw [vars_monomial hr, finsupp.support_single_ne_zero he]
lemma vars_eq_support_bind_support : p.vars = p.support.bind finsupp.support :=
by { ext i, rw [mem_vars, finset.mem_bind] }
end map
end vars
section degree_of
/-! ### `degree_of` -/
/-- `degree_of n p` gives the highest power of X_n that appears in `p` -/
def degree_of (n : σ) (p : mv_polynomial σ α) : ℕ := p.degrees.count n
end degree_of
section total_degree
/-! ### `total_degree` -/
/-- `total_degree p` gives the maximum |s| over the monomials X^s in `p` -/
def total_degree (p : mv_polynomial σ α) : ℕ := p.support.sup (λs, s.sum $ λn e, e)
lemma total_degree_eq (p : mv_polynomial σ α) :
p.total_degree = p.support.sup (λm, m.to_multiset.card) :=
begin
rw [total_degree],
congr, funext m,
exact (finsupp.card_to_multiset _).symm
end
lemma total_degree_le_degrees_card (p : mv_polynomial σ α) :
p.total_degree ≤ p.degrees.card :=
begin
rw [total_degree_eq],
exact finset.sup_le (assume s hs, multiset.card_le_of_le $ finset.le_sup hs)
end
@[simp] lemma total_degree_C (a : α) : (C a : mv_polynomial σ α).total_degree = 0 :=
nat.eq_zero_of_le_zero $ finset.sup_le $ assume n hn,
have _ := finsupp.support_single_subset hn,
begin
rw [finset.mem_singleton] at this,
subst this,
exact le_refl _
end
@[simp] lemma total_degree_zero : (0 : mv_polynomial σ α).total_degree = 0 :=
by rw [← C_0]; exact total_degree_C (0 : α)
@[simp] lemma total_degree_one : (1 : mv_polynomial σ α).total_degree = 0 :=
total_degree_C (1 : α)
@[simp] lemma total_degree_X {α} [comm_semiring α] [nontrivial α] (s : σ) :
(X s : mv_polynomial σ α).total_degree = 1 :=
begin
rw [total_degree, X, monomial, finsupp.support_single_ne_zero (one_ne_zero : (1 : α) ≠ 0)],
simp only [finset.sup, sum_single_index, finset.fold_singleton, sup_bot_eq],
end
lemma total_degree_add (a b : mv_polynomial σ α) :
(a + b).total_degree ≤ max a.total_degree b.total_degree :=
finset.sup_le $ assume n hn,
have _ := finsupp.support_add hn,
begin
rw finset.mem_union at this,
cases this,
{ exact le_max_left_of_le (finset.le_sup this) },
{ exact le_max_right_of_le (finset.le_sup this) }
end
lemma total_degree_mul (a b : mv_polynomial σ α) :
(a * b).total_degree ≤ a.total_degree + b.total_degree :=
finset.sup_le $ assume n hn,
have _ := add_monoid_algebra.support_mul a b hn,
begin
simp only [finset.mem_bind, finset.mem_singleton] at this,
rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩,
rw [finsupp.sum_add_index],
{ exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) },
{ assume a, refl },
{ assume a b₁ b₂, refl }
end
lemma total_degree_pow (a : mv_polynomial σ α) (n : ℕ) :
(a ^ n).total_degree ≤ n * a.total_degree :=
begin
induction n with n ih,
{ simp only [nat.nat_zero_eq_zero, zero_mul, pow_zero, total_degree_one] },
rw pow_succ,
calc total_degree (a * a ^ n) ≤ a.total_degree + (a^n).total_degree : total_degree_mul _ _
... ≤ a.total_degree + n * a.total_degree : add_le_add_left ih _
... = (n+1) * a.total_degree : by rw [add_mul, one_mul, add_comm]
end
lemma total_degree_list_prod :
∀(s : list (mv_polynomial σ α)), s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum
| [] := by rw [@list.prod_nil (mv_polynomial σ α) _, total_degree_one]; refl
| (p :: ps) :=
begin
rw [@list.prod_cons (mv_polynomial σ α) _, list.map, list.sum_cons],
exact le_trans (total_degree_mul _ _) (add_le_add_left (total_degree_list_prod ps) _)
end
lemma total_degree_multiset_prod (s : multiset (mv_polynomial σ α)) :
s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum :=
begin
refine quotient.induction_on s (assume l, _),
rw [multiset.quot_mk_to_coe, multiset.coe_prod, multiset.coe_map, multiset.coe_sum],
exact total_degree_list_prod l
end
lemma total_degree_finset_prod {ι : Type*}
(s : finset ι) (f : ι → mv_polynomial σ α) :
(s.prod f).total_degree ≤ ∑ i in s, (f i).total_degree :=
begin
refine le_trans (total_degree_multiset_prod _) _,
rw [multiset.map_map],
refl
end
lemma exists_degree_lt [fintype σ] (f : mv_polynomial σ α) (n : ℕ)
(h : f.total_degree < n * fintype.card σ) {d : σ →₀ ℕ} (hd : d ∈ f.support) :
∃ i, d i < n :=
begin
contrapose! h,
calc n * fintype.card σ
= ∑ s:σ, n : by rw [finset.sum_const, nat.nsmul_eq_mul, mul_comm, finset.card_univ]
... ≤ ∑ s, d s : finset.sum_le_sum (λ s _, h s)
... ≤ d.sum (λ i e, e) : by { rw [finsupp.sum_fintype], intros, refl }
... ≤ f.total_degree : finset.le_sup hd,
end
lemma coeff_eq_zero_of_total_degree_lt {f : mv_polynomial σ α} {d : σ →₀ ℕ}
(h : f.total_degree < ∑ i in d.support, d i) :
coeff d f = 0 :=
begin
classical,
rw [total_degree, finset.sup_lt_iff] at h,
{ specialize h d, rw mem_support_iff at h,
refine not_not.mp (mt h _), exact lt_irrefl _, },
{ exact lt_of_le_of_lt (nat.zero_le _) h, }
end
end total_degree
section eval_vars
/-! ### `vars` and `eval` -/
variables {R : Type u} {A : Type v} {S : Type w} (f : σ → A)
variables [comm_semiring R] [comm_semiring A] [algebra R A] [comm_semiring S]
lemma eval₂_hom_eq_constant_coeff_of_vars (f : R →+* S) {g : σ → S}
{p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) :
eval₂_hom f g p = f (constant_coeff p) :=
begin
conv_lhs { rw p.as_sum },
simp only [ring_hom.map_sum, eval₂_hom_monomial],
by_cases h0 : constant_coeff p = 0,
work_on_goal 0
{ rw [h0, f.map_zero, finset.sum_eq_zero],
intros d hd },
work_on_goal 1
{ rw [finset.sum_eq_single (0 : σ →₀ ℕ)],
{ rw [finsupp.prod_zero_index, mul_one],
refl },
intros d hd hd0, },
repeat
{ obtain ⟨i, hi⟩ : d.support.nonempty,
{ rw [constant_coeff_eq, coeff, ← finsupp.not_mem_support_iff] at h0,
rw [finset.nonempty_iff_ne_empty, ne.def, finsupp.support_eq_empty],
rintro rfl, contradiction },
rw [finsupp.prod, finset.prod_eq_zero hi, mul_zero],
rw [hp, zero_pow (nat.pos_of_ne_zero $ finsupp.mem_support_iff.mp hi)],
rw [mem_vars],
exact ⟨d, hd, hi⟩ },
{ rw [constant_coeff_eq, coeff, ← ne.def, ← finsupp.mem_support_iff] at h0,
intro, contradiction }
end
lemma aeval_eq_constant_coeff_of_vars [algebra R S] {g : σ → S}
{p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) :
aeval g p = algebra_map _ _ (constant_coeff p) :=
eval₂_hom_eq_constant_coeff_of_vars _ hp
end eval_vars
end comm_semiring
end mv_polynomial
|
e368c651a8686b4c3139832c46c067a72604b199 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/linear_algebra/finsupp.lean | 22068faa614a8218db9e392a2605a87753e37152 | [
"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 | 43,117 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import data.finsupp.defs
import linear_algebra.pi
import linear_algebra.span
/-!
# Properties of the module `α →₀ M`
Given an `R`-module `M`, the `R`-module structure on `α →₀ M` is defined in
`data.finsupp.basic`.
In this file we define `finsupp.supported s` to be the set `{f : α →₀ M | f.support ⊆ s}`
interpreted as a submodule of `α →₀ M`. We also define `linear_map` versions of various maps:
* `finsupp.lsingle a : M →ₗ[R] ι →₀ M`: `finsupp.single a` as a linear map;
* `finsupp.lapply a : (ι →₀ M) →ₗ[R] M`: the map `λ f, f a` as a linear map;
* `finsupp.lsubtype_domain (s : set α) : (α →₀ M) →ₗ[R] (s →₀ M)`: restriction to a subtype as a
linear map;
* `finsupp.restrict_dom`: `finsupp.filter` as a linear map to `finsupp.supported s`;
* `finsupp.lsum`: `finsupp.sum` or `finsupp.lift_add_hom` as a `linear_map`;
* `finsupp.total α M R (v : ι → M)`: sends `l : ι → R` to the linear combination of `v i` with
coefficients `l i`;
* `finsupp.total_on`: a restricted version of `finsupp.total` with domain `finsupp.supported R R s`
and codomain `submodule.span R (v '' s)`;
* `finsupp.supported_equiv_finsupp`: a linear equivalence between the functions `α →₀ M` supported
on `s` and the functions `s →₀ M`;
* `finsupp.lmap_domain`: a linear map version of `finsupp.map_domain`;
* `finsupp.dom_lcongr`: a `linear_equiv` version of `finsupp.dom_congr`;
* `finsupp.congr`: if the sets `s` and `t` are equivalent, then `supported M R s` is equivalent to
`supported M R t`;
* `finsupp.lcongr`: a `linear_equiv`alence between `α →₀ M` and `β →₀ N` constructed using `e : α ≃
β` and `e' : M ≃ₗ[R] N`.
## Tags
function with finite support, module, linear algebra
-/
noncomputable theory
open set linear_map submodule
open_locale classical big_operators
namespace finsupp
variables {α : Type*} {M : Type*} {N : Type*} {P : Type*} {R : Type*} {S : Type*}
variables [semiring R] [semiring S] [add_comm_monoid M] [module R M]
variables [add_comm_monoid N] [module R N]
variables [add_comm_monoid P] [module R P]
/-- Interpret `finsupp.single a` as a linear map. -/
def lsingle (a : α) : M →ₗ[R] (α →₀ M) :=
{ map_smul' := assume a b, (smul_single _ _ _).symm, ..finsupp.single_add_hom a }
/-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere. -/
lemma lhom_ext ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a b, φ (single a b) = ψ (single a b)) :
φ = ψ :=
linear_map.to_add_monoid_hom_injective $ add_hom_ext h
/-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere.
We formulate this fact using equality of linear maps `φ.comp (lsingle a)` and `ψ.comp (lsingle a)`
so that the `ext` tactic can apply a type-specific extensionality lemma to prove equality of these
maps. E.g., if `M = R`, then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/
@[ext] lemma lhom_ext' ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a, φ.comp (lsingle a) = ψ.comp (lsingle a)) :
φ = ψ :=
lhom_ext $ λ a, linear_map.congr_fun (h a)
/-- Interpret `λ (f : α →₀ M), f a` as a linear map. -/
def lapply (a : α) : (α →₀ M) →ₗ[R] M :=
{ map_smul' := assume a b, rfl, ..finsupp.apply_add_hom a }
/-- Forget that a function is finitely supported.
This is the linear version of `finsupp.to_fun`. -/
@[simps]
def lcoe_fun : (α →₀ M) →ₗ[R] α → M :=
{ to_fun := coe_fn,
map_add' := λ x y, by { ext, simp },
map_smul' := λ x y, by { ext, simp } }
section lsubtype_domain
variables (s : set α)
/-- Interpret `finsupp.subtype_domain s` as a linear map. -/
def lsubtype_domain : (α →₀ M) →ₗ[R] (s →₀ M) :=
{ to_fun := subtype_domain (λx, x ∈ s),
map_add' := λ a b, subtype_domain_add,
map_smul' := λ c a, ext $ λ a, rfl }
lemma lsubtype_domain_apply (f : α →₀ M) :
(lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)) f = subtype_domain (λx, x ∈ s) f := rfl
end lsubtype_domain
@[simp] lemma lsingle_apply (a : α) (b : M) : (lsingle a : M →ₗ[R] (α →₀ M)) b = single a b :=
rfl
@[simp] lemma lapply_apply (a : α) (f : α →₀ M) : (lapply a : (α →₀ M) →ₗ[R] M) f = f a :=
rfl
@[simp] lemma ker_lsingle (a : α) : (lsingle a : M →ₗ[R] (α →₀ M)).ker = ⊥ :=
ker_eq_bot_of_injective (single_injective a)
lemma lsingle_range_le_ker_lapply (s t : set α) (h : disjoint s t) :
(⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) ≤ (⨅a∈t, ker (lapply a : (α →₀ M) →ₗ[R] M)) :=
begin
refine supr_le (assume a₁, supr_le $ assume h₁, range_le_iff_comap.2 _),
simp only [(ker_comp _ _).symm, eq_top_iff, set_like.le_def, mem_ker, comap_infi, mem_infi],
assume b hb a₂ h₂,
have : a₁ ≠ a₂ := assume eq, h.le_bot ⟨h₁, eq.symm ▸ h₂⟩,
exact single_eq_of_ne this
end
lemma infi_ker_lapply_le_bot : (⨅a, ker (lapply a : (α →₀ M) →ₗ[R] M)) ≤ ⊥ :=
begin
simp only [set_like.le_def, mem_infi, mem_ker, mem_bot, lapply_apply],
exact assume a h, finsupp.ext h
end
lemma supr_lsingle_range : (⨆a, (lsingle a : M →ₗ[R] (α →₀ M)).range) = ⊤ :=
begin
refine (eq_top_iff.2 $ set_like.le_def.2 $ assume f _, _),
rw [← sum_single f],
exact sum_mem (assume a ha, submodule.mem_supr_of_mem a ⟨_, rfl⟩),
end
lemma disjoint_lsingle_lsingle (s t : set α) (hs : disjoint s t) :
disjoint (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range)
(⨆a∈t, (lsingle a : M →ₗ[R] (α →₀ M)).range) :=
begin
refine (disjoint.mono
(lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right)
(lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right)) _,
rw disjoint_iff_inf_le,
refine (le_trans (le_infi $ assume i, _) infi_ker_lapply_le_bot),
classical,
by_cases his : i ∈ s,
{ by_cases hit : i ∈ t,
{ exact (hs.le_bot ⟨his, hit⟩).elim },
exact inf_le_of_right_le (infi_le_of_le i $ infi_le _ hit) },
exact inf_le_of_left_le (infi_le_of_le i $ infi_le _ his)
end
lemma span_single_image (s : set M) (a : α) :
submodule.span R (single a '' s) = (submodule.span R s).map (lsingle a : M →ₗ[R] (α →₀ M)) :=
by rw ← span_image; refl
variables (M R)
/-- `finsupp.supported M R s` is the `R`-submodule of all `p : α →₀ M` such that `p.support ⊆ s`. -/
def supported (s : set α) : submodule R (α →₀ M) :=
begin
refine ⟨ {p | ↑p.support ⊆ s }, _, _, _ ⟩,
{ assume p q hp hq,
refine subset.trans
(subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq),
rw [finset.coe_union] },
{ simp only [subset_def, finset.mem_coe, set.mem_set_of_eq, mem_support_iff, zero_apply],
assume h ha, exact (ha rfl).elim },
{ assume a p hp,
refine subset.trans (finset.coe_subset.2 support_smul) hp }
end
variables {M}
lemma mem_supported {s : set α} (p : α →₀ M) : p ∈ (supported M R s) ↔ ↑p.support ⊆ s :=
iff.rfl
lemma mem_supported' {s : set α} (p : α →₀ M) :
p ∈ supported M R s ↔ ∀ x ∉ s, p x = 0 :=
by haveI := classical.dec_pred (λ (x : α), x ∈ s);
simp [mem_supported, set.subset_def, not_imp_comm]
lemma mem_supported_support (p : α →₀ M) :
p ∈ finsupp.supported M R (p.support : set α) :=
by rw finsupp.mem_supported
lemma single_mem_supported {s : set α} {a : α} (b : M) (h : a ∈ s) :
single a b ∈ supported M R s :=
set.subset.trans support_single_subset (finset.singleton_subset_set_iff.2 h)
lemma supported_eq_span_single (s : set α) :
supported R R s = span R ((λ i, single i 1) '' s) :=
begin
refine (span_eq_of_le _ _ (set_like.le_def.2 $ λ l hl, _)).symm,
{ rintro _ ⟨_, hp, rfl ⟩ , exact single_mem_supported R 1 hp },
{ rw ← l.sum_single,
refine sum_mem (λ i il, _),
convert @smul_mem R (α →₀ R) _ _ _ _ (single i 1) (l i) _,
{ simp },
apply subset_span,
apply set.mem_image_of_mem _ (hl il) }
end
variables (M R)
/-- Interpret `finsupp.filter s` as a linear map from `α →₀ M` to `supported M R s`. -/
def restrict_dom (s : set α) : (α →₀ M) →ₗ[R] supported M R s :=
linear_map.cod_restrict _
{ to_fun := filter (∈ s),
map_add' := λ l₁ l₂, filter_add,
map_smul' := λ a l, filter_smul }
(λ l, (mem_supported' _ _).2 $ λ x, filter_apply_neg (∈ s) l)
variables {M R}
section
@[simp] theorem restrict_dom_apply (s : set α) (l : α →₀ M) :
((restrict_dom M R s : (α →₀ M) →ₗ[R] supported M R s) l : α →₀ M) = finsupp.filter (∈ s) l := rfl
end
theorem restrict_dom_comp_subtype (s : set α) :
(restrict_dom M R s).comp (submodule.subtype _) = linear_map.id :=
begin
ext l a,
by_cases a ∈ s; simp [h],
exact ((mem_supported' R l.1).1 l.2 a h).symm
end
theorem range_restrict_dom (s : set α) :
(restrict_dom M R s).range = ⊤ :=
range_eq_top.2 $ function.right_inverse.surjective $
linear_map.congr_fun (restrict_dom_comp_subtype s)
theorem supported_mono {s t : set α} (st : s ⊆ t) :
supported M R s ≤ supported M R t :=
λ l h, set.subset.trans h st
@[simp] theorem supported_empty : supported M R (∅ : set α) = ⊥ :=
eq_bot_iff.2 $ λ l h, (submodule.mem_bot R).2 $
by ext; simp [*, mem_supported'] at *
@[simp] theorem supported_univ : supported M R (set.univ : set α) = ⊤ :=
eq_top_iff.2 $ λ l _, set.subset_univ _
theorem supported_Union {δ : Type*} (s : δ → set α) :
supported M R (⋃ i, s i) = ⨆ i, supported M R (s i) :=
begin
refine le_antisymm _ (supr_le $ λ i, supported_mono $ set.subset_Union _ _),
haveI := classical.dec_pred (λ x, x ∈ (⋃ i, s i)),
suffices : ((submodule.subtype _).comp (restrict_dom M R (⋃ i, s i))).range ≤
⨆ i, supported M R (s i),
{ rwa [linear_map.range_comp, range_restrict_dom, map_top, range_subtype] at this },
rw [range_le_iff_comap, eq_top_iff],
rintro l ⟨⟩,
apply finsupp.induction l, { exact zero_mem _ },
refine λ x a l hl a0, add_mem _,
by_cases (∃ i, x ∈ s i); simp [h],
{ cases h with i hi,
exact le_supr (λ i, supported M R (s i)) i (single_mem_supported R _ hi) }
end
theorem supported_union (s t : set α) :
supported M R (s ∪ t) = supported M R s ⊔ supported M R t :=
by erw [set.union_eq_Union, supported_Union, supr_bool_eq]; refl
theorem supported_Inter {ι : Type*} (s : ι → set α) :
supported M R (⋂ i, s i) = ⨅ i, supported M R (s i) :=
submodule.ext $ λ x, by simp [mem_supported, subset_Inter_iff]
theorem supported_inter (s t : set α) :
supported M R (s ∩ t) = supported M R s ⊓ supported M R t :=
by rw [set.inter_eq_Inter, supported_Inter, infi_bool_eq]; refl
theorem disjoint_supported_supported {s t : set α} (h : disjoint s t) :
disjoint (supported M R s) (supported M R t) :=
disjoint_iff.2 $ by rw [← supported_inter, disjoint_iff_inter_eq_empty.1 h, supported_empty]
theorem disjoint_supported_supported_iff [nontrivial M] {s t : set α} :
disjoint (supported M R s) (supported M R t) ↔ disjoint s t :=
begin
refine ⟨λ h, set.disjoint_left.mpr $ λ x hx1 hx2, _, disjoint_supported_supported⟩,
rcases exists_ne (0 : M) with ⟨y, hy⟩,
have := h.le_bot ⟨single_mem_supported R y hx1, single_mem_supported R y hx2⟩,
rw [mem_bot, single_eq_zero] at this,
exact hy this
end
/-- Interpret `finsupp.restrict_support_equiv` as a linear equivalence between
`supported M R s` and `s →₀ M`. -/
def supported_equiv_finsupp (s : set α) : (supported M R s) ≃ₗ[R] (s →₀ M) :=
begin
let F : (supported M R s) ≃ (s →₀ M) := restrict_support_equiv s M,
refine F.to_linear_equiv _,
have : (F : (supported M R s) → (↥s →₀ M)) = ((lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)).comp
(submodule.subtype (supported M R s))) := rfl,
rw this,
exact linear_map.is_linear _
end
section lsum
variables (S) [module S N] [smul_comm_class R S N]
/-- Lift a family of linear maps `M →ₗ[R] N` indexed by `x : α` to a linear map from `α →₀ M` to
`N` using `finsupp.sum`. This is an upgraded version of `finsupp.lift_add_hom`.
See note [bundled maps over different rings] for why separate `R` and `S` semirings are used.
-/
def lsum : (α → M →ₗ[R] N) ≃ₗ[S] ((α →₀ M) →ₗ[R] N) :=
{ to_fun := λ F,
{ to_fun := λ d, d.sum (λ i, F i),
map_add' := (lift_add_hom (λ x, (F x).to_add_monoid_hom)).map_add,
map_smul' := λ c f, by simp [sum_smul_index', smul_sum] },
inv_fun := λ F x, F.comp (lsingle x),
left_inv := λ F, by { ext x y, simp },
right_inv := λ F, by { ext x y, simp },
map_add' := λ F G, by { ext x y, simp },
map_smul' := λ F G, by { ext x y, simp } }
@[simp] lemma coe_lsum (f : α → M →ₗ[R] N) : (lsum S f : (α →₀ M) → N) = λ d, d.sum (λ i, f i) :=
rfl
theorem lsum_apply (f : α → M →ₗ[R] N) (l : α →₀ M) :
finsupp.lsum S f l = l.sum (λ b, f b) := rfl
theorem lsum_single (f : α → M →ₗ[R] N) (i : α) (m : M) :
finsupp.lsum S f (finsupp.single i m) = f i m :=
finsupp.sum_single_index (f i).map_zero
theorem lsum_symm_apply (f : (α →₀ M) →ₗ[R] N) (x : α) :
(lsum S).symm f x = f.comp (lsingle x) := rfl
end lsum
section
variables (M) (R) (X : Type*)
/--
A slight rearrangement from `lsum` gives us
the bijection underlying the free-forgetful adjunction for R-modules.
-/
noncomputable def lift : (X → M) ≃+ ((X →₀ R) →ₗ[R] M) :=
(add_equiv.arrow_congr (equiv.refl X) (ring_lmap_equiv_self R ℕ M).to_add_equiv.symm).trans
(lsum _ : _ ≃ₗ[ℕ] _).to_add_equiv
@[simp]
lemma lift_symm_apply (f) (x) : ((lift M R X).symm f) x = f (single x 1) :=
rfl
@[simp]
lemma lift_apply (f) (g) :
((lift M R X) f) g = g.sum (λ x r, r • f x) :=
rfl
end
section lmap_domain
variables {α' : Type*} {α'' : Type*} (M R)
/-- Interpret `finsupp.map_domain` as a linear map. -/
def lmap_domain (f : α → α') : (α →₀ M) →ₗ[R] (α' →₀ M) :=
{ to_fun := map_domain f, map_add' := λ a b, map_domain_add, map_smul' := map_domain_smul }
@[simp] theorem lmap_domain_apply (f : α → α') (l : α →₀ M) :
(lmap_domain M R f : (α →₀ M) →ₗ[R] (α' →₀ M)) l = map_domain f l := rfl
@[simp] theorem lmap_domain_id : (lmap_domain M R id : (α →₀ M) →ₗ[R] α →₀ M) = linear_map.id :=
linear_map.ext $ λ l, map_domain_id
theorem lmap_domain_comp (f : α → α') (g : α' → α'') :
lmap_domain M R (g ∘ f) = (lmap_domain M R g).comp (lmap_domain M R f) :=
linear_map.ext $ λ l, map_domain_comp
theorem supported_comap_lmap_domain (f : α → α') (s : set α') :
supported M R (f ⁻¹' s) ≤ (supported M R s).comap (lmap_domain M R f) :=
λ l (hl : ↑l.support ⊆ f ⁻¹' s),
show ↑(map_domain f l).support ⊆ s, begin
rw [← set.image_subset_iff, ← finset.coe_image] at hl,
exact set.subset.trans map_domain_support hl
end
theorem lmap_domain_supported [nonempty α] (f : α → α') (s : set α) :
(supported M R s).map (lmap_domain M R f) = supported M R (f '' s) :=
begin
inhabit α,
refine le_antisymm (map_le_iff_le_comap.2 $
le_trans (supported_mono $ set.subset_preimage_image _ _)
(supported_comap_lmap_domain _ _ _ _)) _,
intros l hl,
refine ⟨(lmap_domain M R (function.inv_fun_on f s) : (α' →₀ M) →ₗ[R] α →₀ M) l, λ x hx, _, _⟩,
{ rcases finset.mem_image.1 (map_domain_support hx) with ⟨c, hc, rfl⟩,
exact function.inv_fun_on_mem (by simpa using hl hc) },
{ rw [← linear_map.comp_apply, ← lmap_domain_comp],
refine (map_domain_congr $ λ c hc, _).trans map_domain_id,
exact function.inv_fun_on_eq (by simpa using hl hc) }
end
theorem lmap_domain_disjoint_ker (f : α → α') {s : set α}
(H : ∀ a b ∈ s, f a = f b → a = b) :
disjoint (supported M R s) (lmap_domain M R f).ker :=
begin
rw disjoint_iff_inf_le,
rintro l ⟨h₁, h₂⟩,
rw [set_like.mem_coe, mem_ker, lmap_domain_apply, map_domain] at h₂,
simp, ext x,
haveI := classical.dec_pred (λ x, x ∈ s),
by_cases xs : x ∈ s,
{ have : finsupp.sum l (λ a, finsupp.single (f a)) (f x) = 0, {rw h₂, refl},
rw [finsupp.sum_apply, finsupp.sum, finset.sum_eq_single x] at this,
{ simpa [finsupp.single_apply] },
{ intros y hy xy, simp [mt (H _ (h₁ hy) _ xs) xy] },
{ simp {contextual := tt} } },
{ by_contra h, exact xs (h₁ $ finsupp.mem_support_iff.2 h) }
end
end lmap_domain
section lcomap_domain
variables {β : Type*} {R M}
/-- Given `f : α → β` and a proof `hf` that `f` is injective, `lcomap_domain f hf` is the linear map
sending `l : β →₀ M` to the finitely supported function from `α` to `M` given by composing
`l` with `f`.
This is the linear version of `finsupp.comap_domain`. -/
def lcomap_domain (f : α → β) (hf : function.injective f) :
(β →₀ M) →ₗ[R] α →₀ M:=
{ to_fun := λ l, finsupp.comap_domain f l (hf.inj_on _),
map_add' := λ x y, by { ext, simp },
map_smul' := λ c x, by { ext, simp } }
end lcomap_domain
section total
variables (α) {α' : Type*} (M) {M' : Type*} (R)
[add_comm_monoid M'] [module R M']
(v : α → M) {v' : α' → M'}
/-- Interprets (l : α →₀ R) as linear combination of the elements in the family (v : α → M) and
evaluates this linear combination. -/
protected def total : (α →₀ R) →ₗ[R] M := finsupp.lsum ℕ (λ i, linear_map.id.smul_right (v i))
variables {α M v}
theorem total_apply (l : α →₀ R) :
finsupp.total α M R v l = l.sum (λ i a, a • v i) := rfl
theorem total_apply_of_mem_supported {l : α →₀ R} {s : finset α}
(hs : l ∈ supported R R (↑s : set α)) :
finsupp.total α M R v l = s.sum (λ i, l i • v i) :=
finset.sum_subset hs $ λ x _ hxg, show l x • v x = 0, by rw [not_mem_support_iff.1 hxg, zero_smul]
@[simp] theorem total_single (c : R) (a : α) :
finsupp.total α M R v (single a c) = c • (v a) :=
by simp [total_apply, sum_single_index]
lemma total_zero_apply (x : α →₀ R) :
(finsupp.total α M R 0) x = 0 := by simp [finsupp.total_apply]
variables (α M)
@[simp] lemma total_zero :
finsupp.total α M R 0 = 0 :=
linear_map.ext (total_zero_apply R)
variables {α M}
theorem apply_total (f : M →ₗ[R] M') (v) (l : α →₀ R) :
f (finsupp.total α M R v l) = finsupp.total α M' R (f ∘ v) l :=
by apply finsupp.induction_linear l; simp { contextual := tt, }
theorem total_unique [unique α] (l : α →₀ R) (v) :
finsupp.total α M R v l = l default • v default :=
by rw [← total_single, ← unique_single l]
lemma total_surjective (h : function.surjective v) : function.surjective (finsupp.total α M R v) :=
begin
intro x,
obtain ⟨y, hy⟩ := h x,
exact ⟨finsupp.single y 1, by simp [hy]⟩
end
theorem total_range (h : function.surjective v) : (finsupp.total α M R v).range = ⊤ :=
range_eq_top.2 $ total_surjective R h
/-- Any module is a quotient of a free module. This is stated as surjectivity of
`finsupp.total M M R id : (M →₀ R) →ₗ[R] M`. -/
lemma total_id_surjective (M) [add_comm_monoid M] [module R M] :
function.surjective (finsupp.total M M R id) :=
total_surjective R function.surjective_id
lemma range_total : (finsupp.total α M R v).range = span R (range v) :=
begin
ext x,
split,
{ intros hx,
rw [linear_map.mem_range] at hx,
rcases hx with ⟨l, hl⟩,
rw ← hl,
rw finsupp.total_apply,
exact sum_mem (λ i hi, submodule.smul_mem _ _ (subset_span (mem_range_self i))) },
{ apply span_le.2,
intros x hx,
rcases hx with ⟨i, hi⟩,
rw [set_like.mem_coe, linear_map.mem_range],
use finsupp.single i 1,
simp [hi] }
end
theorem lmap_domain_total (f : α → α') (g : M →ₗ[R] M') (h : ∀ i, g (v i) = v' (f i)) :
(finsupp.total α' M' R v').comp (lmap_domain R R f) = g.comp (finsupp.total α M R v) :=
by ext l; simp [total_apply, finsupp.sum_map_domain_index, add_smul, h]
theorem total_comp_lmap_domain (f : α → α') :
(finsupp.total α' M' R v').comp (finsupp.lmap_domain R R f) = (finsupp.total α M' R (v' ∘ f)) :=
by { ext, simp }
@[simp] theorem total_emb_domain (f : α ↪ α') (l : α →₀ R) :
(finsupp.total α' M' R v') (emb_domain f l) = (finsupp.total α M' R (v' ∘ f)) l :=
by simp [total_apply, finsupp.sum, support_emb_domain, emb_domain_apply]
@[simp] theorem total_map_domain (f : α → α') (l : α →₀ R) :
(finsupp.total α' M' R v') (map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l :=
linear_map.congr_fun (total_comp_lmap_domain _ _) l
@[simp] theorem total_equiv_map_domain (f : α ≃ α') (l : α →₀ R) :
(finsupp.total α' M' R v') (equiv_map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l :=
by rw [equiv_map_domain_eq_map_domain, total_map_domain]
/-- A version of `finsupp.range_total` which is useful for going in the other direction -/
theorem span_eq_range_total (s : set M) :
span R s = (finsupp.total s M R coe).range :=
by rw [range_total, subtype.range_coe_subtype, set.set_of_mem_eq]
theorem mem_span_iff_total (s : set M) (x : M) :
x ∈ span R s ↔ ∃ l : s →₀ R, finsupp.total s M R coe l = x :=
(set_like.ext_iff.1 $ span_eq_range_total _ _) x
variables {R}
lemma mem_span_range_iff_exists_finsupp {v : α → M} {x : M} :
x ∈ span R (range v) ↔ ∃ (c : α →₀ R), c.sum (λ i a, a • v i) = x :=
by simp only [←finsupp.range_total, linear_map.mem_range, finsupp.total_apply]
variables (R)
theorem span_image_eq_map_total (s : set α):
span R (v '' s) = submodule.map (finsupp.total α M R v) (supported R R s) :=
begin
apply span_eq_of_le,
{ intros x hx,
rw set.mem_image at hx,
apply exists.elim hx,
intros i hi,
exact ⟨_, finsupp.single_mem_supported R 1 hi.1, by simp [hi.2]⟩ },
{ refine map_le_iff_le_comap.2 (λ z hz, _),
have : ∀i, z i • v i ∈ span R (v '' s),
{ intro c,
haveI := classical.dec_pred (λ x, x ∈ s),
by_cases c ∈ s,
{ exact smul_mem _ _ (subset_span (set.mem_image_of_mem _ h)) },
{ simp [(finsupp.mem_supported' R _).1 hz _ h] } },
refine sum_mem _, simp [this] }
end
theorem mem_span_image_iff_total {s : set α} {x : M} :
x ∈ span R (v '' s) ↔ ∃ l ∈ supported R R s, finsupp.total α M R v l = x :=
by { rw span_image_eq_map_total, simp, }
lemma total_option (v : option α → M) (f : option α →₀ R) :
finsupp.total (option α) M R v f =
f none • v none + finsupp.total α M R (v ∘ option.some) f.some :=
by rw [total_apply, sum_option_index_smul, total_apply]
lemma total_total {α β : Type*} (A : α → M) (B : β → (α →₀ R)) (f : β →₀ R) :
finsupp.total α M R A (finsupp.total β (α →₀ R) R B f) =
finsupp.total β M R (λ b, finsupp.total α M R A (B b)) f :=
begin
simp only [total_apply],
apply induction_linear f,
{ simp only [sum_zero_index], },
{ intros f₁ f₂ h₁ h₂,
simp [sum_add_index, h₁, h₂, add_smul], },
{ simp [sum_single_index, sum_smul_index, smul_sum, mul_smul], }
end
@[simp] lemma total_fin_zero (f : fin 0 → M) :
finsupp.total (fin 0) M R f = 0 :=
by { ext i, apply fin_zero_elim i }
variables (α) (M) (v)
/-- `finsupp.total_on M v s` interprets `p : α →₀ R` as a linear combination of a
subset of the vectors in `v`, mapping it to the span of those vectors.
The subset is indicated by a set `s : set α` of indices.
-/
protected def total_on (s : set α) : supported R R s →ₗ[R] span R (v '' s) :=
linear_map.cod_restrict _ ((finsupp.total _ _ _ v).comp (submodule.subtype (supported R R s))) $
λ ⟨l, hl⟩, (mem_span_image_iff_total _).2 ⟨l, hl, rfl⟩
variables {α} {M} {v}
theorem total_on_range (s : set α) : (finsupp.total_on α M R v s).range = ⊤ :=
begin
rw [finsupp.total_on, linear_map.range_eq_map, linear_map.map_cod_restrict,
← linear_map.range_le_iff_comap, range_subtype, map_top, linear_map.range_comp, range_subtype],
exact (span_image_eq_map_total _ _).le
end
theorem total_comp (f : α' → α) :
(finsupp.total α' M R (v ∘ f)) = (finsupp.total α M R v).comp (lmap_domain R R f) :=
by { ext, simp [total_apply] }
lemma total_comap_domain
(f : α → α') (l : α' →₀ R) (hf : set.inj_on f (f ⁻¹' ↑l.support)) :
finsupp.total α M R v (finsupp.comap_domain f l hf) =
(l.support.preimage f hf).sum (λ i, (l (f i)) • (v i)) :=
by rw finsupp.total_apply; refl
lemma total_on_finset
{s : finset α} {f : α → R} (g : α → M) (hf : ∀ a, f a ≠ 0 → a ∈ s):
finsupp.total α M R g (finsupp.on_finset s f hf) =
finset.sum s (λ (x : α), f x • g x) :=
begin
simp only [finsupp.total_apply, finsupp.sum, finsupp.on_finset_apply, finsupp.support_on_finset],
rw finset.sum_filter_of_ne,
intros x hx h,
contrapose! h,
simp [h],
end
end total
/-- An equivalence of domains induces a linear equivalence of finitely supported functions.
This is `finsupp.dom_congr` as a `linear_equiv`.
See also `linear_map.fun_congr_left` for the case of arbitrary functions. -/
protected def dom_lcongr {α₁ α₂ : Type*} (e : α₁ ≃ α₂) :
(α₁ →₀ M) ≃ₗ[R] (α₂ →₀ M) :=
(finsupp.dom_congr e : (α₁ →₀ M) ≃+ (α₂ →₀ M)).to_linear_equiv $
by simpa only [equiv_map_domain_eq_map_domain, dom_congr_apply]
using (lmap_domain M R e).map_smul
@[simp]
lemma dom_lcongr_apply {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) (v : α₁ →₀ M) :
(finsupp.dom_lcongr e : _ ≃ₗ[R] _) v = finsupp.dom_congr e v :=
rfl
@[simp]
lemma dom_lcongr_refl : finsupp.dom_lcongr (equiv.refl α) = linear_equiv.refl R (α →₀ M) :=
linear_equiv.ext $ λ _, equiv_map_domain_refl _
lemma dom_lcongr_trans {α₁ α₂ α₃ : Type*} (f : α₁ ≃ α₂) (f₂ : α₂ ≃ α₃) :
(finsupp.dom_lcongr f).trans (finsupp.dom_lcongr f₂) =
(finsupp.dom_lcongr (f.trans f₂) : (_ →₀ M) ≃ₗ[R] _) :=
linear_equiv.ext $ λ _, (equiv_map_domain_trans _ _ _).symm
@[simp]
lemma dom_lcongr_symm {α₁ α₂ : Type*} (f : α₁ ≃ α₂) :
((finsupp.dom_lcongr f).symm : (_ →₀ M) ≃ₗ[R] _) = finsupp.dom_lcongr f.symm :=
linear_equiv.ext $ λ x, rfl
@[simp] theorem dom_lcongr_single {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) (i : α₁) (m : M) :
(finsupp.dom_lcongr e : _ ≃ₗ[R] _) (finsupp.single i m) = finsupp.single (e i) m :=
by simp [finsupp.dom_lcongr, finsupp.dom_congr, equiv_map_domain_single]
/-- An equivalence of sets induces a linear equivalence of `finsupp`s supported on those sets. -/
noncomputable def congr {α' : Type*} (s : set α) (t : set α') (e : s ≃ t) :
supported M R s ≃ₗ[R] supported M R t :=
begin
haveI := classical.dec_pred (λ x, x ∈ s),
haveI := classical.dec_pred (λ x, x ∈ t),
refine (finsupp.supported_equiv_finsupp s) ≪≫ₗ
(_ ≪≫ₗ (finsupp.supported_equiv_finsupp t).symm),
exact finsupp.dom_lcongr e
end
/-- `finsupp.map_range` as a `linear_map`. -/
@[simps]
def map_range.linear_map (f : M →ₗ[R] N) : (α →₀ M) →ₗ[R] (α →₀ N) :=
{ to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)),
map_smul' := λ c v, map_range_smul c v (f.map_smul c),
..map_range.add_monoid_hom f.to_add_monoid_hom }
@[simp]
lemma map_range.linear_map_id :
map_range.linear_map linear_map.id = (linear_map.id : (α →₀ M) →ₗ[R] _):=
linear_map.ext map_range_id
lemma map_range.linear_map_comp (f : N →ₗ[R] P) (f₂ : M →ₗ[R] N) :
(map_range.linear_map (f.comp f₂) : (α →₀ _) →ₗ[R] _) =
(map_range.linear_map f).comp (map_range.linear_map f₂) :=
linear_map.ext $ map_range_comp _ _ _ _ _
@[simp]
lemma map_range.linear_map_to_add_monoid_hom (f : M →ₗ[R] N) :
(map_range.linear_map f).to_add_monoid_hom =
(map_range.add_monoid_hom f.to_add_monoid_hom : (α →₀ M) →+ _):=
add_monoid_hom.ext $ λ _, rfl
/-- `finsupp.map_range` as a `linear_equiv`. -/
@[simps apply]
def map_range.linear_equiv (e : M ≃ₗ[R] N) : (α →₀ M) ≃ₗ[R] (α →₀ N) :=
{ to_fun := map_range e e.map_zero,
inv_fun := map_range e.symm e.symm.map_zero,
..map_range.linear_map e.to_linear_map,
..map_range.add_equiv e.to_add_equiv}
@[simp]
lemma map_range.linear_equiv_refl :
map_range.linear_equiv (linear_equiv.refl R M) = linear_equiv.refl R (α →₀ M) :=
linear_equiv.ext map_range_id
lemma map_range.linear_equiv_trans (f : M ≃ₗ[R] N) (f₂ : N ≃ₗ[R] P) :
(map_range.linear_equiv (f.trans f₂) : (α →₀ _) ≃ₗ[R] _) =
(map_range.linear_equiv f).trans (map_range.linear_equiv f₂) :=
linear_equiv.ext $ map_range_comp _ _ _ _ _
@[simp]
lemma map_range.linear_equiv_symm (f : M ≃ₗ[R] N) :
((map_range.linear_equiv f).symm : (α →₀ _) ≃ₗ[R] _) = map_range.linear_equiv f.symm :=
linear_equiv.ext $ λ x, rfl
@[simp]
lemma map_range.linear_equiv_to_add_equiv (f : M ≃ₗ[R] N) :
(map_range.linear_equiv f).to_add_equiv =
(map_range.add_equiv f.to_add_equiv : (α →₀ M) ≃+ _):=
add_equiv.ext $ λ _, rfl
@[simp]
lemma map_range.linear_equiv_to_linear_map (f : M ≃ₗ[R] N) :
(map_range.linear_equiv f).to_linear_map =
(map_range.linear_map f.to_linear_map : (α →₀ M) →ₗ[R] _):=
linear_map.ext $ λ _, rfl
/-- An equivalence of domain and a linear equivalence of codomain induce a linear equivalence of the
corresponding finitely supported functions. -/
def lcongr {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) : (ι →₀ M) ≃ₗ[R] (κ →₀ N) :=
(finsupp.dom_lcongr e₁).trans (map_range.linear_equiv e₂)
@[simp] theorem lcongr_single {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (i : ι) (m : M) :
lcongr e₁ e₂ (finsupp.single i m) = finsupp.single (e₁ i) (e₂ m) :=
by simp [lcongr]
@[simp] lemma lcongr_apply_apply {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (f : ι →₀ M) (k : κ) :
lcongr e₁ e₂ f k = e₂ (f (e₁.symm k)) :=
rfl
theorem lcongr_symm_single {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (k : κ) (n : N) :
(lcongr e₁ e₂).symm (finsupp.single k n) = finsupp.single (e₁.symm k) (e₂.symm n) :=
begin
apply_fun lcongr e₁ e₂ using (lcongr e₁ e₂).injective,
simp,
end
@[simp] lemma lcongr_symm {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) :
(lcongr e₁ e₂).symm = lcongr e₁.symm e₂.symm :=
by { ext, refl }
section sum
variables (R)
/-- The linear equivalence between `(α ⊕ β) →₀ M` and `(α →₀ M) × (β →₀ M)`.
This is the `linear_equiv` version of `finsupp.sum_finsupp_equiv_prod_finsupp`. -/
@[simps apply symm_apply] def sum_finsupp_lequiv_prod_finsupp {α β : Type*} :
((α ⊕ β) →₀ M) ≃ₗ[R] (α →₀ M) × (β →₀ M) :=
{ map_smul' :=
by { intros, ext;
simp only [add_equiv.to_fun_eq_coe, prod.smul_fst, prod.smul_snd, smul_apply,
snd_sum_finsupp_add_equiv_prod_finsupp, fst_sum_finsupp_add_equiv_prod_finsupp,
ring_hom.id_apply] },
.. sum_finsupp_add_equiv_prod_finsupp }
lemma fst_sum_finsupp_lequiv_prod_finsupp {α β : Type*}
(f : (α ⊕ β) →₀ M) (x : α) :
(sum_finsupp_lequiv_prod_finsupp R f).1 x = f (sum.inl x) :=
rfl
lemma snd_sum_finsupp_lequiv_prod_finsupp {α β : Type*}
(f : (α ⊕ β) →₀ M) (y : β) :
(sum_finsupp_lequiv_prod_finsupp R f).2 y = f (sum.inr y) :=
rfl
lemma sum_finsupp_lequiv_prod_finsupp_symm_inl {α β : Type*}
(fg : (α →₀ M) × (β →₀ M)) (x : α) :
((sum_finsupp_lequiv_prod_finsupp R).symm fg) (sum.inl x) = fg.1 x :=
rfl
lemma sum_finsupp_lequiv_prod_finsupp_symm_inr {α β : Type*}
(fg : (α →₀ M) × (β →₀ M)) (y : β) :
((sum_finsupp_lequiv_prod_finsupp R).symm fg) (sum.inr y) = fg.2 y :=
rfl
end sum
section sigma
variables {η : Type*} [fintype η] {ιs : η → Type*} [has_zero α]
variables (R)
/-- On a `fintype η`, `finsupp.split` is a linear equivalence between
`(Σ (j : η), ιs j) →₀ M` and `Π j, (ιs j →₀ M)`.
This is the `linear_equiv` version of `finsupp.sigma_finsupp_add_equiv_pi_finsupp`. -/
noncomputable def sigma_finsupp_lequiv_pi_finsupp
{M : Type*} {ιs : η → Type*} [add_comm_monoid M] [module R M] :
((Σ j, ιs j) →₀ M) ≃ₗ[R] Π j, (ιs j →₀ M) :=
{ map_smul' := λ c f, by { ext, simp },
.. sigma_finsupp_add_equiv_pi_finsupp }
@[simp] lemma sigma_finsupp_lequiv_pi_finsupp_apply
{M : Type*} {ιs : η → Type*} [add_comm_monoid M] [module R M]
(f : (Σ j, ιs j) →₀ M) (j i) :
sigma_finsupp_lequiv_pi_finsupp R f j i = f ⟨j, i⟩ := rfl
@[simp] lemma sigma_finsupp_lequiv_pi_finsupp_symm_apply
{M : Type*} {ιs : η → Type*} [add_comm_monoid M] [module R M]
(f : Π j, (ιs j →₀ M)) (ji) :
(finsupp.sigma_finsupp_lequiv_pi_finsupp R).symm f ji = f ji.1 ji.2 := rfl
end sigma
section prod
/-- The linear equivalence between `α × β →₀ M` and `α →₀ β →₀ M`.
This is the `linear_equiv` version of `finsupp.finsupp_prod_equiv`. -/
noncomputable def finsupp_prod_lequiv {α β : Type*} (R : Type*) {M : Type*}
[semiring R] [add_comm_monoid M] [module R M] :
(α × β →₀ M) ≃ₗ[R] (α →₀ β →₀ M) :=
{ map_add' := λ f g, by { ext, simp [finsupp_prod_equiv, curry_apply] },
map_smul' := λ c f, by { ext, simp [finsupp_prod_equiv, curry_apply] },
.. finsupp_prod_equiv }
@[simp] lemma finsupp_prod_lequiv_apply {α β R M : Type*}
[semiring R] [add_comm_monoid M] [module R M] (f : α × β →₀ M) (x y) :
finsupp_prod_lequiv R f x y = f (x, y) :=
by rw [finsupp_prod_lequiv, linear_equiv.coe_mk, finsupp_prod_equiv, finsupp.curry_apply]
@[simp] lemma finsupp_prod_lequiv_symm_apply {α β R M : Type*}
[semiring R] [add_comm_monoid M] [module R M] (f : α →₀ β →₀ M) (xy) :
(finsupp_prod_lequiv R).symm f xy = f xy.1 xy.2 :=
by conv_rhs
{ rw [← (finsupp_prod_lequiv R).apply_symm_apply f, finsupp_prod_lequiv_apply, prod.mk.eta] }
end prod
end finsupp
section fintype
variables {α M : Type*} (R : Type*) [fintype α] [semiring R] [add_comm_monoid M] [module R M]
variables (S : Type*) [semiring S] [module S M] [smul_comm_class R S M]
variable (v : α → M)
/-- `fintype.total R S v f` is the linear combination of vectors in `v` with weights in `f`.
This variant of `finsupp.total` is defined on fintype indexed vectors.
This map is linear in `v` if `R` is commutative, and always linear in `f`.
See note [bundled maps over different rings] for why separate `R` and `S` semirings are used.
-/
protected def fintype.total : (α → M) →ₗ[S] (α → R) →ₗ[R] M :=
{ to_fun := λ v, { to_fun := λ f, ∑ i, f i • v i,
map_add' := λ f g, by { simp_rw [← finset.sum_add_distrib, ← add_smul], refl },
map_smul' := λ r f, by { simp_rw [finset.smul_sum, smul_smul], refl } },
map_add' := λ u v, by { ext, simp [finset.sum_add_distrib, pi.add_apply, smul_add] },
map_smul' := λ r v, by { ext, simp [finset.smul_sum, smul_comm _ r] } }
variables {S}
lemma fintype.total_apply (f) : fintype.total R S v f = ∑ i, f i • v i := rfl
@[simp]
lemma fintype.total_apply_single (i : α) (r : R) :
fintype.total R S v (pi.single i r) = r • v i :=
begin
simp_rw [fintype.total_apply, pi.single_apply, ite_smul, zero_smul],
rw [finset.sum_ite_eq', if_pos (finset.mem_univ _)]
end
variables (S)
lemma finsupp.total_eq_fintype_total_apply (x : α → R) :
finsupp.total α M R v ((finsupp.linear_equiv_fun_on_finite R R α).symm x) =
fintype.total R S v x :=
begin
apply finset.sum_subset,
{ exact finset.subset_univ _ },
{ intros x _ hx,
rw finsupp.not_mem_support_iff.mp hx,
exact zero_smul _ _ }
end
lemma finsupp.total_eq_fintype_total :
(finsupp.total α M R v).comp (finsupp.linear_equiv_fun_on_finite R R α).symm.to_linear_map =
fintype.total R S v :=
linear_map.ext $ finsupp.total_eq_fintype_total_apply R S v
variables {S}
@[simp]
lemma fintype.range_total : (fintype.total R S v).range = submodule.span R (set.range v) :=
by rw [← finsupp.total_eq_fintype_total, linear_map.range_comp,
linear_equiv.to_linear_map_eq_coe, linear_equiv.range, submodule.map_top, finsupp.range_total]
section span_range
variables {v} {x : M}
/--
An element `x` lies in the span of `v` iff it can be written as sum `∑ cᵢ • vᵢ = x`.
-/
lemma mem_span_range_iff_exists_fun :
x ∈ span R (range v) ↔ ∃ (c : α → R), ∑ i, c i • v i = x :=
begin
simp only [finsupp.mem_span_range_iff_exists_finsupp,
finsupp.equiv_fun_on_finite.surjective.exists, finsupp.equiv_fun_on_finite_apply],
exact exists_congr (λ c, eq.congr_left $ finsupp.sum_fintype _ _ $ λ i, zero_smul _ _)
end
/--
A family `v : α → V` is generating `V` iff every element `(x : V)`
can be written as sum `∑ cᵢ • vᵢ = x`.
-/
theorem top_le_span_range_iff_forall_exists_fun :
⊤ ≤ span R (range v) ↔ ∀ x, ∃ (c : α → R), ∑ i, (c i) • (v i) = x :=
begin
simp_rw ←mem_span_range_iff_exists_fun,
exact ⟨λ h x, h trivial, λ h x _, h x⟩,
end
end span_range
end fintype
variables {R : Type*} {M : Type*} {N : Type*}
variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N]
section
variables (R)
/--
Pick some representation of `x : span R w` as a linear combination in `w`,
using the axiom of choice.
-/
def span.repr (w : set M) (x : span R w) : w →₀ R :=
((finsupp.mem_span_iff_total _ _ _).mp x.2).some
@[simp] lemma span.finsupp_total_repr {w : set M} (x : span R w) :
finsupp.total w M R coe (span.repr R w x) = x :=
((finsupp.mem_span_iff_total _ _ _).mp x.2).some_spec
attribute [irreducible] span.repr
end
protected lemma submodule.finsupp_sum_mem {ι β : Type*} [has_zero β] (S : submodule R M)
(f : ι →₀ β) (g : ι → β → M) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ S) : f.sum g ∈ S :=
add_submonoid_class.finsupp_sum_mem S f g h
lemma linear_map.map_finsupp_total
(f : M →ₗ[R] N) {ι : Type*} {g : ι → M} (l : ι →₀ R) :
f (finsupp.total ι M R g l) = finsupp.total ι N R (f ∘ g) l :=
by simp only [finsupp.total_apply, finsupp.total_apply, finsupp.sum, f.map_sum, f.map_smul]
lemma submodule.exists_finset_of_mem_supr
{ι : Sort*} (p : ι → submodule R M) {m : M} (hm : m ∈ ⨆ i, p i) :
∃ s : finset ι, m ∈ ⨆ i ∈ s, p i :=
begin
have := complete_lattice.is_compact_element.exists_finset_of_le_supr (submodule R M)
(submodule.singleton_span_is_compact_element m) p,
simp only [submodule.span_singleton_le_iff_mem] at this,
exact this hm,
end
/-- `submodule.exists_finset_of_mem_supr` as an `iff` -/
lemma submodule.mem_supr_iff_exists_finset
{ι : Sort*} {p : ι → submodule R M} {m : M} :
(m ∈ ⨆ i, p i) ↔ ∃ s : finset ι, m ∈ ⨆ i ∈ s, p i :=
⟨submodule.exists_finset_of_mem_supr p,
λ ⟨_, hs⟩, supr_mono (λ i, (supr_const_le : _ ≤ p i)) hs⟩
lemma mem_span_finset {s : finset M} {x : M} :
x ∈ span R (↑s : set M) ↔ ∃ f : M → R, ∑ i in s, f i • i = x :=
⟨λ hx, let ⟨v, hvs, hvx⟩ := (finsupp.mem_span_image_iff_total _).1
(show x ∈ span R (id '' (↑s : set M)), by rwa set.image_id) in
⟨v, hvx ▸ (finsupp.total_apply_of_mem_supported _ hvs).symm⟩,
λ ⟨f, hf⟩, hf ▸ sum_mem (λ i hi, smul_mem _ _ $ subset_span hi)⟩
/-- An element `m ∈ M` is contained in the `R`-submodule spanned by a set `s ⊆ M`, if and only if
`m` can be written as a finite `R`-linear combination of elements of `s`.
The implementation uses `finsupp.sum`. -/
lemma mem_span_set {m : M} {s : set M} :
m ∈ submodule.span R s ↔ ∃ c : M →₀ R, (c.support : set M) ⊆ s ∧ c.sum (λ mi r, r • mi) = m :=
begin
conv_lhs { rw ←set.image_id s },
simp_rw ←exists_prop,
exact finsupp.mem_span_image_iff_total R,
end
/-- If `subsingleton R`, then `M ≃ₗ[R] ι →₀ R` for any type `ι`. -/
@[simps]
def module.subsingleton_equiv (R M ι: Type*) [semiring R] [subsingleton R] [add_comm_monoid M]
[module R M] : M ≃ₗ[R] ι →₀ R :=
{ to_fun := λ m, 0,
inv_fun := λ f, 0,
left_inv := λ m, by { letI := module.subsingleton R M, simp only [eq_iff_true_of_subsingleton] },
right_inv := λ f, by simp only [eq_iff_true_of_subsingleton],
map_add' := λ m n, (add_zero 0).symm,
map_smul' := λ r m, (smul_zero r).symm }
namespace linear_map
variables {R M} {α : Type*}
open finsupp function
/-- A surjective linear map to finitely supported functions has a splitting. -/
-- See also `linear_map.splitting_of_fun_on_fintype_surjective`
def splitting_of_finsupp_surjective (f : M →ₗ[R] (α →₀ R)) (s : surjective f) : (α →₀ R) →ₗ[R] M :=
finsupp.lift _ _ _ (λ x : α, (s (finsupp.single x 1)).some)
lemma splitting_of_finsupp_surjective_splits (f : M →ₗ[R] (α →₀ R)) (s : surjective f) :
f.comp (splitting_of_finsupp_surjective f s) = linear_map.id :=
begin
ext x y,
dsimp [splitting_of_finsupp_surjective],
congr,
rw [sum_single_index, one_smul],
{ exact (s (finsupp.single x 1)).some_spec, },
{ rw zero_smul, },
end
lemma left_inverse_splitting_of_finsupp_surjective (f : M →ₗ[R] (α →₀ R)) (s : surjective f) :
left_inverse f (splitting_of_finsupp_surjective f s) :=
λ g, linear_map.congr_fun (splitting_of_finsupp_surjective_splits f s) g
lemma splitting_of_finsupp_surjective_injective (f : M →ₗ[R] (α →₀ R)) (s : surjective f) :
injective (splitting_of_finsupp_surjective f s) :=
(left_inverse_splitting_of_finsupp_surjective f s).injective
/-- A surjective linear map to functions on a finite type has a splitting. -/
-- See also `linear_map.splitting_of_finsupp_surjective`
def splitting_of_fun_on_fintype_surjective [fintype α] (f : M →ₗ[R] (α → R)) (s : surjective f) :
(α → R) →ₗ[R] M :=
(finsupp.lift _ _ _ (λ x : α, (s (finsupp.single x 1)).some)).comp
(linear_equiv_fun_on_finite R R α).symm.to_linear_map
lemma splitting_of_fun_on_fintype_surjective_splits
[fintype α] (f : M →ₗ[R] (α → R)) (s : surjective f) :
f.comp (splitting_of_fun_on_fintype_surjective f s) = linear_map.id :=
begin
ext x y,
dsimp [splitting_of_fun_on_fintype_surjective],
rw [linear_equiv_fun_on_finite_symm_single, finsupp.sum_single_index, one_smul,
(s (finsupp.single x 1)).some_spec, finsupp.single_eq_pi_single],
rw [zero_smul],
end
lemma left_inverse_splitting_of_fun_on_fintype_surjective
[fintype α] (f : M →ₗ[R] (α → R)) (s : surjective f) :
left_inverse f (splitting_of_fun_on_fintype_surjective f s) :=
λ g, linear_map.congr_fun (splitting_of_fun_on_fintype_surjective_splits f s) g
lemma splitting_of_fun_on_fintype_surjective_injective
[fintype α] (f : M →ₗ[R] (α → R)) (s : surjective f) :
injective (splitting_of_fun_on_fintype_surjective f s) :=
(left_inverse_splitting_of_fun_on_fintype_surjective f s).injective
end linear_map
|
383ea9a49530b7e59520048c51ea5a6ef38ddf0c | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/category/Born.lean | fbc84ec0410445d70f957e9e34e78534384a6102 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 1,208 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import category_theory.concrete_category.bundled_hom
import topology.bornology.hom
/-!
# The category of bornologies
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This defines `Born`, the category of bornologies.
-/
universes u
open category_theory
/-- The category of bornologies. -/
def Born := bundled bornology
namespace Born
instance : has_coe_to_sort Born Type* := bundled.has_coe_to_sort
instance (X : Born) : bornology X := X.str
/-- Construct a bundled `Born` from a `bornology`. -/
def of (α : Type*) [bornology α] : Born := bundled.of α
instance : inhabited Born := ⟨of punit⟩
instance : bundled_hom @locally_bounded_map :=
{ to_fun := λ _ _ _ _, coe_fn,
id := @locally_bounded_map.id,
comp := @locally_bounded_map.comp,
hom_ext := λ X Y _ _, by exactI fun_like.coe_injective }
instance : large_category.{u} Born := bundled_hom.category locally_bounded_map
instance : concrete_category Born := bundled_hom.concrete_category locally_bounded_map
end Born
|
6ff10cc4f9451a306eb747e40bc1ad60b3daa4d7 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/probability/process/stopping.lean | 424706ee2a3030ab5c2aee15603b5334b66ef061 | [
"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 | 50,609 | lean | /-
Copyright (c) 2021 Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kexing Ying, Rémy Degenne
-/
import probability.process.adapted
/-!
# Stopping times, stopped processes and stopped values
Definition and properties of stopping times.
## Main definitions
* `measure_theory.is_stopping_time`: a stopping time with respect to some filtration `f` is a
function `τ` such that for all `i`, the preimage of `{j | j ≤ i}` along `τ` is
`f i`-measurable
* `measure_theory.is_stopping_time.measurable_space`: the σ-algebra associated with a stopping time
## Main results
* `prog_measurable.stopped_process`: the stopped process of a progressively measurable process is
progressively measurable.
* `mem_ℒp_stopped_process`: if a process belongs to `ℒp` at every time in `ℕ`, then its stopped
process belongs to `ℒp` as well.
## Tags
stopping time, stochastic process
-/
open filter order topological_space
open_locale classical measure_theory nnreal ennreal topological_space big_operators
namespace measure_theory
variables {Ω β ι : Type*} {m : measurable_space Ω}
/-! ### Stopping times -/
/-- A stopping time with respect to some filtration `f` is a function
`τ` such that for all `i`, the preimage of `{j | j ≤ i}` along `τ` is measurable
with respect to `f i`.
Intuitively, the stopping time `τ` describes some stopping rule such that at time
`i`, we may determine it with the information we have at time `i`. -/
def is_stopping_time [preorder ι] (f : filtration ι m) (τ : Ω → ι) :=
∀ i : ι, measurable_set[f i] $ {ω | τ ω ≤ i}
lemma is_stopping_time_const [preorder ι] (f : filtration ι m) (i : ι) :
is_stopping_time f (λ ω, i) :=
λ j, by simp only [measurable_set.const]
section measurable_set
section preorder
variables [preorder ι] {f : filtration ι m} {τ : Ω → ι}
protected lemma is_stopping_time.measurable_set_le (hτ : is_stopping_time f τ) (i : ι) :
measurable_set[f i] {ω | τ ω ≤ i} :=
hτ i
lemma is_stopping_time.measurable_set_lt_of_pred [pred_order ι]
(hτ : is_stopping_time f τ) (i : ι) :
measurable_set[f i] {ω | τ ω < i} :=
begin
by_cases hi_min : is_min i,
{ suffices : {ω : Ω | τ ω < i} = ∅, by { rw this, exact @measurable_set.empty _ (f i), },
ext1 ω,
simp only [set.mem_set_of_eq, set.mem_empty_iff_false, iff_false],
rw is_min_iff_forall_not_lt at hi_min,
exact hi_min (τ ω), },
have : {ω : Ω | τ ω < i} = τ ⁻¹' (set.Iio i) := rfl,
rw [this, ←Iic_pred_of_not_is_min hi_min],
exact f.mono (pred_le i) _ (hτ.measurable_set_le $ pred i),
end
end preorder
section countable_stopping_time
namespace is_stopping_time
variables [partial_order ι] {τ : Ω → ι} {f : filtration ι m}
protected lemma measurable_set_eq_of_countable_range
(hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) :
measurable_set[f i] {ω | τ ω = i} :=
begin
have : {ω | τ ω = i} = {ω | τ ω ≤ i} \ (⋃ (j ∈ set.range τ) (hj : j < i), {ω | τ ω ≤ j}),
{ ext1 a,
simp only [set.mem_set_of_eq, set.mem_range, set.Union_exists, set.Union_Union_eq',
set.mem_diff, set.mem_Union, exists_prop, not_exists, not_and, not_le],
split; intro h,
{ simp only [h, lt_iff_le_not_le, le_refl, and_imp, imp_self, implies_true_iff, and_self], },
{ have h_lt_or_eq : τ a < i ∨ τ a = i := lt_or_eq_of_le h.1,
rcases h_lt_or_eq with h_lt | rfl,
{ exfalso,
exact h.2 a h_lt (le_refl (τ a)), },
{ refl, }, }, },
rw this,
refine (hτ.measurable_set_le i).diff _,
refine measurable_set.bUnion h_countable (λ j hj, _),
by_cases hji : j < i,
{ simp only [hji, set.Union_true],
exact f.mono hji.le _ (hτ.measurable_set_le j), },
{ simp only [hji, set.Union_false],
exact @measurable_set.empty _ (f i), },
end
protected lemma measurable_set_eq_of_countable [countable ι] (hτ : is_stopping_time f τ) (i : ι) :
measurable_set[f i] {ω | τ ω = i} :=
hτ.measurable_set_eq_of_countable_range (set.to_countable _) i
protected lemma measurable_set_lt_of_countable_range
(hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) :
measurable_set[f i] {ω | τ ω < i} :=
begin
have : {ω | τ ω < i} = {ω | τ ω ≤ i} \ {ω | τ ω = i},
{ ext1 ω, simp [lt_iff_le_and_ne], },
rw this,
exact (hτ.measurable_set_le i).diff (hτ.measurable_set_eq_of_countable_range h_countable i),
end
protected lemma measurable_set_lt_of_countable [countable ι] (hτ : is_stopping_time f τ) (i : ι) :
measurable_set[f i] {ω | τ ω < i} :=
hτ.measurable_set_lt_of_countable_range (set.to_countable _) i
protected lemma measurable_set_ge_of_countable_range {ι} [linear_order ι] {τ : Ω → ι}
{f : filtration ι m}
(hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) :
measurable_set[f i] {ω | i ≤ τ ω} :=
begin
have : {ω | i ≤ τ ω} = {ω | τ ω < i}ᶜ,
{ ext1 ω, simp only [set.mem_set_of_eq, set.mem_compl_iff, not_lt], },
rw this,
exact (hτ.measurable_set_lt_of_countable_range h_countable i).compl,
end
protected lemma measurable_set_ge_of_countable {ι} [linear_order ι] {τ : Ω → ι} {f : filtration ι m}
[countable ι] (hτ : is_stopping_time f τ) (i : ι) :
measurable_set[f i] {ω | i ≤ τ ω} :=
hτ.measurable_set_ge_of_countable_range (set.to_countable _) i
end is_stopping_time
end countable_stopping_time
section linear_order
variables [linear_order ι] {f : filtration ι m} {τ : Ω → ι}
lemma is_stopping_time.measurable_set_gt (hτ : is_stopping_time f τ) (i : ι) :
measurable_set[f i] {ω | i < τ ω} :=
begin
have : {ω | i < τ ω} = {ω | τ ω ≤ i}ᶜ,
{ ext1 ω, simp only [set.mem_set_of_eq, set.mem_compl_iff, not_le], },
rw this,
exact (hτ.measurable_set_le i).compl,
end
section topological_space
variables [topological_space ι] [order_topology ι] [first_countable_topology ι]
/-- Auxiliary lemma for `is_stopping_time.measurable_set_lt`. -/
lemma is_stopping_time.measurable_set_lt_of_is_lub
(hτ : is_stopping_time f τ) (i : ι) (h_lub : is_lub (set.Iio i) i) :
measurable_set[f i] {ω | τ ω < i} :=
begin
by_cases hi_min : is_min i,
{ suffices : {ω | τ ω < i} = ∅, by { rw this, exact @measurable_set.empty _ (f i), },
ext1 ω,
simp only [set.mem_set_of_eq, set.mem_empty_iff_false, iff_false],
exact is_min_iff_forall_not_lt.mp hi_min (τ ω), },
obtain ⟨seq, -, -, h_tendsto, h_bound⟩ : ∃ seq : ℕ → ι,
monotone seq ∧ (∀ j, seq j ≤ i) ∧ tendsto seq at_top (𝓝 i) ∧ (∀ j, seq j < i),
from h_lub.exists_seq_monotone_tendsto (not_is_min_iff.mp hi_min),
have h_Ioi_eq_Union : set.Iio i = ⋃ j, {k | k ≤ seq j},
{ ext1 k,
simp only [set.mem_Iio, set.mem_Union, set.mem_set_of_eq],
refine ⟨λ hk_lt_i, _, λ h_exists_k_le_seq, _⟩,
{ rw tendsto_at_top' at h_tendsto,
have h_nhds : set.Ici k ∈ 𝓝 i,
from mem_nhds_iff.mpr ⟨set.Ioi k, set.Ioi_subset_Ici le_rfl, is_open_Ioi, hk_lt_i⟩,
obtain ⟨a, ha⟩ : ∃ (a : ℕ), ∀ (b : ℕ), b ≥ a → k ≤ seq b := h_tendsto (set.Ici k) h_nhds,
exact ⟨a, ha a le_rfl⟩, },
{ obtain ⟨j, hk_seq_j⟩ := h_exists_k_le_seq,
exact hk_seq_j.trans_lt (h_bound j), }, },
have h_lt_eq_preimage : {ω | τ ω < i} = τ ⁻¹' (set.Iio i),
{ ext1 ω, simp only [set.mem_set_of_eq, set.mem_preimage, set.mem_Iio], },
rw [h_lt_eq_preimage, h_Ioi_eq_Union],
simp only [set.preimage_Union, set.preimage_set_of_eq],
exact measurable_set.Union
(λ n, f.mono (h_bound n).le _ (hτ.measurable_set_le (seq n))),
end
lemma is_stopping_time.measurable_set_lt (hτ : is_stopping_time f τ) (i : ι) :
measurable_set[f i] {ω | τ ω < i} :=
begin
obtain ⟨i', hi'_lub⟩ : ∃ i', is_lub (set.Iio i) i', from exists_lub_Iio i,
cases lub_Iio_eq_self_or_Iio_eq_Iic i hi'_lub with hi'_eq_i h_Iio_eq_Iic,
{ rw ← hi'_eq_i at hi'_lub ⊢,
exact hτ.measurable_set_lt_of_is_lub i' hi'_lub, },
{ have h_lt_eq_preimage : {ω : Ω | τ ω < i} = τ ⁻¹' (set.Iio i) := rfl,
rw [h_lt_eq_preimage, h_Iio_eq_Iic],
exact f.mono (lub_Iio_le i hi'_lub) _ (hτ.measurable_set_le i'), },
end
lemma is_stopping_time.measurable_set_ge (hτ : is_stopping_time f τ) (i : ι) :
measurable_set[f i] {ω | i ≤ τ ω} :=
begin
have : {ω | i ≤ τ ω} = {ω | τ ω < i}ᶜ,
{ ext1 ω, simp only [set.mem_set_of_eq, set.mem_compl_iff, not_lt], },
rw this,
exact (hτ.measurable_set_lt i).compl,
end
lemma is_stopping_time.measurable_set_eq (hτ : is_stopping_time f τ) (i : ι) :
measurable_set[f i] {ω | τ ω = i} :=
begin
have : {ω | τ ω = i} = {ω | τ ω ≤ i} ∩ {ω | τ ω ≥ i},
{ ext1 ω, simp only [set.mem_set_of_eq, ge_iff_le, set.mem_inter_iff, le_antisymm_iff], },
rw this,
exact (hτ.measurable_set_le i).inter (hτ.measurable_set_ge i),
end
lemma is_stopping_time.measurable_set_eq_le (hτ : is_stopping_time f τ) {i j : ι} (hle : i ≤ j) :
measurable_set[f j] {ω | τ ω = i} :=
f.mono hle _ $ hτ.measurable_set_eq i
lemma is_stopping_time.measurable_set_lt_le (hτ : is_stopping_time f τ) {i j : ι} (hle : i ≤ j) :
measurable_set[f j] {ω | τ ω < i} :=
f.mono hle _ $ hτ.measurable_set_lt i
end topological_space
end linear_order
section countable
lemma is_stopping_time_of_measurable_set_eq [preorder ι] [countable ι]
{f : filtration ι m} {τ : Ω → ι} (hτ : ∀ i, measurable_set[f i] {ω | τ ω = i}) :
is_stopping_time f τ :=
begin
intro i,
rw show {ω | τ ω ≤ i} = ⋃ k ≤ i, {ω | τ ω = k}, by { ext, simp },
refine measurable_set.bUnion (set.to_countable _) (λ k hk, _),
exact f.mono hk _ (hτ k),
end
end countable
end measurable_set
namespace is_stopping_time
protected lemma max [linear_order ι] {f : filtration ι m} {τ π : Ω → ι}
(hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) :
is_stopping_time f (λ ω, max (τ ω) (π ω)) :=
begin
intro i,
simp_rw [max_le_iff, set.set_of_and],
exact (hτ i).inter (hπ i),
end
protected lemma max_const [linear_order ι] {f : filtration ι m} {τ : Ω → ι}
(hτ : is_stopping_time f τ) (i : ι) :
is_stopping_time f (λ ω, max (τ ω) i) :=
hτ.max (is_stopping_time_const f i)
protected lemma min [linear_order ι] {f : filtration ι m} {τ π : Ω → ι}
(hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) :
is_stopping_time f (λ ω, min (τ ω) (π ω)) :=
begin
intro i,
simp_rw [min_le_iff, set.set_of_or],
exact (hτ i).union (hπ i),
end
protected lemma min_const [linear_order ι] {f : filtration ι m} {τ : Ω → ι}
(hτ : is_stopping_time f τ) (i : ι) :
is_stopping_time f (λ ω, min (τ ω) i) :=
hτ.min (is_stopping_time_const f i)
lemma add_const [add_group ι] [preorder ι] [covariant_class ι ι (function.swap (+)) (≤)]
[covariant_class ι ι (+) (≤)]
{f : filtration ι m} {τ : Ω → ι} (hτ : is_stopping_time f τ) {i : ι} (hi : 0 ≤ i) :
is_stopping_time f (λ ω, τ ω + i) :=
begin
intro j,
simp_rw [← le_sub_iff_add_le],
exact f.mono (sub_le_self j hi) _ (hτ (j - i)),
end
lemma add_const_nat
{f : filtration ℕ m} {τ : Ω → ℕ} (hτ : is_stopping_time f τ) {i : ℕ} :
is_stopping_time f (λ ω, τ ω + i) :=
begin
refine is_stopping_time_of_measurable_set_eq (λ j, _),
by_cases hij : i ≤ j,
{ simp_rw [eq_comm, ← nat.sub_eq_iff_eq_add hij, eq_comm],
exact f.mono (j.sub_le i) _ (hτ.measurable_set_eq (j - i)) },
{ rw not_le at hij,
convert measurable_set.empty,
ext ω,
simp only [set.mem_empty_iff_false, iff_false],
rintro (hx : τ ω + i = j),
linarith },
end
-- generalize to certain countable type?
lemma add
{f : filtration ℕ m} {τ π : Ω → ℕ} (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) :
is_stopping_time f (τ + π) :=
begin
intro i,
rw (_ : {ω | (τ + π) ω ≤ i} = ⋃ k ≤ i, {ω | π ω = k} ∩ {ω | τ ω + k ≤ i}),
{ exact measurable_set.Union (λ k, measurable_set.Union
(λ hk, (hπ.measurable_set_eq_le hk).inter (hτ.add_const_nat i))) },
ext ω,
simp only [pi.add_apply, set.mem_set_of_eq, set.mem_Union, set.mem_inter_iff, exists_prop],
refine ⟨λ h, ⟨π ω, by linarith, rfl, h⟩, _⟩,
rintro ⟨j, hj, rfl, h⟩,
assumption
end
section preorder
variables [preorder ι] {f : filtration ι m} {τ π : Ω → ι}
/-- The associated σ-algebra with a stopping time. -/
protected def measurable_space (hτ : is_stopping_time f τ) : measurable_space Ω :=
{ measurable_set' := λ s, ∀ i : ι, measurable_set[f i] (s ∩ {ω | τ ω ≤ i}),
measurable_set_empty :=
λ i, (set.empty_inter {ω | τ ω ≤ i}).symm ▸ @measurable_set.empty _ (f i),
measurable_set_compl := λ s hs i,
begin
rw (_ : sᶜ ∩ {ω | τ ω ≤ i} = (sᶜ ∪ {ω | τ ω ≤ i}ᶜ) ∩ {ω | τ ω ≤ i}),
{ refine measurable_set.inter _ _,
{ rw ← set.compl_inter,
exact (hs i).compl },
{ exact hτ i} },
{ rw set.union_inter_distrib_right,
simp only [set.compl_inter_self, set.union_empty] }
end,
measurable_set_Union := λ s hs i,
begin
rw forall_swap at hs,
rw set.Union_inter,
exact measurable_set.Union (hs i),
end }
protected lemma measurable_set (hτ : is_stopping_time f τ) (s : set Ω) :
measurable_set[hτ.measurable_space] s ↔
∀ i : ι, measurable_set[f i] (s ∩ {ω | τ ω ≤ i}) :=
iff.rfl
lemma measurable_space_mono
(hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) (hle : τ ≤ π) :
hτ.measurable_space ≤ hπ.measurable_space :=
begin
intros s hs i,
rw (_ : s ∩ {ω | π ω ≤ i} = s ∩ {ω | τ ω ≤ i} ∩ {ω | π ω ≤ i}),
{ exact (hs i).inter (hπ i) },
{ ext,
simp only [set.mem_inter_iff, iff_self_and, and.congr_left_iff, set.mem_set_of_eq],
intros hle' _,
exact le_trans (hle _) hle' },
end
lemma measurable_space_le_of_countable [countable ι] (hτ : is_stopping_time f τ) :
hτ.measurable_space ≤ m :=
begin
intros s hs,
change ∀ i, measurable_set[f i] (s ∩ {ω | τ ω ≤ i}) at hs,
rw (_ : s = ⋃ i, s ∩ {ω | τ ω ≤ i}),
{ exact measurable_set.Union (λ i, f.le i _ (hs i)) },
{ ext ω, split; rw set.mem_Union,
{ exact λ hx, ⟨τ ω, hx, le_rfl⟩ },
{ rintro ⟨_, hx, _⟩,
exact hx } }
end
lemma measurable_space_le' [is_countably_generated (at_top : filter ι)] [(at_top : filter ι).ne_bot]
(hτ : is_stopping_time f τ) :
hτ.measurable_space ≤ m :=
begin
intros s hs,
change ∀ i, measurable_set[f i] (s ∩ {ω | τ ω ≤ i}) at hs,
obtain ⟨seq : ℕ → ι, h_seq_tendsto⟩ := at_top.exists_seq_tendsto,
rw (_ : s = ⋃ n, s ∩ {ω | τ ω ≤ seq n}),
{ exact measurable_set.Union (λ i, f.le (seq i) _ (hs (seq i))), },
{ ext ω, split; rw set.mem_Union,
{ intros hx,
suffices : ∃ i, τ ω ≤ seq i, from ⟨this.some, hx, this.some_spec⟩,
rw tendsto_at_top at h_seq_tendsto,
exact (h_seq_tendsto (τ ω)).exists, },
{ rintro ⟨_, hx, _⟩,
exact hx }, },
all_goals { apply_instance, },
end
lemma measurable_space_le {ι} [semilattice_sup ι] {f : filtration ι m} {τ : Ω → ι}
[is_countably_generated (at_top : filter ι)] (hτ : is_stopping_time f τ) :
hτ.measurable_space ≤ m :=
begin
casesI is_empty_or_nonempty ι,
{ haveI : is_empty Ω := ⟨λ ω, is_empty.false (τ ω)⟩,
intros s hsτ,
suffices hs : s = ∅, by { rw hs, exact measurable_set.empty, },
haveI : unique (set Ω) := set.unique_empty,
rw [unique.eq_default s, unique.eq_default ∅], },
exact measurable_space_le' hτ,
end
example {f : filtration ℕ m} {τ : Ω → ℕ} (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m :=
hτ.measurable_space_le
example {f : filtration ℝ m} {τ : Ω → ℝ} (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m :=
hτ.measurable_space_le
@[simp] lemma measurable_space_const (f : filtration ι m) (i : ι) :
(is_stopping_time_const f i).measurable_space = f i :=
begin
ext1 s,
change measurable_set[(is_stopping_time_const f i).measurable_space] s ↔ measurable_set[f i] s,
rw is_stopping_time.measurable_set,
split; intro h,
{ specialize h i,
simpa only [le_refl, set.set_of_true, set.inter_univ] using h, },
{ intro j,
by_cases hij : i ≤ j,
{ simp only [hij, set.set_of_true, set.inter_univ],
exact f.mono hij _ h, },
{ simp only [hij, set.set_of_false, set.inter_empty, measurable_set.empty], }, },
end
lemma measurable_set_inter_eq_iff (hτ : is_stopping_time f τ) (s : set Ω) (i : ι) :
measurable_set[hτ.measurable_space] (s ∩ {ω | τ ω = i})
↔ measurable_set[f i] (s ∩ {ω | τ ω = i}) :=
begin
have : ∀ j, ({ω : Ω | τ ω = i} ∩ {ω : Ω | τ ω ≤ j}) = {ω : Ω | τ ω = i} ∩ {ω | i ≤ j},
{ intro j,
ext1 ω,
simp only [set.mem_inter_iff, set.mem_set_of_eq, and.congr_right_iff],
intro hxi,
rw hxi, },
split; intro h,
{ specialize h i,
simpa only [set.inter_assoc, this, le_refl, set.set_of_true, set.inter_univ] using h, },
{ intro j,
rw [set.inter_assoc, this],
by_cases hij : i ≤ j,
{ simp only [hij, set.set_of_true, set.inter_univ],
exact f.mono hij _ h, },
{ simp [hij], }, },
end
lemma measurable_space_le_of_le_const (hτ : is_stopping_time f τ) {i : ι} (hτ_le : ∀ ω, τ ω ≤ i) :
hτ.measurable_space ≤ f i :=
(measurable_space_mono hτ _ hτ_le).trans (measurable_space_const _ _).le
lemma measurable_space_le_of_le (hτ : is_stopping_time f τ) {n : ι} (hτ_le : ∀ ω, τ ω ≤ n) :
hτ.measurable_space ≤ m :=
(hτ.measurable_space_le_of_le_const hτ_le).trans (f.le n)
lemma le_measurable_space_of_const_le (hτ : is_stopping_time f τ) {i : ι} (hτ_le : ∀ ω, i ≤ τ ω) :
f i ≤ hτ.measurable_space :=
(measurable_space_const _ _).symm.le.trans (measurable_space_mono _ hτ hτ_le)
end preorder
instance sigma_finite_stopping_time {ι} [semilattice_sup ι] [order_bot ι]
[(filter.at_top : filter ι).is_countably_generated]
{μ : measure Ω} {f : filtration ι m} {τ : Ω → ι}
[sigma_finite_filtration μ f] (hτ : is_stopping_time f τ) :
sigma_finite (μ.trim hτ.measurable_space_le) :=
begin
refine sigma_finite_trim_mono hτ.measurable_space_le _,
{ exact f ⊥, },
{ exact hτ.le_measurable_space_of_const_le (λ _, bot_le), },
{ apply_instance, },
end
instance sigma_finite_stopping_time_of_le {ι} [semilattice_sup ι] [order_bot ι]
{μ : measure Ω} {f : filtration ι m} {τ : Ω → ι}
[sigma_finite_filtration μ f] (hτ : is_stopping_time f τ) {n : ι} (hτ_le : ∀ ω, τ ω ≤ n) :
sigma_finite (μ.trim (hτ.measurable_space_le_of_le hτ_le)) :=
begin
refine sigma_finite_trim_mono (hτ.measurable_space_le_of_le hτ_le) _,
{ exact f ⊥, },
{ exact hτ.le_measurable_space_of_const_le (λ _, bot_le), },
{ apply_instance, },
end
section linear_order
variables [linear_order ι] {f : filtration ι m} {τ π : Ω → ι}
protected lemma measurable_set_le' (hτ : is_stopping_time f τ) (i : ι) :
measurable_set[hτ.measurable_space] {ω | τ ω ≤ i} :=
begin
intro j,
have : {ω : Ω | τ ω ≤ i} ∩ {ω : Ω | τ ω ≤ j} = {ω : Ω | τ ω ≤ min i j},
{ ext1 ω, simp only [set.mem_inter_iff, set.mem_set_of_eq, le_min_iff], },
rw this,
exact f.mono (min_le_right i j) _ (hτ _),
end
protected lemma measurable_set_gt' (hτ : is_stopping_time f τ) (i : ι) :
measurable_set[hτ.measurable_space] {ω | i < τ ω} :=
begin
have : {ω : Ω | i < τ ω} = {ω : Ω | τ ω ≤ i}ᶜ, by { ext1 ω, simp, },
rw this,
exact (hτ.measurable_set_le' i).compl,
end
protected lemma measurable_set_eq' [topological_space ι] [order_topology ι]
[first_countable_topology ι]
(hτ : is_stopping_time f τ) (i : ι) :
measurable_set[hτ.measurable_space] {ω | τ ω = i} :=
begin
rw [← set.univ_inter {ω | τ ω = i}, measurable_set_inter_eq_iff, set.univ_inter],
exact hτ.measurable_set_eq i,
end
protected lemma measurable_set_ge' [topological_space ι] [order_topology ι]
[first_countable_topology ι]
(hτ : is_stopping_time f τ) (i : ι) :
measurable_set[hτ.measurable_space] {ω | i ≤ τ ω} :=
begin
have : {ω | i ≤ τ ω} = {ω | τ ω = i} ∪ {ω | i < τ ω},
{ ext1 ω,
simp only [le_iff_lt_or_eq, set.mem_set_of_eq, set.mem_union],
rw [@eq_comm _ i, or_comm], },
rw this,
exact (hτ.measurable_set_eq' i).union (hτ.measurable_set_gt' i),
end
protected lemma measurable_set_lt' [topological_space ι] [order_topology ι]
[first_countable_topology ι]
(hτ : is_stopping_time f τ) (i : ι) :
measurable_set[hτ.measurable_space] {ω | τ ω < i} :=
begin
have : {ω | τ ω < i} = {ω | τ ω ≤ i} \ {ω | τ ω = i},
{ ext1 ω,
simp only [lt_iff_le_and_ne, set.mem_set_of_eq, set.mem_diff], },
rw this,
exact (hτ.measurable_set_le' i).diff (hτ.measurable_set_eq' i),
end
section countable
protected lemma measurable_set_eq_of_countable_range'
(hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) :
measurable_set[hτ.measurable_space] {ω | τ ω = i} :=
begin
rw [← set.univ_inter {ω | τ ω = i}, measurable_set_inter_eq_iff, set.univ_inter],
exact hτ.measurable_set_eq_of_countable_range h_countable i,
end
protected lemma measurable_set_eq_of_countable' [countable ι] (hτ : is_stopping_time f τ) (i : ι) :
measurable_set[hτ.measurable_space] {ω | τ ω = i} :=
hτ.measurable_set_eq_of_countable_range' (set.to_countable _) i
protected lemma measurable_set_ge_of_countable_range'
(hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) :
measurable_set[hτ.measurable_space] {ω | i ≤ τ ω} :=
begin
have : {ω | i ≤ τ ω} = {ω | τ ω = i} ∪ {ω | i < τ ω},
{ ext1 ω,
simp only [le_iff_lt_or_eq, set.mem_set_of_eq, set.mem_union],
rw [@eq_comm _ i, or_comm], },
rw this,
exact (hτ.measurable_set_eq_of_countable_range' h_countable i).union (hτ.measurable_set_gt' i),
end
protected lemma measurable_set_ge_of_countable' [countable ι] (hτ : is_stopping_time f τ) (i : ι) :
measurable_set[hτ.measurable_space] {ω | i ≤ τ ω} :=
hτ.measurable_set_ge_of_countable_range' (set.to_countable _) i
protected lemma measurable_set_lt_of_countable_range'
(hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) :
measurable_set[hτ.measurable_space] {ω | τ ω < i} :=
begin
have : {ω | τ ω < i} = {ω | τ ω ≤ i} \ {ω | τ ω = i},
{ ext1 ω,
simp only [lt_iff_le_and_ne, set.mem_set_of_eq, set.mem_diff], },
rw this,
exact (hτ.measurable_set_le' i).diff (hτ.measurable_set_eq_of_countable_range' h_countable i),
end
protected lemma measurable_set_lt_of_countable' [countable ι] (hτ : is_stopping_time f τ) (i : ι) :
measurable_set[hτ.measurable_space] {ω | τ ω < i} :=
hτ.measurable_set_lt_of_countable_range' (set.to_countable _) i
protected lemma measurable_space_le_of_countable_range (hτ : is_stopping_time f τ)
(h_countable : (set.range τ).countable) :
hτ.measurable_space ≤ m :=
begin
intros s hs,
change ∀ i, measurable_set[f i] (s ∩ {ω | τ ω ≤ i}) at hs,
rw (_ : s = ⋃ (i ∈ set.range τ), s ∩ {ω | τ ω ≤ i}),
{ exact measurable_set.bUnion h_countable (λ i _, f.le i _ (hs i)), },
{ ext ω,
split; rw set.mem_Union,
{ exact λ hx, ⟨τ ω, by simpa using hx⟩,},
{ rintro ⟨i, hx⟩,
simp only [set.mem_range, set.Union_exists, set.mem_Union, set.mem_inter_iff,
set.mem_set_of_eq, exists_prop, exists_and_distrib_right] at hx,
exact hx.1.2, } }
end
end countable
protected lemma measurable [topological_space ι] [measurable_space ι]
[borel_space ι] [order_topology ι] [second_countable_topology ι]
(hτ : is_stopping_time f τ) :
measurable[hτ.measurable_space] τ :=
@measurable_of_Iic ι Ω _ _ _ hτ.measurable_space _ _ _ _ (λ i, hτ.measurable_set_le' i)
protected lemma measurable_of_le [topological_space ι] [measurable_space ι]
[borel_space ι] [order_topology ι] [second_countable_topology ι]
(hτ : is_stopping_time f τ) {i : ι} (hτ_le : ∀ ω, τ ω ≤ i) :
measurable[f i] τ :=
hτ.measurable.mono (measurable_space_le_of_le_const _ hτ_le) le_rfl
lemma measurable_space_min (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) :
(hτ.min hπ).measurable_space = hτ.measurable_space ⊓ hπ.measurable_space :=
begin
refine le_antisymm _ _,
{ exact le_inf (measurable_space_mono _ hτ (λ _, min_le_left _ _))
(measurable_space_mono _ hπ (λ _, min_le_right _ _)), },
{ intro s,
change measurable_set[hτ.measurable_space] s ∧ measurable_set[hπ.measurable_space] s
→ measurable_set[(hτ.min hπ).measurable_space] s,
simp_rw is_stopping_time.measurable_set,
have : ∀ i, {ω | min (τ ω) (π ω) ≤ i} = {ω | τ ω ≤ i} ∪ {ω | π ω ≤ i},
{ intro i, ext1 ω, simp, },
simp_rw [this, set.inter_union_distrib_left],
exact λ h i, (h.left i).union (h.right i), },
end
lemma measurable_set_min_iff (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) (s : set Ω) :
measurable_set[(hτ.min hπ).measurable_space] s
↔ measurable_set[hτ.measurable_space] s ∧ measurable_set[hπ.measurable_space] s :=
by { rw measurable_space_min, refl, }
lemma measurable_space_min_const (hτ : is_stopping_time f τ) {i : ι} :
(hτ.min_const i).measurable_space = hτ.measurable_space ⊓ f i :=
by rw [hτ.measurable_space_min (is_stopping_time_const _ i), measurable_space_const]
lemma measurable_set_min_const_iff (hτ : is_stopping_time f τ) (s : set Ω)
{i : ι} :
measurable_set[(hτ.min_const i).measurable_space] s
↔ measurable_set[hτ.measurable_space] s ∧ measurable_set[f i] s :=
by rw [measurable_space_min_const, measurable_space.measurable_set_inf]
lemma measurable_set_inter_le [topological_space ι] [second_countable_topology ι] [order_topology ι]
[measurable_space ι] [borel_space ι]
(hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) (s : set Ω)
(hs : measurable_set[hτ.measurable_space] s) :
measurable_set[(hτ.min hπ).measurable_space] (s ∩ {ω | τ ω ≤ π ω}) :=
begin
simp_rw is_stopping_time.measurable_set at ⊢ hs,
intro i,
have : (s ∩ {ω | τ ω ≤ π ω} ∩ {ω | min (τ ω) (π ω) ≤ i})
= (s ∩ {ω | τ ω ≤ i}) ∩ {ω | min (τ ω) (π ω) ≤ i} ∩ {ω | min (τ ω) i ≤ min (min (τ ω) (π ω)) i},
{ ext1 ω,
simp only [min_le_iff, set.mem_inter_iff, set.mem_set_of_eq, le_min_iff, le_refl, true_and,
and_true, true_or, or_true],
by_cases hτi : τ ω ≤ i,
{ simp only [hτi, true_or, and_true, and.congr_right_iff],
intro hx,
split; intro h,
{ exact or.inl h, },
{ cases h,
{ exact h, },
{ exact hτi.trans h, }, }, },
simp only [hτi, false_or, and_false, false_and, iff_false, not_and, not_le, and_imp],
refine λ hx hτ_le_π, lt_of_lt_of_le _ hτ_le_π,
rw ← not_le,
exact hτi, },
rw this,
refine ((hs i).inter ((hτ.min hπ) i)).inter _,
apply measurable_set_le,
{ exact (hτ.min_const i).measurable_of_le (λ _, min_le_right _ _), },
{ exact ((hτ.min hπ).min_const i).measurable_of_le (λ _, min_le_right _ _), },
end
lemma measurable_set_inter_le_iff [topological_space ι]
[second_countable_topology ι] [order_topology ι] [measurable_space ι] [borel_space ι]
(hτ : is_stopping_time f τ) (hπ : is_stopping_time f π)
(s : set Ω) :
measurable_set[hτ.measurable_space] (s ∩ {ω | τ ω ≤ π ω})
↔ measurable_set[(hτ.min hπ).measurable_space] (s ∩ {ω | τ ω ≤ π ω}) :=
begin
split; intro h,
{ have : s ∩ {ω | τ ω ≤ π ω} = s ∩ {ω | τ ω ≤ π ω} ∩ {ω | τ ω ≤ π ω},
by rw [set.inter_assoc, set.inter_self],
rw this,
exact measurable_set_inter_le _ _ _ h, },
{ rw measurable_set_min_iff at h,
exact h.1, },
end
lemma measurable_set_inter_le_const_iff (hτ : is_stopping_time f τ) (s : set Ω) (i : ι) :
measurable_set[hτ.measurable_space] (s ∩ {ω | τ ω ≤ i})
↔ measurable_set[(hτ.min_const i).measurable_space] (s ∩ {ω | τ ω ≤ i}) :=
begin
rw [is_stopping_time.measurable_set_min_iff hτ (is_stopping_time_const _ i),
is_stopping_time.measurable_space_const, is_stopping_time.measurable_set],
refine ⟨λ h, ⟨h, _⟩, λ h j, h.1 j⟩,
specialize h i,
rwa [set.inter_assoc, set.inter_self] at h,
end
lemma measurable_set_le_stopping_time [topological_space ι]
[second_countable_topology ι] [order_topology ι] [measurable_space ι] [borel_space ι]
(hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) :
measurable_set[hτ.measurable_space] {ω | τ ω ≤ π ω} :=
begin
rw hτ.measurable_set,
intro j,
have : {ω | τ ω ≤ π ω} ∩ {ω | τ ω ≤ j} = {ω | min (τ ω) j ≤ min (π ω) j} ∩ {ω | τ ω ≤ j},
{ ext1 ω,
simp only [set.mem_inter_iff, set.mem_set_of_eq, min_le_iff, le_min_iff, le_refl, and_true,
and.congr_left_iff],
intro h,
simp only [h, or_self, and_true],
by_cases hj : j ≤ π ω,
{ simp only [hj, h.trans hj, or_self], },
{ simp only [hj, or_false], }, },
rw this,
refine measurable_set.inter _ (hτ.measurable_set_le j),
apply measurable_set_le,
{ exact (hτ.min_const j).measurable_of_le (λ _, min_le_right _ _), },
{ exact (hπ.min_const j).measurable_of_le (λ _, min_le_right _ _), },
end
lemma measurable_set_stopping_time_le [topological_space ι]
[second_countable_topology ι] [order_topology ι] [measurable_space ι] [borel_space ι]
(hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) :
measurable_set[hπ.measurable_space] {ω | τ ω ≤ π ω} :=
begin
suffices : measurable_set[(hτ.min hπ).measurable_space] {ω : Ω | τ ω ≤ π ω},
by { rw measurable_set_min_iff hτ hπ at this, exact this.2, },
rw [← set.univ_inter {ω : Ω | τ ω ≤ π ω}, ← hτ.measurable_set_inter_le_iff hπ, set.univ_inter],
exact measurable_set_le_stopping_time hτ hπ,
end
lemma measurable_set_eq_stopping_time [add_group ι]
[topological_space ι] [measurable_space ι] [borel_space ι] [order_topology ι]
[measurable_singleton_class ι] [second_countable_topology ι] [has_measurable_sub₂ ι]
(hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) :
measurable_set[hτ.measurable_space] {ω | τ ω = π ω} :=
begin
rw hτ.measurable_set,
intro j,
have : {ω | τ ω = π ω} ∩ {ω | τ ω ≤ j}
= {ω | min (τ ω) j = min (π ω) j} ∩ {ω | τ ω ≤ j} ∩ {ω | π ω ≤ j},
{ ext1 ω,
simp only [set.mem_inter_iff, set.mem_set_of_eq],
refine ⟨λ h, ⟨⟨_, h.2⟩, _⟩, λ h, ⟨_, h.1.2⟩⟩,
{ rw h.1, },
{ rw ← h.1, exact h.2, },
{ cases h with h' hσ_le,
cases h' with h_eq hτ_le,
rwa [min_eq_left hτ_le, min_eq_left hσ_le] at h_eq, }, },
rw this,
refine measurable_set.inter (measurable_set.inter _ (hτ.measurable_set_le j))
(hπ.measurable_set_le j),
apply measurable_set_eq_fun,
{ exact (hτ.min_const j).measurable_of_le (λ _, min_le_right _ _), },
{ exact (hπ.min_const j).measurable_of_le (λ _, min_le_right _ _), },
end
lemma measurable_set_eq_stopping_time_of_countable [countable ι]
[topological_space ι] [measurable_space ι] [borel_space ι] [order_topology ι]
[measurable_singleton_class ι] [second_countable_topology ι]
(hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) :
measurable_set[hτ.measurable_space] {ω | τ ω = π ω} :=
begin
rw hτ.measurable_set,
intro j,
have : {ω | τ ω = π ω} ∩ {ω | τ ω ≤ j}
= {ω | min (τ ω) j = min (π ω) j} ∩ {ω | τ ω ≤ j} ∩ {ω | π ω ≤ j},
{ ext1 ω,
simp only [set.mem_inter_iff, set.mem_set_of_eq],
refine ⟨λ h, ⟨⟨_, h.2⟩, _⟩, λ h, ⟨_, h.1.2⟩⟩,
{ rw h.1, },
{ rw ← h.1, exact h.2, },
{ cases h with h' hπ_le,
cases h' with h_eq hτ_le,
rwa [min_eq_left hτ_le, min_eq_left hπ_le] at h_eq, }, },
rw this,
refine measurable_set.inter (measurable_set.inter _ (hτ.measurable_set_le j))
(hπ.measurable_set_le j),
apply measurable_set_eq_fun_of_countable,
{ exact (hτ.min_const j).measurable_of_le (λ _, min_le_right _ _), },
{ exact (hπ.min_const j).measurable_of_le (λ _, min_le_right _ _), },
end
end linear_order
end is_stopping_time
section linear_order
/-! ## Stopped value and stopped process -/
/-- Given a map `u : ι → Ω → E`, its stopped value with respect to the stopping
time `τ` is the map `x ↦ u (τ ω) ω`. -/
def stopped_value (u : ι → Ω → β) (τ : Ω → ι) : Ω → β :=
λ ω, u (τ ω) ω
lemma stopped_value_const (u : ι → Ω → β) (i : ι) : stopped_value u (λ ω, i) = u i :=
rfl
variable [linear_order ι]
/-- Given a map `u : ι → Ω → E`, the stopped process with respect to `τ` is `u i ω` if
`i ≤ τ ω`, and `u (τ ω) ω` otherwise.
Intuitively, the stopped process stops evolving once the stopping time has occured. -/
def stopped_process (u : ι → Ω → β) (τ : Ω → ι) : ι → Ω → β :=
λ i ω, u (min i (τ ω)) ω
lemma stopped_process_eq_stopped_value {u : ι → Ω → β} {τ : Ω → ι} :
stopped_process u τ = λ i, stopped_value u (λ ω, min i (τ ω)) := rfl
lemma stopped_value_stopped_process {u : ι → Ω → β} {τ σ : Ω → ι} :
stopped_value (stopped_process u τ) σ = stopped_value u (λ ω, min (σ ω) (τ ω)) := rfl
lemma stopped_process_eq_of_le {u : ι → Ω → β} {τ : Ω → ι}
{i : ι} {ω : Ω} (h : i ≤ τ ω) : stopped_process u τ i ω = u i ω :=
by simp [stopped_process, min_eq_left h]
lemma stopped_process_eq_of_ge {u : ι → Ω → β} {τ : Ω → ι}
{i : ι} {ω : Ω} (h : τ ω ≤ i) : stopped_process u τ i ω = u (τ ω) ω :=
by simp [stopped_process, min_eq_right h]
section prog_measurable
variables [measurable_space ι] [topological_space ι] [order_topology ι]
[second_countable_topology ι] [borel_space ι]
[topological_space β]
{u : ι → Ω → β} {τ : Ω → ι} {f : filtration ι m}
lemma prog_measurable_min_stopping_time [metrizable_space ι] (hτ : is_stopping_time f τ) :
prog_measurable f (λ i ω, min i (τ ω)) :=
begin
intro i,
let m_prod : measurable_space (set.Iic i × Ω) := measurable_space.prod _ (f i),
let m_set : ∀ t : set (set.Iic i × Ω), measurable_space t :=
λ _, @subtype.measurable_space (set.Iic i × Ω) _ m_prod,
let s := {p : set.Iic i × Ω | τ p.2 ≤ i},
have hs : measurable_set[m_prod] s, from @measurable_snd (set.Iic i) Ω _ (f i) _ (hτ i),
have h_meas_fst : ∀ t : set (set.Iic i × Ω),
measurable[m_set t] (λ x : t, ((x : set.Iic i × Ω).fst : ι)),
from λ t, (@measurable_subtype_coe (set.Iic i × Ω) m_prod _).fst.subtype_coe,
apply measurable.strongly_measurable,
refine measurable_of_restrict_of_restrict_compl hs _ _,
{ refine @measurable.min _ _ _ _ _ (m_set s) _ _ _ _ _ (h_meas_fst s) _,
refine @measurable_of_Iic ι s _ _ _ (m_set s) _ _ _ _ (λ j, _),
have h_set_eq : (λ x : s, τ (x : set.Iic i × Ω).snd) ⁻¹' set.Iic j
= (λ x : s, (x : set.Iic i × Ω).snd) ⁻¹' {ω | τ ω ≤ min i j},
{ ext1 ω,
simp only [set.mem_preimage, set.mem_Iic, iff_and_self, le_min_iff, set.mem_set_of_eq],
exact λ _, ω.prop, },
rw h_set_eq,
suffices h_meas : @measurable _ _ (m_set s) (f i) (λ x : s, (x : set.Iic i × Ω).snd),
from h_meas (f.mono (min_le_left _ _) _ (hτ.measurable_set_le (min i j))),
exact measurable_snd.comp (@measurable_subtype_coe _ m_prod _), },
{ suffices h_min_eq_left : (λ x : sᶜ, min ↑((x : set.Iic i × Ω).fst) (τ (x : set.Iic i × Ω).snd))
= λ x : sᶜ, ↑((x : set.Iic i × Ω).fst),
{ rw [set.restrict, h_min_eq_left],
exact h_meas_fst _, },
ext1 ω,
rw min_eq_left,
have hx_fst_le : ↑(ω : set.Iic i × Ω).fst ≤ i, from (ω : set.Iic i × Ω).fst.prop,
refine hx_fst_le.trans (le_of_lt _),
convert ω.prop,
simp only [not_le, set.mem_compl_iff, set.mem_set_of_eq], },
end
lemma prog_measurable.stopped_process [metrizable_space ι]
(h : prog_measurable f u) (hτ : is_stopping_time f τ) :
prog_measurable f (stopped_process u τ) :=
h.comp (prog_measurable_min_stopping_time hτ) (λ i x, min_le_left _ _)
lemma prog_measurable.adapted_stopped_process [metrizable_space ι]
(h : prog_measurable f u) (hτ : is_stopping_time f τ) :
adapted f (stopped_process u τ) :=
(h.stopped_process hτ).adapted
lemma prog_measurable.strongly_measurable_stopped_process [metrizable_space ι]
(hu : prog_measurable f u) (hτ : is_stopping_time f τ) (i : ι) :
strongly_measurable (stopped_process u τ i) :=
(hu.adapted_stopped_process hτ i).mono (f.le _)
lemma strongly_measurable_stopped_value_of_le
(h : prog_measurable f u) (hτ : is_stopping_time f τ) {n : ι} (hτ_le : ∀ ω, τ ω ≤ n) :
strongly_measurable[f n] (stopped_value u τ) :=
begin
have : stopped_value u τ = (λ (p : set.Iic n × Ω), u ↑(p.fst) p.snd) ∘ (λ ω, (⟨τ ω, hτ_le ω⟩, ω)),
{ ext1 ω, simp only [stopped_value, function.comp_app, subtype.coe_mk], },
rw this,
refine strongly_measurable.comp_measurable (h n) _,
exact (hτ.measurable_of_le hτ_le).subtype_mk.prod_mk measurable_id,
end
lemma measurable_stopped_value [metrizable_space β] [measurable_space β] [borel_space β]
(hf_prog : prog_measurable f u) (hτ : is_stopping_time f τ) :
measurable[hτ.measurable_space] (stopped_value u τ) :=
begin
have h_str_meas : ∀ i, strongly_measurable[f i] (stopped_value u (λ ω, min (τ ω) i)),
from λ i, strongly_measurable_stopped_value_of_le hf_prog (hτ.min_const i)
(λ _, min_le_right _ _),
intros t ht i,
suffices : stopped_value u τ ⁻¹' t ∩ {ω : Ω | τ ω ≤ i}
= stopped_value u (λ ω, min (τ ω) i) ⁻¹' t ∩ {ω : Ω | τ ω ≤ i},
by { rw this, exact ((h_str_meas i).measurable ht).inter (hτ.measurable_set_le i), },
ext1 ω,
simp only [stopped_value, set.mem_inter_iff, set.mem_preimage, set.mem_set_of_eq,
and.congr_left_iff],
intro h,
rw min_eq_left h,
end
end prog_measurable
end linear_order
section stopped_value_of_mem_finset
variables {μ : measure Ω} {τ σ : Ω → ι} {E : Type*} {p : ℝ≥0∞} {u : ι → Ω → E}
lemma stopped_value_eq_of_mem_finset [add_comm_monoid E] {s : finset ι} (hbdd : ∀ ω, τ ω ∈ s) :
stopped_value u τ = ∑ i in s, set.indicator {ω | τ ω = i} (u i) :=
begin
ext y,
rw [stopped_value, finset.sum_apply, finset.sum_indicator_eq_sum_filter],
suffices : finset.filter (λ i, y ∈ {ω : Ω | τ ω = i}) s = ({τ y} : finset ι),
by rw [this, finset.sum_singleton],
ext1 ω,
simp only [set.mem_set_of_eq, finset.mem_filter, finset.mem_singleton],
split; intro h,
{ exact h.2.symm, },
{ refine ⟨_, h.symm⟩, rw h, exact hbdd y, },
end
lemma stopped_value_eq' [preorder ι] [locally_finite_order_bot ι] [add_comm_monoid E]
{N : ι} (hbdd : ∀ ω, τ ω ≤ N) :
stopped_value u τ = ∑ i in finset.Iic N, set.indicator {ω | τ ω = i} (u i) :=
stopped_value_eq_of_mem_finset (λ ω, finset.mem_Iic.mpr (hbdd ω))
lemma stopped_process_eq_of_mem_finset [linear_order ι] [add_comm_monoid E]
{s : finset ι} (n : ι) (hbdd : ∀ ω, τ ω < n → τ ω ∈ s) :
stopped_process u τ n =
set.indicator {a | n ≤ τ a} (u n) + ∑ i in s.filter (< n), set.indicator {ω | τ ω = i} (u i) :=
begin
ext ω,
rw [pi.add_apply, finset.sum_apply],
cases le_or_lt n (τ ω),
{ rw [stopped_process_eq_of_le h, set.indicator_of_mem, finset.sum_eq_zero, add_zero],
{ intros m hm,
refine set.indicator_of_not_mem _ _,
rw [finset.mem_filter] at hm,
exact (hm.2.trans_le h).ne', },
{ exact h, } },
{ rw [stopped_process_eq_of_ge (le_of_lt h), finset.sum_eq_single_of_mem (τ ω)],
{ rw [set.indicator_of_not_mem, zero_add, set.indicator_of_mem],
{ exact rfl }, -- refl does not work
{ exact not_le.2 h } },
{ rw [finset.mem_filter],
exact ⟨hbdd ω h, h⟩, },
{ intros b hb hneq,
rw set.indicator_of_not_mem,
exact hneq.symm } },
end
lemma stopped_process_eq'' [linear_order ι] [locally_finite_order_bot ι] [add_comm_monoid E]
(n : ι) :
stopped_process u τ n =
set.indicator {a | n ≤ τ a} (u n) + ∑ i in finset.Iio n, set.indicator {ω | τ ω = i} (u i) :=
begin
have h_mem : ∀ ω, τ ω < n → τ ω ∈ finset.Iio n := λ ω h, finset.mem_Iio.mpr h,
rw stopped_process_eq_of_mem_finset n h_mem,
swap, { apply_instance, },
congr' with i,
simp only [finset.Iio_filter_lt, min_eq_right],
end
section stopped_value
variables [partial_order ι] {ℱ : filtration ι m} [normed_add_comm_group E]
lemma mem_ℒp_stopped_value_of_mem_finset (hτ : is_stopping_time ℱ τ) (hu : ∀ n, mem_ℒp (u n) p μ)
{s : finset ι} (hbdd : ∀ ω, τ ω ∈ s) :
mem_ℒp (stopped_value u τ) p μ :=
begin
rw stopped_value_eq_of_mem_finset hbdd,
swap, apply_instance,
refine mem_ℒp_finset_sum' _ (λ i hi, mem_ℒp.indicator _ (hu i)),
refine ℱ.le i {a : Ω | τ a = i} (hτ.measurable_set_eq_of_countable_range _ i),
refine ((finset.finite_to_set s).subset (λ ω hω, _)).countable,
obtain ⟨y, rfl⟩ := hω,
exact hbdd y,
end
lemma mem_ℒp_stopped_value [locally_finite_order_bot ι]
(hτ : is_stopping_time ℱ τ) (hu : ∀ n, mem_ℒp (u n) p μ) {N : ι} (hbdd : ∀ ω, τ ω ≤ N) :
mem_ℒp (stopped_value u τ) p μ :=
mem_ℒp_stopped_value_of_mem_finset hτ hu (λ ω, finset.mem_Iic.mpr (hbdd ω))
lemma integrable_stopped_value_of_mem_finset (hτ : is_stopping_time ℱ τ)
(hu : ∀ n, integrable (u n) μ) {s : finset ι} (hbdd : ∀ ω, τ ω ∈ s) :
integrable (stopped_value u τ) μ :=
begin
simp_rw ← mem_ℒp_one_iff_integrable at hu ⊢,
exact mem_ℒp_stopped_value_of_mem_finset hτ hu hbdd,
end
variables (ι)
lemma integrable_stopped_value [locally_finite_order_bot ι]
(hτ : is_stopping_time ℱ τ) (hu : ∀ n, integrable (u n) μ) {N : ι} (hbdd : ∀ ω, τ ω ≤ N) :
integrable (stopped_value u τ) μ :=
integrable_stopped_value_of_mem_finset hτ hu (λ ω, finset.mem_Iic.mpr (hbdd ω))
end stopped_value
section stopped_process
variables [linear_order ι] [topological_space ι] [order_topology ι] [first_countable_topology ι]
{ℱ : filtration ι m} [normed_add_comm_group E]
lemma mem_ℒp_stopped_process_of_mem_finset (hτ : is_stopping_time ℱ τ)
(hu : ∀ n, mem_ℒp (u n) p μ) (n : ι) {s : finset ι} (hbdd : ∀ ω, τ ω < n → τ ω ∈ s) :
mem_ℒp (stopped_process u τ n) p μ :=
begin
rw stopped_process_eq_of_mem_finset n hbdd,
swap, { apply_instance, },
refine mem_ℒp.add _ _,
{ exact mem_ℒp.indicator (ℱ.le n {a : Ω | n ≤ τ a} (hτ.measurable_set_ge n)) (hu n) },
{ suffices : mem_ℒp (λ ω, ∑ i in s.filter (< n), {a : Ω | τ a = i}.indicator (u i) ω) p μ,
{ convert this, ext1 ω, simp only [finset.sum_apply] },
refine mem_ℒp_finset_sum _ (λ i hi, mem_ℒp.indicator _ (hu i)),
exact ℱ.le i {a : Ω | τ a = i} (hτ.measurable_set_eq i) },
end
lemma mem_ℒp_stopped_process [locally_finite_order_bot ι] (hτ : is_stopping_time ℱ τ)
(hu : ∀ n, mem_ℒp (u n) p μ) (n : ι) :
mem_ℒp (stopped_process u τ n) p μ :=
mem_ℒp_stopped_process_of_mem_finset hτ hu n (λ ω h, finset.mem_Iio.mpr h)
lemma integrable_stopped_process_of_mem_finset (hτ : is_stopping_time ℱ τ)
(hu : ∀ n, integrable (u n) μ) (n : ι) {s : finset ι} (hbdd : ∀ ω, τ ω < n → τ ω ∈ s) :
integrable (stopped_process u τ n) μ :=
begin
simp_rw ← mem_ℒp_one_iff_integrable at hu ⊢,
exact mem_ℒp_stopped_process_of_mem_finset hτ hu n hbdd,
end
lemma integrable_stopped_process [locally_finite_order_bot ι] (hτ : is_stopping_time ℱ τ)
(hu : ∀ n, integrable (u n) μ) (n : ι) :
integrable (stopped_process u τ n) μ :=
integrable_stopped_process_of_mem_finset hτ hu n (λ ω h, finset.mem_Iio.mpr h)
end stopped_process
end stopped_value_of_mem_finset
section adapted_stopped_process
variables [topological_space β] [pseudo_metrizable_space β]
[linear_order ι]
[topological_space ι] [second_countable_topology ι] [order_topology ι]
[measurable_space ι] [borel_space ι]
{f : filtration ι m} {u : ι → Ω → β} {τ : Ω → ι}
/-- The stopped process of an adapted process with continuous paths is adapted. -/
lemma adapted.stopped_process [metrizable_space ι]
(hu : adapted f u) (hu_cont : ∀ ω, continuous (λ i, u i ω)) (hτ : is_stopping_time f τ) :
adapted f (stopped_process u τ) :=
((hu.prog_measurable_of_continuous hu_cont).stopped_process hτ).adapted
/-- If the indexing order has the discrete topology, then the stopped process of an adapted process
is adapted. -/
lemma adapted.stopped_process_of_discrete [discrete_topology ι]
(hu : adapted f u) (hτ : is_stopping_time f τ) :
adapted f (stopped_process u τ) :=
(hu.prog_measurable_of_discrete.stopped_process hτ).adapted
lemma adapted.strongly_measurable_stopped_process [metrizable_space ι]
(hu : adapted f u) (hu_cont : ∀ ω, continuous (λ i, u i ω)) (hτ : is_stopping_time f τ)
(n : ι) :
strongly_measurable (stopped_process u τ n) :=
(hu.prog_measurable_of_continuous hu_cont).strongly_measurable_stopped_process hτ n
lemma adapted.strongly_measurable_stopped_process_of_discrete [discrete_topology ι]
(hu : adapted f u) (hτ : is_stopping_time f τ) (n : ι) :
strongly_measurable (stopped_process u τ n) :=
hu.prog_measurable_of_discrete.strongly_measurable_stopped_process hτ n
end adapted_stopped_process
section nat
/-! ### Filtrations indexed by `ℕ` -/
open filtration
variables {f : filtration ℕ m} {u : ℕ → Ω → β} {τ π : Ω → ℕ}
lemma stopped_value_sub_eq_sum [add_comm_group β] (hle : τ ≤ π) :
stopped_value u π - stopped_value u τ =
λ ω, (∑ i in finset.Ico (τ ω) (π ω), (u (i + 1) - u i)) ω :=
begin
ext ω,
rw [finset.sum_Ico_eq_sub _ (hle ω), finset.sum_range_sub, finset.sum_range_sub],
simp [stopped_value],
end
lemma stopped_value_sub_eq_sum' [add_comm_group β] (hle : τ ≤ π) {N : ℕ} (hbdd : ∀ ω, π ω ≤ N) :
stopped_value u π - stopped_value u τ =
λ ω, (∑ i in finset.range (N + 1),
set.indicator {ω | τ ω ≤ i ∧ i < π ω} (u (i + 1) - u i)) ω :=
begin
rw stopped_value_sub_eq_sum hle,
ext ω,
simp only [finset.sum_apply, finset.sum_indicator_eq_sum_filter],
refine finset.sum_congr _ (λ _ _, rfl),
ext i,
simp only [finset.mem_filter, set.mem_set_of_eq, finset.mem_range, finset.mem_Ico],
exact ⟨λ h, ⟨lt_trans h.2 (nat.lt_succ_iff.2 $ hbdd _), h⟩, λ h, h.2⟩
end
section add_comm_monoid
variables [add_comm_monoid β]
lemma stopped_value_eq {N : ℕ} (hbdd : ∀ ω, τ ω ≤ N) :
stopped_value u τ =
λ x, (∑ i in finset.range (N + 1), set.indicator {ω | τ ω = i} (u i)) x :=
stopped_value_eq_of_mem_finset (λ ω, finset.mem_range_succ_iff.mpr (hbdd ω))
lemma stopped_process_eq (n : ℕ) :
stopped_process u τ n =
set.indicator {a | n ≤ τ a} (u n) + ∑ i in finset.range n, set.indicator {ω | τ ω = i} (u i) :=
begin
rw stopped_process_eq'' n,
swap, { apply_instance, },
congr' with i,
rw [finset.mem_Iio, finset.mem_range],
end
lemma stopped_process_eq' (n : ℕ) :
stopped_process u τ n =
set.indicator {a | n + 1 ≤ τ a} (u n) +
∑ i in finset.range (n + 1), set.indicator {a | τ a = i} (u i) :=
begin
have : {a | n ≤ τ a}.indicator (u n) =
{a | n + 1 ≤ τ a}.indicator (u n) + {a | τ a = n}.indicator (u n),
{ ext x,
rw [add_comm, pi.add_apply, ← set.indicator_union_of_not_mem_inter],
{ simp_rw [@eq_comm _ _ n, @le_iff_eq_or_lt _ _ n, nat.succ_le_iff],
refl },
{ rintro ⟨h₁, h₂⟩,
exact (nat.succ_le_iff.1 h₂).ne h₁.symm } },
rw [stopped_process_eq, this, finset.sum_range_succ_comm, ← add_assoc],
end
end add_comm_monoid
end nat
section piecewise_const
variables [preorder ι] {𝒢 : filtration ι m} {τ η : Ω → ι} {i j : ι} {s : set Ω}
[decidable_pred (∈ s)]
/-- Given stopping times `τ` and `η` which are bounded below, `set.piecewise s τ η` is also
a stopping time with respect to the same filtration. -/
lemma is_stopping_time.piecewise_of_le (hτ_st : is_stopping_time 𝒢 τ)
(hη_st : is_stopping_time 𝒢 η) (hτ : ∀ ω, i ≤ τ ω) (hη : ∀ ω, i ≤ η ω)
(hs : measurable_set[𝒢 i] s) :
is_stopping_time 𝒢 (s.piecewise τ η) :=
begin
intro n,
have : {ω | s.piecewise τ η ω ≤ n} = (s ∩ {ω | τ ω ≤ n}) ∪ (sᶜ ∩ {ω | η ω ≤ n}),
{ ext1 ω,
simp only [set.piecewise, set.mem_inter_iff, set.mem_set_of_eq, and.congr_right_iff],
by_cases hx : ω ∈ s; simp [hx], },
rw this,
by_cases hin : i ≤ n,
{ have hs_n : measurable_set[𝒢 n] s, from 𝒢.mono hin _ hs,
exact (hs_n.inter (hτ_st n)).union (hs_n.compl.inter (hη_st n)), },
{ have hτn : ∀ ω, ¬ τ ω ≤ n := λ ω hτn, hin ((hτ ω).trans hτn),
have hηn : ∀ ω, ¬ η ω ≤ n := λ ω hηn, hin ((hη ω).trans hηn),
simp [hτn, hηn], },
end
lemma is_stopping_time_piecewise_const (hij : i ≤ j) (hs : measurable_set[𝒢 i] s) :
is_stopping_time 𝒢 (s.piecewise (λ _, i) (λ _, j)) :=
(is_stopping_time_const 𝒢 i).piecewise_of_le (is_stopping_time_const 𝒢 j)
(λ x, le_rfl) (λ _, hij) hs
lemma stopped_value_piecewise_const {ι' : Type*} {i j : ι'} {f : ι' → Ω → ℝ} :
stopped_value f (s.piecewise (λ _, i) (λ _, j)) = s.piecewise (f i) (f j) :=
by { ext ω, rw stopped_value, by_cases hx : ω ∈ s; simp [hx] }
lemma stopped_value_piecewise_const' {ι' : Type*} {i j : ι'} {f : ι' → Ω → ℝ} :
stopped_value f (s.piecewise (λ _, i) (λ _, j)) = s.indicator (f i) + sᶜ.indicator (f j) :=
by { ext ω, rw stopped_value, by_cases hx : ω ∈ s; simp [hx] }
end piecewise_const
end measure_theory
|
f7cd535c2c7d46aaea463f52c39b1038decf70a1 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/analysis/normed/field/basic.lean | 8787a8bbf213142a9871328358d57a61cbb174ee | [
"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 | 36,485 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Johannes Hölzl
-/
import analysis.normed.group.infinite_sum
import topology.algebra.module.basic
import topology.instances.ennreal
import topology.instances.rat
/-!
# Normed fields
In this file we define (semi)normed rings and fields. We also prove some theorems about these
definitions.
-/
variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*}
noncomputable theory
open filter metric
open_locale topological_space big_operators nnreal ennreal uniformity pointwise
/-- A non-unital seminormed ring is a not-necessarily-unital ring
endowed with a seminorm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/
class non_unital_semi_normed_ring (α : Type*)
extends has_norm α, non_unital_ring α, pseudo_metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b)
/-- A seminormed ring is a ring endowed with a seminorm which satisfies the inequality
`∥x y∥ ≤ ∥x∥ ∥y∥`. -/
class semi_normed_ring (α : Type*) extends has_norm α, ring α, pseudo_metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b)
/-- A seminormed ring is a non-unital seminormed ring. -/
@[priority 100] -- see Note [lower instance priority]
instance semi_normed_ring.to_non_unital_semi_normed_ring [β : semi_normed_ring α] :
non_unital_semi_normed_ring α :=
{ ..β }
/-- A non-unital normed ring is a not-necessarily-unital ring
endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/
class non_unital_normed_ring (α : Type*) extends has_norm α, non_unital_ring α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b)
/-- A non-unital normed ring is a non-unital seminormed ring. -/
@[priority 100] -- see Note [lower instance priority]
instance non_unital_normed_ring.to_non_unital_semi_normed_ring [β : non_unital_normed_ring α] :
non_unital_semi_normed_ring α :=
{ ..β }
/-- A normed ring is a ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/
class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b)
/-- A normed division ring is a division ring endowed with a seminorm which satisfies the equality
`∥x y∥ = ∥x∥ ∥y∥`. -/
class normed_division_ring (α : Type*) extends has_norm α, division_ring α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_mul' : ∀ a b, norm (a * b) = norm a * norm b)
/-- A normed division ring is a normed ring. -/
@[priority 100] -- see Note [lower instance priority]
instance normed_division_ring.to_normed_ring [β : normed_division_ring α] : normed_ring α :=
{ norm_mul := λ a b, (normed_division_ring.norm_mul' a b).le,
..β }
/-- A normed ring is a seminormed ring. -/
@[priority 100] -- see Note [lower instance priority]
instance normed_ring.to_semi_normed_ring [β : normed_ring α] : semi_normed_ring α :=
{ ..β }
/-- A normed ring is a non-unital normed ring. -/
@[priority 100] -- see Note [lower instance priority]
instance normed_ring.to_non_unital_normed_ring [β : normed_ring α] : non_unital_normed_ring α :=
{ ..β }
/-- A seminormed commutative ring is a commutative ring endowed with a seminorm which satisfies
the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/
class semi_normed_comm_ring (α : Type*) extends semi_normed_ring α :=
(mul_comm : ∀ x y : α, x * y = y * x)
/-- A normed commutative ring is a commutative ring endowed with a norm which satisfies
the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/
class normed_comm_ring (α : Type*) extends normed_ring α :=
(mul_comm : ∀ x y : α, x * y = y * x)
/-- A normed commutative ring is a seminormed commutative ring. -/
@[priority 100] -- see Note [lower instance priority]
instance normed_comm_ring.to_semi_normed_comm_ring [β : normed_comm_ring α] :
semi_normed_comm_ring α := { ..β }
instance : normed_comm_ring punit :=
{ norm_mul := λ _ _, by simp,
..punit.normed_group,
..punit.comm_ring, }
/-- A mixin class with the axiom `∥1∥ = 1`. Many `normed_ring`s and all `normed_field`s satisfy this
axiom. -/
class norm_one_class (α : Type*) [has_norm α] [has_one α] : Prop :=
(norm_one : ∥(1:α)∥ = 1)
export norm_one_class (norm_one)
attribute [simp] norm_one
@[simp] lemma nnnorm_one [semi_normed_group α] [has_one α] [norm_one_class α] : ∥(1 : α)∥₊ = 1 :=
nnreal.eq norm_one
lemma norm_one_class.nontrivial (α : Type*) [semi_normed_group α] [has_one α] [norm_one_class α] :
nontrivial α :=
nontrivial_of_ne 0 1 $ ne_of_apply_ne norm $ by simp
@[priority 100] -- see Note [lower instance priority]
instance semi_normed_comm_ring.to_comm_ring [β : semi_normed_comm_ring α] : comm_ring α := { ..β }
@[priority 100] -- see Note [lower instance priority]
instance non_unital_normed_ring.to_normed_group [β : non_unital_normed_ring α] : normed_group α :=
{ ..β }
@[priority 100] -- see Note [lower instance priority]
instance non_unital_semi_normed_ring.to_semi_normed_group [β : non_unital_semi_normed_ring α] :
semi_normed_group α := { ..β }
instance [semi_normed_group α] [has_one α] [norm_one_class α] : norm_one_class (ulift α) :=
⟨by simp [ulift.norm_def]⟩
instance prod.norm_one_class [semi_normed_group α] [has_one α] [norm_one_class α]
[semi_normed_group β] [has_one β] [norm_one_class β] :
norm_one_class (α × β) :=
⟨by simp [prod.norm_def]⟩
instance pi.norm_one_class {ι : Type*} {α : ι → Type*} [nonempty ι] [fintype ι]
[Π i, semi_normed_group (α i)] [Π i, has_one (α i)] [∀ i, norm_one_class (α i)] :
norm_one_class (Π i, α i) :=
⟨by simp [pi.norm_def, finset.sup_const finset.univ_nonempty]⟩
section non_unital_semi_normed_ring
variables [non_unital_semi_normed_ring α]
lemma norm_mul_le (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) :=
non_unital_semi_normed_ring.norm_mul _ _
lemma nnnorm_mul_le (a b : α) : ∥a * b∥₊ ≤ ∥a∥₊ * ∥b∥₊ :=
by simpa only [←norm_to_nnreal, ←real.to_nnreal_mul (norm_nonneg _)]
using real.to_nnreal_mono (norm_mul_le _ _)
lemma one_le_norm_one (β) [normed_ring β] [nontrivial β] : 1 ≤ ∥(1 : β)∥ :=
(le_mul_iff_one_le_left $ norm_pos_iff.mpr (one_ne_zero : (1 : β) ≠ 0)).mp
(by simpa only [mul_one] using norm_mul_le (1 : β) 1)
lemma one_le_nnnorm_one (β) [normed_ring β] [nontrivial β] : 1 ≤ ∥(1 : β)∥₊ :=
one_le_norm_one β
lemma filter.tendsto.zero_mul_is_bounded_under_le {f g : ι → α} {l : filter ι}
(hf : tendsto f l (𝓝 0)) (hg : is_bounded_under (≤) l (norm ∘ g)) :
tendsto (λ x, f x * g x) l (𝓝 0) :=
hf.op_zero_is_bounded_under_le hg (*) norm_mul_le
lemma filter.is_bounded_under_le.mul_tendsto_zero {f g : ι → α} {l : filter ι}
(hf : is_bounded_under (≤) l (norm ∘ f)) (hg : tendsto g l (𝓝 0)) :
tendsto (λ x, f x * g x) l (𝓝 0) :=
hg.op_zero_is_bounded_under_le hf (flip (*)) (λ x y, ((norm_mul_le y x).trans_eq (mul_comm _ _)))
/-- In a seminormed ring, the left-multiplication `add_monoid_hom` is bounded. -/
lemma mul_left_bound (x : α) :
∀ (y:α), ∥add_monoid_hom.mul_left x y∥ ≤ ∥x∥ * ∥y∥ :=
norm_mul_le x
/-- In a seminormed ring, the right-multiplication `add_monoid_hom` is bounded. -/
lemma mul_right_bound (x : α) :
∀ (y:α), ∥add_monoid_hom.mul_right x y∥ ≤ ∥x∥ * ∥y∥ :=
λ y, by {rw mul_comm, convert norm_mul_le y x}
instance : non_unital_semi_normed_ring (ulift α) :=
{ norm_mul := λ x y, (norm_mul_le x.down y.down : _),
.. ulift.semi_normed_group }
/-- Non-unital seminormed ring structure on the product of two non-unital seminormed rings,
using the sup norm. -/
instance prod.non_unital_semi_normed_ring [non_unital_semi_normed_ring β] :
non_unital_semi_normed_ring (α × β) :=
{ norm_mul := assume x y,
calc
∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl
... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl
... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) :
max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2))
... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm]
... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) :
by apply max_mul_mul_le_max_mul_max; simp [norm_nonneg]
... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp [max_comm]
... = (∥x∥*∥y∥) : rfl,
..prod.semi_normed_group }
/-- Non-unital seminormed ring structure on the product of finitely many non-unital seminormed
rings, using the sup norm. -/
instance pi.non_unital_semi_normed_ring {π : ι → Type*} [fintype ι]
[Π i, non_unital_semi_normed_ring (π i)] :
non_unital_semi_normed_ring (Π i, π i) :=
{ norm_mul := λ x y, nnreal.coe_mono $
calc finset.univ.sup (λ i, ∥x i * y i∥₊)
≤ finset.univ.sup ((λ i, ∥x i∥₊) * (λ i, ∥y i∥₊)) :
finset.sup_mono_fun $ λ b hb, norm_mul_le _ _
... ≤ finset.univ.sup (λ i, ∥x i∥₊) * finset.univ.sup (λ i, ∥y i∥₊) :
finset.sup_mul_le_mul_sup_of_nonneg _ (λ i _, zero_le _) (λ i _, zero_le _),
..pi.semi_normed_group }
end non_unital_semi_normed_ring
section semi_normed_ring
variables [semi_normed_ring α]
/-- A subalgebra of a seminormed ring is also a seminormed ring, with the restriction of the norm.
See note [implicit instance arguments]. -/
instance subalgebra.semi_normed_ring {𝕜 : Type*} {_ : comm_ring 𝕜}
{E : Type*} [semi_normed_ring E] {_ : algebra 𝕜 E} (s : subalgebra 𝕜 E) : semi_normed_ring s :=
{ norm_mul := λ a b, norm_mul_le a.1 b.1,
..s.to_submodule.semi_normed_group }
/-- A subalgebra of a normed ring is also a normed ring, with the restriction of the norm.
See note [implicit instance arguments]. -/
instance subalgebra.normed_ring {𝕜 : Type*} {_ : comm_ring 𝕜}
{E : Type*} [normed_ring E] {_ : algebra 𝕜 E} (s : subalgebra 𝕜 E) : normed_ring s :=
{ ..s.semi_normed_ring }
lemma nat.norm_cast_le : ∀ n : ℕ, ∥(n : α)∥ ≤ n * ∥(1 : α)∥
| 0 := by simp
| (n + 1) := by { rw [n.cast_succ, n.cast_succ, add_mul, one_mul],
exact norm_add_le_of_le (nat.norm_cast_le n) le_rfl }
lemma list.norm_prod_le' : ∀ {l : list α}, l ≠ [] → ∥l.prod∥ ≤ (l.map norm).prod
| [] h := (h rfl).elim
| [a] _ := by simp
| (a :: b :: l) _ :=
begin
rw [list.map_cons, list.prod_cons, @list.prod_cons _ _ _ ∥a∥],
refine le_trans (norm_mul_le _ _) (mul_le_mul_of_nonneg_left _ (norm_nonneg _)),
exact list.norm_prod_le' (list.cons_ne_nil b l)
end
lemma list.nnnorm_prod_le' {l : list α} (hl : l ≠ []) : ∥l.prod∥₊ ≤ (l.map nnnorm).prod :=
(list.norm_prod_le' hl).trans_eq $ by simp [nnreal.coe_list_prod, list.map_map]
lemma list.norm_prod_le [norm_one_class α] : ∀ l : list α, ∥l.prod∥ ≤ (l.map norm).prod
| [] := by simp
| (a::l) := list.norm_prod_le' (list.cons_ne_nil a l)
lemma list.nnnorm_prod_le [norm_one_class α] (l : list α) : ∥l.prod∥₊ ≤ (l.map nnnorm).prod :=
l.norm_prod_le.trans_eq $ by simp [nnreal.coe_list_prod, list.map_map]
lemma finset.norm_prod_le' {α : Type*} [normed_comm_ring α] (s : finset ι) (hs : s.nonempty)
(f : ι → α) :
∥∏ i in s, f i∥ ≤ ∏ i in s, ∥f i∥ :=
begin
rcases s with ⟨⟨l⟩, hl⟩,
have : l.map f ≠ [], by simpa using hs,
simpa using list.norm_prod_le' this
end
lemma finset.nnnorm_prod_le' {α : Type*} [normed_comm_ring α] (s : finset ι) (hs : s.nonempty)
(f : ι → α) :
∥∏ i in s, f i∥₊ ≤ ∏ i in s, ∥f i∥₊ :=
(s.norm_prod_le' hs f).trans_eq $ by simp [nnreal.coe_prod]
lemma finset.norm_prod_le {α : Type*} [normed_comm_ring α] [norm_one_class α] (s : finset ι)
(f : ι → α) :
∥∏ i in s, f i∥ ≤ ∏ i in s, ∥f i∥ :=
begin
rcases s with ⟨⟨l⟩, hl⟩,
simpa using (l.map f).norm_prod_le
end
lemma finset.nnnorm_prod_le {α : Type*} [normed_comm_ring α] [norm_one_class α] (s : finset ι)
(f : ι → α) :
∥∏ i in s, f i∥₊ ≤ ∏ i in s, ∥f i∥₊ :=
(s.norm_prod_le f).trans_eq $ by simp [nnreal.coe_prod]
/-- If `α` is a seminormed ring, then `∥a ^ n∥₊ ≤ ∥a∥₊ ^ n` for `n > 0`.
See also `nnnorm_pow_le`. -/
lemma nnnorm_pow_le' (a : α) : ∀ {n : ℕ}, 0 < n → ∥a ^ n∥₊ ≤ ∥a∥₊ ^ n
| 1 h := by simp only [pow_one]
| (n + 2) h := by simpa only [pow_succ _ (n + 1)] using
le_trans (nnnorm_mul_le _ _) (mul_le_mul_left' (nnnorm_pow_le' n.succ_pos) _)
/-- If `α` is a seminormed ring with `∥1∥₊ = 1`, then `∥a ^ n∥₊ ≤ ∥a∥₊ ^ n`.
See also `nnnorm_pow_le'`.-/
lemma nnnorm_pow_le [norm_one_class α] (a : α) (n : ℕ) : ∥a ^ n∥₊ ≤ ∥a∥₊ ^ n :=
nat.rec_on n (by simp only [pow_zero, nnnorm_one]) (λ k hk, nnnorm_pow_le' a k.succ_pos)
/-- If `α` is a seminormed ring, then `∥a ^ n∥ ≤ ∥a∥ ^ n` for `n > 0`. See also `norm_pow_le`. -/
lemma norm_pow_le' (a : α) {n : ℕ} (h : 0 < n) : ∥a ^ n∥ ≤ ∥a∥ ^ n :=
by simpa only [nnreal.coe_pow, coe_nnnorm] using nnreal.coe_mono (nnnorm_pow_le' a h)
/-- If `α` is a seminormed ring with `∥1∥ = 1`, then `∥a ^ n∥ ≤ ∥a∥ ^ n`. See also `norm_pow_le'`.-/
lemma norm_pow_le [norm_one_class α] (a : α) (n : ℕ) : ∥a ^ n∥ ≤ ∥a∥ ^ n :=
nat.rec_on n (by simp only [pow_zero, norm_one]) (λ n hn, norm_pow_le' a n.succ_pos)
lemma eventually_norm_pow_le (a : α) : ∀ᶠ (n:ℕ) in at_top, ∥a ^ n∥ ≤ ∥a∥ ^ n :=
eventually_at_top.mpr ⟨1, λ b h, norm_pow_le' a (nat.succ_le_iff.mp h)⟩
instance : semi_normed_ring (ulift α) :=
{ .. ulift.non_unital_semi_normed_ring,
.. ulift.semi_normed_group }
/-- Seminormed ring structure on the product of two seminormed rings,
using the sup norm. -/
instance prod.semi_normed_ring [semi_normed_ring β] :
semi_normed_ring (α × β) :=
{ ..prod.non_unital_semi_normed_ring,
..prod.semi_normed_group, }
/-- Seminormed ring structure on the product of finitely many seminormed rings,
using the sup norm. -/
instance pi.semi_normed_ring {π : ι → Type*} [fintype ι] [Π i, semi_normed_ring (π i)] :
semi_normed_ring (Π i, π i) :=
{ ..pi.non_unital_semi_normed_ring,
..pi.semi_normed_group, }
end semi_normed_ring
section non_unital_normed_ring
variables [non_unital_normed_ring α]
instance : non_unital_normed_ring (ulift α) :=
{ .. ulift.non_unital_semi_normed_ring,
.. ulift.semi_normed_group }
/-- Non-unital normed ring structure on the product of two non-unital normed rings,
using the sup norm. -/
instance prod.non_unital_normed_ring [non_unital_normed_ring β] : non_unital_normed_ring (α × β) :=
{ norm_mul := norm_mul_le,
..prod.semi_normed_group }
/-- Normed ring structure on the product of finitely many non-unital normed rings, using the sup
norm. -/
instance pi.non_unital_normed_ring {π : ι → Type*} [fintype ι] [Π i, non_unital_normed_ring (π i)] :
non_unital_normed_ring (Π i, π i) :=
{ norm_mul := norm_mul_le,
..pi.normed_group }
end non_unital_normed_ring
section normed_ring
variables [normed_ring α]
lemma units.norm_pos [nontrivial α] (x : αˣ) : 0 < ∥(x:α)∥ :=
norm_pos_iff.mpr (units.ne_zero x)
lemma units.nnnorm_pos [nontrivial α] (x : αˣ) : 0 < ∥(x:α)∥₊ :=
x.norm_pos
instance : normed_ring (ulift α) :=
{ .. ulift.semi_normed_ring,
.. ulift.normed_group }
/-- Normed ring structure on the product of two normed rings, using the sup norm. -/
instance prod.normed_ring [normed_ring β] : normed_ring (α × β) :=
{ norm_mul := norm_mul_le,
..prod.normed_group }
/-- Normed ring structure on the product of finitely many normed rings, using the sup norm. -/
instance pi.normed_ring {π : ι → Type*} [fintype ι] [Π i, normed_ring (π i)] :
normed_ring (Π i, π i) :=
{ norm_mul := norm_mul_le,
..pi.normed_group }
end normed_ring
@[priority 100] -- see Note [lower instance priority]
instance semi_normed_ring_top_monoid [non_unital_semi_normed_ring α] : has_continuous_mul α :=
⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $
begin
have : ∀ e : α × α, ∥e.1 * e.2 - x.1 * x.2∥ ≤ ∥e.1∥ * ∥e.2 - x.2∥ + ∥e.1 - x.1∥ * ∥x.2∥,
{ intro e,
calc ∥e.1 * e.2 - x.1 * x.2∥ ≤ ∥e.1 * (e.2 - x.2) + (e.1 - x.1) * x.2∥ :
by rw [mul_sub, sub_mul, sub_add_sub_cancel]
... ≤ ∥e.1∥ * ∥e.2 - x.2∥ + ∥e.1 - x.1∥ * ∥x.2∥ :
norm_add_le_of_le (norm_mul_le _ _) (norm_mul_le _ _) },
refine squeeze_zero (λ e, norm_nonneg _) this _,
convert ((continuous_fst.tendsto x).norm.mul ((continuous_snd.tendsto x).sub
tendsto_const_nhds).norm).add
(((continuous_fst.tendsto x).sub tendsto_const_nhds).norm.mul _),
show tendsto _ _ _, from tendsto_const_nhds,
simp
end ⟩
/-- A seminormed ring is a topological ring. -/
@[priority 100] -- see Note [lower instance priority]
instance semi_normed_top_ring [non_unital_semi_normed_ring α] : topological_ring α := { }
section normed_division_ring
variables [normed_division_ring α]
@[simp] lemma norm_mul (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ :=
normed_division_ring.norm_mul' a b
@[priority 900]
instance normed_division_ring.to_norm_one_class : norm_one_class α :=
⟨mul_left_cancel₀ (mt norm_eq_zero.1 (@one_ne_zero α _ _)) $
by rw [← norm_mul, mul_one, mul_one]⟩
@[simp] lemma nnnorm_mul (a b : α) : ∥a * b∥₊ = ∥a∥₊ * ∥b∥₊ :=
nnreal.eq $ norm_mul a b
/-- `norm` as a `monoid_with_zero_hom`. -/
@[simps] def norm_hom : α →*₀ ℝ := ⟨norm, norm_zero, norm_one, norm_mul⟩
/-- `nnnorm` as a `monoid_with_zero_hom`. -/
@[simps] def nnnorm_hom : α →*₀ ℝ≥0 := ⟨nnnorm, nnnorm_zero, nnnorm_one, nnnorm_mul⟩
@[simp] lemma norm_pow (a : α) : ∀ (n : ℕ), ∥a ^ n∥ = ∥a∥ ^ n :=
(norm_hom.to_monoid_hom : α →* ℝ).map_pow a
@[simp] lemma nnnorm_pow (a : α) (n : ℕ) : ∥a ^ n∥₊ = ∥a∥₊ ^ n :=
(nnnorm_hom.to_monoid_hom : α →* ℝ≥0).map_pow a n
protected lemma list.norm_prod (l : list α) : ∥l.prod∥ = (l.map norm).prod :=
(norm_hom.to_monoid_hom : α →* ℝ).map_list_prod _
protected lemma list.nnnorm_prod (l : list α) : ∥l.prod∥₊ = (l.map nnnorm).prod :=
(nnnorm_hom.to_monoid_hom : α →* ℝ≥0).map_list_prod _
@[simp] lemma norm_div (a b : α) : ∥a / b∥ = ∥a∥ / ∥b∥ := (norm_hom : α →*₀ ℝ).map_div a b
@[simp] lemma nnnorm_div (a b : α) : ∥a / b∥₊ = ∥a∥₊ / ∥b∥₊ := (nnnorm_hom : α →*₀ ℝ≥0).map_div a b
@[simp] lemma norm_inv (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ := (norm_hom : α →*₀ ℝ).map_inv a
@[simp] lemma nnnorm_inv (a : α) : ∥a⁻¹∥₊ = ∥a∥₊⁻¹ :=
nnreal.eq $ by simp
@[simp] lemma norm_zpow : ∀ (a : α) (n : ℤ), ∥a^n∥ = ∥a∥^n := (norm_hom : α →*₀ ℝ).map_zpow
@[simp] lemma nnnorm_zpow : ∀ (a : α) (n : ℤ), ∥a ^ n∥₊ = ∥a∥₊ ^ n :=
(nnnorm_hom : α →*₀ ℝ≥0).map_zpow
/-- Multiplication on the left by a nonzero element of a normed division ring tends to infinity at
infinity. TODO: use `bornology.cobounded` instead of `filter.comap has_norm.norm filter.at_top`. -/
lemma filter.tendsto_mul_left_cobounded {a : α} (ha : a ≠ 0) :
tendsto ((*) a) (comap norm at_top) (comap norm at_top) :=
by simpa only [tendsto_comap_iff, (∘), norm_mul]
using tendsto_const_nhds.mul_at_top (norm_pos_iff.2 ha) tendsto_comap
/-- Multiplication on the right by a nonzero element of a normed division ring tends to infinity at
infinity. TODO: use `bornology.cobounded` instead of `filter.comap has_norm.norm filter.at_top`. -/
lemma filter.tendsto_mul_right_cobounded {a : α} (ha : a ≠ 0) :
tendsto (λ x, x * a) (comap norm at_top) (comap norm at_top) :=
by simpa only [tendsto_comap_iff, (∘), norm_mul]
using tendsto_comap.at_top_mul (norm_pos_iff.2 ha) tendsto_const_nhds
@[priority 100] -- see Note [lower instance priority]
instance normed_division_ring.to_has_continuous_inv₀ : has_continuous_inv₀ α :=
begin
refine ⟨λ r r0, tendsto_iff_norm_tendsto_zero.2 _⟩,
have r0' : 0 < ∥r∥ := norm_pos_iff.2 r0,
rcases exists_between r0' with ⟨ε, ε0, εr⟩,
have : ∀ᶠ e in 𝓝 r, ∥e⁻¹ - r⁻¹∥ ≤ ∥r - e∥ / ∥r∥ / ε,
{ filter_upwards [(is_open_lt continuous_const continuous_norm).eventually_mem εr] with e he,
have e0 : e ≠ 0 := norm_pos_iff.1 (ε0.trans he),
calc ∥e⁻¹ - r⁻¹∥ = ∥r∥⁻¹ * ∥r - e∥ * ∥e∥⁻¹ : by
{ rw [←norm_inv, ←norm_inv, ←norm_mul, ←norm_mul, mul_sub, sub_mul, mul_assoc _ e,
inv_mul_cancel r0, mul_inv_cancel e0, one_mul, mul_one] }
... = ∥r - e∥ / ∥r∥ / ∥e∥ : by field_simp [mul_comm]
... ≤ ∥r - e∥ / ∥r∥ / ε :
div_le_div_of_le_left (div_nonneg (norm_nonneg _) (norm_nonneg _)) ε0 he.le },
refine squeeze_zero' (eventually_of_forall $ λ _, norm_nonneg _) this _,
refine (continuous_const.sub continuous_id).norm.div_const.div_const.tendsto' _ _ _,
simp,
end
end normed_division_ring
/-- A normed field is a field with a norm satisfying ∥x y∥ = ∥x∥ ∥y∥. -/
class normed_field (α : Type*) extends has_norm α, field α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_mul' : ∀ a b, norm (a * b) = norm a * norm b)
/-- A nondiscrete normed field is a normed field in which there is an element of norm different from
`0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication
by the powers of any element, and thus to relate algebra and topology. -/
class nondiscrete_normed_field (α : Type*) extends normed_field α :=
(non_trivial : ∃ x : α, 1 < ∥x∥)
section normed_field
variables [normed_field α]
@[priority 100] -- see Note [lower instance priority]
instance normed_field.to_normed_division_ring : normed_division_ring α :=
{ ..‹normed_field α› }
@[priority 100] -- see Note [lower instance priority]
instance normed_field.to_normed_comm_ring : normed_comm_ring α :=
{ norm_mul := λ a b, (norm_mul a b).le, ..‹normed_field α› }
@[simp] lemma norm_prod (s : finset β) (f : β → α) :
∥∏ b in s, f b∥ = ∏ b in s, ∥f b∥ :=
(norm_hom.to_monoid_hom : α →* ℝ).map_prod f s
@[simp] lemma nnnorm_prod (s : finset β) (f : β → α) :
∥∏ b in s, f b∥₊ = ∏ b in s, ∥f b∥₊ :=
(nnnorm_hom.to_monoid_hom : α →* ℝ≥0).map_prod f s
end normed_field
namespace normed_field
variables (α) [nondiscrete_normed_field α]
lemma exists_one_lt_norm : ∃x : α, 1 < ∥x∥ := ‹nondiscrete_normed_field α›.non_trivial
lemma exists_lt_norm (r : ℝ) : ∃ x : α, r < ∥x∥ :=
let ⟨w, hw⟩ := exists_one_lt_norm α in
let ⟨n, hn⟩ := pow_unbounded_of_one_lt r hw in
⟨w^n, by rwa norm_pow⟩
lemma exists_norm_lt {r : ℝ} (hr : 0 < r) : ∃ x : α, 0 < ∥x∥ ∧ ∥x∥ < r :=
let ⟨w, hw⟩ := exists_lt_norm α r⁻¹ in
⟨w⁻¹, by rwa [← set.mem_Ioo, norm_inv, ← set.mem_inv, set.inv_Ioo_0_left hr]⟩
lemma exists_norm_lt_one : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 :=
exists_norm_lt α one_pos
variable {α}
@[instance]
lemma punctured_nhds_ne_bot (x : α) : ne_bot (𝓝[≠] x) :=
begin
rw [← mem_closure_iff_nhds_within_ne_bot, metric.mem_closure_iff],
rintros ε ε0,
rcases exists_norm_lt α ε0 with ⟨b, hb0, hbε⟩,
refine ⟨x + b, mt (set.mem_singleton_iff.trans add_right_eq_self).1 $ norm_pos_iff.1 hb0, _⟩,
rwa [dist_comm, dist_eq_norm, add_sub_cancel'],
end
@[instance]
lemma nhds_within_is_unit_ne_bot : ne_bot (𝓝[{x : α | is_unit x}] 0) :=
by simpa only [is_unit_iff_ne_zero] using punctured_nhds_ne_bot (0:α)
end normed_field
instance : normed_field ℝ :=
{ norm_mul' := abs_mul,
.. real.normed_group }
instance : nondiscrete_normed_field ℝ :=
{ non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ }
namespace real
lemma norm_of_nonneg {x : ℝ} (hx : 0 ≤ x) : ∥x∥ = x :=
abs_of_nonneg hx
lemma norm_of_nonpos {x : ℝ} (hx : x ≤ 0) : ∥x∥ = -x :=
abs_of_nonpos hx
@[simp] lemma norm_coe_nat (n : ℕ) : ∥(n : ℝ)∥ = n := abs_of_nonneg n.cast_nonneg
@[simp] lemma nnnorm_coe_nat (n : ℕ) : ∥(n : ℝ)∥₊ = n := nnreal.eq $ by simp
@[simp] lemma norm_two : ∥(2 : ℝ)∥ = 2 := abs_of_pos (@zero_lt_two ℝ _ _)
@[simp] lemma nnnorm_two : ∥(2 : ℝ)∥₊ = 2 := nnreal.eq $ by simp
lemma nnnorm_of_nonneg {x : ℝ} (hx : 0 ≤ x) : ∥x∥₊ = ⟨x, hx⟩ :=
nnreal.eq $ norm_of_nonneg hx
lemma ennnorm_eq_of_real {x : ℝ} (hx : 0 ≤ x) : (∥x∥₊ : ℝ≥0∞) = ennreal.of_real x :=
by { rw [← of_real_norm_eq_coe_nnnorm, norm_of_nonneg hx] }
lemma of_real_le_ennnorm (x : ℝ) : ennreal.of_real x ≤ ∥x∥₊ :=
begin
by_cases hx : 0 ≤ x,
{ rw real.ennnorm_eq_of_real hx, refl' },
{ rw [ennreal.of_real_eq_zero.2 (le_of_lt (not_le.1 hx))],
exact bot_le }
end
/-- If `E` is a nontrivial topological module over `ℝ`, then `E` has no isolated points.
This is a particular case of `module.punctured_nhds_ne_bot`. -/
instance punctured_nhds_module_ne_bot
{E : Type*} [add_comm_group E] [topological_space E] [has_continuous_add E] [nontrivial E]
[module ℝ E] [has_continuous_smul ℝ E] (x : E) :
ne_bot (𝓝[≠] x) :=
module.punctured_nhds_ne_bot ℝ E x
end real
namespace nnreal
open_locale nnreal
@[simp] lemma norm_eq (x : ℝ≥0) : ∥(x : ℝ)∥ = x :=
by rw [real.norm_eq_abs, x.abs_eq]
@[simp] lemma nnnorm_eq (x : ℝ≥0) : ∥(x : ℝ)∥₊ = x :=
nnreal.eq $ real.norm_of_nonneg x.2
end nnreal
@[simp] lemma norm_norm [semi_normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ :=
real.norm_of_nonneg (norm_nonneg _)
@[simp] lemma nnnorm_norm [semi_normed_group α] (a : α) : ∥∥a∥∥₊ = ∥a∥₊ :=
by simpa [real.nnnorm_of_nonneg (norm_nonneg a)]
/-- A restatement of `metric_space.tendsto_at_top` in terms of the norm. -/
lemma normed_group.tendsto_at_top [nonempty α] [semilattice_sup α] {β : Type*} [semi_normed_group β]
{f : α → β} {b : β} :
tendsto f at_top (𝓝 b) ↔ ∀ ε, 0 < ε → ∃ N, ∀ n, N ≤ n → ∥f n - b∥ < ε :=
(at_top_basis.tendsto_iff metric.nhds_basis_ball).trans (by simp [dist_eq_norm])
/--
A variant of `normed_group.tendsto_at_top` that
uses `∃ N, ∀ n > N, ...` rather than `∃ N, ∀ n ≥ N, ...`
-/
lemma normed_group.tendsto_at_top' [nonempty α] [semilattice_sup α] [no_max_order α]
{β : Type*} [semi_normed_group β]
{f : α → β} {b : β} :
tendsto f at_top (𝓝 b) ↔ ∀ ε, 0 < ε → ∃ N, ∀ n, N < n → ∥f n - b∥ < ε :=
(at_top_basis_Ioi.tendsto_iff metric.nhds_basis_ball).trans (by simp [dist_eq_norm])
instance : normed_comm_ring ℤ :=
{ norm := λ n, ∥(n : ℝ)∥,
norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul],
dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub],
mul_comm := mul_comm }
@[norm_cast] lemma int.norm_cast_real (m : ℤ) : ∥(m : ℝ)∥ = ∥m∥ := rfl
lemma int.norm_eq_abs (n : ℤ) : ∥n∥ = |n| := rfl
lemma nnreal.coe_nat_abs (n : ℤ) : (n.nat_abs : ℝ≥0) = ∥n∥₊ :=
nnreal.eq $ calc ((n.nat_abs : ℝ≥0) : ℝ)
= (n.nat_abs : ℤ) : by simp only [int.cast_coe_nat, nnreal.coe_nat_cast]
... = |n| : by simp only [← int.abs_eq_nat_abs, int.cast_abs]
... = ∥n∥ : rfl
lemma int.abs_le_floor_nnreal_iff (z : ℤ) (c : ℝ≥0) : |z| ≤ ⌊c⌋₊ ↔ ∥z∥₊ ≤ c :=
begin
rw [int.abs_eq_nat_abs, int.coe_nat_le, nat.le_floor_iff (zero_le c)],
congr',
exact nnreal.coe_nat_abs z,
end
instance : norm_one_class ℤ :=
⟨by simp [← int.norm_cast_real]⟩
instance : normed_field ℚ :=
{ norm := λ r, ∥(r : ℝ)∥,
norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul],
dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] }
instance : nondiscrete_normed_field ℚ :=
{ non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ }
@[norm_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ∥(r : ℝ)∥ = ∥r∥ := rfl
@[norm_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ∥(m : ℚ)∥ = ∥m∥ :=
by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast
-- Now that we've installed the norm on `ℤ`,
-- we can state some lemmas about `nsmul` and `zsmul`.
section
variables [semi_normed_group α]
lemma norm_nsmul_le (n : ℕ) (a : α) : ∥n • a∥ ≤ n * ∥a∥ :=
begin
induction n with n ih,
{ simp only [norm_zero, nat.cast_zero, zero_mul, zero_smul] },
simp only [nat.succ_eq_add_one, add_smul, add_mul, one_mul, nat.cast_add,
nat.cast_one, one_nsmul],
exact norm_add_le_of_le ih le_rfl
end
lemma norm_zsmul_le (n : ℤ) (a : α) : ∥n • a∥ ≤ ∥n∥ * ∥a∥ :=
begin
induction n with n n,
{ simp only [int.of_nat_eq_coe, coe_nat_zsmul],
convert norm_nsmul_le n a,
exact nat.abs_cast n },
{ simp only [int.neg_succ_of_nat_coe, neg_smul, norm_neg, coe_nat_zsmul],
convert norm_nsmul_le n.succ a,
exact nat.abs_cast n.succ, }
end
lemma nnnorm_nsmul_le (n : ℕ) (a : α) : ∥n • a∥₊ ≤ n * ∥a∥₊ :=
by simpa only [←nnreal.coe_le_coe, nnreal.coe_mul, nnreal.coe_nat_cast]
using norm_nsmul_le n a
lemma nnnorm_zsmul_le (n : ℤ) (a : α) : ∥n • a∥₊ ≤ ∥n∥₊ * ∥a∥₊ :=
by simpa only [←nnreal.coe_le_coe, nnreal.coe_mul] using norm_zsmul_le n a
end
section cauchy_product
/-! ## Multiplying two infinite sums in a normed ring
In this section, we prove various results about `(∑' x : ι, f x) * (∑' y : ι', g y)` in a normed
ring. There are similar results proven in `topology/algebra/infinite_sum` (e.g `tsum_mul_tsum`),
but in a normed ring we get summability results which aren't true in general.
We first establish results about arbitrary index types, `β` and `γ`, and then we specialize to
`β = γ = ℕ` to prove the Cauchy product formula
(see `tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm`).
### Arbitrary index types
-/
variables {ι' : Type*} [normed_ring α]
open finset
open_locale classical
lemma summable.mul_of_nonneg {f : ι → ℝ} {g : ι' → ℝ}
(hf : summable f) (hg : summable g) (hf' : 0 ≤ f) (hg' : 0 ≤ g) :
summable (λ (x : ι × ι'), f x.1 * g x.2) :=
let ⟨s, hf⟩ := hf in
let ⟨t, hg⟩ := hg in
suffices this : ∀ u : finset (ι × ι'), ∑ x in u, f x.1 * g x.2 ≤ s*t,
from summable_of_sum_le (λ x, mul_nonneg (hf' _) (hg' _)) this,
assume u,
calc ∑ x in u, f x.1 * g x.2
≤ ∑ x in (u.image prod.fst).product (u.image prod.snd), f x.1 * g x.2 :
sum_mono_set_of_nonneg (λ x, mul_nonneg (hf' _) (hg' _)) subset_product
... = ∑ x in u.image prod.fst, ∑ y in u.image prod.snd, f x * g y : sum_product
... = ∑ x in u.image prod.fst, f x * ∑ y in u.image prod.snd, g y :
sum_congr rfl (λ x _, mul_sum.symm)
... ≤ ∑ x in u.image prod.fst, f x * t :
sum_le_sum
(λ x _, mul_le_mul_of_nonneg_left (sum_le_has_sum _ (λ _ _, hg' _) hg) (hf' _))
... = (∑ x in u.image prod.fst, f x) * t : sum_mul.symm
... ≤ s * t :
mul_le_mul_of_nonneg_right (sum_le_has_sum _ (λ _ _, hf' _) hf) (hg.nonneg $ λ _, hg' _)
lemma summable.mul_norm {f : ι → α} {g : ι' → α}
(hf : summable (λ x, ∥f x∥)) (hg : summable (λ x, ∥g x∥)) :
summable (λ (x : ι × ι'), ∥f x.1 * g x.2∥) :=
summable_of_nonneg_of_le (λ x, norm_nonneg (f x.1 * g x.2)) (λ x, norm_mul_le (f x.1) (g x.2))
(hf.mul_of_nonneg hg (λ x, norm_nonneg $ f x) (λ x, norm_nonneg $ g x) : _)
lemma summable_mul_of_summable_norm [complete_space α] {f : ι → α} {g : ι' → α}
(hf : summable (λ x, ∥f x∥)) (hg : summable (λ x, ∥g x∥)) :
summable (λ (x : ι × ι'), f x.1 * g x.2) :=
summable_of_summable_norm (hf.mul_norm hg)
/-- Product of two infinites sums indexed by arbitrary types.
See also `tsum_mul_tsum` if `f` and `g` are *not* absolutely summable. -/
lemma tsum_mul_tsum_of_summable_norm [complete_space α] {f : ι → α} {g : ι' → α}
(hf : summable (λ x, ∥f x∥)) (hg : summable (λ x, ∥g x∥)) :
(∑' x, f x) * (∑' y, g y) = (∑' z : ι × ι', f z.1 * g z.2) :=
tsum_mul_tsum (summable_of_summable_norm hf) (summable_of_summable_norm hg)
(summable_mul_of_summable_norm hf hg)
/-! ### `ℕ`-indexed families (Cauchy product)
We prove two versions of the Cauchy product formula. The first one is
`tsum_mul_tsum_eq_tsum_sum_range_of_summable_norm`, where the `n`-th term is a sum over
`finset.range (n+1)` involving `nat` substraction.
In order to avoid `nat` substraction, we also provide
`tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm`,
where the `n`-th term is a sum over all pairs `(k, l)` such that `k+l=n`, which corresponds to the
`finset` `finset.nat.antidiagonal n`. -/
section nat
open finset.nat
lemma summable_norm_sum_mul_antidiagonal_of_summable_norm {f g : ℕ → α}
(hf : summable (λ x, ∥f x∥)) (hg : summable (λ x, ∥g x∥)) :
summable (λ n, ∥∑ kl in antidiagonal n, f kl.1 * g kl.2∥) :=
begin
have := summable_sum_mul_antidiagonal_of_summable_mul
(summable.mul_of_nonneg hf hg (λ _, norm_nonneg _) (λ _, norm_nonneg _)),
refine summable_of_nonneg_of_le (λ _, norm_nonneg _) _ this,
intros n,
calc ∥∑ kl in antidiagonal n, f kl.1 * g kl.2∥
≤ ∑ kl in antidiagonal n, ∥f kl.1 * g kl.2∥ : norm_sum_le _ _
... ≤ ∑ kl in antidiagonal n, ∥f kl.1∥ * ∥g kl.2∥ : sum_le_sum (λ i _, norm_mul_le _ _)
end
/-- The Cauchy product formula for the product of two infinite sums indexed by `ℕ`,
expressed by summing on `finset.nat.antidiagonal`.
See also `tsum_mul_tsum_eq_tsum_sum_antidiagonal` if `f` and `g` are
*not* absolutely summable. -/
lemma tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm [complete_space α] {f g : ℕ → α}
(hf : summable (λ x, ∥f x∥)) (hg : summable (λ x, ∥g x∥)) :
(∑' n, f n) * (∑' n, g n) = ∑' n, ∑ kl in antidiagonal n, f kl.1 * g kl.2 :=
tsum_mul_tsum_eq_tsum_sum_antidiagonal (summable_of_summable_norm hf) (summable_of_summable_norm hg)
(summable_mul_of_summable_norm hf hg)
lemma summable_norm_sum_mul_range_of_summable_norm {f g : ℕ → α}
(hf : summable (λ x, ∥f x∥)) (hg : summable (λ x, ∥g x∥)) :
summable (λ n, ∥∑ k in range (n+1), f k * g (n - k)∥) :=
begin
simp_rw ← sum_antidiagonal_eq_sum_range_succ (λ k l, f k * g l),
exact summable_norm_sum_mul_antidiagonal_of_summable_norm hf hg
end
/-- The Cauchy product formula for the product of two infinite sums indexed by `ℕ`,
expressed by summing on `finset.range`.
See also `tsum_mul_tsum_eq_tsum_sum_range` if `f` and `g` are
*not* absolutely summable. -/
lemma tsum_mul_tsum_eq_tsum_sum_range_of_summable_norm [complete_space α] {f g : ℕ → α}
(hf : summable (λ x, ∥f x∥)) (hg : summable (λ x, ∥g x∥)) :
(∑' n, f n) * (∑' n, g n) = ∑' n, ∑ k in range (n+1), f k * g (n - k) :=
begin
simp_rw ← sum_antidiagonal_eq_sum_range_succ (λ k l, f k * g l),
exact tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm hf hg
end
end nat
end cauchy_product
section ring_hom_isometric
variables {R₁ : Type*} {R₂ : Type*} {R₃ : Type*}
/-- This class states that a ring homomorphism is isometric. This is a sufficient assumption
for a continuous semilinear map to be bounded and this is the main use for this typeclass. -/
class ring_hom_isometric [semiring R₁] [semiring R₂] [has_norm R₁] [has_norm R₂]
(σ : R₁ →+* R₂) : Prop :=
(is_iso : ∀ {x : R₁}, ∥σ x∥ = ∥x∥)
attribute [simp] ring_hom_isometric.is_iso
variables [semi_normed_ring R₁] [semi_normed_ring R₂] [semi_normed_ring R₃]
instance ring_hom_isometric.ids : ring_hom_isometric (ring_hom.id R₁) :=
⟨λ x, rfl⟩
end ring_hom_isometric
|
8f70ad4b2b853d5f8447152bc467eced521c695d | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/preadditive/opposite.lean | 045521e03a507f04445a1227aa35aa80163beb05 | [
"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,994 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Adam Topaz, Johan Commelin, Joël Riou
-/
import category_theory.preadditive.basic
import category_theory.preadditive.additive_functor
import logic.equiv.transfer_instance
/-!
# If `C` is preadditive, `Cᵒᵖ` has a natural preadditive structure.
-/
open opposite
namespace category_theory
variables (C : Type*) [category C] [preadditive C]
instance : preadditive Cᵒᵖ :=
{ hom_group := λ X Y, equiv.add_comm_group (op_equiv X Y),
add_comp' := λ X Y Z f f' g,
congr_arg quiver.hom.op (preadditive.comp_add _ _ _ g.unop f.unop f'.unop),
comp_add' := λ X Y Z f g g',
congr_arg quiver.hom.op (preadditive.add_comp _ _ _ g.unop g'.unop f.unop), }
instance module_End_left {X : Cᵒᵖ} {Y : C} : module (End X) (unop X ⟶ Y) :=
{ smul_add := λ r f g, preadditive.comp_add _ _ _ _ _ _,
smul_zero := λ r, limits.comp_zero,
add_smul := λ r s f, preadditive.add_comp _ _ _ _ _ _,
zero_smul := λ f, limits.zero_comp }
@[simp] lemma unop_zero (X Y : Cᵒᵖ) : (0 : X ⟶ Y).unop = 0 := rfl
@[simp] lemma unop_add {X Y : Cᵒᵖ} (f g : X ⟶ Y) : (f + g).unop = f.unop + g.unop := rfl
@[simp] lemma unop_zsmul {X Y : Cᵒᵖ} (k : ℤ) (f : X ⟶ Y) : (k • f).unop = k • f.unop := rfl
@[simp] lemma unop_neg {X Y : Cᵒᵖ}(f : X ⟶ Y) : (-f).unop = -(f.unop) := rfl
@[simp] lemma op_zero (X Y : C) : (0 : X ⟶ Y).op = 0 := rfl
@[simp] lemma op_add {X Y : C} (f g : X ⟶ Y) : (f + g).op = f.op + g.op := rfl
@[simp] lemma op_zsmul {X Y : C} (k : ℤ) (f : X ⟶ Y) : (k • f).op = k • f.op := rfl
@[simp] lemma op_neg {X Y : C}(f : X ⟶ Y) : (-f).op = -(f.op) := rfl
variable {C}
/-- `unop` induces morphisms of monoids on hom groups of a preadditive category -/
@[simps] def unop_hom (X Y : Cᵒᵖ) : (X ⟶ Y) →+ (opposite.unop Y ⟶ opposite.unop X) :=
add_monoid_hom.mk' (λ f, f.unop) $ λ f g, unop_add _ f g
@[simp] lemma unop_sum (X Y : Cᵒᵖ) {ι : Type*} (s : finset ι) (f : ι → (X ⟶ Y)) :
(s.sum f).unop = s.sum (λ i, (f i).unop) :=
(unop_hom X Y).map_sum _ _
/-- `op` induces morphisms of monoids on hom groups of a preadditive category -/
@[simps] def op_hom (X Y : C) : (X ⟶ Y) →+ (opposite.op Y ⟶ opposite.op X) :=
add_monoid_hom.mk' (λ f, f.op) $ λ f g, op_add _ f g
@[simp] lemma op_sum (X Y : C) {ι : Type*} (s : finset ι) (f : ι → (X ⟶ Y)) :
(s.sum f).op = s.sum (λ i, (f i).op) :=
(op_hom X Y).map_sum _ _
variables {D : Type*} [category D] [preadditive D]
instance functor.op_additive (F : C ⥤ D) [F.additive] : F.op.additive := {}
instance functor.right_op_additive (F : Cᵒᵖ ⥤ D) [F.additive] : F.right_op.additive := {}
instance functor.left_op_additive (F : C ⥤ Dᵒᵖ) [F.additive] : F.left_op.additive := {}
instance functor.unop_additive (F : Cᵒᵖ ⥤ Dᵒᵖ) [F.additive] : F.unop.additive := {}
end category_theory
|
0c65885a96f3b51e5df46051efc946340dab98a5 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/topology/bounded_continuous_function.lean | d4c0cf157044daafbb18bd0952d8bae31532e2d4 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 23,546 | lean | /-
Copyright (c) 2018 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Mario Carneiro
Type of bounded continuous functions taking values in a metric space, with
the uniform distance.
-/
import analysis.normed_space.basic topology.metric_space.cau_seq_filter
topology.metric_space.lipschitz
noncomputable theory
local attribute [instance] classical.decidable_inhabited classical.prop_decidable
open set lattice filter metric
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
/-- A locally uniform limit of continuous functions is continuous -/
lemma continuous_of_locally_uniform_limit_of_continuous [topological_space α] [metric_space β]
{F : ℕ → α → β} {f : α → β}
(L : ∀x:α, ∃s ∈ nhds x, ∀ε>(0:ℝ), ∃n, ∀y∈s, dist (F n y) (f y) ≤ ε)
(C : ∀ n, continuous (F n)) : continuous f :=
continuous_iff'.2 $ λ x ε ε0, begin
rcases L x with ⟨r, rx, hr⟩,
rcases hr (ε/2/2) (half_pos $ half_pos ε0) with ⟨n, hn⟩,
rcases continuous_iff'.1 (C n) x (ε/2) (half_pos ε0) with ⟨s, sx, hs⟩,
refine ⟨_, (nhds x).inter_sets rx sx, _⟩,
rintro y ⟨yr, ys⟩,
calc dist (f y) (f x)
≤ dist (F n y) (F n x) + (dist (F n y) (f y) + dist (F n x) (f x)) : dist_triangle4_left _ _ _ _
... < ε/2 + (ε/2/2 + ε/2/2) :
add_lt_add_of_lt_of_le (hs _ ys) (add_le_add (hn _ yr) (hn _ (mem_of_nhds rx)))
... = ε : by rw [add_halves, add_halves]
end
/-- A uniform limit of continuous functions is continuous -/
lemma continuous_of_uniform_limit_of_continuous [topological_space α] {β : Type v} [metric_space β]
{F : ℕ → α → β} {f : α → β} (L : ∀ε>(0:ℝ), ∃N, ∀y, dist (F N y) (f y) ≤ ε) :
(∀ n, continuous (F n)) → continuous f :=
continuous_of_locally_uniform_limit_of_continuous $ λx,
⟨univ, by simpa [filter.univ_mem_sets] using L⟩
/-- The type of bounded continuous functions from a topological space to a metric space -/
def bounded_continuous_function (α : Type u) (β : Type v) [topological_space α] [metric_space β] : Type (max u v) :=
{f : α → β // continuous f ∧ ∃C, ∀x y:α, dist (f x) (f y) ≤ C}
local infixr ` →ᵇ `:25 := bounded_continuous_function
namespace bounded_continuous_function
section basics
variables [topological_space α] [metric_space β] [metric_space γ]
variables {f g : α →ᵇ β} {x : α} {C : ℝ}
instance : has_coe_to_fun (α →ᵇ β) := ⟨_, subtype.val⟩
lemma bounded_range : bounded (range f) :=
bounded_range_iff.2 f.2.2
/-- If a function is continuous on a compact space, it is automatically bounded,
and therefore gives rise to an element of the type of bounded continuous functions -/
def mk_of_compact [compact_space α] (f : α → β) (hf : continuous f) : α →ᵇ β :=
⟨f, hf, bounded_range_iff.1 $ by rw ← image_univ; exact
bounded_of_compact (compact_image compact_univ hf)⟩
/-- If a function is bounded on a discrete space, it is automatically continuous,
and therefore gives rise to an element of the type of bounded continuous functions -/
def mk_of_discrete [discrete_topology α] (f : α → β) (hf : ∃C, ∀x y, dist (f x) (f y) ≤ C) :
α →ᵇ β :=
⟨f, continuous_of_discrete_topology, hf⟩
/-- The uniform distance between two bounded continuous functions -/
instance : has_dist (α →ᵇ β) :=
⟨λf g, Inf {C | C ≥ 0 ∧ ∀ x : α, dist (f x) (g x) ≤ C}⟩
lemma dist_eq : dist f g = Inf {C | C ≥ 0 ∧ ∀ x : α, dist (f x) (g x) ≤ C} := rfl
lemma dist_set_exists : ∃ C, C ≥ 0 ∧ ∀ x : α, dist (f x) (g x) ≤ C :=
begin
refine if h : nonempty α then _ else ⟨0, le_refl _, λ x, h.elim ⟨x⟩⟩,
cases h with x,
rcases f.2 with ⟨_, Cf, hCf⟩, /- hCf : ∀ (x y : α), dist (f.val x) (f.val y) ≤ Cf -/
rcases g.2 with ⟨_, Cg, hCg⟩, /- hCg : ∀ (x y : α), dist (g.val x) (g.val y) ≤ Cg -/
let C := max 0 (dist (f x) (g x) + (Cf + Cg)),
exact ⟨C, le_max_left _ _, λ y, calc
dist (f y) (g y) ≤ dist (f x) (g x) + (dist (f x) (f y) + dist (g x) (g y)) : dist_triangle4_left _ _ _ _
... ≤ dist (f x) (g x) + (Cf + Cg) : add_le_add_left (add_le_add (hCf _ _) (hCg _ _)) _
... ≤ C : le_max_right _ _⟩
end
/-- The pointwise distance is controlled by the distance between functions, by definition -/
lemma dist_coe_le_dist (x : α) : dist (f x) (g x) ≤ dist f g :=
le_cInf (ne_empty_iff_exists_mem.2 dist_set_exists) $ λb hb, hb.2 x
@[extensionality] lemma ext (H : ∀x, f x = g x) : f = g :=
subtype.eq $ by ext; apply H
/- This lemma will be needed in the proof of the metric space instance, but it will become
useless afterwards as it will be superceded by the general result that the distance is nonnegative
is metric spaces. -/
private lemma dist_nonneg' : 0 ≤ dist f g :=
le_cInf (ne_empty_iff_exists_mem.2 dist_set_exists) (λ C, and.left)
/-- The distance between two functions is controlled by the supremum of the pointwise distances -/
lemma dist_le (C0 : (0 : ℝ) ≤ C) : dist f g ≤ C ↔ ∀x:α, dist (f x) (g x) ≤ C :=
⟨λ h x, le_trans (dist_coe_le_dist x) h, λ H, cInf_le ⟨0, λ C, and.left⟩ ⟨C0, H⟩⟩
/-- On an empty space, bounded continuous functions are at distance 0 -/
lemma dist_zero_of_empty (e : ¬ nonempty α) : dist f g = 0 :=
le_antisymm ((dist_le (le_refl _)).2 $ λ x, e.elim ⟨x⟩) dist_nonneg'
/-- The type of bounded continuous functions, with the uniform distance, is a metric space. -/
instance : metric_space (α →ᵇ β) :=
{ dist_self := λ f, le_antisymm ((dist_le (le_refl _)).2 $ λ x, by simp) dist_nonneg',
eq_of_dist_eq_zero := λ f g hfg, by ext x; exact
eq_of_dist_eq_zero (le_antisymm (hfg ▸ dist_coe_le_dist _) dist_nonneg),
dist_comm := λ f g, by simp [dist_eq, dist_comm],
dist_triangle := λ f g h,
(dist_le (add_nonneg dist_nonneg' dist_nonneg')).2 $ λ x,
le_trans (dist_triangle _ _ _) (add_le_add (dist_coe_le_dist _) (dist_coe_le_dist _)) }
def const (b : β) : α →ᵇ β := ⟨λx, b, continuous_const, 0, by simp [le_refl]⟩
/-- If the target space is inhabited, so is the space of bounded continuous functions -/
instance [inhabited β] : inhabited (α →ᵇ β) := ⟨const (default β)⟩
/-- The evaluation map is continuous, as a joint function of `u` and `x` -/
theorem continuous_eval : continuous (λ p : (α →ᵇ β) × α, p.1 p.2) :=
continuous_iff'.2 $ λ ⟨f, x⟩ ε ε0,
/- use the continuity of `f` to find a neighborhood of `x` where it varies at most by ε/2 -/
let ⟨s, sx, Hs⟩ := continuous_iff'.1 f.2.1 x (ε/2) (half_pos ε0) in
/- s : set α, sx : s ∈ nhds x, Hs : ∀ (b : α), b ∈ s → dist (f.val b) (f.val x) < ε / 2 -/
⟨set.prod (ball f (ε/2)) s, prod_mem_nhds_sets (ball_mem_nhds _ (half_pos ε0)) sx,
λ ⟨g, y⟩ ⟨hg, hy⟩, calc dist (g y) (f x)
≤ dist (g y) (f y) + dist (f y) (f x) : dist_triangle _ _ _
... < ε/2 + ε/2 : add_lt_add (lt_of_le_of_lt (dist_coe_le_dist _) hg) (Hs _ hy)
... = ε : add_halves _⟩
/-- In particular, when `x` is fixed, `f → f x` is continuous -/
theorem continuous_evalx {x : α} : continuous (λ f : α →ᵇ β, f x) :=
(continuous_id.prod_mk continuous_const).comp continuous_eval
/-- When `f` is fixed, `x → f x` is also continuous, by definition -/
theorem continuous_evalf {f : α →ᵇ β} : continuous f := f.2.1
/-- Bounded continuous functions taking values in a complete space form a complete space. -/
instance [complete_space β] : complete_space (α →ᵇ β) :=
complete_of_cauchy_seq_tendsto $ λ (f : ℕ → α →ᵇ β) (hf : cauchy_seq f),
begin
/- We have to show that `f n` converges to a bounded continuous function.
For this, we prove pointwise convergence to define the limit, then check
it is a continuous bounded function, and then check the norm convergence. -/
rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩,
have f_bdd := λx n m N hn hm, le_trans (dist_coe_le_dist x) (b_bound n m N hn hm),
have fx_cau : ∀x, cauchy_seq (λn, f n x) :=
λx, cauchy_seq_iff_le_tendsto_0.2 ⟨b, b0, f_bdd x, b_lim⟩,
choose F hF using λx, cauchy_seq_tendsto_of_complete (fx_cau x),
/- F : α → β, hF : ∀ (x : α), tendsto (λ (n : ℕ), f n x) at_top (nhds (F x))
`F` is the desired limit function. Check that it is uniformly approximated by `f N` -/
have fF_bdd : ∀x N, dist (f N x) (F x) ≤ b N :=
λ x N, le_of_tendsto (by simp)
(tendsto_dist tendsto_const_nhds (hF x))
(filter.mem_at_top_sets.2 ⟨N, λn hn, f_bdd x N n N (le_refl N) hn⟩),
refine ⟨⟨F, _, _⟩, _⟩,
{ /- Check that `F` is continuous -/
refine continuous_of_uniform_limit_of_continuous (λ ε ε0, _) (λN, (f N).2.1),
rcases metric.tendsto_at_top.1 b_lim ε ε0 with ⟨N, hN⟩,
exact ⟨N, λy, calc
dist (f N y) (F y) ≤ b N : fF_bdd y N
... ≤ dist (b N) 0 : begin simp, show b N ≤ abs(b N), from le_abs_self _ end
... ≤ ε : le_of_lt (hN N (le_refl N))⟩ },
{ /- Check that `F` is bounded -/
rcases (f 0).2.2 with ⟨C, hC⟩,
exact ⟨C + (b 0 + b 0), λ x y, calc
dist (F x) (F y) ≤ dist (f 0 x) (f 0 y) + (dist (f 0 x) (F x) + dist (f 0 y) (F y)) : dist_triangle4_left _ _ _ _
... ≤ C + (b 0 + b 0) : add_le_add (hC x y) (add_le_add (fF_bdd x 0) (fF_bdd y 0))⟩ },
{ /- Check that `F` is close to `f N` in distance terms -/
refine tendsto_iff_dist_tendsto_zero.2 (squeeze_zero (λ _, dist_nonneg) _ b_lim),
exact λ N, (dist_le (b0 _)).2 (λx, fF_bdd x N) }
end
/-- Composition (in the target) of a bounded continuous function with a Lipschitz map again
gives a bounded continuous function -/
def comp (G : β → γ) (H : ∀x y, dist (G x) (G y) ≤ C * dist x y)
(f : α →ᵇ β) : α →ᵇ γ :=
⟨λx, G (f x), f.2.1.comp (continuous_of_lipschitz H),
let ⟨D, hD⟩ := f.2.2 in
⟨max C 0 * D, λ x y, calc
dist (G (f x)) (G (f y)) ≤ C * dist (f x) (f y) : H _ _
... ≤ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left C 0) dist_nonneg
... ≤ max C 0 * D : mul_le_mul_of_nonneg_left (hD _ _) (le_max_right C 0)⟩⟩
/-- The composition operator (in the target) with a Lipschitz map is continuous -/
lemma continuous_comp {G : β → γ} (H : ∀x y, dist (G x) (G y) ≤ C * dist x y) :
continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) :=
continuous_of_lipschitz $ λ f g,
(dist_le (mul_nonneg (le_max_right C 0) dist_nonneg)).2 $ λ x,
calc dist (G (f x)) (G (g x)) ≤ C * dist (f x) (g x) : H _ _
... ≤ max C 0 * dist (f x) (g x) : mul_le_mul_of_nonneg_right (le_max_left C 0) (dist_nonneg)
... ≤ max C 0 * dist f g : mul_le_mul_of_nonneg_left (dist_coe_le_dist _) (le_max_right C 0)
/-- Restriction (in the target) of a bounded continuous function taking values in a subset -/
def cod_restrict (s : set β) (f : α →ᵇ β) (H : ∀x, f x ∈ s) : α →ᵇ s :=
⟨λx, ⟨f x, H x⟩, continuous_subtype_mk _ f.2.1, f.2.2⟩
end basics
section arzela_ascoli
variables [topological_space α] [compact_space α] [metric_space β]
variables {f g : α →ᵇ β} {x : α} {C : ℝ}
/- Arzela-Ascoli theorem asserts that, on a compact space, a set of functions sharing
a common modulus of continuity and taking values in a compact set forms a compact
subset for the topology of uniform convergence. In this section, we prove this theorem
and several useful variations around it. -/
/-- First version, with pointwise equicontinuity and range in a compact space -/
theorem arzela_ascoli₁ [compact_space β]
(A : set (α →ᵇ β))
(closed : is_closed A)
(H : ∀ (x:α) (ε > 0), ∃U ∈ nhds x, ∀ (y z ∈ U) (f : α →ᵇ β),
f ∈ A → dist (f y) (f z) < ε) :
compact A :=
begin
refine compact_of_totally_bounded_is_closed _ closed,
refine totally_bounded_of_finite_discretization (λ ε ε0, _),
rcases dense ε0 with ⟨ε₁, ε₁0, εε₁⟩,
let ε₂ := ε₁/2/2,
/- We have to find a finite discretization of `u`, i.e., finite information
that is sufficient to reconstruct `u` up to ε. This information will be
provided by the values of `u` on a sufficiently dense set tα,
slightly translated to fit in a finite ε₂-dense set tβ in the image. Such
sets exist by compactness of the source and range. Then, to check that these
data determine the function up to ε, one uses the control on the modulus of
continuity to extend the closeness on tα to closeness everywhere. -/
have ε₂0 : ε₂ > 0 := half_pos (half_pos ε₁0),
have : ∀x:α, ∃U, x ∈ U ∧ is_open U ∧ ∀ (y z ∈ U) {f : α →ᵇ β},
f ∈ A → dist (f y) (f z) < ε₂ := λ x,
let ⟨U, nhdsU, hU⟩ := H x _ ε₂0,
⟨V, VU, openV, xV⟩ := mem_nhds_sets_iff.1 nhdsU in
⟨V, xV, openV, λy z hy hz f hf, hU y z (VU hy) (VU hz) f hf⟩,
choose U hU using this,
/- For all x, the set hU x is an open set containing x on which the elements of A
fluctuate by at most ε₂.
We extract finitely many of these sets that cover the whole space, by compactness -/
rcases compact_elim_finite_subcover_image compact_univ
(λx _, (hU x).2.1) (λx hx, mem_bUnion (mem_univ _) (hU x).1)
with ⟨tα, _, ⟨_⟩, htα⟩,
/- tα : set α, htα : univ ⊆ ⋃x ∈ tα, U x -/
rcases @finite_cover_balls_of_compact β _ _ compact_univ _ ε₂0
with ⟨tβ, _, ⟨_⟩, htβ⟩, resetI,
/- tβ : set β, htβ : univ ⊆ ⋃y ∈ tβ, ball y ε₂ -/
/- Associate to every point `y` in the space a nearby point `F y` in tβ -/
choose F hF using λy, show ∃z∈tβ, dist y z < ε₂, by simpa using htβ (mem_univ y),
/- F : β → β, hF : ∀ (y : β), F y ∈ tβ ∧ dist y (F y) < ε₂ -/
/- Associate to every function a discrete approximation, mapping each point in `tα`
to a point in `tβ` close to its true image by the function. -/
refine ⟨tα → tβ, by apply_instance, λ f a, ⟨F (f a), (hF (f a)).fst⟩, _⟩,
rintro ⟨f, hf⟩ ⟨g, hg⟩ f_eq_g,
/- If two functions have the same approximation, then they are within distance ε -/
refine lt_of_le_of_lt ((dist_le $ le_of_lt ε₁0).2 (λ x, _)) εε₁,
have : ∃x', x' ∈ tα ∧ x ∈ U x' := mem_bUnion_iff.1 (htα (mem_univ x)),
rcases this with ⟨x', x'tα, hx'⟩,
refine calc dist (f x) (g x)
≤ dist (f x) (f x') + dist (g x) (g x') + dist (f x') (g x') : dist_triangle4_right _ _ _ _
... ≤ ε₂ + ε₂ + ε₁/2 : le_of_lt (add_lt_add (add_lt_add _ _) _)
... = ε₁ : by rw [add_halves, add_halves],
{ exact (hU x').2.2 _ _ hx' ((hU x').1) hf },
{ exact (hU x').2.2 _ _ hx' ((hU x').1) hg },
{ have F_f_g : F (f x') = F (g x') :=
(congr_arg (λ f:tα → tβ, (f ⟨x', x'tα⟩ : β)) f_eq_g : _),
calc dist (f x') (g x')
≤ dist (f x') (F (f x')) + dist (g x') (F (f x')) : dist_triangle_right _ _ _
... = dist (f x') (F (f x')) + dist (g x') (F (g x')) : by rw F_f_g
... < ε₂ + ε₂ : add_lt_add (hF (f x')).snd (hF (g x')).snd
... = ε₁/2 : add_halves _ }
end
/-- Second version, with pointwise equicontinuity and range in a compact subset -/
theorem arzela_ascoli₂
(s : set β) (hs : compact s)
(A : set (α →ᵇ β))
(closed : is_closed A)
(in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s)
(H : ∀(x:α) (ε > 0), ∃U ∈ nhds x, ∀ (y z ∈ U) (f : α →ᵇ β),
f ∈ A → dist (f y) (f z) < ε) :
compact A :=
/- This version is deduced from the previous one by restricting to the compact type in the target,
using compactness there and then lifting everything to the original space. -/
begin
have M : ∀x y : s, dist (x : β) y ≤ 1 * dist x y := λ x y, ge_of_eq (one_mul _),
let F : (α →ᵇ s) → α →ᵇ β := comp coe M,
refine compact_of_is_closed_subset
(compact_image (_ : compact (F ⁻¹' A)) (continuous_comp M)) closed (λ f hf, _),
{ haveI : compact_space s := compact_iff_compact_space.1 hs,
refine arzela_ascoli₁ _ (continuous_iff_is_closed.1 (continuous_comp M) _ closed)
(λ x ε ε0, bex.imp_right (λ U U_nhds hU y z hy hz f hf, _) (H x ε ε0)),
calc dist (f y) (f z) = dist (F f y) (F f z) : rfl
... < ε : hU y z hy hz (F f) hf },
{ let g := cod_restrict s f (λx, in_s f x hf),
rw [show f = F g, by ext; refl] at hf ⊢,
exact ⟨g, hf, rfl⟩ }
end
/-- Third (main) version, with pointwise equicontinuity and range in a compact subset, but
without closedness. The closure is then compact -/
theorem arzela_ascoli
(s : set β) (hs : compact s)
(A : set (α →ᵇ β))
(in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s)
(H : ∀(x:α) (ε > 0), ∃U ∈ nhds x, ∀ (y z ∈ U) (f : α →ᵇ β),
f ∈ A → dist (f y) (f z) < ε) :
compact (closure A) :=
/- This version is deduced from the previous one by checking that the closure of A, in
addition to being closed, still satisfies the properties of compact range and equicontinuity -/
arzela_ascoli₂ s hs (closure A) is_closed_closure
(λ f x hf, (mem_of_closed' (closed_of_compact _ hs)).2 $ λ ε ε0,
let ⟨g, gA, dist_fg⟩ := mem_closure_iff'.1 hf ε ε0 in
⟨g x, in_s g x gA, lt_of_le_of_lt (dist_coe_le_dist _) dist_fg⟩)
(λ x ε ε0, show ∃ U ∈ nhds x,
∀ y z ∈ U, ∀ (f : α →ᵇ β), f ∈ closure A → dist (f y) (f z) < ε,
begin
refine bex.imp_right (λ U U_set hU y z hy hz f hf, _) (H x (ε/2) (half_pos ε0)),
rcases mem_closure_iff'.1 hf (ε/2/2) (half_pos (half_pos ε0)) with ⟨g, gA, dist_fg⟩,
replace dist_fg := λ x, lt_of_le_of_lt (dist_coe_le_dist x) dist_fg,
calc dist (f y) (f z) ≤ dist (f y) (g y) + dist (f z) (g z) + dist (g y) (g z) : dist_triangle4_right _ _ _ _
... < ε/2/2 + ε/2/2 + ε/2 :
add_lt_add (add_lt_add (dist_fg y) (dist_fg z)) (hU y z hy hz g gA)
... = ε : by rw [add_halves, add_halves]
end)
/- To apply the previous theorems, one needs to check the equicontinuity. An important
instance is when the source space is a metric space, and there is a fixed modulus of continuity
for all the functions in the set A -/
lemma equicontinuous_of_continuity_modulus {α : Type u} [metric_space α]
(b : ℝ → ℝ) (b_lim : tendsto b (nhds 0) (nhds 0))
(A : set (α →ᵇ β))
(H : ∀(x y:α) (f : α →ᵇ β), f ∈ A → dist (f x) (f y) ≤ b (dist x y))
(x:α) (ε : ℝ) (ε0 : ε > 0) : ∃U ∈ nhds x, ∀ (y z ∈ U) (f : α →ᵇ β),
f ∈ A → dist (f y) (f z) < ε :=
begin
rcases tendsto_nhds_nhds.1 b_lim ε ε0 with ⟨δ, δ0, hδ⟩,
refine ⟨ball x (δ/2), ball_mem_nhds x (half_pos δ0), λ y z hy hz f hf, _⟩,
have : dist y z < δ := calc
dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _
... < δ/2 + δ/2 : add_lt_add hy hz
... = δ : add_halves _,
calc
dist (f y) (f z) ≤ b (dist y z) : H y z f hf
... ≤ abs (b (dist y z)) : le_abs_self _
... = dist (b (dist y z)) 0 : by simp [real.dist_eq]
... < ε : hδ (by simpa [real.dist_eq] using this),
end
end arzela_ascoli
section normed_group
/- In this section, if β is a normed group, then we show that the space of bounded
continuous functions from α to β inherits a normed group structure, by using
pointwise operations and checking that they are compatible with the uniform distance. -/
variables [topological_space α] [normed_group β]
variables {f g : α →ᵇ β} {x : α} {C : ℝ}
instance : has_zero (α →ᵇ β) := ⟨const 0⟩
@[simp] lemma coe_zero : (0 : α →ᵇ β) x = 0 := rfl
instance : has_norm (α →ᵇ β) := ⟨λu, dist u 0⟩
lemma norm_def : ∥f∥ = dist f 0 := rfl
lemma norm_coe_le_norm (x : α) : ∥f x∥ ≤ ∥f∥ := calc
∥f x∥ = dist (f x) ((0 : α →ᵇ β) x) : by simp [dist_zero_right]
... ≤ ∥f∥ : dist_coe_le_dist _
/-- The norm of a function is controlled by the supremum of the pointwise norms -/
lemma norm_le (C0 : (0 : ℝ) ≤ C) : ∥f∥ ≤ C ↔ ∀x:α, ∥f x∥ ≤ C :=
by simpa only [coe_zero, dist_zero_right] using @dist_le _ _ _ _ f 0 _ C0
/-- The pointwise sum of two bounded continuous functions is again bounded continuous. -/
instance : has_add (α →ᵇ β) :=
⟨λf g, ⟨λx, f x + g x, continuous_add f.2.1 g.2.1, (∥f∥ + ∥g∥) + (∥f∥ + ∥g∥),
λ x y,
have ∀x, dist (f x + g x) 0 ≤ ∥f∥ + ∥g∥ := λx, calc
dist (f x + g x) 0 = ∥f x + g x∥ : dist_zero_right _
... ≤ ∥f x∥ + ∥g x∥ : norm_triangle _ _
... ≤ ∥f∥ + ∥g∥ : add_le_add (norm_coe_le_norm _) (norm_coe_le_norm _),
calc dist (f x + g x) (f y + g y) ≤ dist (f x + g x) 0 + dist (f y + g y) 0 : dist_triangle_right _ _ _
... ≤ (∥f∥ + ∥g∥) + (∥f∥ + ∥g∥) : add_le_add (this x) (this y) ⟩⟩
/-- The pointwise opposite of a bounded continuous function is again bounded continuous. -/
instance : has_neg (α →ᵇ β) :=
⟨λf, ⟨λx, -f x, continuous_neg f.2.1,
begin
have dn : ∀a b : β, dist (-a) (-b) = dist a b := λ a b,
by rw [dist_eq_norm, neg_sub_neg, ← dist_eq_norm, dist_comm],
simpa only [dn] using f.2.2
end⟩⟩
@[simp] lemma coe_add : (f + g) x = f x + g x := rfl
@[simp] lemma coe_neg : (-f) x = - (f x) := rfl
lemma forall_coe_zero_iff_zero : (∀x, f x = 0) ↔ f = 0 :=
⟨@ext _ _ _ _ f 0, by rintro rfl _; refl⟩
instance : add_comm_group (α →ᵇ β) :=
{ add_assoc := assume f g h, by ext; simp,
zero_add := assume f, by ext; simp,
add_zero := assume f, by ext; simp,
add_left_neg := assume f, by ext; simp,
add_comm := assume f g, by ext; simp,
..bounded_continuous_function.has_add,
..bounded_continuous_function.has_neg,
..bounded_continuous_function.has_zero }
@[simp] lemma coe_diff : (f - g) x = f x - g x := rfl
instance : normed_group (α →ᵇ β) :=
normed_group.of_add_dist (λ _, rfl) $ λ f g h,
(dist_le dist_nonneg).2 $ λ x,
le_trans (by rw [dist_eq_norm, dist_eq_norm, coe_add, coe_add,
add_sub_add_right_eq_sub]) (dist_coe_le_dist x)
lemma abs_diff_coe_le_dist : norm (f x - g x) ≤ dist f g :=
by rw normed_group.dist_eq; exact @norm_coe_le_norm _ _ _ _ (f-g) x
lemma coe_le_coe_add_dist {f g : α →ᵇ ℝ} : f x ≤ g x + dist f g :=
sub_le_iff_le_add'.1 $ (abs_le.1 $ @dist_coe_le_dist _ _ _ _ f g x).2
/-- Constructing a bounded continuous function from a uniformly bounded continuous
function taking values in a normed group. -/
def of_normed_group {α : Type u} {β : Type v} [topological_space α] [normed_group β]
(f : α → β) (C : ℝ) (H : ∀x, norm (f x) ≤ C) (Hf : continuous f) : α →ᵇ β :=
⟨λn, f n, ⟨Hf, ⟨C + C, λ m n,
calc dist (f m) (f n) ≤ dist (f m) 0 + dist (f n) 0 : dist_triangle_right _ _ _
... = norm (f m) + norm (f n) : by simp
... ≤ C + C : add_le_add (H m) (H n)⟩⟩⟩
/-- Constructing a bounded continuous function from a uniformly bounded
function on a discrete space, taking values in a normed group -/
def of_normed_group_discrete {α : Type u} {β : Type v}
[topological_space α] [discrete_topology α] [normed_group β]
(f : α → β) (C : ℝ) (H : ∀x, norm (f x) ≤ C) : α →ᵇ β :=
of_normed_group f C H continuous_of_discrete_topology
end normed_group
end bounded_continuous_function
|
a37e5aefbad0a2d347026e8db4f7eb30b53f81cf | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/box_integral/partition/additive.lean | 4932c78468f1728383b96909079e8b5299dc0771 | [
"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 | 9,915 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.box_integral.partition.split
import analysis.normed_space.operator_norm
/-!
# Box additive functions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We say that a function `f : box ι → M` from boxes in `ℝⁿ` to a commutative additive monoid `M` is
*box additive* on subboxes of `I₀ : with_top (box ι)` if for any box `J`, `↑J ≤ I₀`, and a partition
`π` of `J`, `f J = ∑ J' in π.boxes, f J'`. We use `I₀ : with_top (box ι)` instead of `I₀ : box ι` to
use the same definition for functions box additive on subboxes of a box and for functions box
additive on all boxes.
Examples of box-additive functions include the measure of a box and the integral of a fixed
integrable function over a box.
In this file we define box-additive functions and prove that a function such that
`f J = f (J ∩ {x | x i < y}) + f (J ∩ {x | y ≤ x i})` is box-additive.
### Tags
rectangular box, additive function
-/
noncomputable theory
open_locale classical big_operators
open function set
namespace box_integral
variables {ι M : Type*} {n : ℕ}
/-- A function on `box ι` is called box additive if for every box `J` and a partition `π` of `J`
we have `f J = ∑ Ji in π.boxes, f Ji`. A function is called box additive on subboxes of `I : box ι`
if the same property holds for `J ≤ I`. We formalize these two notions in the same definition
using `I : with_bot (box ι)`: the value `I = ⊤` corresponds to functions box additive on the whole
space. -/
structure box_additive_map (ι M : Type*) [add_comm_monoid M] (I : with_top (box ι)) :=
(to_fun : box ι → M)
(sum_partition_boxes' : ∀ J : box ι, ↑J ≤ I → ∀ π : prepartition J, π.is_partition →
∑ Ji in π.boxes, to_fun Ji = to_fun J)
localized "notation (name := box_integral.box_additive_map.top)
ι ` →ᵇᵃ `:25 M := box_integral.box_additive_map ι M ⊤" in box_integral
localized "notation (name := box_integral.box_additive_map)
ι ` →ᵇᵃ[`:25 I `] ` M := box_integral.box_additive_map ι M I" in box_integral
namespace box_additive_map
open box prepartition finset
variables {N : Type*} [add_comm_monoid M] [add_comm_monoid N] {I₀ : with_top (box ι)}
{I J : box ι} {i : ι}
instance : has_coe_to_fun (ι →ᵇᵃ[I₀] M) (λ _, box ι → M) := ⟨to_fun⟩
initialize_simps_projections box_integral.box_additive_map (to_fun → apply)
@[simp] lemma to_fun_eq_coe (f : ι →ᵇᵃ[I₀] M) : f.to_fun = f := rfl
@[simp] lemma coe_mk (f h) : ⇑(mk f h : ι →ᵇᵃ[I₀] M) = f := rfl
lemma coe_injective : injective (λ (f : ι →ᵇᵃ[I₀] M) x, f x) :=
by { rintro ⟨f, hf⟩ ⟨g, hg⟩ (rfl : f = g), refl }
@[simp] lemma coe_inj {f g : ι →ᵇᵃ[I₀] M} : (f : box ι → M) = g ↔ f = g :=
coe_injective.eq_iff
lemma sum_partition_boxes (f : ι →ᵇᵃ[I₀] M) (hI : ↑I ≤ I₀) {π : prepartition I}
(h : π.is_partition) :
∑ J in π.boxes, f J = f I :=
f.sum_partition_boxes' I hI π h
@[simps { fully_applied := ff }] instance : has_zero (ι →ᵇᵃ[I₀] M) :=
⟨⟨0, λ I hI π hπ, sum_const_zero⟩⟩
instance : inhabited (ι →ᵇᵃ[I₀] M) := ⟨0⟩
instance : has_add (ι →ᵇᵃ[I₀] M) :=
⟨λ f g, ⟨f + g, λ I hI π hπ,
by simp only [pi.add_apply, sum_add_distrib, sum_partition_boxes _ hI hπ]⟩⟩
instance {R} [monoid R] [distrib_mul_action R M] : has_smul R (ι →ᵇᵃ[I₀] M) :=
⟨λ r f, ⟨r • f, λ I hI π hπ,
by simp only [pi.smul_apply, ←smul_sum, sum_partition_boxes _ hI hπ]⟩⟩
instance : add_comm_monoid (ι →ᵇᵃ[I₀] M) :=
function.injective.add_comm_monoid _ coe_injective rfl (λ _ _, rfl) (λ _ _, rfl)
@[simp] lemma map_split_add (f : ι →ᵇᵃ[I₀] M) (hI : ↑I ≤ I₀) (i : ι) (x : ℝ) :
(I.split_lower i x).elim 0 f + (I.split_upper i x).elim 0 f = f I :=
by rw [← f.sum_partition_boxes hI (is_partition_split I i x), sum_split_boxes]
/-- If `f` is box-additive on subboxes of `I₀`, then it is box-additive on subboxes of any
`I ≤ I₀`. -/
@[simps] def restrict (f : ι →ᵇᵃ[I₀] M) (I : with_top (box ι)) (hI : I ≤ I₀) : ι →ᵇᵃ[I] M :=
⟨f, λ J hJ, f.2 J (hJ.trans hI)⟩
/-- If `f : box ι → M` is box additive on partitions of the form `split I i x`, then it is box
additive. -/
def of_map_split_add [fintype ι] (f : box ι → M) (I₀ : with_top (box ι))
(hf : ∀ I : box ι, ↑I ≤ I₀ → ∀ {i x}, x ∈ Ioo (I.lower i) (I.upper i) →
(I.split_lower i x).elim 0 f + (I.split_upper i x).elim 0 f = f I) :
ι →ᵇᵃ[I₀] M :=
begin
refine ⟨f, _⟩,
replace hf : ∀ I : box ι, ↑I ≤ I₀ → ∀ s, ∑ J in (split_many I s).boxes, f J = f I,
{ intros I hI s,
induction s using finset.induction_on with a s ha ihs, { simp },
rw [split_many_insert, inf_split, ← ihs, bUnion_boxes, sum_bUnion_boxes],
refine finset.sum_congr rfl (λ J' hJ', _),
by_cases h : a.2 ∈ Ioo (J'.lower a.1) (J'.upper a.1),
{ rw sum_split_boxes,
exact hf _ ((with_top.coe_le_coe.2 $ le_of_mem _ hJ').trans hI) h },
{ rw [split_of_not_mem_Ioo h, top_boxes, finset.sum_singleton] } },
intros I hI π hπ,
have Hle : ∀ J ∈ π, ↑J ≤ I₀, from λ J hJ, (with_top.coe_le_coe.2 $ π.le_of_mem hJ).trans hI,
rcases hπ.exists_split_many_le with ⟨s, hs⟩,
rw [← hf _ hI, ← inf_of_le_right hs, inf_split_many, bUnion_boxes, sum_bUnion_boxes],
exact finset.sum_congr rfl (λ J hJ, (hf _ (Hle _ hJ) _).symm)
end
/-- If `g : M → N` is an additive map and `f` is a box additive map, then `g ∘ f` is a box additive
map. -/
@[simps { fully_applied := ff }] def map (f : ι →ᵇᵃ[I₀] M) (g : M →+ N) :
ι →ᵇᵃ[I₀] N :=
{ to_fun := g ∘ f,
sum_partition_boxes' := λ I hI π hπ, by rw [← g.map_sum, f.sum_partition_boxes hI hπ] }
/-- If `f` is a box additive function on subboxes of `I` and `π₁`, `π₂` are two prepartitions of
`I` that cover the same part of `I`, then `∑ J in π₁.boxes, f J = ∑ J in π₂.boxes, f J`. -/
lemma sum_boxes_congr [finite ι] (f : ι →ᵇᵃ[I₀] M) (hI : ↑I ≤ I₀) {π₁ π₂ : prepartition I}
(h : π₁.Union = π₂.Union) :
∑ J in π₁.boxes, f J = ∑ J in π₂.boxes, f J :=
begin
rcases exists_split_many_inf_eq_filter_of_finite {π₁, π₂} ((finite_singleton _).insert _)
with ⟨s, hs⟩, simp only [inf_split_many] at hs,
rcases ⟨hs _ (or.inl rfl), hs _ (or.inr rfl)⟩ with ⟨h₁, h₂⟩, clear hs,
rw h at h₁,
calc ∑ J in π₁.boxes, f J = ∑ J in π₁.boxes, ∑ J' in (split_many J s).boxes, f J' :
finset.sum_congr rfl (λ J hJ, (f.sum_partition_boxes _ (is_partition_split_many _ _)).symm)
... = ∑ J in (π₁.bUnion (λ J, split_many J s)).boxes, f J : (sum_bUnion_boxes _ _ _).symm
... = ∑ J in (π₂.bUnion (λ J, split_many J s)).boxes, f J : by rw [h₁, h₂]
... = ∑ J in π₂.boxes, ∑ J' in (split_many J s).boxes, f J' : sum_bUnion_boxes _ _ _
... = ∑ J in π₂.boxes, f J :
finset.sum_congr rfl (λ J hJ, (f.sum_partition_boxes _ (is_partition_split_many _ _))),
exacts [(with_top.coe_le_coe.2 $ π₁.le_of_mem hJ).trans hI,
(with_top.coe_le_coe.2 $ π₂.le_of_mem hJ).trans hI]
end
section to_smul
variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E]
/-- If `f` is a box-additive map, then so is the map sending `I` to the scalar multiplication
by `f I` as a continuous linear map from `E` to itself. -/
def to_smul (f : ι →ᵇᵃ[I₀] ℝ) : ι →ᵇᵃ[I₀] (E →L[ℝ] E) :=
f.map (continuous_linear_map.lsmul ℝ ℝ).to_linear_map.to_add_monoid_hom
@[simp] lemma to_smul_apply (f : ι →ᵇᵃ[I₀] ℝ) (I : box ι) (x : E) : f.to_smul I x = f I • x := rfl
end to_smul
/-- Given a box `I₀` in `ℝⁿ⁺¹`, `f x : box (fin n) → G` is a family of functions indexed by a real
`x` and for `x ∈ [I₀.lower i, I₀.upper i]`, `f x` is box-additive on subboxes of the `i`-th face of
`I₀`, then `λ J, f (J.upper i) (J.face i) - f (J.lower i) (J.face i)` is box-additive on subboxes of
`I₀`. -/
@[simps] def {u} upper_sub_lower {G : Type u} [add_comm_group G]
(I₀ : box (fin (n + 1))) (i : fin (n + 1)) (f : ℝ → box (fin n) → G)
(fb : Icc (I₀.lower i) (I₀.upper i) → fin n →ᵇᵃ[I₀.face i] G)
(hf : ∀ x (hx : x ∈ Icc (I₀.lower i) (I₀.upper i)) J, f x J = fb ⟨x, hx⟩ J) :
fin (n + 1) →ᵇᵃ[I₀] G :=
of_map_split_add
(λ J : box (fin (n + 1)), f (J.upper i) (J.face i) - f (J.lower i) (J.face i)) I₀
begin
intros J hJ j,
rw with_top.coe_le_coe at hJ,
refine i.succ_above_cases _ _ j,
{ intros x hx,
simp only [box.split_lower_def hx, box.split_upper_def hx, update_same,
← with_bot.some_eq_coe, option.elim, box.face, (∘), update_noteq (fin.succ_above_ne _ _)],
abel },
{ clear j, intros j x hx,
have : (J.face i : with_top (box (fin n))) ≤ I₀.face i,
from with_top.coe_le_coe.2 (face_mono hJ i),
rw [le_iff_Icc, @box.Icc_eq_pi _ I₀] at hJ,
rw [hf _ (hJ J.upper_mem_Icc _ trivial), hf _ (hJ J.lower_mem_Icc _ trivial),
← (fb _).map_split_add this j x, ← (fb _).map_split_add this j x],
have hx' : x ∈ Ioo ((J.face i).lower j) ((J.face i).upper j) := hx,
simp only [box.split_lower_def hx, box.split_upper_def hx,
box.split_lower_def hx', box.split_upper_def hx',
← with_bot.some_eq_coe, option.elim, box.face_mk,
update_noteq (fin.succ_above_ne _ _).symm, sub_add_sub_comm,
update_comp_eq_of_injective _ i.succ_above.injective j x, ← hf],
simp only [box.face] }
end
end box_additive_map
end box_integral
|
34db34c10138bf2710efc4c800066ab6157d33bb | c777c32c8e484e195053731103c5e52af26a25d1 | /src/measure_theory/integral/vitali_caratheodory.lean | e5e59cfb7fbdd94c81caebcbb5c9877f8d45626a | [
"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 | 29,806 | lean | /-
Copyright (c) 2021 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import measure_theory.measure.regular
import topology.semicontinuous
import measure_theory.integral.bochner
import topology.instances.ereal
/-!
# Vitali-Carathéodory theorem
Vitali-Carathéodory theorem asserts the following. Consider an integrable function `f : α → ℝ` on
a space with a regular measure. Then there exists a function `g : α → ereal` such that `f x < g x`
everywhere, `g` is lower semicontinuous, and the integral of `g` is arbitrarily close to that of
`f`. This theorem is proved in this file, as `exists_lt_lower_semicontinuous_integral_lt`.
Symmetrically, there exists `g < f` which is upper semicontinuous, with integral arbitrarily close
to that of `f`. It follows from the previous statement applied to `-f`. It is formalized under
the name `exists_upper_semicontinuous_lt_integral_gt`.
The most classical version of Vitali-Carathéodory theorem only ensures a large inequality
`f x ≤ g x`. For applications to the fundamental theorem of calculus, though, the strict inequality
`f x < g x` is important. Therefore, we prove the stronger version with strict inequalities in this
file. There is a price to pay: we require that the measure is `σ`-finite, which is not necessary for
the classical Vitali-Carathéodory theorem. Since this is satisfied in all applications, this is
not a real problem.
## Sketch of proof
Decomposing `f` as the difference of its positive and negative parts, it suffices to show that a
positive function can be bounded from above by a lower semicontinuous function, and from below
by an upper semicontinuous function, with integrals close to that of `f`.
For the bound from above, write `f` as a series `∑' n, cₙ * indicator (sₙ)` of simple functions.
Then, approximate `sₙ` by a larger open set `uₙ` with measure very close to that of `sₙ` (this is
possible by regularity of the measure), and set `g = ∑' n, cₙ * indicator (uₙ)`. It is
lower semicontinuous as a series of lower semicontinuous functions, and its integral is arbitrarily
close to that of `f`.
For the bound from below, use finitely many terms in the series, and approximate `sₙ` from inside by
a closed set `Fₙ`. Then `∑ n < N, cₙ * indicator (Fₙ)` is bounded from above by `f`, it is
upper semicontinuous as a finite sum of upper semicontinuous functions, and its integral is
arbitrarily close to that of `f`.
The main pain point in the implementation is that one needs to jump between the spaces `ℝ`, `ℝ≥0`,
`ℝ≥0∞` and `ereal` (and be careful that addition is not well behaved on `ereal`), and between
`lintegral` and `integral`.
We first show the bound from above for simple functions and the nonnegative integral
(this is the main nontrivial mathematical point), then deduce it for general nonnegative functions,
first for the nonnegative integral and then for the Bochner integral.
Then we follow the same steps for the lower bound.
Finally, we glue them together to obtain the main statement
`exists_lt_lower_semicontinuous_integral_lt`.
## Related results
Are you looking for a result on approximation by continuous functions (not just semicontinuous)?
See result `measure_theory.Lp.continuous_map_dense`, in the file
`measure_theory.continuous_map_dense`.
## References
[Rudin, *Real and Complex Analysis* (Theorem 2.24)][rudin2006real]
-/
open_locale ennreal nnreal
open measure_theory measure_theory.measure
variables {α : Type*} [topological_space α] [measurable_space α] [borel_space α] (μ : measure α)
[weakly_regular μ]
namespace measure_theory
local infixr ` →ₛ `:25 := simple_func
/-! ### Lower semicontinuous upper bound for nonnegative functions -/
/-- Given a simple function `f` with values in `ℝ≥0`, there exists a lower semicontinuous
function `g ≥ f` with integral arbitrarily close to that of `f`. Formulation in terms of
`lintegral`.
Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/
lemma simple_func.exists_le_lower_semicontinuous_lintegral_ge (f : α →ₛ ℝ≥0)
{ε : ℝ≥0∞} (ε0 : ε ≠ 0) :
∃ g : α → ℝ≥0, (∀ x, f x ≤ g x) ∧ lower_semicontinuous g ∧
(∫⁻ x, g x ∂μ ≤ ∫⁻ x, f x ∂μ + ε) :=
begin
induction f using measure_theory.simple_func.induction with c s hs f₁ f₂ H h₁ h₂ generalizing ε,
{ let f := simple_func.piecewise s hs (simple_func.const α c) (simple_func.const α 0),
by_cases h : ∫⁻ x, f x ∂μ = ⊤,
{ refine ⟨λ x, c, λ x, _, lower_semicontinuous_const, by simp only [_root_.top_add, le_top, h]⟩,
simp only [simple_func.coe_const, simple_func.const_zero, simple_func.coe_zero,
set.piecewise_eq_indicator, simple_func.coe_piecewise],
exact set.indicator_le_self _ _ _ },
by_cases hc : c = 0,
{ refine ⟨λ x, 0, _, lower_semicontinuous_const, _⟩,
{ simp only [hc, set.indicator_zero', pi.zero_apply, simple_func.const_zero, implies_true_iff,
eq_self_iff_true, simple_func.coe_zero, set.piecewise_eq_indicator,
simple_func.coe_piecewise, le_zero_iff] },
{ simp only [lintegral_const, zero_mul, zero_le, ennreal.coe_zero] } },
have : μ s < μ s + ε / c,
{ have : (0 : ℝ≥0∞) < ε / c := ennreal.div_pos_iff.2 ⟨ε0, ennreal.coe_ne_top⟩,
simpa using ennreal.add_lt_add_left _ this,
simpa only [hs, hc, lt_top_iff_ne_top, true_and, simple_func.coe_const, function.const_apply,
lintegral_const, ennreal.coe_indicator, set.univ_inter, ennreal.coe_ne_top,
measurable_set.univ, with_top.mul_eq_top_iff, simple_func.const_zero, or_false,
lintegral_indicator, ennreal.coe_eq_zero, ne.def, not_false_iff, simple_func.coe_zero,
set.piecewise_eq_indicator, simple_func.coe_piecewise, false_and, restrict_apply] using h },
obtain ⟨u, su, u_open, μu⟩ : ∃ u ⊇ s, is_open u ∧ μ u < μ s + ε / c :=
s.exists_is_open_lt_of_lt _ this,
refine ⟨set.indicator u (λ x, c), λ x, _, u_open.lower_semicontinuous_indicator (zero_le _), _⟩,
{ simp only [simple_func.coe_const, simple_func.const_zero, simple_func.coe_zero,
set.piecewise_eq_indicator, simple_func.coe_piecewise],
exact set.indicator_le_indicator_of_subset su (λ x, zero_le _) _ },
{ suffices : (c : ℝ≥0∞) * μ u ≤ c * μ s + ε, by
simpa only [hs, u_open.measurable_set, simple_func.coe_const, function.const_apply,
lintegral_const, ennreal.coe_indicator, set.univ_inter, measurable_set.univ,
simple_func.const_zero, lintegral_indicator, simple_func.coe_zero,
set.piecewise_eq_indicator, simple_func.coe_piecewise, restrict_apply],
calc (c : ℝ≥0∞) * μ u ≤ c * (μ s + ε / c) : mul_le_mul_left' μu.le _
... = c * μ s + ε :
begin
simp_rw [mul_add],
rw ennreal.mul_div_cancel' _ ennreal.coe_ne_top,
simpa using hc,
end } },
{ rcases h₁ (ennreal.half_pos ε0).ne' with ⟨g₁, f₁_le_g₁, g₁cont, g₁int⟩,
rcases h₂ (ennreal.half_pos ε0).ne' with ⟨g₂, f₂_le_g₂, g₂cont, g₂int⟩,
refine ⟨λ x, g₁ x + g₂ x, λ x, add_le_add (f₁_le_g₁ x) (f₂_le_g₂ x), g₁cont.add g₂cont, _⟩,
simp only [simple_func.coe_add, ennreal.coe_add, pi.add_apply],
rw [lintegral_add_left f₁.measurable.coe_nnreal_ennreal,
lintegral_add_left g₁cont.measurable.coe_nnreal_ennreal],
convert add_le_add g₁int g₂int using 1,
simp only [],
conv_lhs { rw ← ennreal.add_halves ε },
abel }
end
open simple_func (eapprox_diff tsum_eapprox_diff)
/-- Given a measurable function `f` with values in `ℝ≥0`, there exists a lower semicontinuous
function `g ≥ f` with integral arbitrarily close to that of `f`. Formulation in terms of
`lintegral`.
Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/
lemma exists_le_lower_semicontinuous_lintegral_ge
(f : α → ℝ≥0∞) (hf : measurable f) {ε : ℝ≥0∞} (εpos : ε ≠ 0) :
∃ g : α → ℝ≥0∞, (∀ x, f x ≤ g x) ∧ lower_semicontinuous g ∧ (∫⁻ x, g x ∂μ ≤ ∫⁻ x, f x ∂μ + ε) :=
begin
rcases ennreal.exists_pos_sum_of_countable' εpos ℕ with ⟨δ, δpos, hδ⟩,
have : ∀ n, ∃ g : α → ℝ≥0, (∀ x, simple_func.eapprox_diff f n x ≤ g x) ∧ lower_semicontinuous g ∧
(∫⁻ x, g x ∂μ ≤ ∫⁻ x, simple_func.eapprox_diff f n x ∂μ + δ n) :=
λ n, simple_func.exists_le_lower_semicontinuous_lintegral_ge μ
(simple_func.eapprox_diff f n) (δpos n).ne',
choose g f_le_g gcont hg using this,
refine ⟨λ x, (∑' n, g n x), λ x, _, _, _⟩,
{ rw ← tsum_eapprox_diff f hf,
exact ennreal.tsum_le_tsum (λ n, ennreal.coe_le_coe.2 (f_le_g n x)) },
{ apply lower_semicontinuous_tsum (λ n, _),
exact ennreal.continuous_coe.comp_lower_semicontinuous (gcont n)
(λ x y hxy, ennreal.coe_le_coe.2 hxy) },
{ calc ∫⁻ x, ∑' (n : ℕ), g n x ∂μ
= ∑' n, ∫⁻ x, g n x ∂μ :
by rw lintegral_tsum (λ n, (gcont n).measurable.coe_nnreal_ennreal.ae_measurable)
... ≤ ∑' n, (∫⁻ x, eapprox_diff f n x ∂μ + δ n) : ennreal.tsum_le_tsum hg
... = ∑' n, (∫⁻ x, eapprox_diff f n x ∂μ) + ∑' n, δ n : ennreal.tsum_add
... ≤ ∫⁻ (x : α), f x ∂μ + ε :
begin
refine add_le_add _ hδ.le,
rw [← lintegral_tsum],
{ simp_rw [tsum_eapprox_diff f hf, le_refl] },
{ assume n, exact (simple_func.measurable _).coe_nnreal_ennreal.ae_measurable }
end }
end
/-- Given a measurable function `f` with values in `ℝ≥0` in a sigma-finite space, there exists a
lower semicontinuous function `g > f` with integral arbitrarily close to that of `f`.
Formulation in terms of `lintegral`.
Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/
lemma exists_lt_lower_semicontinuous_lintegral_ge [sigma_finite μ]
(f : α → ℝ≥0) (fmeas : measurable f) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) :
∃ g : α → ℝ≥0∞, (∀ x, (f x : ℝ≥0∞) < g x) ∧ lower_semicontinuous g ∧
(∫⁻ x, g x ∂μ ≤ ∫⁻ x, f x ∂μ + ε) :=
begin
have : ε / 2 ≠ 0 := (ennreal.half_pos ε0).ne',
rcases exists_pos_lintegral_lt_of_sigma_finite μ this with ⟨w, wpos, wmeas, wint⟩,
let f' := λ x, ((f x + w x : ℝ≥0) : ℝ≥0∞),
rcases exists_le_lower_semicontinuous_lintegral_ge μ f' (fmeas.add wmeas).coe_nnreal_ennreal this
with ⟨g, le_g, gcont, gint⟩,
refine ⟨g, λ x, _, gcont, _⟩,
{ calc (f x : ℝ≥0∞) < f' x : by simpa [← ennreal.coe_lt_coe] using add_lt_add_left (wpos x) (f x)
... ≤ g x : le_g x },
{ calc ∫⁻ (x : α), g x ∂μ
≤ ∫⁻ (x : α), f x + w x ∂μ + ε / 2 : gint
... = ∫⁻ (x : α), f x ∂ μ + ∫⁻ (x : α), w x ∂ μ + (ε / 2) :
by rw lintegral_add_right _ wmeas.coe_nnreal_ennreal
... ≤ ∫⁻ (x : α), f x ∂ μ + ε / 2 + ε / 2 :
add_le_add_right (add_le_add_left wint.le _) _
... = ∫⁻ (x : α), f x ∂μ + ε : by rw [add_assoc, ennreal.add_halves] },
end
/-- Given an almost everywhere measurable function `f` with values in `ℝ≥0` in a sigma-finite space,
there exists a lower semicontinuous function `g > f` with integral arbitrarily close to that of `f`.
Formulation in terms of `lintegral`.
Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/
lemma exists_lt_lower_semicontinuous_lintegral_ge_of_ae_measurable [sigma_finite μ]
(f : α → ℝ≥0) (fmeas : ae_measurable f μ) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) :
∃ g : α → ℝ≥0∞, (∀ x, (f x : ℝ≥0∞) < g x) ∧ lower_semicontinuous g ∧
(∫⁻ x, g x ∂μ ≤ ∫⁻ x, f x ∂μ + ε) :=
begin
have : ε / 2 ≠ 0 := (ennreal.half_pos ε0).ne',
rcases exists_lt_lower_semicontinuous_lintegral_ge μ (fmeas.mk f) fmeas.measurable_mk this
with ⟨g0, f_lt_g0, g0_cont, g0_int⟩,
rcases exists_measurable_superset_of_null fmeas.ae_eq_mk with ⟨s, hs, smeas, μs⟩,
rcases exists_le_lower_semicontinuous_lintegral_ge μ (s.indicator (λ x, ∞))
(measurable_const.indicator smeas) this
with ⟨g1, le_g1, g1_cont, g1_int⟩,
refine ⟨λ x, g0 x + g1 x, λ x, _, g0_cont.add g1_cont, _⟩,
{ by_cases h : x ∈ s,
{ have := le_g1 x,
simp only [h, set.indicator_of_mem, top_le_iff] at this,
simp [this] },
{ have : f x = fmeas.mk f x,
by { rw set.compl_subset_comm at hs, exact hs h },
rw this,
exact (f_lt_g0 x).trans_le le_self_add } },
{ calc ∫⁻ x, g0 x + g1 x ∂μ = ∫⁻ x, g0 x ∂μ + ∫⁻ x, g1 x ∂μ :
lintegral_add_left g0_cont.measurable _
... ≤ (∫⁻ x, f x ∂μ + ε / 2) + (0 + ε / 2) :
begin
refine add_le_add _ _,
{ convert g0_int using 2,
exact lintegral_congr_ae (fmeas.ae_eq_mk.fun_comp _) },
{ convert g1_int,
simp only [smeas, μs, lintegral_const, set.univ_inter, measurable_set.univ,
lintegral_indicator, mul_zero, restrict_apply] }
end
... = ∫⁻ x, f x ∂μ + ε : by simp only [add_assoc, ennreal.add_halves, zero_add] }
end
variable {μ}
/-- Given an integrable function `f` with values in `ℝ≥0` in a sigma-finite space, there exists a
lower semicontinuous function `g > f` with integral arbitrarily close to that of `f`.
Formulation in terms of `integral`.
Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/
lemma exists_lt_lower_semicontinuous_integral_gt_nnreal [sigma_finite μ] (f : α → ℝ≥0)
(fint : integrable (λ x, (f x : ℝ)) μ) {ε : ℝ} (εpos : 0 < ε) :
∃ g : α → ℝ≥0∞, (∀ x, (f x : ℝ≥0∞) < g x) ∧ lower_semicontinuous g ∧ (∀ᵐ x ∂ μ, g x < ⊤)
∧ (integrable (λ x, (g x).to_real) μ) ∧ (∫ x, (g x).to_real ∂μ < ∫ x, f x ∂μ + ε) :=
begin
have fmeas : ae_measurable f μ,
by { convert fint.ae_strongly_measurable.real_to_nnreal.ae_measurable, ext1 x,
simp only [real.to_nnreal_coe] },
lift ε to ℝ≥0 using εpos.le,
obtain ⟨δ, δpos, hδε⟩ : ∃ δ : ℝ≥0, 0 < δ ∧ δ < ε, from exists_between εpos,
have int_f_ne_top : ∫⁻ (a : α), (f a) ∂μ ≠ ∞ :=
(has_finite_integral_iff_of_nnreal.1 fint.has_finite_integral).ne,
rcases exists_lt_lower_semicontinuous_lintegral_ge_of_ae_measurable μ f fmeas
(ennreal.coe_ne_zero.2 δpos.ne')
with ⟨g, f_lt_g, gcont, gint⟩,
have gint_ne : ∫⁻ (x : α), g x ∂μ ≠ ∞ := ne_top_of_le_ne_top (by simpa) gint,
have g_lt_top : ∀ᵐ (x : α) ∂μ, g x < ∞ := ae_lt_top gcont.measurable gint_ne,
have Ig : ∫⁻ (a : α), ennreal.of_real (g a).to_real ∂μ = ∫⁻ (a : α), g a ∂μ,
{ apply lintegral_congr_ae,
filter_upwards [g_lt_top] with _ hx,
simp only [hx.ne, ennreal.of_real_to_real, ne.def, not_false_iff], },
refine ⟨g, f_lt_g, gcont, g_lt_top, _, _⟩,
{ refine ⟨gcont.measurable.ennreal_to_real.ae_measurable.ae_strongly_measurable, _⟩,
simp only [has_finite_integral_iff_norm, real.norm_eq_abs,
abs_of_nonneg ennreal.to_real_nonneg],
convert gint_ne.lt_top using 1 },
{ rw [integral_eq_lintegral_of_nonneg_ae, integral_eq_lintegral_of_nonneg_ae],
{ calc
ennreal.to_real (∫⁻ (a : α), ennreal.of_real (g a).to_real ∂μ)
= ennreal.to_real (∫⁻ (a : α), g a ∂μ) : by congr' 1
... ≤ ennreal.to_real (∫⁻ (a : α), f a ∂μ + δ) :
begin
apply ennreal.to_real_mono _ gint,
simpa using int_f_ne_top,
end
... = ennreal.to_real (∫⁻ (a : α), f a ∂μ) + δ :
by rw [ennreal.to_real_add int_f_ne_top ennreal.coe_ne_top, ennreal.coe_to_real]
... < ennreal.to_real (∫⁻ (a : α), f a ∂μ) + ε :
add_lt_add_left hδε _
... = (∫⁻ (a : α), ennreal.of_real ↑(f a) ∂μ).to_real + ε :
by simp },
{ apply filter.eventually_of_forall (λ x, _), simp },
{ exact fmeas.coe_nnreal_real.ae_strongly_measurable, },
{ apply filter.eventually_of_forall (λ x, _), simp },
{ apply gcont.measurable.ennreal_to_real.ae_measurable.ae_strongly_measurable } }
end
/-! ### Upper semicontinuous lower bound for nonnegative functions -/
/-- Given a simple function `f` with values in `ℝ≥0`, there exists an upper semicontinuous
function `g ≤ f` with integral arbitrarily close to that of `f`. Formulation in terms of
`lintegral`.
Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/
lemma simple_func.exists_upper_semicontinuous_le_lintegral_le
(f : α →ₛ ℝ≥0) (int_f : ∫⁻ x, f x ∂μ ≠ ∞) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) :
∃ g : α → ℝ≥0, (∀ x, g x ≤ f x) ∧ upper_semicontinuous g ∧ (∫⁻ x, f x ∂μ ≤ ∫⁻ x, g x ∂μ + ε) :=
begin
induction f using measure_theory.simple_func.induction with c s hs f₁ f₂ H h₁ h₂ generalizing ε,
{ let f := simple_func.piecewise s hs (simple_func.const α c) (simple_func.const α 0),
by_cases hc : c = 0,
{ refine ⟨λ x, 0, _, upper_semicontinuous_const, _⟩,
{ simp only [hc, set.indicator_zero', pi.zero_apply, simple_func.const_zero, implies_true_iff,
eq_self_iff_true, simple_func.coe_zero, set.piecewise_eq_indicator,
simple_func.coe_piecewise, le_zero_iff] },
{ simp only [hc, set.indicator_zero', lintegral_const, zero_mul, pi.zero_apply,
simple_func.const_zero, zero_add, zero_le', simple_func.coe_zero,
set.piecewise_eq_indicator, ennreal.coe_zero, simple_func.coe_piecewise, zero_le] } },
have μs_lt_top : μ s < ∞,
by simpa only [hs, hc, lt_top_iff_ne_top, true_and, simple_func.coe_const, or_false,
lintegral_const, ennreal.coe_indicator, set.univ_inter, ennreal.coe_ne_top, restrict_apply
measurable_set.univ, with_top.mul_eq_top_iff, simple_func.const_zero, function.const_apply,
lintegral_indicator, ennreal.coe_eq_zero, ne.def, not_false_iff, simple_func.coe_zero,
set.piecewise_eq_indicator, simple_func.coe_piecewise, false_and] using int_f,
have : (0 : ℝ≥0∞) < ε / c := ennreal.div_pos_iff.2 ⟨ε0, ennreal.coe_ne_top⟩,
obtain ⟨F, Fs, F_closed, μF⟩ : ∃ F ⊆ s, is_closed F ∧ μ s < μ F + ε / c :=
hs.exists_is_closed_lt_add μs_lt_top.ne this.ne',
refine ⟨set.indicator F (λ x, c), λ x, _,
F_closed.upper_semicontinuous_indicator (zero_le _), _⟩,
{ simp only [simple_func.coe_const, simple_func.const_zero, simple_func.coe_zero,
set.piecewise_eq_indicator, simple_func.coe_piecewise],
exact set.indicator_le_indicator_of_subset Fs (λ x, zero_le _) _ },
{ suffices : (c : ℝ≥0∞) * μ s ≤ c * μ F + ε,
by simpa only [hs, F_closed.measurable_set, simple_func.coe_const, function.const_apply,
lintegral_const, ennreal.coe_indicator, set.univ_inter, measurable_set.univ,
simple_func.const_zero, lintegral_indicator, simple_func.coe_zero,
set.piecewise_eq_indicator, simple_func.coe_piecewise, restrict_apply],
calc (c : ℝ≥0∞) * μ s ≤ c * (μ F + ε / c) : mul_le_mul_left' μF.le _
... = c * μ F + ε :
begin
simp_rw [mul_add],
rw ennreal.mul_div_cancel' _ ennreal.coe_ne_top,
simpa using hc,
end } },
{ have A : ∫⁻ (x : α), f₁ x ∂μ + ∫⁻ (x : α), f₂ x ∂μ ≠ ⊤,
by rwa ← lintegral_add_left f₁.measurable.coe_nnreal_ennreal,
rcases h₁ (ennreal.add_ne_top.1 A).1 (ennreal.half_pos ε0).ne'
with ⟨g₁, f₁_le_g₁, g₁cont, g₁int⟩,
rcases h₂ (ennreal.add_ne_top.1 A).2 (ennreal.half_pos ε0).ne'
with ⟨g₂, f₂_le_g₂, g₂cont, g₂int⟩,
refine ⟨λ x, g₁ x + g₂ x, λ x, add_le_add (f₁_le_g₁ x) (f₂_le_g₂ x), g₁cont.add g₂cont, _⟩,
simp only [simple_func.coe_add, ennreal.coe_add, pi.add_apply],
rw [lintegral_add_left f₁.measurable.coe_nnreal_ennreal,
lintegral_add_left g₁cont.measurable.coe_nnreal_ennreal],
convert add_le_add g₁int g₂int using 1,
simp only [],
conv_lhs { rw ← ennreal.add_halves ε },
abel }
end
/-- Given an integrable function `f` with values in `ℝ≥0`, there exists an upper semicontinuous
function `g ≤ f` with integral arbitrarily close to that of `f`. Formulation in terms of
`lintegral`.
Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/
lemma exists_upper_semicontinuous_le_lintegral_le
(f : α → ℝ≥0) (int_f : ∫⁻ x, f x ∂μ ≠ ∞) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) :
∃ g : α → ℝ≥0, (∀ x, g x ≤ f x) ∧ upper_semicontinuous g ∧ (∫⁻ x, f x ∂μ ≤ ∫⁻ x, g x ∂μ + ε) :=
begin
obtain ⟨fs, fs_le_f, int_fs⟩ : ∃ (fs : α →ₛ ℝ≥0), (∀ x, fs x ≤ f x) ∧
(∫⁻ x, f x ∂μ ≤ ∫⁻ x, fs x ∂μ + ε/2) :=
begin
have := ennreal.lt_add_right int_f (ennreal.half_pos ε0).ne',
conv_rhs at this { rw lintegral_eq_nnreal (λ x, (f x : ℝ≥0∞)) μ },
erw ennreal.bsupr_add at this; [skip, exact ⟨0, λ x, by simp⟩],
simp only [lt_supr_iff] at this,
rcases this with ⟨fs, fs_le_f, int_fs⟩,
refine ⟨fs, λ x, by simpa only [ennreal.coe_le_coe] using fs_le_f x, _⟩,
convert int_fs.le,
rw ← simple_func.lintegral_eq_lintegral,
refl
end,
have int_fs_lt_top : ∫⁻ x, fs x ∂μ ≠ ∞,
{ apply ne_top_of_le_ne_top int_f (lintegral_mono (λ x, _)),
simpa only [ennreal.coe_le_coe] using fs_le_f x },
obtain ⟨g, g_le_fs, gcont, gint⟩ : ∃ g : α → ℝ≥0,
(∀ x, g x ≤ fs x) ∧ upper_semicontinuous g ∧ (∫⁻ x, fs x ∂μ ≤ ∫⁻ x, g x ∂μ + ε/2) :=
fs.exists_upper_semicontinuous_le_lintegral_le int_fs_lt_top (ennreal.half_pos ε0).ne',
refine ⟨g, λ x, (g_le_fs x).trans (fs_le_f x), gcont, _⟩,
calc ∫⁻ x, f x ∂μ ≤ ∫⁻ x, fs x ∂μ + ε / 2 : int_fs
... ≤ (∫⁻ x, g x ∂μ + ε / 2) + ε / 2 : add_le_add gint le_rfl
... = ∫⁻ x, g x ∂μ + ε : by rw [add_assoc, ennreal.add_halves]
end
/-- Given an integrable function `f` with values in `ℝ≥0`, there exists an upper semicontinuous
function `g ≤ f` with integral arbitrarily close to that of `f`. Formulation in terms of
`integral`.
Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/
lemma exists_upper_semicontinuous_le_integral_le (f : α → ℝ≥0)
(fint : integrable (λ x, (f x : ℝ)) μ) {ε : ℝ} (εpos : 0 < ε) :
∃ g : α → ℝ≥0, (∀ x, g x ≤ f x) ∧ upper_semicontinuous g ∧ (integrable (λ x, (g x : ℝ)) μ)
∧ (∫ x, (f x : ℝ) ∂μ - ε ≤ ∫ x, g x ∂μ) :=
begin
lift ε to ℝ≥0 using εpos.le,
rw [nnreal.coe_pos, ← ennreal.coe_pos] at εpos,
have If : ∫⁻ x, f x ∂ μ < ∞ := has_finite_integral_iff_of_nnreal.1 fint.has_finite_integral,
rcases exists_upper_semicontinuous_le_lintegral_le f If.ne εpos.ne' with ⟨g, gf, gcont, gint⟩,
have Ig : ∫⁻ x, g x ∂ μ < ∞,
{ apply lt_of_le_of_lt (lintegral_mono (λ x, _)) If,
simpa using gf x },
refine ⟨g, gf, gcont, _, _⟩,
{ refine integrable.mono fint
gcont.measurable.coe_nnreal_real.ae_measurable.ae_strongly_measurable _,
exact filter.eventually_of_forall (λ x, by simp [gf x]) },
{ rw [integral_eq_lintegral_of_nonneg_ae, integral_eq_lintegral_of_nonneg_ae],
{ rw sub_le_iff_le_add,
convert ennreal.to_real_mono _ gint,
{ simp, },
{ rw ennreal.to_real_add Ig.ne ennreal.coe_ne_top, simp },
{ simpa using Ig.ne } },
{ apply filter.eventually_of_forall, simp },
{ exact gcont.measurable.coe_nnreal_real.ae_measurable.ae_strongly_measurable },
{ apply filter.eventually_of_forall, simp },
{ exact fint.ae_strongly_measurable } }
end
/-! ### Vitali-Carathéodory theorem -/
/-- **Vitali-Carathéodory Theorem**: given an integrable real function `f`, there exists an
integrable function `g > f` which is lower semicontinuous, with integral arbitrarily close
to that of `f`. This function has to be `ereal`-valued in general. -/
lemma exists_lt_lower_semicontinuous_integral_lt [sigma_finite μ]
(f : α → ℝ) (hf : integrable f μ) {ε : ℝ} (εpos : 0 < ε) :
∃ g : α → ereal, (∀ x, (f x : ereal) < g x) ∧ lower_semicontinuous g ∧
(integrable (λ x, ereal.to_real (g x)) μ) ∧ (∀ᵐ x ∂ μ, g x < ⊤) ∧
(∫ x, ereal.to_real (g x) ∂μ < ∫ x, f x ∂μ + ε) :=
begin
let δ : ℝ≥0 := ⟨ε/2, (half_pos εpos).le⟩,
have δpos : 0 < δ := half_pos εpos,
let fp : α → ℝ≥0 := λ x, real.to_nnreal (f x),
have int_fp : integrable (λ x, (fp x : ℝ)) μ := hf.real_to_nnreal,
rcases exists_lt_lower_semicontinuous_integral_gt_nnreal fp int_fp δpos
with ⟨gp, fp_lt_gp, gpcont, gp_lt_top, gp_integrable, gpint⟩,
let fm : α → ℝ≥0 := λ x, real.to_nnreal (-f x),
have int_fm : integrable (λ x, (fm x : ℝ)) μ := hf.neg.real_to_nnreal,
rcases exists_upper_semicontinuous_le_integral_le fm int_fm δpos
with ⟨gm, gm_le_fm, gmcont, gm_integrable, gmint⟩,
let g : α → ereal := λ x, (gp x : ereal) - (gm x),
have ae_g : ∀ᵐ x ∂ μ, (g x).to_real = (gp x : ereal).to_real - (gm x : ereal).to_real,
{ filter_upwards [gp_lt_top] with _ hx,
rw ereal.to_real_sub;
simp [hx.ne], },
refine ⟨g, _, _, _, _, _⟩,
show integrable (λ x, ereal.to_real (g x)) μ,
{ rw integrable_congr ae_g,
convert gp_integrable.sub gm_integrable,
ext x,
simp },
show ∫ (x : α), (g x).to_real ∂μ < ∫ (x : α), f x ∂μ + ε, from calc
∫ (x : α), (g x).to_real ∂μ = ∫ (x : α), ereal.to_real (gp x) - ereal.to_real (gm x) ∂μ :
integral_congr_ae ae_g
... = ∫ (x : α), ereal.to_real (gp x) ∂ μ - ∫ (x : α), gm x ∂μ :
begin
simp only [ereal.to_real_coe_ennreal, ennreal.coe_to_real, coe_coe],
exact integral_sub gp_integrable gm_integrable,
end
... < ∫ (x : α), ↑(fp x) ∂μ + ↑δ - ∫ (x : α), gm x ∂μ :
begin
apply sub_lt_sub_right,
convert gpint,
simp only [ereal.to_real_coe_ennreal],
end
... ≤ ∫ (x : α), ↑(fp x) ∂μ + ↑δ - (∫ (x : α), fm x ∂μ - δ) :
sub_le_sub_left gmint _
... = ∫ (x : α), f x ∂μ + 2 * δ :
by { simp_rw [integral_eq_integral_pos_part_sub_integral_neg_part hf, fp, fm], ring }
... = ∫ (x : α), f x ∂μ + ε :
by { congr' 1, field_simp [δ, mul_comm] },
show ∀ᵐ (x : α) ∂μ, g x < ⊤,
{ filter_upwards [gp_lt_top] with _ hx,
simp only [g, sub_eq_add_neg, coe_coe, ne.def, (ereal.add_lt_top _ _).ne, lt_top_iff_ne_top,
lt_top_iff_ne_top.1 hx, ereal.coe_ennreal_eq_top_iff, not_false_iff, ereal.neg_eq_top_iff,
ereal.coe_ennreal_ne_bot] },
show ∀ x, (f x : ereal) < g x,
{ assume x,
rw ereal.coe_real_ereal_eq_coe_to_nnreal_sub_coe_to_nnreal (f x),
refine ereal.sub_lt_sub_of_lt_of_le _ _ _ _,
{ simp only [ereal.coe_ennreal_lt_coe_ennreal_iff, coe_coe], exact (fp_lt_gp x) },
{ simp only [ennreal.coe_le_coe, ereal.coe_ennreal_le_coe_ennreal_iff, coe_coe],
exact (gm_le_fm x) },
{ simp only [ereal.coe_ennreal_ne_bot, ne.def, not_false_iff, coe_coe] },
{ simp only [ereal.coe_nnreal_ne_top, ne.def, not_false_iff, coe_coe] } },
show lower_semicontinuous g,
{ apply lower_semicontinuous.add',
{ exact continuous_coe_ennreal_ereal.comp_lower_semicontinuous gpcont
(λ x y hxy, ereal.coe_ennreal_le_coe_ennreal_iff.2 hxy) },
{ apply ereal.continuous_neg.comp_upper_semicontinuous_antitone _
(λ x y hxy, ereal.neg_le_neg_iff.2 hxy),
dsimp,
apply continuous_coe_ennreal_ereal.comp_upper_semicontinuous _
(λ x y hxy, ereal.coe_ennreal_le_coe_ennreal_iff.2 hxy),
exact ennreal.continuous_coe.comp_upper_semicontinuous gmcont
(λ x y hxy, ennreal.coe_le_coe.2 hxy) },
{ assume x,
exact ereal.continuous_at_add (by simp) (by simp) } }
end
/-- **Vitali-Carathéodory Theorem**: given an integrable real function `f`, there exists an
integrable function `g < f` which is upper semicontinuous, with integral arbitrarily close to that
of `f`. This function has to be `ereal`-valued in general. -/
lemma exists_upper_semicontinuous_lt_integral_gt [sigma_finite μ]
(f : α → ℝ) (hf : integrable f μ) {ε : ℝ} (εpos : 0 < ε) :
∃ g : α → ereal, (∀ x, (g x : ereal) < f x) ∧ upper_semicontinuous g ∧
(integrable (λ x, ereal.to_real (g x)) μ) ∧ (∀ᵐ x ∂μ, ⊥ < g x) ∧
(∫ x, f x ∂μ < ∫ x, ereal.to_real (g x) ∂μ + ε) :=
begin
rcases exists_lt_lower_semicontinuous_integral_lt (λ x, - f x) hf.neg εpos
with ⟨g, g_lt_f, gcont, g_integrable, g_lt_top, gint⟩,
refine ⟨λ x, - g x, _, _, _, _, _⟩,
{ exact λ x, ereal.neg_lt_iff_neg_lt.1 (by simpa only [ereal.coe_neg] using g_lt_f x) },
{ exact ereal.continuous_neg.comp_lower_semicontinuous_antitone gcont
(λ x y hxy, ereal.neg_le_neg_iff.2 hxy) },
{ convert g_integrable.neg,
ext x,
simp },
{ simpa [bot_lt_iff_ne_bot, lt_top_iff_ne_top] using g_lt_top },
{ simp_rw [integral_neg, lt_neg_add_iff_add_lt] at gint,
rw add_comm at gint,
simpa [integral_neg] using gint }
end
end measure_theory
|
418295cd65c76c570149f78078a60dab83def906 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/tidy_auto.lean | 35f6a84d23fe165dcf64a8c849bbbf96c3a78d61 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,333 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.auto_cases
import Mathlib.tactic.chain
import Mathlib.tactic.norm_cast
import Mathlib.PostPort
namespace Mathlib
namespace tactic
namespace tidy
/-- Tag interactive tactics (locally) with `[tidy]` to add them to the list of default tactics
called by `tidy`. -/
end tidy
namespace interactive
/-- Use a variety of conservative tactics to solve goals.
`tidy?` reports back the tactic script it found. As an example
```lean
example : ∀ x : unit, x = unit.star :=
begin
tidy? -- Prints the trace message: "Try this: intros x, exact dec_trivial"
end
```
The default list of tactics is stored in `tactic.tidy.default_tidy_tactics`.
This list can be overridden using `tidy { tactics := ... }`.
(The list must be a `list` of `tactic string`, so that `tidy?`
can report a usable tactic script.)
Tactics can also be added to the list by tagging them (locally) with the
`[tidy]` attribute. -/
end interactive
/-- Invoking the hole command `tidy` ("Use `tidy` to complete the goal") runs the tactic of
the same name, replacing the hole with the tactic script `tidy` produces.
-/
end Mathlib |
c767e09dedd815e6b78c0915ab1ec5f6adec4e9d | 4e0d7c3132ce31edc5829849735dd25db406b144 | /lean/love12_basic_mathematical_structures_exercise_sheet.lean | a6568331cf53fb13f690b1038bf332db43f83bbe | [] | no_license | gonzalgu/logical_verification_2020 | a0013a6c22ea254e9f4d245f2948f0f4d44df4bb | 724d0457dff2c3ff10f9ab2170388f4c5e958b75 | refs/heads/master | 1,660,886,374,533 | 1,589,859,641,000 | 1,589,859,641,000 | 256,069,971 | 0 | 0 | null | 1,586,997,430,000 | 1,586,997,429,000 | null | UTF-8 | Lean | false | false | 3,909 | lean | import .love12_basic_mathematical_structures_demo
/-! # LoVe Exercise 12: Basic Mathematical Structures -/
set_option pp.beta true
namespace LoVe
/-! ## Question 1: Type Classes
Recall the datatype `btree` we introduced earlier: -/
#check btree
/-! The following function takes two trees and attaches copies of the second
tree to each leaf of the first tree. -/
def btree.graft {α : Type} : btree α → btree α → btree α
| btree.empty u := u
| (btree.node a l r) u := btree.node a (btree.graft l u) (btree.graft r u)
#reduce btree.graft (btree.node 1 btree.empty btree.empty)
(btree.node 2 btree.empty btree.empty)
/-! 1.1. Prove the following two lemmas by structural induction on `t`. -/
lemma btree.graft_assoc {α : Type} (t u v : btree α) :
btree.graft (btree.graft t u) v = btree.graft t (btree.graft u v) :=
begin
induction t with a tl tr htl htr,
{
simp [btree.graft],
},
{
simp [btree.graft, htl, htr],
}
end
lemma btree.graft_empty {α : Type} (t : btree α) :
btree.graft t btree.empty = t :=
begin
induction t with a tl tr htl htr,
{
refl,
},
{
simp [btree.graft, htl, htr],
}
end
/-! 1.2. Declare btree an instance of `add_monoid` using `graft` as addition
operator. -/
#print add_monoid
@[instance] def btree.add_monid {α : Type} : add_monoid (btree α) :=
{
add := btree.graft,
add_assoc := btree.graft_assoc,
zero := btree.empty,
zero_add :=
begin
intro t,
refl,
end,
add_zero := btree.graft_empty,
}
/-! 1.3. Explain why `btree` with `graft` as addition cannot be declared an
instance of `add_group`. -/
#print add_group
/- For any btree t, there is no 'inverse tree' t⁻¹ such that btree.graft t t⁻¹ = btree.nil
In other words, for a given tree t, there is no tree w that can be grafted onto t
and produce an empty tree.
-/
/-! 1.4 (**optional**). Prove the following lemma illustrating why `btree` with
`graft` as addition does not constitute an `add_group`. -/
lemma btree.add_left_neg_counterexample :
∃x : btree ℕ, ∀ y : btree ℕ, btree.graft y x ≠ btree.empty :=
⟨ (btree.node 1 btree.empty btree.empty),
λ t : btree ℕ,
begin
induction t with a tl tr htl htr,
{
intro h,
cases h,
},
{
simp [btree.graft],
}
end
⟩
/-! ## Question 2: Multisets and Finsets
Recall the following definitions from the lecture: -/
#check multiset.elems
#check finset.elems
#check list.elems
/-! 2.1. Prove that the multiset of nodes does not change when mirroring a tree.
Hints:
* Perform structural induction on `t`.
* The `cc` tactic also works with set operations. -/
lemma multiset.elems_mirror (t : btree ℕ) :
multiset.elems (mirror t) = multiset.elems t :=
begin
induction t with a tl tr htl htr,
{
simp [mirror],
},
{
simp [mirror, multiset.elems, htl, htr],
cc,
}
end
/-! 2.2. Prove that the finite set of nodes does not change when mirroring a
tree. -/
lemma finset.elems_mirror (t : btree ℕ) :
finset.elems (mirror t) = finset.elems t :=
begin
induction t with a tl tr htl htr,
{
simp [mirror],
},
{
simp [mirror, finset.elems, htl, htr],
}
end
/-! 2.3. Show that this does not hold for the list of nodes by providing a
tree `t` for which `nodes_list t ≠ nodes_list (mirror t)`.
If you define a suitable counterexample, the proof below will succeed. -/
def rotten_tree : btree ℕ :=
(btree.node 1 (btree.node 5 btree.empty btree.empty) (btree.node 2 (btree.node 3 btree.empty btree.empty) btree.empty))
#print rotten_tree
#eval rotten_tree
#eval mirror rotten_tree
#eval list.elems rotten_tree
#eval list.elems (mirror rotten_tree)
lemma list.elems_mirror_counterexample :
∃t : btree ℕ, list.elems t ≠ list.elems (mirror t) :=
begin
apply exists.intro rotten_tree,
exact dec_trivial
end
end LoVe
|
4618e2c1a48f979fe44e4f7e44c0930f15ca58da | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Elab/Deriving/Basic.lean | 6fd387d5dfaa24190ca0603305a4ca27852a7467 | [
"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 | 5,862 | 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, Wojciech Nawrocki
-/
import Lean.Elab.Command
namespace Lean.Elab
open Command
namespace Term
open Meta
/-- Result for `mkInst?` -/
structure MkInstResult where
instVal : Expr
instType : Expr
outParams : Array Expr := #[]
/--
Construct an instance for `className out₁ ... outₙ type`.
The method support classes with a prefix of `outParam`s (e.g. `MonadReader`). -/
private partial def mkInst? (className : Name) (type : Expr) : MetaM (Option MkInstResult) := do
let rec go? (instType instTypeType : Expr) (outParams : Array Expr) : MetaM (Option MkInstResult) := do
let instTypeType ← whnfD instTypeType
unless instTypeType.isForall do
return none
let d := instTypeType.bindingDomain!
if d.isOutParam then
let mvar ← mkFreshExprMVar d
go? (mkApp instType mvar) (instTypeType.bindingBody!.instantiate1 mvar) (outParams.push mvar)
else
unless (← isDefEqGuarded (← inferType type) d) do
return none
let instType ← instantiateMVars (mkApp instType type)
let instVal ← synthInstance instType
return some { instVal, instType, outParams }
let instType ← mkConstWithFreshMVarLevels className
go? instType (← inferType instType) #[]
def processDefDeriving (className : Name) (declName : Name) : TermElabM Bool := do
try
let ConstantInfo.defnInfo info ← getConstInfo declName | return false
let some result ← mkInst? className info.value | return false
let instTypeNew := mkApp result.instType.appFn! (Lean.mkConst declName (info.levelParams.map mkLevelParam))
Meta.check instTypeNew
let instName ← liftMacroM <| mkUnusedBaseName (declName.appendBefore "inst" |>.appendAfter className.getString!)
addAndCompile <| Declaration.defnDecl {
name := instName
levelParams := info.levelParams
type := (← instantiateMVars instTypeNew)
value := (← instantiateMVars result.instVal)
hints := info.hints
safety := info.safety
}
addInstance instName AttributeKind.global (eval_prio default)
return true
catch _ =>
return false
end Term
def DerivingHandler := (typeNames : Array Name) → (args? : Option (TSyntax ``Parser.Term.structInst)) → CommandElabM Bool
def DerivingHandlerNoArgs := (typeNames : Array Name) → CommandElabM Bool
builtin_initialize derivingHandlersRef : IO.Ref (NameMap (List DerivingHandler)) ← IO.mkRef {}
/-- A `DerivingHandler` is called on the fully qualified names of all types it is running for
as well as the syntax of a `with` argument, if present.
For example, `deriving instance Foo with fooArgs for Bar, Baz` invokes
``fooHandler #[`Bar, `Baz] `(fooArgs)``. -/
def registerDerivingHandlerWithArgs (className : Name) (handler : DerivingHandler) : IO Unit := do
unless (← initializing) do
throw (IO.userError "failed to register deriving handler, it can only be registered during initialization")
derivingHandlersRef.modify fun m => match m.find? className with
| some handlers => m.insert className (handler :: handlers)
| none => m.insert className [handler]
/-- Like `registerBuiltinDerivingHandlerWithArgs` but ignoring any `with` argument. -/
def registerDerivingHandler (className : Name) (handler : DerivingHandlerNoArgs) : IO Unit := do
registerDerivingHandlerWithArgs className fun typeNames _ => handler typeNames
def defaultHandler (className : Name) (typeNames : Array Name) : CommandElabM Unit := do
throwError "default handlers have not been implemented yet, class: '{className}' types: {typeNames}"
def applyDerivingHandlers (className : Name) (typeNames : Array Name) (args? : Option (TSyntax ``Parser.Term.structInst)) : CommandElabM Unit := do
match (← derivingHandlersRef.get).find? className with
| some handlers =>
for handler in handlers do
if (← handler typeNames args?) then
return ()
defaultHandler className typeNames
| none => defaultHandler className typeNames
private def tryApplyDefHandler (className : Name) (declName : Name) : CommandElabM Bool :=
liftTermElabM do
Term.processDefDeriving className declName
@[builtin_command_elab «deriving»] def elabDeriving : CommandElab
| `(deriving instance $[$classes $[with $argss?]?],* for $[$declNames],*) => do
let declNames ← declNames.mapM resolveGlobalConstNoOverloadWithInfo
for cls in classes, args? in argss? do
try
let className ← resolveGlobalConstNoOverloadWithInfo cls
withRef cls do
if declNames.size == 1 && args?.isNone then
if (← tryApplyDefHandler className declNames[0]!) then
return ()
applyDerivingHandlers className declNames args?
catch ex =>
logException ex
| _ => throwUnsupportedSyntax
structure DerivingClassView where
ref : Syntax
className : Name
args? : Option (TSyntax ``Parser.Term.structInst)
def getOptDerivingClasses [Monad m] [MonadEnv m] [MonadResolveName m] [MonadError m] [MonadInfoTree m] (optDeriving : Syntax) : m (Array DerivingClassView) := do
match optDeriving with
| `(Parser.Command.optDeriving| deriving $[$classes $[with $argss?]?],*) =>
let mut ret := #[]
for cls in classes, args? in argss? do
let className ← resolveGlobalConstNoOverloadWithInfo cls
ret := ret.push { ref := cls, className := className, args? }
return ret
| _ => return #[]
def DerivingClassView.applyHandlers (view : DerivingClassView) (declNames : Array Name) : CommandElabM Unit :=
withRef view.ref do applyDerivingHandlers view.className declNames view.args?
builtin_initialize
registerTraceClass `Elab.Deriving
end Lean.Elab
|
cf1bb289b22024f7ec7e225e7190aa212b5ec5e1 | 46125763b4dbf50619e8846a1371029346f4c3db | /test/lint.lean | 1aae822d78bcf0fc2707dfcf361f7f6f6710c8d3 | [
"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 | 4,661 | lean | import tactic.lint
def foo1 (n m : ℕ) : ℕ := n + 1
def foo2 (n m : ℕ) : m = m := by refl
lemma foo3 (n m : ℕ) : ℕ := n - m
lemma foo.foo (n m : ℕ) : n ≥ n := le_refl n
instance bar.bar : has_add ℕ := by apply_instance -- we don't check the name of instances
lemma foo.bar (ε > 0) : ε = ε := rfl -- >/≥ is allowed in binders (and in fact, in all hypotheses)
-- section
-- local attribute [instance, priority 1001] classical.prop_decidable
-- lemma foo4 : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl)
-- end
open tactic
meta def fold_over_with_cond {α} (l : list declaration) (tac : declaration → tactic (option α)) :
tactic (list (declaration × α)) :=
l.mmap_filter $ λ d, option.map (λ x, (d, x)) <$> tac d
run_cmd do
let t := name × list ℕ,
e ← get_env,
l ← e.mfilter (λ d, return $
e.in_current_file' d.to_name && ¬ d.to_name.is_internal && ¬ d.is_auto_generated e),
l2 ← fold_over_with_cond l (return ∘ check_unused_arguments),
guard $ l2.length = 4,
let l2 : list t := l2.map $ λ x, ⟨x.1.to_name, x.2⟩,
guard $ (⟨`foo1, [2]⟩ : t) ∈ l2,
guard $ (⟨`foo2, [1]⟩ : t) ∈ l2,
guard $ (⟨`foo.foo, [2]⟩ : t) ∈ l2,
guard $ (⟨`foo.bar, [2]⟩ : t) ∈ l2,
l2 ← fold_over_with_cond l incorrect_def_lemma,
guard $ l2.length = 2,
let l2 : list (name × _) := l2.map $ λ x, ⟨x.1.to_name, x.2⟩,
guard $ ∃(x ∈ l2), (x : name × _).1 = `foo2,
guard $ ∃(x ∈ l2), (x : name × _).1 = `foo3,
l3 ← fold_over_with_cond l dup_namespace,
guard $ l3.length = 1,
guard $ ∃(x ∈ l3), (x : declaration × _).1.to_name = `foo.foo,
l4 ← fold_over_with_cond l ge_or_gt_in_statement,
guard $ l4.length = 1,
guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo.foo,
-- guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo4,
(_, s) ← lint ff,
guard $ "/- (slow tests skipped) -/\n".is_suffix_of s.to_string,
(_, s2) ← lint tt,
guard $ s.to_string ≠ s2.to_string,
skip
/- check customizability and nolint -/
meta def dummy_check (d : declaration) : tactic (option string) :=
return $ if d.to_name.last = "foo" then some "gotcha!" else none
meta def linter.dummy_linter : linter :=
{ test := dummy_check,
no_errors_found := "found nothing",
errors_found := "found something" }
@[nolint dummy_linter]
def bar.foo : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl)
run_cmd do
(_, s) ← lint tt tt [`linter.dummy_linter] tt,
guard $ "/- found something: -/\n#print foo.foo /- gotcha! -/".is_suffix_of s.to_string
def incorrect_type_class_argument_test {α : Type} (x : α) [x = x] [decidable_eq α] [group α] :
unit := ()
run_cmd do
d ← get_decl `incorrect_type_class_argument_test,
x ← incorrect_type_class_argument d,
guard $ x = some "These are not classes. argument 3: [_inst_1 : x = x]"
section
def impossible_instance_test {α β : Type} [add_group α] : has_add α := infer_instance
local attribute [instance] impossible_instance_test
run_cmd do
d ← get_decl `impossible_instance_test,
x ← impossible_instance d,
guard $ x = some "Impossible to infer argument 2: {β : Type}"
def dangerous_instance_test {α β γ : Type} [ring α] [add_comm_group β] [has_coe α β]
[has_inv γ] : has_add β := infer_instance
local attribute [instance] dangerous_instance_test
run_cmd do
d ← get_decl `dangerous_instance_test,
x ← dangerous_instance d,
guard $ x = some "The following arguments become metavariables. argument 1: {α : Type}, argument 3: {γ : Type}"
end
section
def foo_has_mul {α} [has_mul α] : has_mul α := infer_instance
local attribute [instance, priority 1] foo_has_mul
run_cmd do
d ← get_decl `has_mul,
some s ← fails_quickly 500 d,
guard $ s = "type-class inference timed out"
local attribute [instance, priority 10000] foo_has_mul
run_cmd do
d ← get_decl `has_mul,
some s ← fails_quickly 3000 d,
guard $ "maximum class-instance resolution depth has been reached".is_prefix_of s
end
section
def foo_instance {α} (R : setoid α) : has_coe α (quotient R) := ⟨quotient.mk⟩
local attribute [instance, priority 1] foo_instance
run_cmd do
d ← get_decl `foo_instance,
some "illegal instance" ← has_coe_variable d,
d ← get_decl `has_coe_to_fun,
some s ← fails_quickly 3000 d,
guard $ "maximum class-instance resolution depth has been reached".is_prefix_of s
end
/- test of `apply_to_fresh_variables` -/
run_cmd do
e ← mk_const `id,
e2 ← apply_to_fresh_variables e,
type_check e2,
`(@id %%α %%a) ← instantiate_mvars e2,
expr.sort (level.succ $ level.mvar u) ← infer_type α,
skip
|
23a60212c28ab7992a94ad5614da1a1192e97f77 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/fintype/basic.lean | 751e7d4d6ae7c9ce00bb9b7688190dca749a4ca7 | [] | 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 | 47,006 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Finite types.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.wlog
import Mathlib.data.finset.powerset
import Mathlib.data.finset.lattice
import Mathlib.data.finset.pi
import Mathlib.data.array.lemmas
import Mathlib.order.well_founded
import Mathlib.group_theory.perm.basic
import Mathlib.PostPort
universes u_4 l u_1 u_2 u v
namespace Mathlib
/-- `fintype α` means that `α` is finite, i.e. there are only
finitely many distinct elements of type `α`. The evidence of this
is a finset `elems` (a list up to permutation without duplicates),
together with a proof that everything of type `α` is in the list. -/
class fintype (α : Type u_4)
where
elems : finset α
complete : ∀ (x : α), x ∈ elems
namespace finset
/-- `univ` is the universal finite set of type `finset α` implied from
the assumption `fintype α`. -/
def univ {α : Type u_1} [fintype α] : finset α :=
fintype.elems α
@[simp] theorem mem_univ {α : Type u_1} [fintype α] (x : α) : x ∈ univ :=
fintype.complete x
@[simp] theorem mem_univ_val {α : Type u_1} [fintype α] (x : α) : x ∈ val univ :=
mem_univ
@[simp] theorem coe_univ {α : Type u_1} [fintype α] : ↑univ = set.univ := sorry
theorem univ_nonempty_iff {α : Type u_1} [fintype α] : finset.nonempty univ ↔ Nonempty α := sorry
theorem univ_nonempty {α : Type u_1} [fintype α] [Nonempty α] : finset.nonempty univ :=
iff.mpr univ_nonempty_iff _inst_2
theorem univ_eq_empty {α : Type u_1} [fintype α] : univ = ∅ ↔ ¬Nonempty α := sorry
theorem subset_univ {α : Type u_1} [fintype α] (s : finset α) : s ⊆ univ :=
fun (a : α) (_x : a ∈ s) => mem_univ a
protected instance order_top {α : Type u_1} [fintype α] : order_top (finset α) :=
order_top.mk univ partial_order.le partial_order.lt sorry sorry sorry subset_univ
protected instance boolean_algebra {α : Type u_1} [fintype α] [DecidableEq α] : boolean_algebra (finset α) :=
boolean_algebra.mk distrib_lattice.sup distrib_lattice.le distrib_lattice.lt sorry sorry sorry sorry sorry sorry
distrib_lattice.inf sorry sorry sorry sorry order_top.top sorry semilattice_inf_bot.bot sorry
(fun (s : finset α) => univ \ s) has_sdiff.sdiff sorry sorry sorry
theorem compl_eq_univ_sdiff {α : Type u_1} [fintype α] [DecidableEq α] (s : finset α) : sᶜ = univ \ s :=
rfl
@[simp] theorem mem_compl {α : Type u_1} [fintype α] [DecidableEq α] {s : finset α} {x : α} : x ∈ (sᶜ) ↔ ¬x ∈ s := sorry
@[simp] theorem coe_compl {α : Type u_1} [fintype α] [DecidableEq α] (s : finset α) : ↑(sᶜ) = (↑sᶜ) :=
set.ext fun (x : α) => mem_compl
theorem eq_univ_iff_forall {α : Type u_1} [fintype α] {s : finset α} : s = univ ↔ ∀ (x : α), x ∈ s := sorry
theorem compl_ne_univ_iff_nonempty {α : Type u_1} [fintype α] [DecidableEq α] (s : finset α) : sᶜ ≠ univ ↔ finset.nonempty s := sorry
@[simp] theorem univ_inter {α : Type u_1} [fintype α] [DecidableEq α] (s : finset α) : univ ∩ s = s := sorry
@[simp] theorem inter_univ {α : Type u_1} [fintype α] [DecidableEq α] (s : finset α) : s ∩ univ = s :=
eq.mpr (id (Eq._oldrec (Eq.refl (s ∩ univ = s)) (inter_comm s univ)))
(eq.mpr (id (Eq._oldrec (Eq.refl (univ ∩ s = s)) (univ_inter s))) (Eq.refl s))
@[simp] theorem piecewise_univ {α : Type u_1} [fintype α] [(i : α) → Decidable (i ∈ univ)] {δ : α → Sort u_2} (f : (i : α) → δ i) (g : (i : α) → δ i) : piecewise univ f g = f := sorry
theorem piecewise_compl {α : Type u_1} [fintype α] [DecidableEq α] (s : finset α) [(i : α) → Decidable (i ∈ s)] [(i : α) → Decidable (i ∈ (sᶜ))] {δ : α → Sort u_2} (f : (i : α) → δ i) (g : (i : α) → δ i) : piecewise (sᶜ) f g = piecewise s g f := sorry
theorem univ_map_equiv_to_embedding {α : Type u_1} {β : Type u_2} [fintype α] [fintype β] (e : α ≃ β) : map (equiv.to_embedding e) univ = univ := sorry
@[simp] theorem univ_filter_exists {α : Type u_1} {β : Type u_2} [fintype α] (f : α → β) [fintype β] [decidable_pred fun (y : β) => ∃ (x : α), f x = y] [DecidableEq β] : filter (fun (y : β) => ∃ (x : α), f x = y) univ = image f univ := sorry
/-- Note this is a special case of `(finset.image_preimage f univ _).symm`. -/
theorem univ_filter_mem_range {α : Type u_1} {β : Type u_2} [fintype α] (f : α → β) [fintype β] [decidable_pred fun (y : β) => y ∈ set.range f] [DecidableEq β] : filter (fun (y : β) => y ∈ set.range f) univ = image f univ :=
univ_filter_exists f
end finset
namespace fintype
protected instance decidable_pi_fintype {α : Type u_1} {β : α → Type u_2} [(a : α) → DecidableEq (β a)] [fintype α] : DecidableEq ((a : α) → β a) :=
fun (f g : (a : α) → β a) => decidable_of_iff (∀ (a : α), a ∈ elems α → f a = g a) sorry
protected instance decidable_forall_fintype {α : Type u_1} {p : α → Prop} [decidable_pred p] [fintype α] : Decidable (∀ (a : α), p a) :=
decidable_of_iff (∀ (a : α), a ∈ finset.univ → p a) sorry
protected instance decidable_exists_fintype {α : Type u_1} {p : α → Prop} [decidable_pred p] [fintype α] : Decidable (∃ (a : α), p a) :=
decidable_of_iff (∃ (a : α), ∃ (H : a ∈ finset.univ), p a) sorry
protected instance decidable_eq_equiv_fintype {α : Type u_1} {β : Type u_2} [DecidableEq β] [fintype α] : DecidableEq (α ≃ β) :=
fun (a b : α ≃ β) => decidable_of_iff (equiv.to_fun a = equiv.to_fun b) sorry
protected instance decidable_injective_fintype {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] [fintype α] : decidable_pred function.injective :=
fun (x : α → β) => eq.mpr sorry fintype.decidable_forall_fintype
protected instance decidable_surjective_fintype {α : Type u_1} {β : Type u_2} [DecidableEq β] [fintype α] [fintype β] : decidable_pred function.surjective :=
fun (x : α → β) => eq.mpr sorry fintype.decidable_forall_fintype
protected instance decidable_bijective_fintype {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] [fintype α] [fintype β] : decidable_pred function.bijective :=
fun (x : α → β) => eq.mpr sorry and.decidable
protected instance decidable_left_inverse_fintype {α : Type u_1} {β : Type u_2} [DecidableEq α] [fintype α] (f : α → β) (g : β → α) : Decidable (function.right_inverse f g) :=
(fun (this : Decidable (∀ (x : α), g (f x) = x)) => this) fintype.decidable_forall_fintype
protected instance decidable_right_inverse_fintype {α : Type u_1} {β : Type u_2} [DecidableEq β] [fintype β] (f : α → β) (g : β → α) : Decidable (function.left_inverse f g) :=
(fun (this : Decidable (∀ (x : β), f (g x) = x)) => this) fintype.decidable_forall_fintype
/-- Construct a proof of `fintype α` from a universal multiset -/
def of_multiset {α : Type u_1} [DecidableEq α] (s : multiset α) (H : ∀ (x : α), x ∈ s) : fintype α :=
mk (multiset.to_finset s) sorry
/-- Construct a proof of `fintype α` from a universal list -/
def of_list {α : Type u_1} [DecidableEq α] (l : List α) (H : ∀ (x : α), x ∈ l) : fintype α :=
mk (list.to_finset l) sorry
theorem exists_univ_list (α : Type u_1) [fintype α] : ∃ (l : List α), list.nodup l ∧ ∀ (x : α), x ∈ l := sorry
/-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/
def card (α : Type u_1) [fintype α] : ℕ :=
finset.card finset.univ
/-- If `l` lists all the elements of `α` without duplicates, then `α ≃ fin (l.length)`. -/
def equiv_fin_of_forall_mem_list {α : Type u_1} [DecidableEq α] {l : List α} (h : ∀ (x : α), x ∈ l) (nd : list.nodup l) : α ≃ fin (list.length l) :=
equiv.mk (fun (a : α) => { val := list.index_of a l, property := sorry })
(fun (i : fin (list.length l)) => list.nth_le l (subtype.val i) sorry) sorry sorry
/-- There is (computably) a bijection between `α` and `fin n` where
`n = card α`. Since it is not unique, and depends on which permutation
of the universe list is used, the bijection is wrapped in `trunc` to
preserve computability. -/
def equiv_fin (α : Type u_1) [DecidableEq α] [fintype α] : trunc (α ≃ fin (card α)) :=
eq.mpr sorry
(quot.rec_on_subsingleton (finset.val finset.univ)
(fun (l : List α) (h : ∀ (x : α), x ∈ l) (nd : list.nodup l) => trunc.mk (equiv_fin_of_forall_mem_list h nd))
finset.mem_univ_val sorry)
theorem exists_equiv_fin (α : Type u_1) [fintype α] : ∃ (n : ℕ), Nonempty (α ≃ fin n) :=
Exists.intro (card α) (nonempty_of_trunc (equiv_fin α))
protected instance subsingleton (α : Type u_1) : subsingleton (fintype α) :=
subsingleton.intro fun (_x : fintype α) => sorry
/-- Given a predicate that can be represented by a finset, the subtype
associated to the predicate is a fintype. -/
protected def subtype {α : Type u_1} {p : α → Prop} (s : finset α) (H : ∀ (x : α), x ∈ s ↔ p x) : fintype (Subtype fun (x : α) => p x) :=
mk (finset.mk (multiset.pmap Subtype.mk (finset.val s) sorry) sorry) sorry
theorem subtype_card {α : Type u_1} {p : α → Prop} (s : finset α) (H : ∀ (x : α), x ∈ s ↔ p x) : card (Subtype fun (x : α) => p x) = finset.card s :=
multiset.card_pmap Subtype.mk (finset.val s) (subtype._proof_1 s H)
theorem card_of_subtype {α : Type u_1} {p : α → Prop} (s : finset α) (H : ∀ (x : α), x ∈ s ↔ p x) [fintype (Subtype fun (x : α) => p x)] : card (Subtype fun (x : α) => p x) = finset.card s := sorry
/-- Construct a fintype from a finset with the same elements. -/
def of_finset {α : Type u_1} {p : set α} (s : finset α) (H : ∀ (x : α), x ∈ s ↔ x ∈ p) : fintype ↥p :=
fintype.subtype s H
@[simp] theorem card_of_finset {α : Type u_1} {p : set α} (s : finset α) (H : ∀ (x : α), x ∈ s ↔ x ∈ p) : card ↥p = finset.card s :=
subtype_card s H
theorem card_of_finset' {α : Type u_1} {p : set α} (s : finset α) (H : ∀ (x : α), x ∈ s ↔ x ∈ p) [fintype ↥p] : card ↥p = finset.card s := sorry
/-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/
def of_bijective {α : Type u_1} {β : Type u_2} [fintype α] (f : α → β) (H : function.bijective f) : fintype β :=
mk (finset.map (function.embedding.mk f sorry) finset.univ) sorry
/-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/
def of_surjective {α : Type u_1} {β : Type u_2} [DecidableEq β] [fintype α] (f : α → β) (H : function.surjective f) : fintype β :=
mk (finset.image f finset.univ) sorry
/-- Given an injective function to a fintype, the domain is also a
fintype. This is noncomputable because injectivity alone cannot be
used to construct preimages. -/
def of_injective {α : Type u_1} {β : Type u_2} [fintype β] (f : α → β) (H : function.injective f) : fintype α :=
let _inst : (p : Prop) → Decidable p := classical.dec;
dite (Nonempty α) (fun (hα : Nonempty α) => of_surjective (function.inv_fun f) (function.inv_fun_surjective H))
fun (hα : ¬Nonempty α) => mk ∅ sorry
/-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/
def of_equiv {β : Type u_2} (α : Type u_1) [fintype α] (f : α ≃ β) : fintype β :=
of_bijective (⇑f) (equiv.bijective f)
theorem of_equiv_card {α : Type u_1} {β : Type u_2} [fintype α] (f : α ≃ β) : card β = card α :=
multiset.card_map (⇑(function.embedding.mk (⇑f) (of_bijective._proof_1 (⇑f) (equiv.bijective f))))
(finset.val finset.univ)
theorem card_congr {α : Type u_1} {β : Type u_2} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := sorry
theorem card_eq {α : Type u_1} {β : Type u_2} [F : fintype α] [G : fintype β] : card α = card β ↔ Nonempty (α ≃ β) := sorry
/-- Subsingleton types are fintypes (with zero or one terms). -/
def of_subsingleton {α : Type u_1} (a : α) [subsingleton α] : fintype α :=
mk (singleton a) sorry
@[simp] theorem univ_of_subsingleton {α : Type u_1} (a : α) [subsingleton α] : finset.univ = singleton a :=
rfl
@[simp] theorem card_of_subsingleton {α : Type u_1} (a : α) [subsingleton α] : card α = 1 :=
rfl
end fintype
namespace set
/-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/
def to_finset {α : Type u_1} (s : set α) [fintype ↥s] : finset α :=
finset.mk (multiset.map subtype.val (finset.val finset.univ)) sorry
@[simp] theorem mem_to_finset {α : Type u_1} {s : set α} [fintype ↥s] {a : α} : a ∈ to_finset s ↔ a ∈ s := sorry
@[simp] theorem mem_to_finset_val {α : Type u_1} {s : set α} [fintype ↥s] {a : α} : a ∈ finset.val (to_finset s) ↔ a ∈ s :=
mem_to_finset
-- We use an arbitrary `[fintype s]` instance here,
-- not necessarily coming from a `[fintype α]`.
@[simp] theorem to_finset_card {α : Type u_1} (s : set α) [fintype ↥s] : finset.card (to_finset s) = fintype.card ↥s :=
multiset.card_map subtype.val (finset.val finset.univ)
@[simp] theorem coe_to_finset {α : Type u_1} (s : set α) [fintype ↥s] : ↑(to_finset s) = s :=
ext fun (_x : α) => mem_to_finset
@[simp] theorem to_finset_inj {α : Type u_1} {s : set α} {t : set α} [fintype ↥s] [fintype ↥t] : to_finset s = to_finset t ↔ s = t := sorry
end set
theorem finset.card_univ {α : Type u_1} [fintype α] : finset.card finset.univ = fintype.card α :=
rfl
theorem finset.eq_univ_of_card {α : Type u_1} [fintype α] (s : finset α) (hs : finset.card s = fintype.card α) : s = finset.univ := sorry
theorem finset.card_eq_iff_eq_univ {α : Type u_1} [fintype α] (s : finset α) : finset.card s = fintype.card α ↔ s = finset.univ :=
{ mp := finset.eq_univ_of_card s, mpr := fun (ᾰ : s = finset.univ) => Eq._oldrec finset.card_univ (Eq.symm ᾰ) }
theorem finset.card_le_univ {α : Type u_1} [fintype α] (s : finset α) : finset.card s ≤ fintype.card α :=
finset.card_le_of_subset (finset.subset_univ s)
theorem finset.card_lt_iff_ne_univ {α : Type u_1} [fintype α] (s : finset α) : finset.card s < fintype.card α ↔ s ≠ finset.univ :=
iff.trans (has_le.le.lt_iff_ne (finset.card_le_univ s)) (not_iff_not_of_iff (finset.card_eq_iff_eq_univ s))
theorem finset.card_compl_lt_iff_nonempty {α : Type u_1} [fintype α] [DecidableEq α] (s : finset α) : finset.card (sᶜ) < fintype.card α ↔ finset.nonempty s :=
iff.trans (finset.card_lt_iff_ne_univ (sᶜ)) (finset.compl_ne_univ_iff_nonempty s)
theorem finset.card_univ_diff {α : Type u_1} [DecidableEq α] [fintype α] (s : finset α) : finset.card (finset.univ \ s) = fintype.card α - finset.card s :=
finset.card_sdiff (finset.subset_univ s)
theorem finset.card_compl {α : Type u_1} [DecidableEq α] [fintype α] (s : finset α) : finset.card (sᶜ) = fintype.card α - finset.card s :=
finset.card_univ_diff s
protected instance fin.fintype (n : ℕ) : fintype (fin n) :=
fintype.mk (finset.fin_range n) finset.mem_fin_range
theorem fin.univ_def (n : ℕ) : finset.univ = finset.fin_range n :=
rfl
@[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n :=
list.length_fin_range n
@[simp] theorem finset.card_fin (n : ℕ) : finset.card finset.univ = n :=
eq.mpr (id (Eq._oldrec (Eq.refl (finset.card finset.univ = n)) finset.card_univ))
(eq.mpr (id (Eq._oldrec (Eq.refl (fintype.card (fin n) = n)) (fintype.card_fin n))) (Eq.refl n))
theorem fin.equiv_iff_eq {m : ℕ} {n : ℕ} : Nonempty (fin m ≃ fin n) ↔ m = n := sorry
/-- Embed `fin n` into `fin (n + 1)` by prepending zero to the `univ` -/
theorem fin.univ_succ (n : ℕ) : finset.univ = insert 0 (finset.image fin.succ finset.univ) := sorry
/-- Embed `fin n` into `fin (n + 1)` by appending a new `fin.last n` to the `univ` -/
theorem fin.univ_cast_succ (n : ℕ) : finset.univ = insert (fin.last n) (finset.image (⇑fin.cast_succ) finset.univ) := sorry
/-- Embed `fin n` into `fin (n + 1)` by inserting
around a specified pivot `p : fin (n + 1)` into the `univ` -/
theorem fin.univ_succ_above (n : ℕ) (p : fin (n + 1)) : finset.univ = insert p (finset.image (⇑(fin.succ_above p)) finset.univ) := sorry
instance unique.fintype {α : Type u_1} [unique α] : fintype α :=
fintype.of_subsingleton Inhabited.default
@[simp] theorem univ_unique {α : Type u_1} [unique α] [f : fintype α] : finset.univ = singleton Inhabited.default :=
eq.mpr (id (Eq._oldrec (Eq.refl (finset.univ = singleton Inhabited.default)) (subsingleton.elim f unique.fintype)))
(Eq.refl finset.univ)
protected instance empty.fintype : fintype empty :=
fintype.mk ∅ sorry
@[simp] theorem fintype.univ_empty : finset.univ = ∅ :=
rfl
@[simp] theorem fintype.card_empty : fintype.card empty = 0 :=
rfl
protected instance pempty.fintype : fintype pempty :=
fintype.mk ∅ sorry
@[simp] theorem fintype.univ_pempty : finset.univ = ∅ :=
rfl
@[simp] theorem fintype.card_pempty : fintype.card pempty = 0 :=
rfl
protected instance unit.fintype : fintype Unit :=
fintype.of_subsingleton Unit.unit
theorem fintype.univ_unit : finset.univ = singleton Unit.unit :=
rfl
theorem fintype.card_unit : fintype.card Unit = 1 :=
rfl
protected instance punit.fintype : fintype PUnit :=
fintype.of_subsingleton PUnit.unit
@[simp] theorem fintype.univ_punit : finset.univ = singleton PUnit.unit :=
rfl
@[simp] theorem fintype.card_punit : fintype.card PUnit = 1 :=
rfl
protected instance bool.fintype : fintype Bool :=
fintype.mk (finset.mk (tt ::ₘ false ::ₘ 0) sorry) sorry
@[simp] theorem fintype.univ_bool : finset.univ = insert tt (singleton false) :=
rfl
protected instance units_int.fintype : fintype (units ℤ) :=
fintype.mk (insert 1 (singleton (-1))) sorry
protected instance additive.fintype {α : Type u_1} [fintype α] : fintype (additive α) :=
id
protected instance multiplicative.fintype {α : Type u_1} [fintype α] : fintype (multiplicative α) :=
id
@[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = bit0 1 :=
rfl
protected instance units.fintype {α : Type u_1} [monoid α] [fintype α] : fintype (units α) :=
fintype.of_injective units.val units.ext
@[simp] theorem fintype.card_bool : fintype.card Bool = bit0 1 :=
rfl
/-- Given a finset on `α`, lift it to being a finset on `option α`
using `option.some` and then insert `option.none`. -/
def finset.insert_none {α : Type u_1} (s : finset α) : finset (Option α) :=
finset.mk (none ::ₘ multiset.map some (finset.val s)) sorry
@[simp] theorem finset.mem_insert_none {α : Type u_1} {s : finset α} {o : Option α} : o ∈ finset.insert_none s ↔ ∀ (a : α), a ∈ o → a ∈ s := sorry
theorem finset.some_mem_insert_none {α : Type u_1} {s : finset α} {a : α} : some a ∈ finset.insert_none s ↔ a ∈ s := sorry
protected instance option.fintype {α : Type u_1} [fintype α] : fintype (Option α) :=
fintype.mk (finset.insert_none finset.univ) sorry
@[simp] theorem fintype.card_option {α : Type u_1} [fintype α] : fintype.card (Option α) = fintype.card α + 1 := sorry
protected instance sigma.fintype {α : Type u_1} (β : α → Type u_2) [fintype α] [(a : α) → fintype (β a)] : fintype (sigma β) :=
fintype.mk (finset.sigma finset.univ fun (_x : α) => finset.univ) sorry
@[simp] theorem finset.univ_sigma_univ {α : Type u_1} {β : α → Type u_2} [fintype α] [(a : α) → fintype (β a)] : (finset.sigma finset.univ fun (a : α) => finset.univ) = finset.univ :=
rfl
protected instance prod.fintype (α : Type u_1) (β : Type u_2) [fintype α] [fintype β] : fintype (α × β) :=
fintype.mk (finset.product finset.univ finset.univ) sorry
@[simp] theorem finset.univ_product_univ {α : Type u_1} {β : Type u_2} [fintype α] [fintype β] : finset.product finset.univ finset.univ = finset.univ :=
rfl
@[simp] theorem fintype.card_prod (α : Type u_1) (β : Type u_2) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β :=
finset.card_product finset.univ finset.univ
/-- Given that `α × β` is a fintype, `α` is also a fintype. -/
def fintype.fintype_prod_left {α : Type u_1} {β : Type u_2} [DecidableEq α] [fintype (α × β)] [Nonempty β] : fintype α :=
fintype.mk (finset.image prod.fst (fintype.elems (α × β))) sorry
/-- Given that `α × β` is a fintype, `β` is also a fintype. -/
def fintype.fintype_prod_right {α : Type u_1} {β : Type u_2} [DecidableEq β] [fintype (α × β)] [Nonempty α] : fintype β :=
fintype.mk (finset.image prod.snd (fintype.elems (α × β))) sorry
protected instance ulift.fintype (α : Type u_1) [fintype α] : fintype (ulift α) :=
fintype.of_equiv α (equiv.symm equiv.ulift)
@[simp] theorem fintype.card_ulift (α : Type u_1) [fintype α] : fintype.card (ulift α) = fintype.card α :=
fintype.of_equiv_card (equiv.symm equiv.ulift)
theorem univ_sum_type {α : Type u_1} {β : Type u_2} [fintype α] [fintype β] [fintype (α ⊕ β)] [DecidableEq (α ⊕ β)] : finset.univ = finset.map function.embedding.inl finset.univ ∪ finset.map function.embedding.inr finset.univ := sorry
protected instance sum.fintype (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) :=
fintype.of_equiv (sigma fun (b : Bool) => cond b (ulift α) (ulift β))
(equiv.trans (equiv.symm (equiv.sum_equiv_sigma_bool (ulift α) (ulift β))) (equiv.sum_congr equiv.ulift equiv.ulift))
namespace fintype
theorem card_le_of_injective {α : Type u_1} {β : Type u_2} [fintype α] [fintype β] (f : α → β) (hf : function.injective f) : card α ≤ card β :=
finset.card_le_card_of_inj_on f (fun (_x : α) (_x_1 : _x ∈ finset.univ) => finset.mem_univ (f _x))
fun (_x : α) (_x_1 : _x ∈ finset.univ) (_x_2 : α) (_x_3 : _x_2 ∈ finset.univ) (h : f _x = f _x_2) => hf h
/--
The pigeonhole principle for finitely many pigeons and pigeonholes.
This is the `fintype` version of `finset.exists_ne_map_eq_of_card_lt_of_maps_to`.
-/
theorem exists_ne_map_eq_of_card_lt {α : Type u_1} {β : Type u_2} [fintype α] [fintype β] (f : α → β) (h : card β < card α) : ∃ (x : α), ∃ (y : α), x ≠ y ∧ f x = f y := sorry
theorem card_eq_one_iff {α : Type u_1} [fintype α] : card α = 1 ↔ ∃ (x : α), ∀ (y : α), y = x := sorry
theorem card_eq_zero_iff {α : Type u_1} [fintype α] : card α = 0 ↔ α → False := sorry
/-- A `fintype` with cardinality zero is (constructively) equivalent to `pempty`. -/
def card_eq_zero_equiv_equiv_pempty {α : Type u_1} [fintype α] : card α = 0 ≃ (α ≃ pempty) :=
equiv.mk
(fun (h : card α = 0) => equiv.mk (fun (a : α) => false.elim sorry) (fun (a : pempty) => pempty.elim a) sorry sorry)
sorry sorry sorry
theorem card_pos_iff {α : Type u_1} [fintype α] : 0 < card α ↔ Nonempty α := sorry
theorem card_le_one_iff {α : Type u_1} [fintype α] : card α ≤ 1 ↔ ∀ (a b : α), a = b := sorry
theorem card_le_one_iff_subsingleton {α : Type u_1} [fintype α] : card α ≤ 1 ↔ subsingleton α :=
iff.trans card_le_one_iff (iff.symm subsingleton_iff)
theorem one_lt_card_iff_nontrivial {α : Type u_1} [fintype α] : 1 < card α ↔ nontrivial α := sorry
theorem exists_ne_of_one_lt_card {α : Type u_1} [fintype α] (h : 1 < card α) (a : α) : ∃ (b : α), b ≠ a :=
exists_ne a
theorem exists_pair_of_one_lt_card {α : Type u_1} [fintype α] (h : 1 < card α) : ∃ (a : α), ∃ (b : α), a ≠ b :=
exists_pair_ne α
theorem card_eq_one_of_forall_eq {α : Type u_1} [fintype α] {i : α} (h : ∀ (j : α), j = i) : card α = 1 :=
le_antisymm (iff.mpr card_le_one_iff fun (a b : α) => Eq.trans (h a) (Eq.symm (h b)))
(iff.mpr finset.card_pos (Exists.intro i (finset.mem_univ i)))
theorem injective_iff_surjective {α : Type u_1} [fintype α] {f : α → α} : function.injective f ↔ function.surjective f := sorry
theorem injective_iff_bijective {α : Type u_1} [fintype α] {f : α → α} : function.injective f ↔ function.bijective f := sorry
theorem surjective_iff_bijective {α : Type u_1} [fintype α] {f : α → α} : function.surjective f ↔ function.bijective f := sorry
theorem injective_iff_surjective_of_equiv {α : Type u_1} [fintype α] {β : Type u_2} {f : α → β} (e : α ≃ β) : function.injective f ↔ function.surjective f := sorry
theorem nonempty_equiv_of_card_eq {α : Type u_1} {β : Type u_2} [fintype α] [fintype β] (h : card α = card β) : Nonempty (α ≃ β) := sorry
theorem bijective_iff_injective_and_card {α : Type u_1} {β : Type u_2} [fintype α] [fintype β] (f : α → β) : function.bijective f ↔ function.injective f ∧ card α = card β := sorry
theorem bijective_iff_surjective_and_card {α : Type u_1} {β : Type u_2} [fintype α] [fintype β] (f : α → β) : function.bijective f ↔ function.surjective f ∧ card α = card β := sorry
end fintype
theorem fintype.coe_image_univ {α : Type u_1} {β : Type u_2} [fintype α] [DecidableEq β] {f : α → β} : ↑(finset.image f finset.univ) = set.range f := sorry
protected instance list.subtype.fintype {α : Type u_1} [DecidableEq α] (l : List α) : fintype (Subtype fun (x : α) => x ∈ l) :=
fintype.of_list (list.attach l) (list.mem_attach l)
protected instance multiset.subtype.fintype {α : Type u_1} [DecidableEq α] (s : multiset α) : fintype (Subtype fun (x : α) => x ∈ s) :=
fintype.of_multiset (multiset.attach s) (multiset.mem_attach s)
protected instance finset.subtype.fintype {α : Type u_1} (s : finset α) : fintype (Subtype fun (x : α) => x ∈ s) :=
fintype.mk (finset.attach s) (finset.mem_attach s)
protected instance finset_coe.fintype {α : Type u_1} (s : finset α) : fintype ↥↑s :=
finset.subtype.fintype s
@[simp] theorem fintype.card_coe {α : Type u_1} (s : finset α) : fintype.card ↥↑s = finset.card s :=
finset.card_attach
theorem finset.attach_eq_univ {α : Type u_1} {s : finset α} : finset.attach s = finset.univ :=
rfl
theorem finset.card_le_one_iff {α : Type u_1} {s : finset α} : finset.card s ≤ 1 ↔ ∀ {x y : α}, x ∈ s → y ∈ s → x = y := sorry
/-- A `finset` of a subsingleton type has cardinality at most one. -/
theorem finset.card_le_one_of_subsingleton {α : Type u_1} [subsingleton α] (s : finset α) : finset.card s ≤ 1 :=
iff.mpr finset.card_le_one_iff fun (_x _x_1 : α) (_x_2 : _x ∈ s) (_x_3 : _x_1 ∈ s) => subsingleton.elim _x _x_1
theorem finset.one_lt_card_iff {α : Type u_1} {s : finset α} : 1 < finset.card s ↔ ∃ (x : α), ∃ (y : α), x ∈ s ∧ y ∈ s ∧ x ≠ y := sorry
protected instance plift.fintype (p : Prop) [Decidable p] : fintype (plift p) :=
fintype.mk (dite p (fun (h : p) => singleton (plift.up h)) fun (h : ¬p) => ∅) sorry
protected instance Prop.fintype : fintype Prop :=
fintype.mk (finset.mk (True ::ₘ False ::ₘ 0) sorry) sorry
protected instance subtype.fintype {α : Type u_1} (p : α → Prop) [decidable_pred p] [fintype α] : fintype (Subtype fun (x : α) => p x) :=
fintype.subtype (finset.filter p finset.univ) sorry
/-- A set on a fintype, when coerced to a type, is a fintype. -/
def set_fintype {α : Type u_1} [fintype α] (s : set α) [decidable_pred s] : fintype ↥s :=
subtype.fintype fun (x : α) => x ∈ s
namespace function.embedding
/-- An embedding from a `fintype` to itself can be promoted to an equivalence. -/
def equiv_of_fintype_self_embedding {α : Type u_1} [fintype α] (e : α ↪ α) : α ≃ α :=
equiv.of_bijective ⇑e sorry
@[simp] theorem equiv_of_fintype_self_embedding_to_embedding {α : Type u_1} [fintype α] (e : α ↪ α) : equiv.to_embedding (equiv_of_fintype_self_embedding e) = e :=
ext fun (x : α) => Eq.refl (coe_fn (equiv.to_embedding (equiv_of_fintype_self_embedding e)) x)
end function.embedding
@[simp] theorem finset.univ_map_embedding {α : Type u_1} [fintype α] (e : α ↪ α) : finset.map e finset.univ = finset.univ := sorry
namespace fintype
/-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the
finset `fintype.pi_finset t` of all functions taking values in `t a` for all `a`. This is the
analogue of `finset.pi` where the base finset is `univ` (but formally they are not the same, as
there is an additional condition `i ∈ finset.univ` in the `finset.pi` definition). -/
def pi_finset {α : Type u_1} [DecidableEq α] [fintype α] {δ : α → Type u_4} (t : (a : α) → finset (δ a)) : finset ((a : α) → δ a) :=
finset.map (function.embedding.mk (fun (f : (a : α) → a ∈ finset.univ → δ a) (a : α) => f a (finset.mem_univ a)) sorry)
(finset.pi finset.univ t)
@[simp] theorem mem_pi_finset {α : Type u_1} [DecidableEq α] [fintype α] {δ : α → Type u_4} {t : (a : α) → finset (δ a)} {f : (a : α) → δ a} : f ∈ pi_finset t ↔ ∀ (a : α), f a ∈ t a := sorry
theorem pi_finset_subset {α : Type u_1} [DecidableEq α] [fintype α] {δ : α → Type u_4} (t₁ : (a : α) → finset (δ a)) (t₂ : (a : α) → finset (δ a)) (h : ∀ (a : α), t₁ a ⊆ t₂ a) : pi_finset t₁ ⊆ pi_finset t₂ :=
fun (g : (a : α) → δ a) (hg : g ∈ pi_finset t₁) => iff.mpr mem_pi_finset fun (a : α) => h a (iff.mp mem_pi_finset hg a)
theorem pi_finset_disjoint_of_disjoint {α : Type u_1} [DecidableEq α] [fintype α] {δ : α → Type u_4} [(a : α) → DecidableEq (δ a)] (t₁ : (a : α) → finset (δ a)) (t₂ : (a : α) → finset (δ a)) {a : α} (h : disjoint (t₁ a) (t₂ a)) : disjoint (pi_finset t₁) (pi_finset t₂) := sorry
end fintype
/-! ### pi -/
/-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/
protected instance pi.fintype {α : Type u_1} {β : α → Type u_2} [DecidableEq α] [fintype α] [(a : α) → fintype (β a)] : fintype ((a : α) → β a) :=
fintype.mk (fintype.pi_finset fun (_x : α) => finset.univ) sorry
@[simp] theorem fintype.pi_finset_univ {α : Type u_1} {β : α → Type u_2} [DecidableEq α] [fintype α] [(a : α) → fintype (β a)] : (fintype.pi_finset fun (a : α) => finset.univ) = finset.univ :=
rfl
protected instance d_array.fintype {n : ℕ} {α : fin n → Type u_1} [(n : fin n) → fintype (α n)] : fintype (d_array n α) :=
fintype.of_equiv ((i : fin n) → α i) (equiv.symm (equiv.d_array_equiv_fin α))
protected instance array.fintype {n : ℕ} {α : Type u_1} [fintype α] : fintype (array n α) :=
d_array.fintype
protected instance vector.fintype {α : Type u_1} [fintype α] {n : ℕ} : fintype (vector α n) :=
fintype.of_equiv (fin n → α) (equiv.symm (equiv.vector_equiv_fin α n))
protected instance quotient.fintype {α : Type u_1} [fintype α] (s : setoid α) [DecidableRel has_equiv.equiv] : fintype (quotient s) :=
fintype.of_surjective quotient.mk sorry
protected instance finset.fintype {α : Type u_1} [fintype α] : fintype (finset α) :=
fintype.mk (finset.powerset finset.univ) sorry
@[simp] theorem fintype.card_finset {α : Type u_1} [fintype α] : fintype.card (finset α) = bit0 1 ^ fintype.card α :=
finset.card_powerset finset.univ
@[simp] theorem set.to_finset_univ {α : Type u_1} [fintype α] : set.to_finset set.univ = finset.univ := sorry
@[simp] theorem set.to_finset_empty {α : Type u_1} [fintype α] : set.to_finset ∅ = ∅ := sorry
theorem fintype.card_subtype_le {α : Type u_1} [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card (Subtype fun (x : α) => p x) ≤ fintype.card α := sorry
theorem fintype.card_subtype_lt {α : Type u_1} [fintype α] {p : α → Prop} [decidable_pred p] {x : α} (hx : ¬p x) : fintype.card (Subtype fun (x : α) => p x) < fintype.card α := sorry
protected instance psigma.fintype {α : Type u_1} {β : α → Type u_2} [fintype α] [(a : α) → fintype (β a)] : fintype (psigma fun (a : α) => β a) :=
fintype.of_equiv (sigma fun (a : α) => β a) (equiv.symm (equiv.psigma_equiv_sigma fun (a : α) => β a))
protected instance psigma.fintype_prop_left {α : Prop} {β : α → Type u_1} [Decidable α] [(a : α) → fintype (β a)] : fintype (psigma fun (a : α) => β a) :=
dite α (fun (h : α) => fintype.of_equiv (β h) (equiv.mk (fun (x : β h) => psigma.mk h x) psigma.snd sorry sorry))
fun (h : ¬α) => fintype.mk ∅ sorry
protected instance psigma.fintype_prop_right {α : Type u_1} {β : α → Prop} [(a : α) → Decidable (β a)] [fintype α] : fintype (psigma fun (a : α) => β a) :=
fintype.of_equiv (Subtype fun (a : α) => β a)
(equiv.mk (fun (_x : Subtype fun (a : α) => β a) => sorry) (fun (_x : psigma fun (a : α) => β a) => sorry) sorry
sorry)
protected instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [Decidable α] [(a : α) → Decidable (β a)] : fintype (psigma fun (a : α) => β a) :=
dite (∃ (a : α), β a) (fun (h : ∃ (a : α), β a) => fintype.mk (singleton (psigma.mk sorry sorry)) sorry)
fun (h : ¬∃ (a : α), β a) => fintype.mk ∅ sorry
protected instance set.fintype {α : Type u_1} [fintype α] : fintype (set α) :=
fintype.mk (finset.map (function.embedding.mk coe finset.coe_injective) (finset.powerset finset.univ)) sorry
protected instance pfun_fintype (p : Prop) [Decidable p] (α : p → Type u_1) [(hp : p) → fintype (α hp)] : fintype ((hp : p) → α hp) :=
dite p
(fun (hp : p) =>
fintype.of_equiv (α hp) (equiv.mk (fun (a : α hp) (_x : p) => a) (fun (f : (hp : p) → α hp) => f hp) sorry sorry))
fun (hp : ¬p) => fintype.mk (singleton fun (h : p) => false.elim (hp h)) sorry
@[simp] theorem finset.univ_pi_univ {α : Type u_1} {β : α → Type u_2} [DecidableEq α] [fintype α] [(a : α) → fintype (β a)] : (finset.pi finset.univ fun (a : α) => finset.univ) = finset.univ := sorry
theorem mem_image_univ_iff_mem_range {α : Type u_1} {β : Type u_2} [fintype α] [DecidableEq β] {f : α → β} {b : β} : b ∈ finset.image f finset.univ ↔ b ∈ set.range f := sorry
theorem card_lt_card_of_injective_of_not_mem {α : Type u_1} {β : Type u_2} [fintype α] [fintype β] (f : α → β) (h : function.injective f) {b : β} (w : ¬b ∈ set.range f) : fintype.card α < fintype.card β := sorry
/-- An auxiliary function for `quotient.fin_choice`. Given a
collection of setoids indexed by a type `ι`, a (finite) list `l` of
indices, and a function that for each `i ∈ l` gives a term of the
corresponding quotient type, then there is a corresponding term in the
quotient of the product of the setoids indexed by `l`. -/
def quotient.fin_choice_aux {ι : Type u_1} [DecidableEq ι] {α : ι → Type u_2} [S : (i : ι) → setoid (α i)] (l : List ι) : ((i : ι) → i ∈ l → quotient (S i)) → quotient Mathlib.pi_setoid :=
sorry
theorem quotient.fin_choice_aux_eq {ι : Type u_1} [DecidableEq ι] {α : ι → Type u_2} [S : (i : ι) → setoid (α i)] (l : List ι) (f : (i : ι) → i ∈ l → α i) : (quotient.fin_choice_aux l fun (i : ι) (h : i ∈ l) => quotient.mk (f i h)) = quotient.mk f := sorry
/-- Given a collection of setoids indexed by a fintype `ι` and a
function that for each `i : ι` gives a term of the corresponding
quotient type, then there is corresponding term in the quotient of the
product of the setoids. -/
def quotient.fin_choice {ι : Type u_1} [DecidableEq ι] [fintype ι] {α : ι → Type u_2} [S : (i : ι) → setoid (α i)] (f : (i : ι) → quotient (S i)) : quotient Mathlib.pi_setoid :=
quotient.lift_on
(quotient.rec_on (finset.val finset.univ)
(fun (l : List ι) => quotient.fin_choice_aux l fun (i : ι) (_x : i ∈ l) => f i) sorry)
(fun (f : (i : ι) → i ∈ finset.val finset.univ → α i) => quotient.mk fun (i : ι) => f i (finset.mem_univ i)) sorry
theorem quotient.fin_choice_eq {ι : Type u_1} [DecidableEq ι] [fintype ι] {α : ι → Type u_2} [(i : ι) → setoid (α i)] (f : (i : ι) → α i) : (quotient.fin_choice fun (i : ι) => quotient.mk (f i)) = quotient.mk f := sorry
/-- Given a list, produce a list of all permutations of its elements. -/
def perms_of_list {α : Type u_1} [DecidableEq α] : List α → List (equiv.perm α) :=
sorry
theorem length_perms_of_list {α : Type u_1} [DecidableEq α] (l : List α) : list.length (perms_of_list l) = nat.factorial (list.length l) := sorry
theorem mem_perms_of_list_of_mem {α : Type u_1} [DecidableEq α] {l : List α} {f : equiv.perm α} (h : ∀ (x : α), coe_fn f x ≠ x → x ∈ l) : f ∈ perms_of_list l := sorry
theorem mem_of_mem_perms_of_list {α : Type u_1} [DecidableEq α] {l : List α} {f : equiv.perm α} : f ∈ perms_of_list l → ∀ {x : α}, coe_fn f x ≠ x → x ∈ l := sorry
theorem mem_perms_of_list_iff {α : Type u_1} [DecidableEq α] {l : List α} {f : equiv.perm α} : f ∈ perms_of_list l ↔ ∀ {x : α}, coe_fn f x ≠ x → x ∈ l :=
{ mp := mem_of_mem_perms_of_list, mpr := mem_perms_of_list_of_mem }
theorem nodup_perms_of_list {α : Type u_1} [DecidableEq α] {l : List α} (hl : list.nodup l) : list.nodup (perms_of_list l) := sorry
/-- Given a finset, produce the finset of all permutations of its elements. -/
def perms_of_finset {α : Type u_1} [DecidableEq α] (s : finset α) : finset (equiv.perm α) :=
quotient.hrec_on (finset.val s)
(fun (l : List α) (hl : multiset.nodup (quotient.mk l)) => finset.mk ↑(perms_of_list l) sorry) sorry (finset.nodup s)
theorem mem_perms_of_finset_iff {α : Type u_1} [DecidableEq α] {s : finset α} {f : equiv.perm α} : f ∈ perms_of_finset s ↔ ∀ {x : α}, coe_fn f x ≠ x → x ∈ s :=
finset.cases_on s
fun (s_val : multiset α) (hs : multiset.nodup s_val) =>
quot.induction_on s_val (fun (l : List α) (hs : multiset.nodup (Quot.mk setoid.r l)) => mem_perms_of_list_iff) hs
theorem card_perms_of_finset {α : Type u_1} [DecidableEq α] (s : finset α) : finset.card (perms_of_finset s) = nat.factorial (finset.card s) :=
finset.cases_on s
fun (s_val : multiset α) (hs : multiset.nodup s_val) =>
quot.induction_on s_val (fun (l : List α) (hs : multiset.nodup (Quot.mk setoid.r l)) => length_perms_of_list l) hs
/-- The collection of permutations of a fintype is a fintype. -/
def fintype_perm {α : Type u_1} [DecidableEq α] [fintype α] : fintype (equiv.perm α) :=
fintype.mk (perms_of_finset finset.univ) sorry
protected instance equiv.fintype {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] [fintype α] [fintype β] : fintype (α ≃ β) :=
dite (fintype.card β = fintype.card α)
(fun (h : fintype.card β = fintype.card α) =>
trunc.rec_on_subsingleton (fintype.equiv_fin α)
fun (eα : α ≃ fin (fintype.card α)) =>
trunc.rec_on_subsingleton (fintype.equiv_fin β)
fun (eβ : β ≃ fin (fintype.card β)) =>
fintype.of_equiv (equiv.perm α)
(equiv.equiv_congr (equiv.refl α) (equiv.trans eα (eq.rec_on h (equiv.symm eβ)))))
fun (h : ¬fintype.card β = fintype.card α) => fintype.mk ∅ sorry
theorem fintype.card_perm {α : Type u_1} [DecidableEq α] [fintype α] : fintype.card (equiv.perm α) = nat.factorial (fintype.card α) :=
subsingleton.elim fintype_perm equiv.fintype ▸ card_perms_of_finset finset.univ
theorem fintype.card_equiv {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = nat.factorial (fintype.card α) :=
fintype.card_congr (equiv.equiv_congr (equiv.refl α) e) ▸ fintype.card_perm
theorem univ_eq_singleton_of_card_one {α : Type u_1} [fintype α] (x : α) (h : fintype.card α = 1) : finset.univ = singleton x := sorry
namespace fintype
/-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of
`α` satisfying `p` this unique element, as an element of the corresponding subtype. -/
def choose_x {α : Type u_1} [fintype α] (p : α → Prop) [decidable_pred p] (hp : exists_unique fun (a : α) => p a) : Subtype fun (a : α) => p a :=
{ val := finset.choose p finset.univ sorry, property := sorry }
/-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of
`α` satisfying `p` this unique element, as an element of `α`. -/
def choose {α : Type u_1} [fintype α] (p : α → Prop) [decidable_pred p] (hp : exists_unique fun (a : α) => p a) : α :=
↑(choose_x p hp)
theorem choose_spec {α : Type u_1} [fintype α] (p : α → Prop) [decidable_pred p] (hp : exists_unique fun (a : α) => p a) : p (choose p hp) :=
subtype.property (choose_x p hp)
/-- `
`bij_inv f` is the unique inverse to a bijection `f`. This acts
as a computable alternative to `function.inv_fun`. -/
def bij_inv {α : Type u_1} {β : Type u_2} [fintype α] [DecidableEq β] {f : α → β} (f_bij : function.bijective f) (b : β) : α :=
choose (fun (a : α) => f a = b) sorry
theorem left_inverse_bij_inv {α : Type u_1} {β : Type u_2} [fintype α] [DecidableEq β] {f : α → β} (f_bij : function.bijective f) : function.left_inverse (bij_inv f_bij) f :=
fun (a : α) =>
and.left f_bij (bij_inv f_bij (f a)) a (choose_spec (fun (a' : α) => f a' = f a) (bij_inv._proof_1 f_bij (f a)))
theorem right_inverse_bij_inv {α : Type u_1} {β : Type u_2} [fintype α] [DecidableEq β] {f : α → β} (f_bij : function.bijective f) : function.right_inverse (bij_inv f_bij) f :=
fun (b : β) => choose_spec (fun (a' : α) => f a' = b) (bij_inv._proof_1 f_bij b)
theorem bijective_bij_inv {α : Type u_1} {β : Type u_2} [fintype α] [DecidableEq β] {f : α → β} (f_bij : function.bijective f) : function.bijective (bij_inv f_bij) :=
{ left := function.right_inverse.injective (right_inverse_bij_inv f_bij),
right := function.left_inverse.surjective (left_inverse_bij_inv f_bij) }
theorem well_founded_of_trans_of_irrefl {α : Type u_1} [fintype α] (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := sorry
theorem preorder.well_founded {α : Type u_1} [fintype α] [preorder α] : well_founded Less :=
well_founded_of_trans_of_irrefl Less
instance linear_order.is_well_order {α : Type u_1} [fintype α] [linear_order α] : is_well_order α Less :=
is_well_order.mk preorder.well_founded
end fintype
/-- A type is said to be infinite if it has no fintype instance. -/
class infinite (α : Type u_4)
where
not_fintype : fintype α → False
@[simp] theorem not_nonempty_fintype {α : Type u_1} : ¬Nonempty (fintype α) ↔ infinite α := sorry
theorem finset.exists_minimal {α : Type u_1} [preorder α] (s : finset α) (h : finset.nonempty s) : ∃ (m : α), ∃ (H : m ∈ s), ∀ (x : α), x ∈ s → ¬x < m := sorry
theorem finset.exists_maximal {α : Type u_1} [preorder α] (s : finset α) (h : finset.nonempty s) : ∃ (m : α), ∃ (H : m ∈ s), ∀ (x : α), x ∈ s → ¬m < x :=
finset.exists_minimal s h
namespace infinite
theorem exists_not_mem_finset {α : Type u_1} [infinite α] (s : finset α) : ∃ (x : α), ¬x ∈ s :=
iff.mp not_forall fun (h : ∀ (x : α), x ∈ s) => not_fintype (fintype.mk s h)
protected instance nontrivial (α : Type u_1) [H : infinite α] : nontrivial α :=
nontrivial.mk sorry
theorem nonempty (α : Type u_1) [infinite α] : Nonempty α :=
nontrivial.to_nonempty
theorem of_injective {α : Type u_1} {β : Type u_2} [infinite β] (f : β → α) (hf : function.injective f) : infinite α :=
mk fun (I : fintype α) => not_fintype (fintype.of_injective f hf)
theorem of_surjective {α : Type u_1} {β : Type u_2} [infinite β] (f : α → β) (hf : function.surjective f) : infinite α :=
mk fun (I : fintype α) => not_fintype (fintype.of_surjective f hf)
/-- Embedding of `ℕ` into an infinite type. -/
def nat_embedding (α : Type u_1) [infinite α] : ℕ ↪ α :=
function.embedding.mk (nat_embedding_aux α) (nat_embedding_aux_injective α)
theorem exists_subset_card_eq (α : Type u_1) [infinite α] (n : ℕ) : ∃ (s : finset α), finset.card s = n := sorry
end infinite
theorem not_injective_infinite_fintype {α : Type u_1} {β : Type u_2} [infinite α] [fintype β] (f : α → β) : ¬function.injective f :=
fun (hf : function.injective f) => (fun (H : fintype α) => infinite.not_fintype H) (fintype.of_injective f hf)
/--
The pigeonhole principle for infinitely many pigeons in finitely many
pigeonholes. If there are infinitely many pigeons in finitely many
pigeonholes, then there are at least two pigeons in the same
pigeonhole.
See also: `fintype.exists_ne_map_eq_of_card_lt`, `fintype.exists_infinite_fiber`.
-/
theorem fintype.exists_ne_map_eq_of_infinite {α : Type u_1} {β : Type u_2} [infinite α] [fintype β] (f : α → β) : ∃ (x : α), ∃ (y : α), x ≠ y ∧ f x = f y := sorry
/--
The strong pigeonhole principle for infinitely many pigeons in
finitely many pigeonholes. If there are infinitely many pigeons in
finitely many pigeonholes, then there is a pigeonhole with infinitely
many pigeons.
See also: `fintype.exists_ne_map_eq_of_infinite`
-/
theorem fintype.exists_infinite_fiber {α : Type u_1} {β : Type u_2} [infinite α] [fintype β] (f : α → β) : ∃ (y : β), infinite ↥(f ⁻¹' singleton y) := sorry
theorem not_surjective_fintype_infinite {α : Type u_1} {β : Type u_2} [fintype α] [infinite β] (f : α → β) : ¬function.surjective f :=
fun (hf : function.surjective f) =>
(fun (H : infinite α) => infinite.not_fintype infer_instance) (infinite.of_surjective f hf)
protected instance nat.infinite : infinite ℕ :=
infinite.mk fun (_x : fintype ℕ) => sorry
protected instance int.infinite : infinite ℤ :=
infinite.of_injective Int.ofNat fun (_x _x_1 : ℕ) => int.of_nat.inj
/--
For `s : multiset α`, we can lift the existential statement that `∃ x, x ∈ s` to a `trunc α`.
-/
def trunc_of_multiset_exists_mem {α : Type u_1} (s : multiset α) : (∃ (x : α), x ∈ s) → trunc α :=
quotient.rec_on_subsingleton s fun (l : List α) (h : ∃ (x : α), x ∈ quotient.mk l) => sorry
/--
A `nonempty` `fintype` constructively contains an element.
-/
def trunc_of_nonempty_fintype (α : Type u_1) [Nonempty α] [fintype α] : trunc α :=
trunc_of_multiset_exists_mem (finset.val finset.univ) sorry
/--
A `fintype` with positive cardinality constructively contains an element.
-/
def trunc_of_card_pos {α : Type u_1} [fintype α] (h : 0 < fintype.card α) : trunc α :=
let _inst : Nonempty α := sorry;
trunc_of_nonempty_fintype α
/--
By iterating over the elements of a fintype, we can lift an existential statement `∃ a, P a`
to `trunc (Σ' a, P a)`, containing data.
-/
def trunc_sigma_of_exists {α : Type u_1} [fintype α] {P : α → Prop} [decidable_pred P] (h : ∃ (a : α), P a) : trunc (psigma fun (a : α) => P a) :=
trunc_of_nonempty_fintype (psigma fun (a : α) => P a)
|
cfbd70180964cd041be3b943e9b4eb3c700bb42c | a4673261e60b025e2c8c825dfa4ab9108246c32e | /stage0/src/Lean/Elab/Structure.lean | 1244f45a45fa0bab93bca67b90ae445be237b8c3 | [
"Apache-2.0"
] | permissive | jcommelin/lean4 | c02dec0cc32c4bccab009285475f265f17d73228 | 2909313475588cc20ac0436e55548a4502050d0a | refs/heads/master | 1,674,129,550,893 | 1,606,415,348,000 | 1,606,415,348,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 25,865 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Closure
import Lean.Elab.Command
import Lean.Elab.DeclModifiers
import Lean.Elab.DeclUtil
import Lean.Elab.Inductive
namespace Lean.Elab.Command
open Meta
/- Recall that the `structure command syntax is
```
parser! (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> optional (" := " >> optional structCtor >> structFields)
```
-/
structure StructCtorView :=
(ref : Syntax)
(modifiers : Modifiers)
(inferMod : Bool) -- true if `{}` is used in the constructor declaration
(name : Name)
(declName : Name)
structure StructFieldView :=
(ref : Syntax)
(modifiers : Modifiers)
(binderInfo : BinderInfo)
(inferMod : Bool)
(declName : Name)
(name : Name)
(binders : Syntax)
(type? : Option Syntax)
(value? : Option Syntax)
structure StructView :=
(ref : Syntax)
(modifiers : Modifiers)
(scopeLevelNames : List Name) -- All `universe` declarations in the current scope
(allUserLevelNames : List Name) -- `scopeLevelNames` ++ explicit universe parameters provided in the `structure` command
(isClass : Bool)
(declName : Name)
(scopeVars : Array Expr) -- All `variable` declaration in the current scope
(params : Array Expr) -- Explicit parameters provided in the `structure` command
(parents : Array Syntax)
(type : Syntax)
(ctor : StructCtorView)
(fields : Array StructFieldView)
inductive StructFieldKind :=
| newField | fromParent | subobject
structure StructFieldInfo :=
(name : Name)
(declName : Name) -- Remark: this field value doesn't matter for fromParent fields.
(fvar : Expr)
(kind : StructFieldKind)
(inferMod : Bool := false)
(value? : Option Expr := none)
instance : Inhabited StructFieldInfo :=
⟨{ name := arbitrary, declName := arbitrary, fvar := arbitrary, kind := StructFieldKind.newField }⟩
def StructFieldInfo.isFromParent (info : StructFieldInfo) : Bool :=
match info.kind with
| StructFieldKind.fromParent => true
| _ => false
def StructFieldInfo.isSubobject (info : StructFieldInfo) : Bool :=
match info.kind with
| StructFieldKind.subobject => true
| _ => false
/- Auxiliary declaration for `mkProjections` -/
structure ProjectionInfo :=
(declName : Name)
(inferMod : Bool)
structure ElabStructResult :=
(decl : Declaration)
(projInfos : List ProjectionInfo)
(projInstances : List Name) -- projections (to parent classes) that must be marked as instances.
(mctx : MetavarContext)
(lctx : LocalContext)
(localInsts : LocalInstances)
(defaultAuxDecls : Array (Name × Expr × Expr))
private def defaultCtorName := `mk
/-
The structure constructor syntax is
```
parser! try (declModifiers >> ident >> optional inferMod >> " :: ")
```
-/
private def expandCtor (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : CommandElabM StructCtorView :=
let useDefault :=
pure { ref := structStx, modifiers := {}, inferMod := false, name := defaultCtorName, declName := structDeclName ++ defaultCtorName }
if structStx[5].isNone then
useDefault
else
let optCtor := structStx[5][1]
if optCtor.isNone then
useDefault
else
let ctor := optCtor[0]
withRef ctor do
let ctorModifiers ← elabModifiers ctor[0]
checkValidCtorModifier ctorModifiers
if ctorModifiers.isPrivate && structModifiers.isPrivate then
throwError "invalid 'private' constructor in a 'private' structure"
if ctorModifiers.isProtected && structModifiers.isPrivate then
throwError "invalid 'protected' constructor in a 'private' structure"
let inferMod := !ctor[2].isNone
let name := ctor[1].getId
let declName := structDeclName ++ name
let declName ← applyVisibility ctorModifiers.visibility declName
pure { ref := ctor, name := name, modifiers := ctorModifiers, inferMod := inferMod, declName := declName }
def checkValidFieldModifier (modifiers : Modifiers) : CommandElabM Unit := do
if modifiers.isNoncomputable then
throwError "invalid use of 'noncomputable' in field declaration"
if modifiers.isPartial then
throwError "invalid use of 'partial' in field declaration"
if modifiers.isUnsafe then
throwError "invalid use of 'unsafe' in field declaration"
if modifiers.attrs.size != 0 then
throwError "invalid use of attributes in field declaration"
if modifiers.isPrivate then
throwError "private fields are not supported yet"
/-
```
def structExplicitBinder := parser! atomic (declModifiers true >> "(") >> many1 ident >> optional inferMod >> optDeclSig >> optional Term.binderDefault >> ")"
def structImplicitBinder := parser! atomic (declModifiers true >> "{") >> many1 ident >> optional inferMod >> declSig >> "}"
def structInstBinder := parser! atomic (declModifiers true >> "[") >> many1 ident >> optional inferMod >> declSig >> "]"
def structSimpleBinder := parser! atomic (declModifiers true >> many1 ident) >> optional inferMod >> optDeclSig >> optional Term.binderDefault
def structFields := parser! many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder)
```
-/
private def expandFields (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : CommandElabM (Array StructFieldView) :=
let fieldBinders := if structStx[5].isNone then #[] else structStx[5][2][0].getArgs
fieldBinders.foldlM (init := #[]) fun (views : Array StructFieldView) fieldBinder => withRef fieldBinder do
let mut fieldBinder := fieldBinder
if fieldBinder.getKind == `Lean.Parser.Command.structSimpleBinder then
fieldBinder := Syntax.node `Lean.Parser.Command.structExplicitBinder
#[ fieldBinder[0], mkAtomFrom fieldBinder "(", fieldBinder[1], fieldBinder[2], fieldBinder[3], fieldBinder[4], mkAtomFrom fieldBinder ")" ]
let k := fieldBinder.getKind
let binfo ←
if k == `Lean.Parser.Command.structExplicitBinder then pure BinderInfo.default
else if k == `Lean.Parser.Command.structImplicitBinder then pure BinderInfo.implicit
else if k == `Lean.Parser.Command.structInstBinder then pure BinderInfo.instImplicit
else throwError "unexpected kind of structure field"
let fieldModifiers ← elabModifiers fieldBinder[0]
checkValidFieldModifier fieldModifiers
if fieldModifiers.isPrivate && structModifiers.isPrivate then
throwError "invalid 'private' field in a 'private' structure"
if fieldModifiers.isProtected && structModifiers.isPrivate then
throwError "invalid 'protected' field in a 'private' structure"
let inferMod := !fieldBinder[3].isNone
let (binders, type?) :=
if binfo == BinderInfo.default then
expandOptDeclSig fieldBinder[4]
else
let (binders, type) := expandDeclSig fieldBinder[4]
(binders, some type)
let value? :=
if binfo != BinderInfo.default then none
else
let optBinderDefault := fieldBinder[5]
if optBinderDefault.isNone then none
else
-- binderDefault := parser! " := " >> termParser
some optBinderDefault[0][1]
let idents := fieldBinder[2].getArgs
idents.foldlM (init := views) fun (views : Array StructFieldView) ident => withRef ident do
let name := ident.getId
if isInternalSubobjectFieldName name then
throwError! "invalid field name '{name}', identifiers starting with '_' are reserved to the system"
let declName := structDeclName ++ name
let declName ← applyVisibility fieldModifiers.visibility declName
return views.push {
ref := ident,
modifiers := fieldModifiers,
binderInfo := binfo,
inferMod := inferMod,
declName := declName,
name := name,
binders := binders,
type? := type?,
value? := value?
}
private def validStructType (type : Expr) : Bool :=
match type with
| Expr.sort .. => true
| _ => false
private def checkParentIsStructure (parent : Expr) : TermElabM Name :=
match parent.getAppFn with
| Expr.const c _ _ => do
unless isStructure (← getEnv) c do
throwError! "'{c}' is not a structure"
pure c
| _ => throwError "expected structure"
private def findFieldInfo? (infos : Array StructFieldInfo) (fieldName : Name) : Option StructFieldInfo :=
infos.find? fun info => info.name == fieldName
private def containsFieldName (infos : Array StructFieldInfo) (fieldName : Name) : Bool :=
(findFieldInfo? infos fieldName).isSome
private partial def processSubfields (structDeclName : Name) (parentFVar : Expr) (parentStructName : Name) (subfieldNames : Array Name)
(infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α :=
let rec loop (i : Nat) (infos : Array StructFieldInfo) := do
if h : i < subfieldNames.size then
let subfieldName := subfieldNames.get ⟨i, h⟩
if containsFieldName infos subfieldName then
throwError! "field '{subfieldName}' from '{parentStructName}' has already been declared"
let val ← mkProjection parentFVar subfieldName
let type ← inferType val
withLetDecl subfieldName type val fun subfieldFVar =>
/- The following `declName` is only used for creating the `_default` auxiliary declaration name when
its default value is overwritten in the structure. -/
let declName := structDeclName ++ subfieldName
let infos := infos.push { name := subfieldName, declName := declName, fvar := subfieldFVar, kind := StructFieldKind.fromParent }
loop (i+1) infos
else
k infos
loop 0 infos
private partial def withParents (view : StructView) (i : Nat) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do
if h : i < view.parents.size then
let parentStx := view.parents.get ⟨i, h⟩
withRef parentStx do
let parent ← Term.elabType parentStx
let parentName ← checkParentIsStructure parent
let toParentName := Name.mkSimple $ "to" ++ parentName.eraseMacroScopes.getString! -- erase macro scopes?
if containsFieldName infos toParentName then
throwErrorAt! parentStx "field '{toParentName}' has already been declared"
let env ← getEnv
let binfo := if view.isClass && isClass env parentName then BinderInfo.instImplicit else BinderInfo.default
withLocalDecl toParentName binfo parent fun parentFVar =>
let infos := infos.push { name := toParentName, declName := view.declName ++ toParentName, fvar := parentFVar, kind := StructFieldKind.subobject }
let subfieldNames := getStructureFieldsFlattened env parentName
processSubfields view.declName parentFVar parentName subfieldNames infos fun infos => withParents view (i+1) infos k
else
k infos
private def elabFieldTypeValue (view : StructFieldView) (params : Array Expr) : TermElabM (Option Expr × Option Expr) := do
match view.type? with
| none =>
match view.value? with
| none => pure (none, none)
| some valStx =>
let value ← Term.elabTerm valStx none
let value ← mkLambdaFVars params value
pure (none, value)
| some typeStx =>
let type ← Term.elabType typeStx
match view.value? with
| none =>
let type ← mkForallFVars params type
pure (type, none)
| some valStx =>
let value ← Term.elabTermEnsuringType valStx type
let type ← mkForallFVars params type
let value ← mkLambdaFVars params value
pure (type, value)
private partial def withFields
(views : Array StructFieldView) (i : Nat) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do
if h : i < views.size then
let view := views.get ⟨i, h⟩
withRef view.ref $
match findFieldInfo? infos view.name with
| none => do
let (type?, value?) ← Term.elabBinders view.binders.getArgs fun params => elabFieldTypeValue view params
match type?, value? with
| none, none => throwError "invalid field, type expected"
| some type, _ =>
withLocalDecl view.name view.binderInfo type fun fieldFVar =>
let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value?,
kind := StructFieldKind.newField, inferMod := view.inferMod }
withFields views (i+1) infos k
| none, some value =>
let type ← inferType value
withLocalDecl view.name view.binderInfo type fun fieldFVar =>
let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value,
kind := StructFieldKind.newField, inferMod := view.inferMod }
withFields views (i+1) infos k
| some info =>
match info.kind with
| StructFieldKind.newField => throwError! "field '{view.name}' has already been declared"
| StructFieldKind.fromParent =>
match view.value? with
| none => throwError! "field '{view.name}' has been declared in parent structure"
| some valStx => do
if !view.binders.getArgs.isEmpty || view.type?.isSome then
throwErrorAt! view.type?.get! "omit field '{view.name}' type to set default value"
let fvarType ← inferType info.fvar
let value ← Term.elabTermEnsuringType valStx fvarType
let infos := infos.push { info with value? := value }
withFields views (i+1) infos k
| StructFieldKind.subobject => unreachable!
else
k infos
private def getResultUniverse (type : Expr) : TermElabM Level := do
let type ← whnf type
match type with
| Expr.sort u _ => pure u
| _ => throwError "unexpected structure resulting type"
private def collectUsed (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT CollectFVars.State TermElabM Unit := do
params.forM fun p => do
let type ← inferType p
Term.collectUsedFVars type
fieldInfos.forM fun info => do
let fvarType ← inferType info.fvar
Term.collectUsedFVars fvarType
match info.value? with
| none => pure ()
| some value => Term.collectUsedFVars value
private def removeUnused (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo)
: TermElabM (LocalContext × LocalInstances × Array Expr) := do
let (_, used) ← (collectUsed params fieldInfos).run {}
Term.removeUnused scopeVars used
private def withUsed {α} (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) (k : Array Expr → TermElabM α)
: TermElabM α := do
let (lctx, localInsts, vars) ← removeUnused scopeVars params fieldInfos
withLCtx lctx localInsts $ k vars
private def levelMVarToParamFVar (fvar : Expr) : StateRefT Nat TermElabM Unit := do
let type ← inferType fvar
Term.levelMVarToParam' type
pure ()
private def levelMVarToParamFVars (fvars : Array Expr) : StateRefT Nat TermElabM Unit :=
fvars.forM levelMVarToParamFVar
private def levelMVarToParamAux (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo)
: StateRefT Nat TermElabM (Array StructFieldInfo) := do
levelMVarToParamFVars scopeVars
levelMVarToParamFVars params
fieldInfos.mapM fun info => do
levelMVarToParamFVar info.fvar
match info.value? with
| none => pure info
| some value =>
let value ← Term.levelMVarToParam' value
pure { info with value? := value }
private def levelMVarToParam (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (Array StructFieldInfo) :=
(levelMVarToParamAux scopeVars params fieldInfos).run' 1
private partial def collectUniversesFromFields (r : Level) (rOffset : Nat) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Level) := do
fieldInfos.foldlM (init := #[]) fun (us : Array Level) (info : StructFieldInfo) => do
let type ← inferType info.fvar
let u ← getLevel type
let u ← instantiateLevelMVars u
accLevelAtCtor u r rOffset us
private def updateResultingUniverse (fieldInfos : Array StructFieldInfo) (type : Expr) : TermElabM Expr := do
let r ← getResultUniverse type
let rOffset : Nat := r.getOffset
let r : Level := r.getLevelOffset
match r with
| Level.mvar mvarId _ =>
let us ← collectUniversesFromFields r rOffset fieldInfos
let rNew := mkResultUniverse us rOffset
assignLevelMVar mvarId rNew
instantiateMVars type
| _ => throwError "failed to compute resulting universe level of structure, provide universe explicitly"
private def collectLevelParamsInFVar (s : CollectLevelParams.State) (fvar : Expr) : TermElabM CollectLevelParams.State := do
let type ← inferType fvar
let type ← instantiateMVars type
pure $ collectLevelParams s type
private def collectLevelParamsInFVars (fvars : Array Expr) (s : CollectLevelParams.State) : TermElabM CollectLevelParams.State :=
fvars.foldlM collectLevelParamsInFVar s
private def collectLevelParamsInStructure (structType : Expr) (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo)
: TermElabM (Array Name) := do
let s := collectLevelParams {} structType
let s ← collectLevelParamsInFVars scopeVars s
let s ← collectLevelParamsInFVars params s
let s ← fieldInfos.foldlM (fun (s : CollectLevelParams.State) info => collectLevelParamsInFVar s info.fvar) s
pure s.params
private def addCtorFields (fieldInfos : Array StructFieldInfo) : Nat → Expr → TermElabM Expr
| 0, type => pure type
| i+1, type => do
let info := fieldInfos[i]
let decl ← Term.getFVarLocalDecl! info.fvar
let type ← instantiateMVars type
let type := type.abstract #[info.fvar]
match info.kind with
| StructFieldKind.fromParent =>
let val := decl.value
addCtorFields fieldInfos i (type.instantiate1 val)
| StructFieldKind.subobject =>
let n := mkInternalSubobjectFieldName $ decl.userName
addCtorFields fieldInfos i (mkForall n decl.binderInfo decl.type type)
| StructFieldKind.newField =>
addCtorFields fieldInfos i (mkForall decl.userName decl.binderInfo decl.type type)
private def mkCtor (view : StructView) (levelParams : List Name) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM Constructor :=
withRef view.ref do
let type := mkAppN (mkConst view.declName (levelParams.map mkLevelParam)) params
let type ← addCtorFields fieldInfos fieldInfos.size type
let type ← mkForallFVars params type
let type ← instantiateMVars type
let type := type.inferImplicit params.size !view.ctor.inferMod
pure { name := view.ctor.declName, type := type }
@[extern "lean_mk_projections"]
private constant mkProjections (env : Environment) (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : Except String Environment
private def addProjections (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : TermElabM Unit := do
let env ← getEnv
match mkProjections env structName projs isClass with
| Except.ok env => setEnv env
| Except.error msg => throwError msg
private def mkAuxConstructions (declName : Name) : TermElabM Unit := do
let env ← getEnv
let hasUnit := env.contains `PUnit
let hasEq := env.contains `Eq
let hasHEq := env.contains `HEq
mkRecOn declName
if hasUnit then mkCasesOn declName
if hasUnit && hasEq && hasHEq then mkNoConfusion declName
private def addDefaults (lctx : LocalContext) (defaultAuxDecls : Array (Name × Expr × Expr)) : TermElabM Unit := do
let localInsts ← getLocalInstances
withLCtx lctx localInsts do
defaultAuxDecls.forM fun (declName, type, value) => do
/- The identity function is used as "marker". -/
let value ← mkId value
mkAuxDefinition declName type value (zeta := true)
setReducibleAttribute declName
private def elabStructureView (view : StructView) : TermElabM Unit := do
let numExplicitParams := view.params.size
let type ← Term.elabType view.type
unless validStructType type do throwErrorAt view.type "expected Type"
withRef view.ref do
withParents view 0 #[] fun fieldInfos =>
withFields view.fields 0 fieldInfos fun fieldInfos => do
Term.synthesizeSyntheticMVarsNoPostponing
let u ← getResultUniverse type
let inferLevel ← shouldInferResultUniverse u
withUsed view.scopeVars view.params fieldInfos $ fun scopeVars => do
let numParams := scopeVars.size + numExplicitParams
let fieldInfos ← levelMVarToParam scopeVars view.params fieldInfos
let type ← withRef view.ref do
if inferLevel then
updateResultingUniverse fieldInfos type
else
checkResultingUniverse (← getResultUniverse type)
pure type
trace[Elab.structure]! "type: {type}"
let usedLevelNames ← collectLevelParamsInStructure type scopeVars view.params fieldInfos
match sortDeclLevelParams view.scopeLevelNames view.allUserLevelNames usedLevelNames with
| Except.error msg => throwError msg
| Except.ok levelParams =>
let params := scopeVars ++ view.params
let ctor ← mkCtor view levelParams params fieldInfos
let type ← mkForallFVars params type
let type ← instantiateMVars type
let indType := { name := view.declName, type := type, ctors := [ctor] : InductiveType }
let decl := Declaration.inductDecl levelParams params.size [indType] view.modifiers.isUnsafe
Term.ensureNoUnassignedMVars decl
addDecl decl
let projInfos := (fieldInfos.filter fun (info : StructFieldInfo) => !info.isFromParent).toList.map fun (info : StructFieldInfo) =>
{ declName := info.declName, inferMod := info.inferMod : ProjectionInfo }
addProjections view.declName projInfos view.isClass
mkAuxConstructions view.declName
let instParents ← fieldInfos.filterM fun info => do
let decl ← Term.getFVarLocalDecl! info.fvar
pure (info.isSubobject && decl.binderInfo.isInstImplicit)
let projInstances := instParents.toList.map fun info => info.declName
Term.applyAttributesAt view.declName view.modifiers.attrs AttributeApplicationTime.afterTypeChecking
projInstances.forM addGlobalInstance
let lctx ← getLCtx
let fieldsWithDefault := fieldInfos.filter fun info => info.value?.isSome
let defaultAuxDecls ← fieldsWithDefault.mapM fun info => do
let type ← inferType info.fvar
pure (info.declName ++ `_default, type, info.value?.get!)
/- The `lctx` and `defaultAuxDecls` are used to create the auxiliary `_default` declarations
The parameters `params` for these definitions must be marked as implicit, and all others as explicit. -/
let lctx :=
params.foldl (init := lctx) fun (lctx : LocalContext) (p : Expr) =>
lctx.updateBinderInfo p.fvarId! BinderInfo.implicit
let lctx :=
fieldInfos.foldl (init := lctx) fun (lctx : LocalContext) (info : StructFieldInfo) =>
if info.isFromParent then lctx -- `fromParent` fields are elaborated as let-decls, and are zeta-expanded when creating `_default`.
else lctx.updateBinderInfo info.fvar.fvarId! BinderInfo.default
addDefaults lctx defaultAuxDecls
/-
parser! (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> " := " >> optional structCtor >> structFields
where
def «extends» := parser! " extends " >> sepBy1 termParser ", "
def typeSpec := parser! " : " >> termParser
def optType : Parser := optional typeSpec
def structFields := parser! many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder)
def structCtor := parser! try (declModifiers >> ident >> optional inferMod >> " :: ")
-/
def elabStructure (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do
checkValidInductiveModifier modifiers
let isClass := stx[0].getKind == `Lean.Parser.Command.classTk
let modifiers := if isClass then modifiers.addAttribute { name := `class } else modifiers
let declId := stx[1]
let params := stx[2].getArgs
let exts := stx[3]
let parents := if exts.isNone then #[] else exts[0][1].getSepArgs
let optType := stx[4]
let type ← if optType.isNone then `(Sort _) else pure optType[0][1]
let scopeLevelNames ← getLevelNames
let ⟨name, declName, allUserLevelNames⟩ ← expandDeclId declId modifiers
let ctor ← expandCtor stx modifiers declName
let fields ← expandFields stx modifiers declName
runTermElabM declName $ fun scopeVars => Term.withLevelNames allUserLevelNames $ Term.elabBinders params fun params => elabStructureView {
ref := stx,
modifiers := modifiers,
scopeLevelNames := scopeLevelNames,
allUserLevelNames := allUserLevelNames,
declName := declName,
isClass := isClass,
scopeVars := scopeVars,
params := params,
parents := parents,
type := type,
ctor := ctor,
fields := fields
}
builtin_initialize registerTraceClass `Elab.structure
end Lean.Elab.Command
|
6ddd7ecefc45316b5c01ddac6c85cf0af526c24b | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/algebra/group/to_additive.lean | 575d37e270e2e2482587f013047cf291542f001b | [
"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 | 10,902 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Yury Kudryashov.
-/
import tactic.transform_decl
import tactic.algebra
/-!
# Transport multiplicative to additive
This file defines an attribute `to_additive` that can be used to
automatically transport theorems and definitions (but not inductive
types and structures) from a multiplicative theory to an additive theory.
Usage information is contained in the doc string of `to_additive.attr`.
### Missing features
* Automatically transport structures and other inductive types.
* For structures, automatically generate theorems like `group α ↔
add_group (additive α)`.
* Rewrite rules for the last part of the name that work in more
cases. E.g., we can replace `monoid` with `add_monoid` etc.
-/
namespace to_additive
open tactic exceptional
section performance_hack -- see Note [user attribute parameters]
local attribute [semireducible] reflected
local attribute [instance, priority 9000]
private meta def hacky_name_reflect : has_reflect name :=
λ n, `(id %%(expr.const n []) : name)
/-- An auxiliary attribute used to store the names of the additive versions of declarations
that have been processed by `to_additive`. -/
@[user_attribute]
private meta def aux_attr : user_attribute (name_map name) name :=
{ name := `to_additive_aux,
descr := "Auxiliary attribute for `to_additive`. DON'T USE IT",
cache_cfg := ⟨λ ns,
ns.mfoldl
(λ dict n', do
let n := match n' with
| name.mk_string s pre := if s = "_to_additive" then pre else n'
| _ := n'
end,
param ← aux_attr.get_param_untyped n',
pure $ dict.insert n param.app_arg.const_name)
mk_name_map, []⟩,
parser := lean.parser.ident }
end performance_hack
/-- A command that can be used to have future uses of `to_additive` change the `src` namespace
to the `tgt` namespace.
For example:
```
run_cmd to_additive.map_namespace `quotient_group `quotient_add_group
```
Later uses of `to_additive` on declarations in the `quotient_group` namespace will be created
in the `quotient_add_group` namespaces.
-/
meta def map_namespace (src tgt : name) : command :=
do let n := src.mk_string "_to_additive",
let decl := declaration.thm n [] `(unit) (pure (reflect ())),
add_decl decl,
aux_attr.set n tgt tt
/-- `value_type` is the type of the arguments that can be provided to `to_additive`.
`to_additive.parser` parses the provided arguments into `name` for the target and an
optional doc string. -/
@[derive has_reflect, derive inhabited]
structure value_type : Type := (tgt : name) (doc : option string)
/-- Dictionary used by `to_additive.guess_name` to autogenerate names. -/
meta def tr : list string → list string
| ("one" :: "le" :: s) := "nonneg" :: tr s
| ("one" :: "lt" :: s) := "pos" :: tr s
| ("le" :: "one" :: s) := "nonpos" :: tr s
| ("lt" :: "one" :: s) := "neg" :: tr s
| ("mul" :: s) := "add" :: tr s
| ("inv" :: s) := "neg" :: tr s
| ("div" :: s) := "sub" :: tr s
| ("one" :: s) := "zero" :: tr s
| ("prod" :: s) := "sum" :: tr s
| (x :: s) := (x :: tr s)
| [] := []
/-- Autogenerate target name for `to_additive`. -/
meta def guess_name : string → string :=
string.map_tokens ''' $
λ s, string.intercalate (string.singleton '_') $
tr (s.split_on '_')
/-- Return the provided target name or autogenerate one if one was not provided. -/
meta def target_name (src tgt : name) (dict : name_map name) : tactic name :=
(if tgt.get_prefix ≠ name.anonymous -- `tgt` is a full name
then pure tgt
else match src with
| (name.mk_string s pre) :=
do let tgt_auto := guess_name s,
guard (tgt.to_string ≠ tgt_auto)
<|> trace ("`to_additive " ++ src.to_string ++ "`: correctly autogenerated target " ++
"name, you may remove the explicit " ++ tgt_auto ++ " argument."),
pure $ name.mk_string
(if tgt = name.anonymous then tgt_auto else tgt.to_string)
(pre.map_prefix dict.find)
| _ := fail ("to_additive: can't transport " ++ src.to_string)
end) >>=
(λ res,
if res = src
then fail ("to_additive: can't transport " ++ src.to_string ++ " to itself")
else pure res)
/-- the parser for the arguments to `to_additive` -/
meta def parser : lean.parser value_type :=
do
tgt ← optional lean.parser.ident,
e ← optional interactive.types.texpr,
doc ← match e with
| some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string)
| none := pure none
end,
return ⟨tgt.get_or_else name.anonymous, doc⟩
private meta def proceed_fields_aux (src tgt : name) (prio : ℕ) (f : name → tactic (list string)) :
command :=
do
src_fields ← f src,
tgt_fields ← f tgt,
guard (src_fields.length = tgt_fields.length) <|>
fail ("Failed to map fields of " ++ src.to_string),
(src_fields.zip tgt_fields).mmap' $
λ names, guard (names.fst = names.snd) <|>
aux_attr.set (src.append names.fst) (tgt.append names.snd) tt prio
/-- Add the `aux_attr` attribute to the structure fields of `src`
so that future uses of `to_additive` will map them to the corresponding `tgt` fields. -/
meta def proceed_fields (env : environment) (src tgt : name) (prio : ℕ) : command :=
let aux := proceed_fields_aux src tgt prio in
do
aux (λ n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >>
aux (λ n, (list.map (λ (x : name), "to_" ++ x.to_string) <$> get_tagged_ancestors n)) >>
aux (λ n, (env.constructors_of n).mmap $
λ cs, match cs with
| (name.mk_string s pre) :=
(guard (pre = n) <|> fail "Bad constructor name") >>
pure s
| _ := fail "Bad constructor name"
end)
/--
The attribute `to_additive` can be used to automatically transport theorems
and definitions (but not inductive types and structures) from a multiplicative
theory to an additive theory.
To use this attribute, just write:
```
@[to_additive]
theorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm
```
This code will generate a theorem named `add_comm'`. It is also
possible to manually specify the name of the new declaration, and
provide a documentation string:
```
@[to_additive add_foo "add_foo doc string"]
/-- foo doc string -/
theorem foo := sorry
```
The transport tries to do the right thing in most cases using several
heuristics described below. However, in some cases it fails, and
requires manual intervention.
## Implementation notes
The transport process generally works by taking all the names of
identifiers appearing in the name, type, and body of a declaration and
creating a new declaration by mapping those names to additive versions
using a simple string-based dictionary and also using all declarations
that have previously been labeled with `to_additive`.
In the `mul_comm'` example above, `to_additive` maps:
* `mul_comm'` to `add_comm'`,
* `comm_semigroup` to `add_comm_semigroup`,
* `x * y` to `x + y` and `y * x` to `y + x`, and
* `comm_semigroup.mul_comm'` to `add_comm_semigroup.add_comm'`.
Even when `to_additive` is unable to automatically generate the additive
version of a declaration, it can be useful to apply the attribute manually:
```
attribute [to_additive foo_add_bar] foo_bar
```
This will allow future uses of `to_additive` to recognize that
`foo_bar` should be replaced with `foo_add_bar`.
### Handling of hidden definitions
Before transporting the “main” declaration `src`, `to_additive` first
scans its type and value for names starting with `src`, and transports
them. This includes auxiliary definitions like `src._match_1`,
`src._proof_1`.
After transporting the “main” declaration, `to_additive` transports
its equational lemmas.
### Structure fields and constructors
If `src` is a structure, then `to_additive` automatically adds
structure fields to its mapping, and similarly for constructors of
inductive types.
For new structures this means that `to_additive` automatically handles
coercions, and for old structures it does the same, if ancestry
information is present in `@[ancestor]` attributes.
### Name generation
* If `@[to_additive]` is called without a `name` argument, then the
new name is autogenerated. First, it takes the longest prefix of
the source name that is already known to `to_additive`, and replaces
this prefix with its additive counterpart. Second, it takes the last
part of the name (i.e., after the last dot), and replaces common
name parts (“mul”, “one”, “inv”, “prod”) with their additive versions.
* Namespaces can be transformed using `map_namespace`. For example:
```
run_cmd to_additive.map_namespace `quotient_group `quotient_add_group
```
Later uses of `to_additive` on declarations in the `quotient_group`
namespace will be created in the `quotient_add_group` namespaces.
* If `@[to_additive]` is called with a `name` argument `new_name`
/without a dot/, then `to_additive` updates the prefix as described
above, then replaces the last part of the name with `new_name`.
* If `@[to_additive]` is called with a `name` argument
`new_namespace.new_name` /with a dot/, then `to_additive` uses this
new name as is.
As a safety check, in the first two cases `to_additive` double checks
that the new name differs from the original one.
-/
@[user_attribute]
protected meta def attr : user_attribute unit value_type :=
{ name := `to_additive,
descr := "Transport multiplicative to additive",
parser := parser,
after_set := some $ λ src prio persistent, do
guard persistent <|> fail "`to_additive` can't be used as a local attribute",
env ← get_env,
val ← attr.get_param src,
dict ← aux_attr.get_cache,
tgt ← target_name src val.tgt dict,
aux_attr.set src tgt tt,
let dict := dict.insert src tgt,
if env.contains tgt
then proceed_fields env src tgt prio
else do
transform_decl_with_prefix_dict dict src tgt
[`reducible, `simp, `instance, `refl, `symm, `trans, `elab_as_eliminator, `no_rsimp],
match val.doc with
| some doc := add_doc_string tgt doc
| none := skip
end }
add_tactic_doc
{ name := "to_additive",
category := doc_category.attr,
decl_names := [`to_additive.attr],
tags := ["transport", "environment", "lemma derivation"] }
end to_additive
/- map operations -/
attribute [to_additive] has_mul has_one has_inv
|
b55207d94b24e05fbdd3fbb9731fdc29ca07b7ed | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /test/norm_num_ext.lean | 7009667fa041c3709191b2bf4d242d0081f9c83d | [
"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 | 12,614 | lean | /-
Copyright (c) 2021 Mario Carneiro All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.big_operators.norm_num
import data.nat.squarefree
import data.int.gcd
import data.nat.fib
import data.nat.prime
import data.nat.sqrt_norm_num
import analysis.special_functions.pow
import number_theory.legendre_symbol.norm_num
/-!
# Tests for `norm_num` extensions
-/
-- coverage tests
example : nat.sqrt 0 = 0 := by norm_num
example : nat.sqrt 1 = 1 := by norm_num
example : nat.sqrt 2 = 1 := by norm_num
example : nat.sqrt 3 = 1 := by norm_num
example : nat.sqrt 4 = 2 := by norm_num
example : nat.sqrt 9 = 3 := by norm_num
example : nat.sqrt 10 = 3 := by norm_num
example : nat.sqrt 100 = 10 := by norm_num
example : nat.sqrt 120 = 10 := by norm_num
example : nat.sqrt 121 = 11 := by norm_num
example : nat.coprime 1 2 := by norm_num
example : nat.coprime 2 1 := by norm_num
example : ¬ nat.coprime 0 0 := by norm_num
example : ¬ nat.coprime 0 3 := by norm_num
example : ¬ nat.coprime 2 0 := by norm_num
example : nat.coprime 2 3 := by norm_num
example : ¬ nat.coprime 2 4 := by norm_num
example : nat.gcd 1 2 = 1 := by norm_num
example : nat.gcd 2 1 = 1 := by norm_num
example : nat.gcd 0 0 = 0 := by norm_num
example : nat.gcd 0 3 = 3 := by norm_num
example : nat.gcd 2 0 = 2 := by norm_num
example : nat.gcd 2 3 = 1 := by norm_num
example : nat.gcd 2 4 = 2 := by norm_num
example : nat.lcm 1 2 = 2 := by norm_num
example : nat.lcm 2 1 = 2 := by norm_num
example : nat.lcm 0 0 = 0 := by norm_num
example : nat.lcm 0 3 = 0 := by norm_num
example : nat.lcm 2 0 = 0 := by norm_num
example : nat.lcm 2 3 = 6 := by norm_num
example : nat.lcm 2 4 = 4 := by norm_num
example : int.gcd 2 3 = 1 := by norm_num
example : int.gcd (-2) 3 = 1 := by norm_num
example : int.gcd 2 (-3) = 1 := by norm_num
example : int.gcd (-2) (-3) = 1 := by norm_num
example : int.lcm 2 3 = 6 := by norm_num
example : int.lcm (-2) 3 = 6 := by norm_num
example : int.lcm 2 (-3) = 6 := by norm_num
example : int.lcm (-2) (-3) = 6 := by norm_num
example : ¬ nat.prime 0 := by norm_num
example : ¬ nat.prime 1 := by norm_num
example : nat.prime 2 := by norm_num
example : nat.prime 3 := by norm_num
example : ¬ nat.prime 4 := by norm_num
example : nat.prime 5 := by norm_num
example : nat.prime 109 := by norm_num
example : nat.prime 1277 := by norm_num
example : ¬ nat.prime 1000000000000000000000000000000000000000000000000 := by norm_num
example : nat.min_fac 0 = 2 := by norm_num
example : nat.min_fac 1 = 1 := by norm_num
example : nat.min_fac 2 = 2 := by norm_num
example : nat.min_fac 3 = 3 := by norm_num
example : nat.min_fac 4 = 2 := by norm_num
example : nat.min_fac 121 = 11 := by norm_num
example : nat.min_fac 221 = 13 := by norm_num
example : nat.factors 0 = [] := by norm_num
example : nat.factors 1 = [] := by norm_num
example : nat.factors 2 = [2] := by norm_num
example : nat.factors 3 = [3] := by norm_num
example : nat.factors 4 = [2, 2] := by norm_num
example : nat.factors 12 = [2, 2, 3] := by norm_num
example : nat.factors 221 = [13, 17] := by norm_num
-- randomized tests
example : nat.gcd 35 29 = 1 := by norm_num
example : int.gcd 35 29 = 1 := by norm_num
example : nat.lcm 35 29 = 1015 := by norm_num
example : int.gcd 35 29 = 1 := by norm_num
example : nat.coprime 35 29 := by norm_num
example : nat.gcd 80 2 = 2 := by norm_num
example : int.gcd 80 2 = 2 := by norm_num
example : nat.lcm 80 2 = 80 := by norm_num
example : int.gcd 80 2 = 2 := by norm_num
example : ¬ nat.coprime 80 2 := by norm_num
example : nat.gcd 19 17 = 1 := by norm_num
example : int.gcd 19 17 = 1 := by norm_num
example : nat.lcm 19 17 = 323 := by norm_num
example : int.gcd 19 17 = 1 := by norm_num
example : nat.coprime 19 17 := by norm_num
example : nat.gcd 11 18 = 1 := by norm_num
example : int.gcd 11 18 = 1 := by norm_num
example : nat.lcm 11 18 = 198 := by norm_num
example : int.gcd 11 18 = 1 := by norm_num
example : nat.coprime 11 18 := by norm_num
example : nat.gcd 23 73 = 1 := by norm_num
example : int.gcd 23 73 = 1 := by norm_num
example : nat.lcm 23 73 = 1679 := by norm_num
example : int.gcd 23 73 = 1 := by norm_num
example : nat.coprime 23 73 := by norm_num
example : nat.gcd 73 68 = 1 := by norm_num
example : int.gcd 73 68 = 1 := by norm_num
example : nat.lcm 73 68 = 4964 := by norm_num
example : int.gcd 73 68 = 1 := by norm_num
example : nat.coprime 73 68 := by norm_num
example : nat.gcd 28 16 = 4 := by norm_num
example : int.gcd 28 16 = 4 := by norm_num
example : nat.lcm 28 16 = 112 := by norm_num
example : int.gcd 28 16 = 4 := by norm_num
example : ¬ nat.coprime 28 16 := by norm_num
example : nat.gcd 44 98 = 2 := by norm_num
example : int.gcd 44 98 = 2 := by norm_num
example : nat.lcm 44 98 = 2156 := by norm_num
example : int.gcd 44 98 = 2 := by norm_num
example : ¬ nat.coprime 44 98 := by norm_num
example : nat.gcd 21 79 = 1 := by norm_num
example : int.gcd 21 79 = 1 := by norm_num
example : nat.lcm 21 79 = 1659 := by norm_num
example : int.gcd 21 79 = 1 := by norm_num
example : nat.coprime 21 79 := by norm_num
example : nat.gcd 93 34 = 1 := by norm_num
example : int.gcd 93 34 = 1 := by norm_num
example : nat.lcm 93 34 = 3162 := by norm_num
example : int.gcd 93 34 = 1 := by norm_num
example : nat.coprime 93 34 := by norm_num
example : ¬ nat.prime 912 := by norm_num
example : nat.min_fac 912 = 2 := by norm_num
example : nat.factors 912 = [2, 2, 2, 2, 3, 19] := by norm_num
example : ¬ nat.prime 681 := by norm_num
example : nat.min_fac 681 = 3 := by norm_num
example : nat.factors 681 = [3, 227] := by norm_num
example : ¬ nat.prime 728 := by norm_num
example : nat.min_fac 728 = 2 := by norm_num
example : nat.factors 728 = [2, 2, 2, 7, 13] := by norm_num
example : ¬ nat.prime 248 := by norm_num
example : nat.min_fac 248 = 2 := by norm_num
example : nat.factors 248 = [2, 2, 2, 31] := by norm_num
example : ¬ nat.prime 682 := by norm_num
example : nat.min_fac 682 = 2 := by norm_num
example : nat.factors 682 = [2, 11, 31] := by norm_num
example : ¬ nat.prime 115 := by norm_num
example : nat.min_fac 115 = 5 := by norm_num
example : nat.factors 115 = [5, 23] := by norm_num
example : ¬ nat.prime 824 := by norm_num
example : nat.min_fac 824 = 2 := by norm_num
example : nat.factors 824 = [2, 2, 2, 103] := by norm_num
example : ¬ nat.prime 942 := by norm_num
example : nat.min_fac 942 = 2 := by norm_num
example : nat.factors 942 = [2, 3, 157] := by norm_num
example : ¬ nat.prime 34 := by norm_num
example : nat.min_fac 34 = 2 := by norm_num
example : nat.factors 34 = [2, 17] := by norm_num
example : ¬ nat.prime 754 := by norm_num
example : nat.min_fac 754 = 2 := by norm_num
example : nat.factors 754 = [2, 13, 29] := by norm_num
example : ¬ nat.prime 663 := by norm_num
example : nat.min_fac 663 = 3 := by norm_num
example : nat.factors 663 = [3, 13, 17] := by norm_num
example : ¬ nat.prime 923 := by norm_num
example : nat.min_fac 923 = 13 := by norm_num
example : nat.factors 923 = [13, 71] := by norm_num
example : ¬ nat.prime 77 := by norm_num
example : nat.min_fac 77 = 7 := by norm_num
example : nat.factors 77 = [7, 11] := by norm_num
example : ¬ nat.prime 162 := by norm_num
example : nat.min_fac 162 = 2 := by norm_num
example : nat.factors 162 = [2, 3, 3, 3, 3] := by norm_num
example : ¬ nat.prime 669 := by norm_num
example : nat.min_fac 669 = 3 := by norm_num
example : nat.factors 669 = [3, 223] := by norm_num
example : ¬ nat.prime 476 := by norm_num
example : nat.min_fac 476 = 2 := by norm_num
example : nat.factors 476 = [2, 2, 7, 17] := by norm_num
example : nat.prime 251 := by norm_num
example : nat.min_fac 251 = 251 := by norm_num
example : nat.factors 251 = [251] := by norm_num
example : ¬ nat.prime 129 := by norm_num
example : nat.min_fac 129 = 3 := by norm_num
example : nat.factors 129 = [3, 43] := by norm_num
example : ¬ nat.prime 471 := by norm_num
example : nat.min_fac 471 = 3 := by norm_num
example : nat.factors 471 = [3, 157] := by norm_num
example : ¬ nat.prime 851 := by norm_num
example : nat.min_fac 851 = 23 := by norm_num
example : nat.factors 851 = [23, 37] := by norm_num
example : ¬ squarefree 0 := by norm_num
example : squarefree 1 := by norm_num
example : squarefree 2 := by norm_num
example : squarefree 3 := by norm_num
example : ¬ squarefree 4 := by norm_num
example : squarefree 5 := by norm_num
example : squarefree 6 := by norm_num
example : squarefree 7 := by norm_num
example : ¬ squarefree 8 := by norm_num
example : ¬ squarefree 9 := by norm_num
example : squarefree 10 := by norm_num
example : squarefree (2*3*5*17) := by norm_num
example : ¬ squarefree (2*3*5*5*17) := by norm_num
example : squarefree 251 := by norm_num
example : nat.fib 0 = 0 := by norm_num
example : nat.fib 1 = 1 := by norm_num
example : nat.fib 2 = 1 := by norm_num
example : nat.fib 3 = 2 := by norm_num
example : nat.fib 4 = 3 := by norm_num
example : nat.fib 5 = 5 := by norm_num
example : nat.fib 6 = 8 := by norm_num
example : nat.fib 7 = 13 := by norm_num
example : nat.fib 8 = 21 := by norm_num
example : nat.fib 9 = 34 := by norm_num
example : nat.fib 10 = 55 := by norm_num
example : nat.fib 37 = 24157817 := by norm_num
example : nat.fib 64 = 10610209857723 := by norm_num
example : nat.fib 100 + nat.fib 101 = nat.fib 102 := by norm_num
example : (2 : ℝ) ^ (3 : ℝ) = 8 := by norm_num
example : (1 : ℝ) ^ (20 : ℝ) = 1 := by norm_num
example : (2 : ℝ) ^ (-3 : ℝ) = 1/8 := by norm_num
section big_operators
variables {α : Type*} [comm_ring α]
open_locale big_operators
-- Lists:
example : ([1, 2, 1, 3]).sum = 7 := by norm_num [-list.sum_cons]
example : (([1, 2, 1, 3] : list ℚ).map (λ i, i^2)).sum = 15 := by norm_num [-list.map]
example : (list.range 10).sum = 45 := by norm_num [-list.range_succ]
example : (list.fin_range 10).sum = 45 := by norm_num [-list.fin_range_succ]
-- Multisets:
example : (1 ::ₘ 2 ::ₘ 1 ::ₘ 3 ::ₘ {}).sum = 7 := by norm_num [-multiset.sum_cons]
example : ((1 ::ₘ 2 ::ₘ 1 ::ₘ 3 ::ₘ {}).map (λ i, i^2)).sum = 15 := by norm_num [-multiset.map_cons]
example : (({1, 2, 1, 3} : multiset ℚ).map (λ i, i^2)).sum = 15 := by norm_num [-multiset.map_cons]
example : (multiset.range 10).sum = 45 := by norm_num [-multiset.map_cons, -multiset.range_succ]
example : (↑[1, 2, 1, 3] : multiset ℕ).sum = 7 := by norm_num
-- Finsets:
example (f : fin 0 → α) : ∑ i : fin 0, f i = 0 := by norm_num
example (f : ℕ → α) : ∑ i in (∅ : finset ℕ), f i = 0 := by norm_num
example (f : fin 3 → α) : ∑ i : fin 3, f i = f 0 + f 1 + f 2 := by norm_num; ring
example (f : fin 4 → α) : ∑ i : fin 4, f i = f 0 + f 1 + f 2 + f 3 := by norm_num; ring
example (f : ℕ → α) : ∑ i in {0, 1, 2}, f i = f 0 + f 1 + f 2 := by norm_num; ring
example (f : ℕ → α) : ∑ i in {0, 2, 2, 3, 1, 0}, f i = f 0 + f 1 + f 2 + f 3 := by norm_num; ring
example (f : ℕ → α) : ∑ i in {0, 2, 2 - 3, 3 - 1, 1, 0}, f i = f 0 + f 1 + f 2 := by norm_num; ring
example : (∑ i in finset.range 10, (i^2 : ℕ)) = 285 := by norm_num
example : (∑ i in finset.Icc 5 10, (i^2 : ℕ)) = 355 := by norm_num
example : (∑ i in finset.Ico 5 10, (i^2 : ℕ)) = 255 := by norm_num
example : (∑ i in finset.Ioc 5 10, (i^2 : ℕ)) = 330 := by norm_num
example : (∑ i in finset.Ioo 5 10, (i^2 : ℕ)) = 230 := by norm_num
example : (∑ i : ℤ in finset.Ioo (-5) 5, i^2) = 60 := by norm_num
example (f : ℕ → α) : ∑ i in finset.mk {0, 1, 2} dec_trivial, f i = f 0 + f 1 + f 2 :=
by norm_num; ring
-- Combined with other `norm_num` extensions:
example : ∏ i in finset.range 9, nat.sqrt (i + 1) = 96 := by norm_num
example : ∏ i in {1, 4, 9, 16}, nat.sqrt i = 24 := by norm_num
example : ∏ i in finset.Icc 0 8, nat.sqrt (i + 1) = 96 := by norm_num
-- Nested operations:
example : ∑ i : fin 2, ∑ j : fin 2, ![![0, 1], ![2, 3]] i j = 6 := by norm_num
end big_operators
section jacobi
-- Jacobi and Legendre symbols
open_locale number_theory_symbols
example : J(123 | 335) = -1 := by norm_num
example : J(-2345 | 6789) = -1 := by norm_num
example : J(-1 | 1655801) = 1 := by norm_num
example : J(-102334155 | 165580141) = -1 := by norm_num
example : J(58378362899022564339483801989973056405585914719065 |
53974350278769849773003214636618718468638750007307) = -1 := by norm_num
example : J(3 + 4 | 3 * 5) = -1 := by norm_num
example : J(J(-1 | 7) | 11) = -1 := by norm_num
instance prime_1000003 : fact (nat.prime 1000003) := ⟨by norm_num⟩
example : legendre_sym 1000003 7 = -1 := by norm_num
end jacobi
|
344f2664dc44d047aff6132ad658443fb21d6bb4 | d0c6b2ba2af981e9ab0a98f6e169262caad4b9b9 | /stage0/src/Lean/Data/KVMap.lean | 9363712984050f41dc7a2e3e0d96b9512936824f | [
"Apache-2.0"
] | permissive | fizruk/lean4 | 953b7dcd76e78c17a0743a2c1a918394ab64bbc0 | 545ed50f83c570f772ade4edbe7d38a078cbd761 | refs/heads/master | 1,677,655,987,815 | 1,612,393,885,000 | 1,612,393,885,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,929 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Data.Name
namespace Lean
inductive DataValue where
| ofString (v : String)
| ofBool (v : Bool)
| ofName (v : Name)
| ofNat (v : Nat)
| ofInt (v : Int)
deriving Inhabited, BEq
@[export lean_mk_bool_data_value] def mkBoolDataValueEx (b : Bool) : DataValue := DataValue.ofBool b
@[export lean_data_value_bool] def DataValue.getBoolEx : DataValue → Bool
| DataValue.ofBool b => b
| _ => false
def DataValue.sameCtor : DataValue → DataValue → Bool
| DataValue.ofString _, DataValue.ofString _ => true
| DataValue.ofBool _, DataValue.ofBool _ => true
| DataValue.ofName _, DataValue.ofName _ => true
| DataValue.ofNat _, DataValue.ofNat _ => true
| DataValue.ofInt _, DataValue.ofInt _ => true
| _, _ => false
@[export lean_data_value_to_string]
def DataValue.str : DataValue → String
| DataValue.ofString v => v
| DataValue.ofBool v => toString v
| DataValue.ofName v => toString v
| DataValue.ofNat v => toString v
| DataValue.ofInt v => toString v
instance : ToString DataValue := ⟨DataValue.str⟩
instance : Coe String DataValue := ⟨DataValue.ofString⟩
instance : Coe Bool DataValue := ⟨DataValue.ofBool⟩
instance : Coe Name DataValue := ⟨DataValue.ofName⟩
instance : Coe Nat DataValue := ⟨DataValue.ofNat⟩
instance : Coe Int DataValue := ⟨DataValue.ofInt⟩
/- Remark: we do not use RBMap here because we need to manipulate KVMap objects in
C++ and RBMap is implemented in Lean. So, we use just a List until we can
generate C++ code from Lean code. -/
structure KVMap where
entries : List (Name × DataValue) := []
deriving Inhabited
namespace KVMap
instance : ToString KVMap := ⟨fun m => toString m.entries⟩
def empty : KVMap :=
{}
def isEmpty : KVMap → Bool
| ⟨m⟩ => m.isEmpty
def size (m : KVMap) : Nat :=
m.entries.length
def findCore : List (Name × DataValue) → Name → Option DataValue
| [], k' => none
| (k,v)::m, k' => if k == k' then some v else findCore m k'
def find : KVMap → Name → Option DataValue
| ⟨m⟩, k => findCore m k
def findD (m : KVMap) (k : Name) (d₀ : DataValue) : DataValue :=
(m.find k).getD d₀
def insertCore : List (Name × DataValue) → Name → DataValue → List (Name × DataValue)
| [], k', v' => [(k',v')]
| (k,v)::m, k', v' => if k == k' then (k, v') :: m else (k, v) :: insertCore m k' v'
def insert : KVMap → Name → DataValue → KVMap
| ⟨m⟩, k, v => ⟨insertCore m k v⟩
def contains (m : KVMap) (n : Name) : Bool :=
(m.find n).isSome
def getString (m : KVMap) (k : Name) (defVal := "") : String :=
match m.find k with
| some (DataValue.ofString v) => v
| _ => defVal
def getNat (m : KVMap) (k : Name) (defVal := 0) : Nat :=
match m.find k with
| some (DataValue.ofNat v) => v
| _ => defVal
def getInt (m : KVMap) (k : Name) (defVal : Int := 0) : Int :=
match m.find k with
| some (DataValue.ofInt v) => v
| _ => defVal
def getBool (m : KVMap) (k : Name) (defVal := false) : Bool :=
match m.find k with
| some (DataValue.ofBool v) => v
| _ => defVal
def getName (m : KVMap) (k : Name) (defVal := Name.anonymous) : Name :=
match m.find k with
| some (DataValue.ofName v) => v
| _ => defVal
def setString (m : KVMap) (k : Name) (v : String) : KVMap :=
m.insert k (DataValue.ofString v)
def setNat (m : KVMap) (k : Name) (v : Nat) : KVMap :=
m.insert k (DataValue.ofNat v)
def setInt (m : KVMap) (k : Name) (v : Int) : KVMap :=
m.insert k (DataValue.ofInt v)
def setBool (m : KVMap) (k : Name) (v : Bool) : KVMap :=
m.insert k (DataValue.ofBool v)
def setName (m : KVMap) (k : Name) (v : Name) : KVMap :=
m.insert k (DataValue.ofName v)
@[inline] def forIn.{w, w'} {δ : Type w} {m : Type w → Type w'} [Monad m]
(kv : KVMap) (init : δ) (f : Name × DataValue → δ → m (ForInStep δ)) : m δ :=
kv.entries.forIn init f
def subsetAux : List (Name × DataValue) → KVMap → Bool
| [], m₂ => true
| (k, v₁)::m₁, m₂ =>
match m₂.find k with
| some v₂ => v₁ == v₂ && subsetAux m₁ m₂
| none => false
def subset : KVMap → KVMap → Bool
| ⟨m₁⟩, m₂ => subsetAux m₁ m₂
def eqv (m₁ m₂ : KVMap) : Bool :=
subset m₁ m₂ && subset m₂ m₁
instance : BEq KVMap where
beq := eqv
class Value (α : Type) where
toDataValue : α → DataValue
ofDataValue? : DataValue → Option α
@[inline] def get? {α : Type} [s : Value α] (m : KVMap) (k : Name) : Option α :=
m.find k |>.bind Value.ofDataValue?
@[inline] def get {α : Type} [s : Value α] (m : KVMap) (k : Name) (defVal : α) : α :=
m.get? k |>.getD defVal
@[inline] def set {α : Type} [s : Value α] (m : KVMap) (k : Name) (v : α) : KVMap :=
m.insert k (Value.toDataValue v)
instance : Value Bool where
toDataValue := DataValue.ofBool
ofDataValue?
| DataValue.ofBool b => some b
| _ => none
instance : Value Nat where
toDataValue := DataValue.ofNat
ofDataValue?
| DataValue.ofNat n => some n
| _ => none
instance : Value Int where
toDataValue := DataValue.ofInt
ofDataValue?
| DataValue.ofInt i => some i
| _ => none
instance : Value Name where
toDataValue := DataValue.ofName
ofDataValue?
| DataValue.ofName n => some n
| _ => none
instance : Value String where
toDataValue := DataValue.ofString
ofDataValue?
| DataValue.ofString n => some n
| _ => none
end Lean.KVMap
|
6dc2050a14c6c3736767472c40b1172145abc0a6 | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/tactic/finish.lean | 3e5ce4892b8f5c8d89da594483ee680f59cce321 | [
"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 | 23,440 | lean | /-
Copyright (c) 2017 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Jesse Michael Han
-/
import logic.basic tactic.core tactic.hint
/-!
# The `finish` family of tactics
These tactics do straightforward things: they call the simplifier, split conjunctive assumptions,
eliminate existential quantifiers on the left, and look for contradictions. They rely on ematching
and congruence closure to try to finish off a goal at the end.
The procedures *do* split on disjunctions and recreate the smt state for each terminal call, so
they are only meant to be used on small, straightforward problems.
## Main definitions
We provide the following tactics:
* `finish` -- solves the goal or fails
* `clarify` -- makes as much progress as possible while not leaving more than one goal
* `safe` -- splits freely, finishes off whatever subgoals it can, and leaves the rest
All accept an optional list of simplifier rules, typically definitions that should be expanded.
(The equations and identities should not refer to the local context.)
## Implementation notes
The variants `ifinish`, `iclarify`, and `isafe` try to restrict to intuitionistic logic. But the
`done` tactic leaks classical logic:
```lean
example {P : Prop} : ¬¬P → P :=
by using_smt (do smt_tactic.intros, smt_tactic.close)
```
They also do not work well with the current heuristic instantiation method used by `ematch`.
So they are left here mainly for reference.
-/
declare_trace auto.done
declare_trace auto.finish
namespace tactic
/-- call `(assert n t)` with a fresh name `n`. -/
meta def assert_fresh (t : expr) : tactic expr :=
do n ← get_unused_name `h none,
assert n t
/-- call `(assertv n t v)` with a fresh name `n`. -/
meta def assertv_fresh (t : expr) (v : expr) : tactic expr :=
do h ← get_unused_name `h none,
assertv h t v
namespace interactive
meta def revert_all := tactic.revert_all
end interactive
end tactic
open tactic expr
namespace auto
/-! ### Utilities -/
meta def whnf_reducible (e : expr) : tactic expr := whnf e reducible
-- stolen from interactive.lean
meta def add_simps : simp_lemmas → list name → tactic simp_lemmas
| s [] := return s
| s (n::ns) := do s' ← s.add_simp n, add_simps s' ns
/--
Configuration information for the auto tactics.
* `(use_simp := tt)`: call the simplifier
* `(classical := tt)`: use classical logic
* `(max_ematch_rounds := 20)`: for the "done" tactic
-/
@[derive decidable_eq, derive inhabited]
structure auto_config : Type :=
(use_simp := tt)
(classical := tt)
(max_ematch_rounds := 20)
/-!
### Preprocess goal.
We want to move everything to the left of the sequent arrow. For intuitionistic logic,
we replace the goal `p` with `∀ f, (p → f) → f` and introduce.
-/
theorem by_contradiction_trick (p : Prop) (h : ∀ f : Prop, (p → f) → f) : p :=
h p id
meta def preprocess_goal (cfg : auto_config) : tactic unit :=
do repeat (intro1 >> skip),
tgt ← target >>= whnf_reducible,
if (¬ (is_false tgt)) then
if cfg.classical then
(mk_mapp ``classical.by_contradiction [some tgt]) >>= apply >> intro1 >> skip
else
(mk_mapp ``decidable.by_contradiction [some tgt, none] >>= apply >> intro1 >> skip) <|>
applyc ``by_contradiction_trick >> intro1 >> intro1 >> skip
else
skip
/-!
### Normalize hypotheses
Bring conjunctions to the outside (for splitting),
bring universal quantifiers to the outside (for ematching). The classical normalizer
eliminates `a → b` in favor of `¬ a ∨ b`.
For efficiency, we push negations inwards from the top down. (For example, consider
simplifying `¬ ¬ (p ∨ q)`.)
-/
section
universe u
variable {α : Type u}
variables (p q : Prop)
variable (s : α → Prop)
local attribute [instance, priority 10] classical.prop_decidable
theorem not_not_eq : (¬ ¬ p) = p := propext not_not
theorem not_and_eq : (¬ (p ∧ q)) = (¬ p ∨ ¬ q) := propext not_and_distrib
theorem not_or_eq : (¬ (p ∨ q)) = (¬ p ∧ ¬ q) := propext not_or_distrib
theorem not_forall_eq : (¬ ∀ x, s x) = (∃ x, ¬ s x) := propext not_forall
theorem not_exists_eq : (¬ ∃ x, s x) = (∀ x, ¬ s x) := propext not_exists
theorem not_implies_eq : (¬ (p → q)) = (p ∧ ¬ q) := propext not_imp
theorem classical.implies_iff_not_or : (p → q) ↔ (¬ p ∨ q) := imp_iff_not_or
end
def common_normalize_lemma_names : list name :=
[``bex_def, ``forall_and_distrib, ``exists_imp_distrib, ``or.assoc, ``or.comm, ``or.left_comm,
``and.assoc, ``and.comm, ``and.left_comm]
def classical_normalize_lemma_names : list name :=
common_normalize_lemma_names ++ [``classical.implies_iff_not_or]
/-- optionally returns an equivalent expression and proof of equivalence -/
private meta def transform_negation_step (cfg : auto_config) (e : expr) :
tactic (option (expr × expr)) :=
do e ← whnf_reducible e,
match e with
| `(¬ %%ne) :=
(do ne ← whnf_reducible ne,
match ne with
| `(¬ %%a) := if ¬ cfg.classical then return none
else do pr ← mk_app ``not_not_eq [a],
return (some (a, pr))
| `(%%a ∧ %%b) := do pr ← mk_app ``not_and_eq [a, b],
return (some (`(¬ %%a ∨ ¬ %%b), pr))
| `(%%a ∨ %%b) := do pr ← mk_app ``not_or_eq [a, b],
return (some (`(¬ %%a ∧ ¬ %%b), pr))
| `(Exists %%p) := do pr ← mk_app ``not_exists_eq [p],
`(%%_ = %%e') ← infer_type pr,
return (some (e', pr))
| (pi n bi d p) := if ¬ cfg.classical then return none
else if p.has_var then do
pr ← mk_app ``not_forall_eq [lam n bi d (expr.abstract_local p n)],
`(%%_ = %%e') ← infer_type pr,
return (some (e', pr))
else do
pr ← mk_app ``not_implies_eq [d, p],
`(%%_ = %%e') ← infer_type pr,
return (some (e', pr))
| _ := return none
end)
| _ := return none
end
/-- given an expr `e`, returns a new expression and a proof of equality -/
private meta def transform_negation (cfg : auto_config) : expr → tactic (option (expr × expr)) :=
λ e, do
opr ← transform_negation_step cfg e,
match opr with
| (some (e', pr)) := do
opr' ← transform_negation e',
match opr' with
| none := return (some (e', pr))
| (some (e'', pr')) := do pr'' ← mk_eq_trans pr pr',
return (some (e'', pr''))
end
| none := return none
end
meta def normalize_negations (cfg : auto_config) (h : expr) : tactic unit :=
do t ← infer_type h,
(_, e, pr) ← simplify_top_down ()
(λ _, λ e, do
oepr ← transform_negation cfg e,
match oepr with
| (some (e', pr)) := return ((), e', pr)
| none := do pr ← mk_eq_refl e, return ((), e, pr)
end)
t,
replace_hyp h e pr,
skip
meta def normalize_hyp (cfg : auto_config) (simps : simp_lemmas) (h : expr) : tactic unit :=
(do h ← simp_hyp simps [] h, try (normalize_negations cfg h)) <|>
try (normalize_negations cfg h)
meta def normalize_hyps (cfg : auto_config) : tactic unit :=
do simps ← if cfg.classical then
add_simps simp_lemmas.mk classical_normalize_lemma_names
else
add_simps simp_lemmas.mk common_normalize_lemma_names,
local_context >>= monad.mapm' (normalize_hyp cfg simps)
/-!
### Eliminate existential quantifiers
-/
/-- eliminate an existential quantifier if there is one -/
meta def eelim : tactic unit :=
do ctx ← local_context,
first $ ctx.map $ λ h,
do t ← infer_type h >>= whnf_reducible,
guard (is_app_of t ``Exists),
tgt ← target,
to_expr ``(@exists.elim _ _ %%tgt %%h) >>= apply,
intros,
clear h
/-- eliminate all existential quantifiers, fails if there aren't any -/
meta def eelims : tactic unit := eelim >> repeat eelim
/-!
### Substitute if there is a hypothesis `x = t` or `t = x`
-/
/-- carries out a subst if there is one, fails otherwise -/
meta def do_subst : tactic unit :=
do ctx ← local_context,
first $ ctx.map $ λ h,
do t ← infer_type h >>= whnf_reducible,
match t with
| `(%%a = %%b) := subst h
| _ := failed
end
meta def do_substs : tactic unit := do_subst >> repeat do_subst
/-!
### Split all conjunctions
-/
/-- Assumes `pr` is a proof of `t`. Adds the consequences of `t` to the context
and returns `tt` if anything nontrivial has been added. -/
meta def add_conjuncts : expr → expr → tactic bool :=
λ pr t,
let assert_consequences := λ e t, mcond (add_conjuncts e t) skip (assertv_fresh t e >> skip) in
do t' ← whnf_reducible t,
match t' with
| `(%%a ∧ %%b) :=
do e₁ ← mk_app ``and.left [pr],
assert_consequences e₁ a,
e₂ ← mk_app ``and.right [pr],
assert_consequences e₂ b,
return tt
| `(true) :=
do return tt
| _ := return ff
end
/-- return `tt` if any progress is made -/
meta def split_hyp (h : expr) : tactic bool :=
do t ← infer_type h,
mcond (add_conjuncts h t) (clear h >> return tt) (return ff)
/-- return `tt` if any progress is made -/
meta def split_hyps_aux : list expr → tactic bool
| [] := return ff
| (h :: hs) := do b₁ ← split_hyp h,
b₂ ← split_hyps_aux hs,
return (b₁ || b₂)
/-- fail if no progress is made -/
meta def split_hyps : tactic unit := local_context >>= split_hyps_aux >>= guardb
/-!
### Eagerly apply all the preprocessing rules
-/
/-- Eagerly apply all the preprocessing rules -/
meta def preprocess_hyps (cfg : auto_config) : tactic unit :=
do repeat (intro1 >> skip),
preprocess_goal cfg,
normalize_hyps cfg,
repeat (do_substs <|> split_hyps <|> eelim /-<|> self_simplify_hyps-/)
/-!
### Terminal tactic
-/
/--
The terminal tactic, used to try to finish off goals:
- Call the contradiction tactic.
- Open an SMT state, and use ematching and congruence closure, with all the universal
statements in the context.
TODO(Jeremy): allow users to specify attribute for ematching lemmas?
-/
meta def mk_hinst_lemmas : list expr → smt_tactic hinst_lemmas
| [] := -- return hinst_lemmas.mk
do get_hinst_lemmas_for_attr `ematch
| (h :: hs) := do his ← mk_hinst_lemmas hs,
t ← infer_type h,
match t with
| (pi _ _ _ _) :=
do t' ← infer_type t,
if t' = `(Prop) then
(do new_lemma ← hinst_lemma.mk h,
return (hinst_lemmas.add his new_lemma)) <|> return his
else return his
| _ := return his
end
private meta def report_invalid_em_lemma {α : Type} (n : name) : smt_tactic α :=
fail format!"invalid ematch lemma '{n}'"
private meta def add_hinst_lemma_from_name (md : transparency) (lhs_lemma : bool) (n : name)
(hs : hinst_lemmas) (ref : pexpr) : smt_tactic hinst_lemmas :=
do p ← resolve_name n,
match p with
| expr.const n _ := (do h ← hinst_lemma.mk_from_decl_core md n lhs_lemma,
tactic.save_const_type_info n ref, return $ hs.add h) <|>
(do hs₁ ← smt_tactic.mk_ematch_eqn_lemmas_for_core md n,
tactic.save_const_type_info n ref, return $ hs.merge hs₁) <|>
report_invalid_em_lemma n
| _ := (do e ← to_expr p, h ← hinst_lemma.mk_core md e lhs_lemma,
try (tactic.save_type_info e ref), return $ hs.add h) <|>
report_invalid_em_lemma n
end
private meta def add_hinst_lemma_from_pexpr (md : transparency) (lhs_lemma : bool) (hs : hinst_lemmas)
: pexpr → smt_tactic hinst_lemmas
| p@(expr.const c []) := add_hinst_lemma_from_name md lhs_lemma c hs p
| p@(expr.local_const c _ _ _) := add_hinst_lemma_from_name md lhs_lemma c hs p
| p := do new_e ← to_expr p, h ← hinst_lemma.mk_core md new_e lhs_lemma,
return $ hs.add h
private meta def add_hinst_lemmas_from_pexprs (md : transparency) (lhs_lemma : bool)
(ps : list pexpr) (hs : hinst_lemmas) : smt_tactic hinst_lemmas :=
list.mfoldl (add_hinst_lemma_from_pexpr md lhs_lemma) hs ps
/--
`done` first attempts to close the goal using `contradiction`. If this fails, it creates an
SMT state and will repeatedly use `ematch` (using `ematch` lemmas in the environment,
universally quantified assumptions, and the supplied lemmas `ps`) and congruence closure.
-/
meta def done (ps : list pexpr) (cfg : auto_config := {}) : tactic unit :=
do trace_state_if_enabled `auto.done "entering done",
contradiction <|>
(solve1 $
(do revert_all,
using_smt
(do smt_tactic.intros,
ctx ← local_context,
hs ← mk_hinst_lemmas ctx,
hs' ← add_hinst_lemmas_from_pexprs reducible ff ps hs,
smt_tactic.iterate_at_most cfg.max_ematch_rounds
(smt_tactic.ematch_using hs' >> smt_tactic.try smt_tactic.close))))
/-!
### Tactics that perform case splits
-/
@[derive decidable_eq, derive inhabited]
inductive case_option
| force -- fail unless all goals are solved
| at_most_one -- leave at most one goal
| accept -- leave as many goals as necessary
private meta def case_cont (s : case_option) (cont : case_option → tactic unit) : tactic unit :=
do match s with
| case_option.force := cont case_option.force >> cont case_option.force
| case_option.at_most_one :=
-- if the first one succeeds, commit to it, and try the second
(mcond (cont case_option.force >> return tt) (cont case_option.at_most_one) skip) <|>
-- otherwise, try the second
(swap >> cont case_option.force >> cont case_option.at_most_one)
| case_option.accept := focus [cont case_option.accept, cont case_option.accept]
end
-- three possible outcomes:
-- finds something to case, the continuations succeed ==> returns tt
-- finds something to case, the continutations fail ==> fails
-- doesn't find anything to case ==> returns ff
meta def case_hyp (h : expr) (s : case_option) (cont : case_option → tactic unit) : tactic bool :=
do t ← infer_type h,
match t with
| `(%%a ∨ %%b) := cases h >> case_cont s cont >> return tt
| _ := return ff
end
meta def case_some_hyp_aux (s : case_option) (cont : case_option → tactic unit) :
list expr → tactic bool
| [] := return ff
| (h::hs) := mcond (case_hyp h s cont) (return tt) (case_some_hyp_aux hs)
meta def case_some_hyp (s : case_option) (cont : case_option → tactic unit) : tactic bool :=
local_context >>= case_some_hyp_aux s cont
/-!
### The main tactics
-/
/--
`safe_core s ps cfg opt` negates the goal, normalizes hypotheses
(by splitting conjunctions, eliminating existentials, pushing negations inwards,
and calling `simp` with the supplied lemmas `s`), and then tries `contradiction`.
If this fails, it will create an SMT state and repeatedly use `ematch`
(using `ematch` lemmas in the environment, universally quantified assumptions,
and the supplied lemmas `ps`) and congruence closure.
`safe_core` is complete for propositional logic. Depending on the form of `opt`
it will:
- (if `opt` is `case_option.force`) fail if it does not close the goal,
- (if `opt` is `case_option.at_most_one`) fail if it produces more than one goal, and
- (if `opt` is `case_option.accept`) ignore the number of goals it produces.
-/
meta def safe_core (s : simp_lemmas × list name) (ps : list pexpr) (cfg : auto_config) : case_option → tactic unit :=
λ co, focus1 $
do trace_state_if_enabled `auto.finish "entering safe_core",
if cfg.use_simp then do
trace_if_enabled `auto.finish "simplifying hypotheses",
simp_all s.1 s.2 { fail_if_unchanged := ff },
trace_state_if_enabled `auto.finish "result:"
else skip,
tactic.done <|>
do trace_if_enabled `auto.finish "preprocessing hypotheses",
preprocess_hyps cfg,
trace_state_if_enabled `auto.finish "result:",
done ps cfg <|>
(mcond (case_some_hyp co safe_core)
skip
(match co with
| case_option.force := done ps cfg
| case_option.at_most_one := try (done ps cfg)
| case_option.accept := try (done ps cfg)
end))
/--
`clarify` is `safe_core`, but with the `(opt : case_option)`
parameter fixed at `case_option.at_most_one`.
-/
meta def clarify (s : simp_lemmas × list name) (ps : list pexpr)
(cfg : auto_config := {}) : tactic unit := safe_core s ps cfg case_option.at_most_one
/--
`safe` is `safe_core`, but with the `(opt : case_option)`
parameter fixed at `case_option.accept`.
-/
meta def safe (s : simp_lemmas × list name) (ps : list pexpr)
(cfg : auto_config := {}) : tactic unit := safe_core s ps cfg case_option.accept
/--
`finish` is `safe_core`, but with the `(opt : case_option)`
parameter fixed at `case_option.force`.
-/
meta def finish (s : simp_lemmas × list name) (ps : list pexpr)
(cfg : auto_config := {}) : tactic unit := safe_core s ps cfg case_option.force
/--
`iclarify` is like `clarify`, but in some places restricts to intuitionistic logic.
Classical logic still leaks, so this tactic is deprecated.
-/
meta def iclarify (s : simp_lemmas × list name) (ps : list pexpr)
(cfg : auto_config := {}) : tactic unit := clarify s ps {classical := ff, ..cfg}
/--
`isafe` is like `safe`, but in some places restricts to intuitionistic logic.
Classical logic still leaks, so this tactic is deprecated.
-/
meta def isafe (s : simp_lemmas × list name) (ps : list pexpr)
(cfg : auto_config := {}) : tactic unit := safe s ps {classical := ff, ..cfg}
/--
`ifinish` is like `finish`, but in some places restricts to intuitionistic logic.
Classical logic still leaks, so this tactic is deprecated.
-/
meta def ifinish (s : simp_lemmas × list name) (ps : list pexpr) (cfg : auto_config := {}) : tactic unit :=
finish s ps {classical := ff, ..cfg}
end auto
/-! ### interactive versions -/
open auto
namespace tactic
namespace interactive
open lean lean.parser interactive interactive.types
local postfix `?`:9001 := optional
local postfix *:9001 := many
/--
`clarify [h1,...,hn] using [e1,...,en]` negates the goal, normalizes hypotheses
(by splitting conjunctions, eliminating existentials, pushing negations inwards,
and calling `simp` with the supplied lemmas `h1,...,hn`), and then tries `contradiction`.
If this fails, it will create an SMT state and repeatedly use `ematch`
(using `ematch` lemmas in the environment, universally quantified assumptions,
and the supplied lemmas `e1,...,en`) and congruence closure.
`clarify` is complete for propositional logic.
Either of the supplied simp lemmas or the supplied ematch lemmas are optional.
`clarify` will fail if it produces more than one goal.
-/
meta def clarify (hs : parse simp_arg_list) (ps : parse (tk "using" *> pexpr_list_or_texpr)?)
(cfg : auto_config := {}) : tactic unit :=
do s ← mk_simp_set ff [] hs,
auto.clarify s (ps.get_or_else []) cfg
/--
`safe [h1,...,hn] using [e1,...,en]` negates the goal, normalizes hypotheses
(by splitting conjunctions, eliminating existentials, pushing negations inwards,
and calling `simp` with the supplied lemmas `h1,...,hn`), and then tries `contradiction`.
If this fails, it will create an SMT state and repeatedly use `ematch`
(using `ematch` lemmas in the environment, universally quantified assumptions,
and the supplied lemmas `e1,...,en`) and congruence closure.
`safe` is complete for propositional logic.
Either of the supplied simp lemmas or the supplied ematch lemmas are optional.
`safe` ignores the number of goals it produces, and should never fail.
-/
meta def safe (hs : parse simp_arg_list) (ps : parse (tk "using" *> pexpr_list_or_texpr)?)
(cfg : auto_config := {}) : tactic unit :=
do s ← mk_simp_set ff [] hs,
auto.safe s (ps.get_or_else []) cfg
/--
`finish [h1,...,hn] using [e1,...,en]` negates the goal, normalizes hypotheses
(by splitting conjunctions, eliminating existentials, pushing negations inwards,
and calling `simp` with the supplied lemmas `h1,...,hn`), and then tries `contradiction`.
If this fails, it will create an SMT state and repeatedly use `ematch`
(using `ematch` lemmas in the environment, universally quantified assumptions,
and the supplied lemmas `e1,...,en`) and congruence closure.
`finish` is complete for propositional logic.
Either of the supplied simp lemmas or the supplied ematch lemmas are optional.
`finish` will fail if it does not close the goal.
-/
meta def finish (hs : parse simp_arg_list) (ps : parse (tk "using" *> pexpr_list_or_texpr)?)
(cfg : auto_config := {}) : tactic unit :=
do s ← mk_simp_set ff [] hs,
auto.finish s (ps.get_or_else []) cfg
add_hint_tactic "finish"
/--
These tactics do straightforward things: they call the simplifier, split conjunctive assumptions,
eliminate existential quantifiers on the left, and look for contradictions. They rely on ematching
and congruence closure to try to finish off a goal at the end.
The procedures *do* split on disjunctions and recreate the smt state for each terminal call, so
they are only meant to be used on small, straightforward problems.
* `finish`: solves the goal or fails
* `clarify`: makes as much progress as possible while not leaving more than one goal
* `safe`: splits freely, finishes off whatever subgoals it can, and leaves the rest
All accept an optional list of simplifier rules, typically definitions that should be expanded.
(The equations and identities should not refer to the local context.) All also accept an optional
list of `ematch` lemmas, which must be preceded by `using`.
-/
add_tactic_doc
{ name := "finish / clarify / safe",
category := doc_category.tactic,
decl_names := [`tactic.interactive.finish, `tactic.interactive.clarify,
`tactic.interactive.safe],
tags := ["logic", "finishing"] }
/--
`iclarify` is like `clarify`, but only uses intuitionistic logic.
-/
meta def iclarify (hs : parse simp_arg_list) (ps : parse (tk "using" *> pexpr_list_or_texpr)?)
(cfg : auto_config := {}) : tactic unit :=
do s ← mk_simp_set ff [] hs,
auto.iclarify s (ps.get_or_else []) cfg
/--
`isafe` is like `safe`, but only uses intuitionistic logic.
-/
meta def isafe (hs : parse simp_arg_list) (ps : parse (tk "using" *> pexpr_list_or_texpr)?)
(cfg : auto_config := {}) : tactic unit :=
do s ← mk_simp_set ff [] hs,
auto.isafe s (ps.get_or_else []) cfg
/--
`ifinish` is like `finish`, but only uses intuitionistic logic.
-/
meta def ifinish (hs : parse simp_arg_list) (ps : parse (tk "using" *> pexpr_list_or_texpr)?)
(cfg : auto_config := {}) : tactic unit :=
do s ← mk_simp_set ff [] hs,
auto.ifinish s (ps.get_or_else []) cfg
end interactive
end tactic
|
ac657fd001995089e3dc2f7a8e9c279e75ca7fc4 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/category_theory/differential_object.lean | e6a656e86a25cdabf070b26e5f286b7cf19b895a | [
"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 | 8,870 | 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 data.int.basic
import category_theory.shift
import category_theory.concrete_category.basic
/-!
# Differential objects in a category.
A differential object in a category with zero morphisms and a shift is
an object `X` equipped with
a morphism `d : X ⟶ X⟦1⟧`, such that `d^2 = 0`.
We build the category of differential objects, and some basic constructions
such as the forgetful functor, zero morphisms and zero objects, and the shift functor
on differential objects.
-/
open category_theory.limits
universes v u
namespace category_theory
variables (C : Type u) [category.{v} C]
-- TODO: generaize to `has_shift C A` for an arbitrary `[add_monoid A]` `[has_one A]`.
variables [has_zero_morphisms C] [has_shift C ℤ]
/--
A differential object in a category with zero morphisms and a shift is
an object `X` equipped with
a morphism `d : X ⟶ X⟦1⟧`, such that `d^2 = 0`.
-/
@[nolint has_nonempty_instance]
structure differential_object :=
(X : C)
(d : X ⟶ X⟦1⟧)
(d_squared' : d ≫ d⟦(1:ℤ)⟧' = 0 . obviously)
restate_axiom differential_object.d_squared'
attribute [simp] differential_object.d_squared
variables {C}
namespace differential_object
/--
A morphism of differential objects is a morphism commuting with the differentials.
-/
@[ext, nolint has_nonempty_instance]
structure hom (X Y : differential_object C) :=
(f : X.X ⟶ Y.X)
(comm' : X.d ≫ f⟦1⟧' = f ≫ Y.d . obviously)
restate_axiom hom.comm'
attribute [simp, reassoc] hom.comm
namespace hom
/-- The identity morphism of a differential object. -/
@[simps]
def id (X : differential_object C) : hom X X :=
{ f := 𝟙 X.X }
/-- The composition of morphisms of differential objects. -/
@[simps]
def comp {X Y Z : differential_object C} (f : hom X Y) (g : hom Y Z) : hom X Z :=
{ f := f.f ≫ g.f, }
end hom
instance category_of_differential_objects : category (differential_object C) :=
{ hom := hom,
id := hom.id,
comp := λ X Y Z f g, hom.comp f g, }
@[simp]
lemma id_f (X : differential_object C) : ((𝟙 X) : X ⟶ X).f = 𝟙 (X.X) := rfl
@[simp]
lemma comp_f {X Y Z : differential_object C} (f : X ⟶ Y) (g : Y ⟶ Z) :
(f ≫ g).f = f.f ≫ g.f :=
rfl
@[simp]
lemma eq_to_hom_f {X Y : differential_object C} (h : X = Y) :
hom.f (eq_to_hom h) = eq_to_hom (congr_arg _ h) :=
by { subst h, rw [eq_to_hom_refl, eq_to_hom_refl], refl }
variables (C)
/-- The forgetful functor taking a differential object to its underlying object. -/
def forget : (differential_object C) ⥤ C :=
{ obj := λ X, X.X,
map := λ X Y f, f.f, }
instance forget_faithful : faithful (forget C) :=
{ }
instance has_zero_morphisms : has_zero_morphisms (differential_object C) :=
{ has_zero := λ X Y,
⟨{ f := 0 }⟩}
variables {C}
@[simp]
lemma zero_f (P Q : differential_object C) : (0 : P ⟶ Q).f = 0 := rfl
/--
An isomorphism of differential objects gives an isomorphism of the underlying objects.
-/
@[simps] def iso_app {X Y : differential_object C} (f : X ≅ Y) : X.X ≅ Y.X :=
⟨f.hom.f, f.inv.f, by { dsimp, rw [← comp_f, iso.hom_inv_id, id_f] },
by { dsimp, rw [← comp_f, iso.inv_hom_id, id_f] }⟩
@[simp] lemma iso_app_refl (X : differential_object C) : iso_app (iso.refl X) = iso.refl X.X := rfl
@[simp] lemma iso_app_symm {X Y : differential_object C} (f : X ≅ Y) :
iso_app f.symm = (iso_app f).symm := rfl
@[simp] lemma iso_app_trans {X Y Z : differential_object C} (f : X ≅ Y) (g : Y ≅ Z) :
iso_app (f ≪≫ g) = iso_app f ≪≫ iso_app g := rfl
/-- An isomorphism of differential objects can be constructed
from an isomorphism of the underlying objects that commutes with the differentials. -/
@[simps] def mk_iso {X Y : differential_object C}
(f : X.X ≅ Y.X) (hf : X.d ≫ f.hom⟦1⟧' = f.hom ≫ Y.d) : X ≅ Y :=
{ hom := ⟨f.hom, hf⟩,
inv := ⟨f.inv, by { dsimp, rw [← functor.map_iso_inv, iso.comp_inv_eq, category.assoc,
iso.eq_inv_comp, functor.map_iso_hom, hf] }⟩,
hom_inv_id' := by { ext1, dsimp, exact f.hom_inv_id },
inv_hom_id' := by { ext1, dsimp, exact f.inv_hom_id } }
end differential_object
namespace functor
universes v' u'
variables (D : Type u') [category.{v'} D]
variables [has_zero_morphisms D] [has_shift D ℤ]
/--
A functor `F : C ⥤ D` which commutes with shift functors on `C` and `D` and preserves zero morphisms
can be lifted to a functor `differential_object C ⥤ differential_object D`.
-/
@[simps]
def map_differential_object (F : C ⥤ D)
(η : (shift_functor C (1:ℤ)).comp F ⟶ F.comp (shift_functor D (1:ℤ)))
(hF : ∀ c c', F.map (0 : c ⟶ c') = 0) :
differential_object C ⥤ differential_object D :=
{ obj := λ X, { X := F.obj X.X,
d := F.map X.d ≫ η.app X.X,
d_squared' := begin
rw [functor.map_comp, ← functor.comp_map F (shift_functor D (1:ℤ))],
slice_lhs 2 3 { rw [← η.naturality X.d] },
rw [functor.comp_map],
slice_lhs 1 2 { rw [← F.map_comp, X.d_squared, hF] },
rw [zero_comp, zero_comp],
end },
map := λ X Y f, { f := F.map f.f,
comm' := begin
dsimp,
slice_lhs 2 3 { rw [← functor.comp_map F (shift_functor D (1:ℤ)), ← η.naturality f.f] },
slice_lhs 1 2 { rw [functor.comp_map, ← F.map_comp, f.comm, F.map_comp] },
rw [category.assoc]
end },
map_id' := by { intros, ext, simp },
map_comp' := by { intros, ext, simp }, }
end functor
end category_theory
namespace category_theory
namespace differential_object
variables (C : Type u) [category.{v} C]
variables [has_zero_object C] [has_zero_morphisms C] [has_shift C ℤ]
open_locale zero_object
instance has_zero_object : has_zero_object (differential_object C) :=
by { refine ⟨⟨⟨0, 0⟩, λ X, ⟨⟨⟨⟨0⟩⟩, λ f, _⟩⟩, λ X, ⟨⟨⟨⟨0⟩⟩, λ f, _⟩⟩⟩⟩; ext, }
end differential_object
namespace differential_object
variables (C : Type (u+1)) [large_category C] [concrete_category C]
[has_zero_morphisms C] [has_shift C ℤ]
instance concrete_category_of_differential_objects :
concrete_category (differential_object C) :=
{ forget := forget C ⋙ category_theory.forget C }
instance : has_forget₂ (differential_object C) C :=
{ forget₂ := forget C }
end differential_object
/-! The category of differential objects itself has a shift functor. -/
namespace differential_object
variables (C : Type u) [category.{v} C]
variables [has_zero_morphisms C] [has_shift C ℤ]
noncomputable theory
/-- The shift functor on `differential_object C`. -/
@[simps]
def shift_functor (n : ℤ) : differential_object C ⥤ differential_object C :=
{ obj := λ X,
{ X := X.X⟦n⟧,
d := X.d⟦n⟧' ≫ (shift_comm _ _ _).hom,
d_squared' := by rw [functor.map_comp, category.assoc, shift_comm_hom_comp_assoc,
←functor.map_comp_assoc, X.d_squared, functor.map_zero, zero_comp] },
map := λ X Y f,
{ f := f.f⟦n⟧',
comm' := by { dsimp, rw [category.assoc, shift_comm_hom_comp, ← functor.map_comp_assoc,
f.comm, functor.map_comp_assoc], }, },
map_id' := by { intros X, ext1, dsimp, rw functor.map_id },
map_comp' := by { intros X Y Z f g, ext1, dsimp, rw functor.map_comp } }
local attribute [simp] eq_to_hom_map
local attribute [reducible] discrete.add_monoidal shift_comm
/-- The shift functor on `differential_object C` is additive. -/
@[simps] def shift_functor_add (m n : ℤ) :
shift_functor C (m + n) ≅ shift_functor C m ⋙ shift_functor C n :=
begin
refine nat_iso.of_components (λ X, mk_iso (shift_add X.X _ _) _) _,
{ dsimp,
-- This is just `simp, simp [eq_to_hom_map]`.
simp_rw [category.assoc, obj_μ_inv_app, μ_inv_hom_app_assoc, functor.map_comp, obj_μ_app,
category.assoc, μ_naturality_assoc, μ_inv_hom_app_assoc, obj_μ_inv_app, category.assoc,
μ_naturalityₗ_assoc, μ_inv_hom_app_assoc, μ_inv_naturalityᵣ_assoc],
simp only [eq_to_hom_map, eq_to_hom_app, eq_to_iso.hom, eq_to_hom_trans_assoc,
eq_to_iso.inv], },
{ intros X Y f, ext, dsimp, exact nat_trans.naturality _ _ }
end
local attribute [reducible] endofunctor_monoidal_category
section
local attribute [instance] endofunctor_monoidal_category
/-- The shift by zero is naturally isomorphic to the identity. -/
@[simps]
def shift_ε : 𝟭 (differential_object C) ≅ shift_functor C 0 :=
begin
refine nat_iso.of_components (λ X, mk_iso ((shift_monoidal_functor C ℤ).ε_iso.app X.X) _) _,
{ dsimp, simp, dsimp, simp },
{ introv, ext, dsimp, simp }
end
end
local attribute [simp] eq_to_hom_map
instance : has_shift (differential_object C) ℤ :=
has_shift_mk _ _
{ F := shift_functor C,
ε := shift_ε C,
μ := λ m n, (shift_functor_add C m n).symm }
end differential_object
end category_theory
|
43e3e4a972c3be0c331473ce7cb82aa8ba7c4187 | a721fe7446524f18ba361625fc01033d9c8b7a78 | /src/principia/myint/le.lean | 728dea814216969aa0b637418c3fcf49f857b190 | [] | no_license | Sterrs/leaning | 8fd80d1f0a6117a220bb2e57ece639b9a63deadc | 3901cc953694b33adda86cb88ca30ba99594db31 | refs/heads/master | 1,627,023,822,744 | 1,616,515,221,000 | 1,616,515,221,000 | 245,512,190 | 2 | 0 | null | 1,616,429,050,000 | 1,583,527,118,000 | Lean | UTF-8 | Lean | false | false | 5,563 | lean | import .basic
import .int_pair
import ..mynat.sum
import ..myring.order
namespace hidden
namespace myint
open myring
open ordered_myring
def le: myint → myint → Prop :=
quotient.lift₂ int_pair.le int_pair.le_well_defined
instance: has_le myint := ⟨le⟩
theorem le_eq_cls {x y: int_pair.int_pair} {n m: myint}:
n = ⟦x⟧ → m = ⟦y⟧ → (n ≤ m ↔ x ≤ y) :=
λ hnx hmy, by rw [hnx, hmy]; refl
variables m n k x y z : myint
variables a b c : mynat
@[simp]
theorem coe_coe_le: (↑a:myint) ≤ ↑b ↔ a ≤ b := iff.rfl
instance decidable_le: ∀ m n : myint, decidable (m ≤ n) :=
quotient_decidable_rel int_pair.le int_pair.le_well_defined
-- theorems leading up to ordered ring instance proof
private theorem add_eq_cls {x y: int_pair.int_pair} {n m: myint}:
n = ⟦x⟧ → m = ⟦y⟧ → n + m = ⟦x + y⟧ :=
λ hnx hmy, by rw [hnx, hmy]; refl
-- is this somewhere else?
theorem coe_inj {m n: mynat}: (↑m: myint) = ↑n → m = n :=
begin
assume hmn,
have := quotient.exact hmn,
cases this,
refl,
end
lemma le_add_rhs_coe {m n : myint}: m ≤ n → m ≤ n + ↑c :=
begin
assume hmn,
cases quotient.exists_rep m with a ha, subst ha,
cases quotient.exists_rep n with b hb, subst hb,
rw coe_nat_def,
rw add_eq_cls rfl rfl,
rw le_eq_cls rfl rfl,
rw le_eq_cls rfl rfl at hmn,
rw int_pair.le_def at *,
simp,
have: b.a + c + a.b = b.a + a.b + c := by ac_refl,
rw this,
from mynat.le_add_rhs hmn,
end
-- Show old defn of ≤ is equivalent (very useful)
theorem le_iff_exists_nat: m ≤ n ↔ ∃ a : mynat, n = m + ↑a :=
begin
split, {
assume hmn,
cases quotient.exists_rep m with a ha, subst ha,
cases quotient.exists_rep n with b hb, subst hb,
rw le_eq_cls rfl rfl at hmn,
cases hmn with d hd,
existsi d,
rw coe_nat_def,
rw add_eq_cls rfl rfl,
apply quotient.sound,
rw int_pair.setoid_equiv,
simp,
rw hd,
ac_refl,
}, {
assume h,
cases h with a ha,
subst ha,
apply le_add_rhs_coe,
cases quotient.exists_rep m with a ha, subst ha,
from mynat.le_refl,
},
end
instance: ordered_integral_domain myint := ⟨
by apply_instance,
λ a b c: myint,
begin
cases quotient.exists_rep a with n hn, subst hn,
cases quotient.exists_rep b with m hm, subst hm,
cases quotient.exists_rep c with k hk, subst hk,
repeat {rw add_eq_cls rfl rfl},
repeat {rw le_eq_cls rfl rfl},
repeat {rw int_pair.le_def},
repeat {rw int_pair.add_a <|> rw int_pair.add_b},
rw (by ac_refl: n.a + k.a + (m.b + k.b) = n.a + m.b + (k.a + k.b)),
rw (by ac_refl: m.a + k.a + (n.b + k.b) = m.a + n.b + (k.a + k.b)),
apply mynat.le_add,
end,
begin
intros a b,
assume h0a h0b,
cases (le_iff_exists_nat _ _).mp h0a with n hn,
cases (le_iff_exists_nat _ _).mp h0b with m hm,
rw le_iff_exists_nat,
existsi n * m,
rw hn,
rw hm,
repeat {rw zero_add},
rw coe_coe_mul,
end,
begin
intros a b c,
repeat {rw le_iff_exists_nat},
assume hab, cases hab with n hn,
assume hbc, cases hbc with m hm,
existsi n + m,
rw hm,
rw hn,
rw add_assoc,
rw coe_coe_add,
end,
begin
intros a b,
cases quotient.exists_rep a with n hn, subst hn,
cases quotient.exists_rep b with m hm, subst hm,
from mynat.le_total_order _ _,
end,
begin
intros a b,
assume hab hba,
cases (le_iff_exists_nat _ _).mp hab with n hn,
cases (le_iff_exists_nat _ _).mp hba with m hm,
rw hn at hm,
rw add_assoc at hm,
have hnm0 := add_cancel_right_to_zero _ _ hm.symm,
rw coe_coe_add at hnm0,
rw ←coe_zero at hnm0,
have := coe_inj hnm0,
rw mynat.add_integral this at hn,
rw hn,
symmetry,
from add_zero _,
end⟩
-- nonsense theorems that probably aren't used anywhere else
theorem zero_le_iff_coe: 0 ≤ m ↔ ∃ a: mynat, m = ↑a :=
begin
split; assume h, {
rw le_iff_exists_nat at h,
cases h with a h,
rw zero_add at h,
existsi a,
assumption,
}, {
rw le_iff_exists_nat,
cases h with a h,
existsi a,
rwa zero_add,
},
end
theorem le_zero_iff_neg_coe: m ≤ 0 ↔ ∃ a : mynat, m = -↑a :=
begin
rw le_neg_switch_iff,
rw neg_zero,
-- can't rewrite inside a ∃
split, {
assume h0m,
cases (zero_le_iff_coe _).mp h0m with a ha,
existsi a,
rw ←ha,
rw neg_neg,
}, {
assume hex,
apply (zero_le_iff_coe _).mpr,
cases hex with a ha,
existsi a,
rw ha,
rw neg_neg,
},
end
-- add this to myring wherever it belongs
theorem le_sqrt_nonneg {m n : myint} (hm : 0 ≤ m) (hn : 0 ≤ n) :
m ≤ n ↔ m * m ≤ n * n :=
begin
split; assume h, {
apply le_mul_comb_nonneg; assumption,
}, {
-- Should be possible to convert to coercion and then use mynat.le_sqrt
rw zero_le_iff_coe at hm,
rw zero_le_iff_coe at hn,
cases hm with a ha, subst ha,
cases hn with b hb, subst hb,
rw coe_coe_le,
repeat {rw coe_coe_mul at h},
rw coe_coe_le at h,
apply mynat.le_sqrt,
assumption,
},
end
theorem lt_iff_succ_le: m < n ↔ m + 1 ≤ n :=
begin
cases quotient.exists_rep m with a ha, subst ha,
cases quotient.exists_rep n with b hb, subst hb,
rw int_one,
rw add_eq_cls rfl rfl,
rw le_eq_cls rfl rfl,
rw int_pair.le_def,
rw int_pair.add_b,
rw int_pair.add_a,
conv in (a.a + (1: int_pair.int_pair).a + b.b) {
rw mynat.add_assoc,
rw mynat.add_comm _ b.b,
rw ←mynat.add_assoc,
},
from mynat.lt_iff_succ_le,
end
end myint
end hidden
|
5c7ab303c97a6e732678a72f77aa6773f02d13c7 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/geometry/manifold/vector_bundle/basic.lean | 19ea2d529b20276a298ee572fab072c202740201 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 16,953 | lean | /-
Copyright (c) 2022 Floris van Doorn, Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Heather Macbeth
-/
import geometry.manifold.vector_bundle.fiberwise_linear
import topology.vector_bundle.constructions
/-! # Smooth vector bundles
This file defines smooth vector bundles over a smooth manifold.
Let `E` be a topological vector bundle, with model fiber `F` and base space `B`. We consider `E` as
carrying a charted space structure given by its trivializations -- these are charts to `B × F`.
Then, by "composition", if `B` is itself a charted space over `H` (e.g. a smooth manifold), then `E`
is also a charted space over `H × F`
Now, we define `smooth_vector_bundle` as the `Prop` of having smooth transition functions.
Recall the structure groupoid `smooth_fiberwise_linear` on `B × F` consisting of smooth, fiberwise
linear local homeomorphisms. We show that our definition of "smooth vector bundle" implies
`has_groupoid` for this groupoid, and show (by a "composition" of `has_groupoid` instances) that
this means that a smooth vector bundle is a smooth manifold.
Since `smooth_vector_bundle` is a mixin, it should be easy to make variants and for many such
variants to coexist -- vector bundles can be smooth vector bundles over several different base
fields, they can also be C^k vector bundles, etc.
## Main definitions and constructions
* `fiber_bundle.charted_space`: A fiber bundle `E` over a base `B` with model fiber `F` is naturally
a charted space modelled on `B × F`.
* `fiber_bundle.charted_space'`: Let `B` be a charted space modelled on `HB`. Then a fiber bundle
`E` over a base `B` with model fiber `F` is naturally a charted space modelled on `HB.prod F`.
* `smooth_vector_bundle`: Mixin class stating that a (topological) `vector_bundle` is smooth, in the
sense of having smooth transition functions.
* `smooth_fiberwise_linear.has_groupoid`: For a smooth vector bundle `E` over `B` with fiber
modelled on `F`, the change-of-co-ordinates between two trivializations `e`, `e'` for `E`,
considered as charts to `B × F`, is smooth and fiberwise linear, in the sense of belonging to the
structure groupoid `smooth_fiberwise_linear`.
* `bundle.total_space.smooth_manifold_with_corners`: A smooth vector bundle is naturally a smooth
manifold.
* `vector_bundle_core.smooth_vector_bundle`: If a (topological) `vector_bundle_core` is smooth, in
the sense of having smooth transition functions, then the vector bundle constructed from it is a
smooth vector bundle.
* `bundle.prod.smooth_vector_bundle`: The direct sum of two smooth vector bundles is a smooth vector
bundle.
-/
assert_not_exists mfderiv
open bundle set local_homeomorph function (id_def) filter
open_locale manifold bundle topology
variables {𝕜 B B' F M : Type*} {E : B → Type*}
/-! ### Charted space structure on a fiber bundle -/
section
variables [topological_space F] [topological_space (total_space E)] [∀ x, topological_space (E x)]
{HB : Type*} [topological_space HB]
[topological_space B] [charted_space HB B] [fiber_bundle F E]
/-- A fiber bundle `E` over a base `B` with model fiber `F` is naturally a charted space modelled on
`B × F`. -/
instance fiber_bundle.charted_space : charted_space (B × F) (total_space E) :=
{ atlas := (λ e : trivialization F (π E), e.to_local_homeomorph) '' trivialization_atlas F E,
chart_at := λ x, (trivialization_at F E x.proj).to_local_homeomorph,
mem_chart_source := λ x, (trivialization_at F E x.proj).mem_source.mpr
(mem_base_set_trivialization_at F E x.proj),
chart_mem_atlas := λ x, mem_image_of_mem _ (trivialization_mem_atlas F E _) }
section
local attribute [reducible] model_prod
/-- Let `B` be a charted space modelled on `HB`. Then a fiber bundle `E` over a base `B` with model
fiber `F` is naturally a charted space modelled on `HB.prod F`. -/
instance fiber_bundle.charted_space' : charted_space (model_prod HB F) (total_space E) :=
charted_space.comp _ (model_prod B F) _
end
lemma fiber_bundle.charted_space_chart_at (x : total_space E) :
chart_at (model_prod HB F) x =
(trivialization_at F E x.proj).to_local_homeomorph ≫ₕ
(chart_at HB x.proj).prod (local_homeomorph.refl F) :=
begin
dsimp only [fiber_bundle.charted_space', charted_space.comp, fiber_bundle.charted_space,
prod_charted_space, charted_space_self],
rw [trivialization.coe_coe,
trivialization.coe_fst' _ (mem_base_set_trivialization_at F E x.proj)]
end
lemma fiber_bundle.charted_space_chart_at_symm_fst (x : total_space E) (y : model_prod HB F)
(hy : y ∈ (chart_at (model_prod HB F) x).target) :
((chart_at (model_prod HB F) x).symm y).proj = (chart_at HB x.proj).symm y.1 :=
begin
simp only [fiber_bundle.charted_space_chart_at] with mfld_simps at hy ⊢,
exact (trivialization_at F E x.proj).proj_symm_apply hy.2,
end
end
section
variables [nontrivially_normed_field 𝕜]
[normed_add_comm_group F] [normed_space 𝕜 F]
[topological_space (total_space E)] [∀ x, topological_space (E x)]
{EB : Type*} [normed_add_comm_group EB] [normed_space 𝕜 EB]
{HB : Type*} [topological_space HB] (IB : model_with_corners 𝕜 EB HB)
(E' : B → Type*) [Π x, has_zero (E' x)]
{EM : Type*} [normed_add_comm_group EM] [normed_space 𝕜 EM]
{HM : Type*} [topological_space HM] {IM : model_with_corners 𝕜 EM HM}
[topological_space M] [charted_space HM M] [Is : smooth_manifold_with_corners IM M]
{n : ℕ∞}
variables [topological_space B] [charted_space HB B] [fiber_bundle F E]
protected lemma fiber_bundle.ext_chart_at (x : total_space E) :
ext_chart_at (IB.prod 𝓘(𝕜, F)) x =
(trivialization_at F E x.proj).to_local_equiv ≫
(ext_chart_at IB x.proj).prod (local_equiv.refl F) :=
begin
simp_rw [ext_chart_at, fiber_bundle.charted_space_chart_at, extend],
simp only [local_equiv.trans_assoc] with mfld_simps,
end
/-! ### Smoothness of maps in/out fiber bundles
Note: For these results we don't need that the bundle is a smooth vector bundle, or even a vector
bundle at all, just that it is a fiber bundle over a charted base space.
-/
namespace bundle
variables {F E IB}
/-- Characterization of C^n functions into a smooth vector bundle. -/
lemma cont_mdiff_within_at_total_space (f : M → total_space E) {s : set M} {x₀ : M} :
cont_mdiff_within_at IM (IB.prod (𝓘(𝕜, F))) n f s x₀ ↔
cont_mdiff_within_at IM IB n (λ x, (f x).proj) s x₀ ∧
cont_mdiff_within_at IM 𝓘(𝕜, F) n (λ x, (trivialization_at F E (f x₀).proj (f x)).2) s x₀ :=
begin
simp only [cont_mdiff_within_at_iff_target] {single_pass := tt},
rw [and_and_and_comm, ← continuous_within_at_total_space, and.congr_right_iff],
intros hf,
simp_rw [model_with_corners_self_prod, fiber_bundle.ext_chart_at, function.comp,
local_equiv.trans_apply, local_equiv.prod_coe, local_equiv.refl_coe,
ext_chart_at_self_apply, model_with_corners_self_coe, id_def],
refine (cont_mdiff_within_at_prod_iff _).trans _, -- rw doesn't do this?
have h1 : (λ x, (f x).proj) ⁻¹' (trivialization_at F E (f x₀).proj).base_set ∈ 𝓝[s] x₀ :=
((continuous_proj F E).continuous_within_at.comp hf (maps_to_image f s))
.preimage_mem_nhds_within
((trivialization.open_base_set _).mem_nhds (mem_base_set_trivialization_at F E _)),
refine and_congr (eventually_eq.cont_mdiff_within_at_iff (eventually_of_mem h1 $ λ x hx, _) _)
iff.rfl,
{ simp_rw [function.comp, local_homeomorph.coe_coe, trivialization.coe_coe],
rw [trivialization.coe_fst'],
exact hx },
{ simp only with mfld_simps },
end
/-- Characterization of C^n functions into a smooth vector bundle. -/
lemma cont_mdiff_at_total_space (f : M → total_space E) (x₀ : M) :
cont_mdiff_at IM (IB.prod (𝓘(𝕜, F))) n f x₀ ↔
cont_mdiff_at IM IB n (λ x, (f x).proj) x₀ ∧
cont_mdiff_at IM 𝓘(𝕜, F) n (λ x, (trivialization_at F E (f x₀).proj (f x)).2) x₀ :=
by { simp_rw [← cont_mdiff_within_at_univ], exact cont_mdiff_within_at_total_space f }
variables (E)
lemma cont_mdiff_proj : cont_mdiff (IB.prod 𝓘(𝕜, F)) IB n (π E) :=
begin
intro x,
rw [cont_mdiff_at, cont_mdiff_within_at_iff'],
refine ⟨(continuous_proj F E).continuous_within_at, _⟩,
simp_rw [(∘), fiber_bundle.ext_chart_at],
apply cont_diff_within_at_fst.congr,
{ rintros ⟨a, b⟩ hab,
simp only with mfld_simps at hab,
have : ((chart_at HB x.1).symm (IB.symm a), b) ∈ (trivialization_at F E x.fst).target,
{ simp only [hab] with mfld_simps },
simp only [trivialization.proj_symm_apply _ this, hab] with mfld_simps },
{ simp only with mfld_simps }
end
lemma smooth_proj : smooth (IB.prod 𝓘(𝕜, F)) IB (π E) :=
cont_mdiff_proj E
lemma cont_mdiff_on_proj {s : set (total_space E)} :
cont_mdiff_on (IB.prod 𝓘(𝕜, F)) IB n (π E) s :=
(bundle.cont_mdiff_proj E).cont_mdiff_on
lemma smooth_on_proj {s : set (total_space E)} :
smooth_on (IB.prod 𝓘(𝕜, F)) IB (π E) s :=
cont_mdiff_on_proj E
lemma cont_mdiff_at_proj {p : total_space E} :
cont_mdiff_at (IB.prod 𝓘(𝕜, F)) IB n
(π E) p :=
(bundle.cont_mdiff_proj E).cont_mdiff_at
lemma smooth_at_proj {p : total_space E} :
smooth_at (IB.prod 𝓘(𝕜, F)) IB (π E) p :=
bundle.cont_mdiff_at_proj E
lemma cont_mdiff_within_at_proj
{s : set (total_space E)}
{p : total_space E} :
cont_mdiff_within_at (IB.prod 𝓘(𝕜, F)) IB n (π E) s p :=
(bundle.cont_mdiff_at_proj E).cont_mdiff_within_at
lemma smooth_within_at_proj
{s : set (total_space E)}
{p : total_space E} :
smooth_within_at (IB.prod 𝓘(𝕜, F)) IB (π E) s p :=
bundle.cont_mdiff_within_at_proj E
variables (𝕜 E) [∀ x, add_comm_monoid (E x)] [∀ x, module 𝕜 (E x)] [vector_bundle 𝕜 F E]
lemma smooth_zero_section : smooth IB (IB.prod 𝓘(𝕜, F)) (zero_section E) :=
begin
intro x,
rw [bundle.cont_mdiff_at_total_space],
refine ⟨cont_mdiff_at_id, cont_mdiff_at_const.congr_of_eventually_eq _⟩,
{ exact 0 },
refine eventually_of_mem ((trivialization_at F E x).open_base_set.mem_nhds
(mem_base_set_trivialization_at F E x)) (λ x' hx', _),
simp_rw [zero_section_proj, (trivialization_at F E x).zero_section 𝕜 hx']
end
end bundle
end
/-! ### Smooth vector bundles -/
variables [nontrivially_normed_field 𝕜] [∀ x, add_comm_monoid (E x)] [∀ x, module 𝕜 (E x)]
[normed_add_comm_group F] [normed_space 𝕜 F]
[topological_space (total_space E)] [∀ x, topological_space (E x)]
{EB : Type*} [normed_add_comm_group EB] [normed_space 𝕜 EB]
{HB : Type*} [topological_space HB] (IB : model_with_corners 𝕜 EB HB)
[topological_space B] [charted_space HB B] [smooth_manifold_with_corners IB B]
{EM : Type*} [normed_add_comm_group EM] [normed_space 𝕜 EM]
{HM : Type*} [topological_space HM] {IM : model_with_corners 𝕜 EM HM}
[topological_space M] [charted_space HM M] [Is : smooth_manifold_with_corners IM M]
{n : ℕ∞}
variables (F E) [fiber_bundle F E] [vector_bundle 𝕜 F E]
/-- When `B` is a smooth manifold with corners with respect to a model `IB` and `E` is a
topological vector bundle over `B` with fibers isomorphic to `F`, then `smooth_vector_bundle F E IB`
registers that the bundle is smooth, in the sense of having smooth transition functions.
This is a mixin, not carrying any new data`. -/
class smooth_vector_bundle : Prop :=
(smooth_on_coord_change : ∀ (e e' : trivialization F (π E))
[mem_trivialization_atlas e] [mem_trivialization_atlas e'],
smooth_on IB 𝓘(𝕜, F →L[𝕜] F) (λ b : B, (e.coord_changeL 𝕜 e' b : F →L[𝕜] F))
(e.base_set ∩ e'.base_set))
export smooth_vector_bundle (smooth_on_coord_change)
variables [smooth_vector_bundle F E IB]
/-- For a smooth vector bundle `E` over `B` with fiber modelled on `F`, the change-of-co-ordinates
between two trivializations `e`, `e'` for `E`, considered as charts to `B × F`, is smooth and
fiberwise linear. -/
instance : has_groupoid (total_space E) (smooth_fiberwise_linear B F IB) :=
{ compatible := begin
rintros _ _ ⟨e, he, rfl⟩ ⟨e', he', rfl⟩,
haveI : mem_trivialization_atlas e := ⟨he⟩,
haveI : mem_trivialization_atlas e' := ⟨he'⟩,
resetI,
rw mem_smooth_fiberwise_linear_iff,
refine ⟨_, _, e.open_base_set.inter e'.open_base_set, smooth_on_coord_change e e', _, _, _⟩,
{ rw inter_comm,
apply cont_mdiff_on.congr (smooth_on_coord_change e' e),
{ intros b hb,
rw e.symm_coord_changeL e' hb },
{ apply_instance },
{ apply_instance }, },
{ simp only [e.symm_trans_source_eq e', fiberwise_linear.local_homeomorph,
trans_to_local_equiv, symm_to_local_equiv]},
{ rintros ⟨b, v⟩ hb,
have hb' : b ∈ e.base_set ∩ e'.base_set,
{ simpa only [trans_to_local_equiv, symm_to_local_equiv, e.symm_trans_source_eq e',
coe_coe_symm, prod_mk_mem_set_prod_eq, mem_univ, and_true] using hb },
exact e.apply_symm_apply_eq_coord_changeL e' hb' v, }
end }
/-- A smooth vector bundle `E` is naturally a smooth manifold. -/
instance : smooth_manifold_with_corners (IB.prod 𝓘(𝕜, F)) (total_space E) :=
begin
refine { .. structure_groupoid.has_groupoid.comp (smooth_fiberwise_linear B F IB) _ },
intros e he,
rw mem_smooth_fiberwise_linear_iff at he,
obtain ⟨φ, U, hU, hφ, h2φ, heφ⟩ := he,
rw [is_local_structomorph_on_cont_diff_groupoid_iff],
refine ⟨cont_mdiff_on.congr _ heφ.eq_on, cont_mdiff_on.congr _ heφ.symm'.eq_on⟩,
{ rw heφ.source_eq,
apply smooth_on_fst.prod_mk,
exact (hφ.comp cont_mdiff_on_fst $ prod_subset_preimage_fst _ _).clm_apply cont_mdiff_on_snd },
{ rw heφ.target_eq,
apply smooth_on_fst.prod_mk,
exact (h2φ.comp cont_mdiff_on_fst $ prod_subset_preimage_fst _ _).clm_apply cont_mdiff_on_snd },
end
/-! ### Core construction for smooth vector bundles -/
namespace vector_bundle_core
variables {ι : Type*} {F} (Z : vector_bundle_core 𝕜 B F ι)
/-- Mixin for a `vector_bundle_core` stating smoothness (of transition functions). -/
class is_smooth (IB : model_with_corners 𝕜 EB HB) : Prop :=
(smooth_on_coord_change [] :
∀ i j, smooth_on IB 𝓘(𝕜, F →L[𝕜] F) (Z.coord_change i j) (Z.base_set i ∩ Z.base_set j))
export is_smooth (renaming smooth_on_coord_change → vector_bundle_core.smooth_on_coord_change)
variables [Z.is_smooth IB]
/-- If a `vector_bundle_core` has the `is_smooth` mixin, then the vector bundle constructed from it
is a smooth vector bundle. -/
instance smooth_vector_bundle : smooth_vector_bundle F Z.fiber IB :=
{ smooth_on_coord_change := begin
rintros - - ⟨i, rfl⟩ ⟨i', rfl⟩,
refine (Z.smooth_on_coord_change IB i i').congr (λ b hb, _),
ext v,
exact Z.local_triv_coord_change_eq i i' hb v,
end }
end vector_bundle_core
/-! ### The trivial smooth vector bundle -/
/-- A trivial vector bundle over a smooth manifold is a smooth vector bundle. -/
instance bundle.trivial.smooth_vector_bundle : smooth_vector_bundle F (bundle.trivial B F) IB :=
{ smooth_on_coord_change := begin
introsI e e' he he',
unfreezingI { obtain rfl := bundle.trivial.eq_trivialization B F e },
unfreezingI { obtain rfl := bundle.trivial.eq_trivialization B F e' },
simp_rw bundle.trivial.trivialization.coord_changeL,
exact smooth_const.smooth_on
end }
/-! ### Direct sums of smooth vector bundles -/
section prod
variables (F₁ : Type*) [normed_add_comm_group F₁] [normed_space 𝕜 F₁]
(E₁ : B → Type*) [topological_space (total_space E₁)]
[Π x, add_comm_monoid (E₁ x)] [Π x, module 𝕜 (E₁ x)]
variables (F₂ : Type*) [normed_add_comm_group F₂] [normed_space 𝕜 F₂]
(E₂ : B → Type*) [topological_space (total_space E₂)]
[Π x, add_comm_monoid (E₂ x)] [Π x, module 𝕜 (E₂ x)]
variables [Π x : B, topological_space (E₁ x)] [Π x : B, topological_space (E₂ x)]
[fiber_bundle F₁ E₁] [fiber_bundle F₂ E₂]
[vector_bundle 𝕜 F₁ E₁] [vector_bundle 𝕜 F₂ E₂]
[smooth_vector_bundle F₁ E₁ IB] [smooth_vector_bundle F₂ E₂ IB]
/-- The direct sum of two smooth vector bundles over the same base is a smooth vector bundle. -/
instance bundle.prod.smooth_vector_bundle :
smooth_vector_bundle (F₁ × F₂) (E₁ ×ᵇ E₂) IB :=
{ smooth_on_coord_change := begin
rintros _ _ ⟨e₁, e₂, i₁, i₂, rfl⟩ ⟨e₁', e₂', i₁', i₂', rfl⟩,
resetI,
rw [smooth_on],
refine cont_mdiff_on.congr _ (e₁.coord_changeL_prod 𝕜 e₁' e₂ e₂'),
refine cont_mdiff_on.clm_prod_map _ _,
{ refine (smooth_on_coord_change e₁ e₁').mono _,
simp only [trivialization.base_set_prod] with mfld_simps,
mfld_set_tac },
{ refine (smooth_on_coord_change e₂ e₂').mono _,
simp only [trivialization.base_set_prod] with mfld_simps,
mfld_set_tac },
end }
end prod
|
bd9fdc6f2462761a8508864d2fbd78a39c3ce105 | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /library/data/vector.lean | 733ce54bf6ac762d62706ec2cd46db4d7def4f5a | [
"Apache-2.0"
] | permissive | tjiaqi/lean | 4634d729795c164664d10d093f3545287c76628f | d0ce4cf62f4246b0600c07e074d86e51f2195e30 | refs/heads/master | 1,622,323,796,480 | 1,422,643,069,000 | 1,422,643,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,410 | lean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: data.vector
Author: Floris van Doorn, Leonardo de Moura
-/
import data.nat.basic
open nat prod
inductive vector (A : Type) : nat → Type :=
nil {} : vector A zero,
cons : Π {n}, A → vector A n → vector A (succ n)
namespace vector
notation a :: b := cons a b
notation `[` l:(foldr `,` (h t, cons h t) nil) `]` := l
variables {A B C : Type}
protected definition is_inhabited [instance] (h : inhabited A) : ∀ (n : nat), inhabited (vector A n),
is_inhabited 0 := inhabited.mk nil,
is_inhabited (n+1) := inhabited.mk (inhabited.value h :: inhabited.value (is_inhabited n))
theorem vector0_eq_nil : ∀ (v : vector A 0), v = nil,
vector0_eq_nil nil := rfl
definition head : Π {n : nat}, vector A (succ n) → A,
head (a::v) := a
definition tail : Π {n : nat}, vector A (succ n) → vector A n,
tail (a::v) := v
theorem head_cons {n : nat} (h : A) (t : vector A n) : head (h :: t) = h :=
rfl
theorem tail_cons {n : nat} (h : A) (t : vector A n) : tail (h :: t) = t :=
rfl
theorem eta : ∀ {n : nat} (v : vector A (succ n)), head v :: tail v = v,
eta (a::v) := rfl
definition last : Π {n : nat}, vector A (succ n) → A,
last (a::nil) := a,
last (a::v) := last v
theorem last_singleton (a : A) : last (a :: nil) = a :=
rfl
theorem last_cons {n : nat} (a : A) (v : vector A (succ n)) : last (a :: v) = last v :=
rfl
definition const : Π (n : nat), A → vector A n,
const 0 a := nil,
const (succ n) a := a :: const n a
theorem head_const (n : nat) (a : A) : head (const (succ n) a) = a :=
rfl
theorem last_const : ∀ (n : nat) (a : A), last (const (succ n) a) = a,
last_const 0 a := rfl,
last_const (succ n) a := last_const n a
definition map (f : A → B) : Π {n : nat}, vector A n → vector B n,
map nil := nil,
map (a::v) := f a :: map v
theorem map_nil (f : A → B) : map f nil = nil :=
rfl
theorem map_cons {n : nat} (f : A → B) (h : A) (t : vector A n) : map f (h :: t) = f h :: map f t :=
rfl
definition map2 (f : A → B → C) : Π {n : nat}, vector A n → vector B n → vector C n,
map2 nil nil := nil,
map2 (a::va) (b::vb) := f a b :: map2 va vb
theorem map2_nil (f : A → B → C) : map2 f nil nil = nil :=
rfl
theorem map2_cons {n : nat} (f : A → B → C) (h₁ : A) (h₂ : B) (t₁ : vector A n) (t₂ : vector B n) :
map2 f (h₁ :: t₁) (h₂ :: t₂) = f h₁ h₂ :: map2 f t₁ t₂ :=
rfl
-- Remark: why do we need to provide indices?
definition append : Π {n m : nat}, vector A n → vector A m → vector A (n ⊕ m),
@append 0 m nil w := w,
@append (succ n) m (a::v) w := a :: (append v w)
theorem append_nil {n : nat} (v : vector A n) : append nil v = v :=
rfl
theorem append_cons {n m : nat} (h : A) (t : vector A n) (v : vector A m) :
append (h::t) v = h :: (append t v) :=
rfl
definition unzip : Π {n : nat}, vector (A × B) n → vector A n × vector B n,
unzip nil := (nil, nil),
unzip ((a, b) :: v) := (a :: pr₁ (unzip v), b :: pr₂ (unzip v))
theorem unzip_nil : unzip (@nil (A × B)) = (nil, nil) :=
rfl
theorem unzip_cons {n : nat} (a : A) (b : B) (v : vector (A × B) n) :
unzip ((a, b) :: v) = (a :: pr₁ (unzip v), b :: pr₂ (unzip v)) :=
rfl
definition zip : Π {n : nat}, vector A n → vector B n → vector (A × B) n,
zip nil nil := nil,
zip (a::va) (b::vb) := ((a, b) :: zip va vb)
theorem zip_nil_nil : zip (@nil A) (@nil B) = nil :=
rfl
theorem zip_cons_cons {n : nat} (a : A) (b : B) (va : vector A n) (vb : vector B n) :
zip (a::va) (b::vb) = ((a, b) :: zip va vb) :=
rfl
theorem unzip_zip : ∀ {n : nat} (v₁ : vector A n) (v₂ : vector B n), unzip (zip v₁ v₂) = (v₁, v₂),
@unzip_zip 0 nil nil := rfl,
@unzip_zip (succ n) (a::va) (b::vb) := calc
unzip (zip (a :: va) (b :: vb))
= (a :: pr₁ (unzip (zip va vb)), b :: pr₂ (unzip (zip va vb))) : rfl
... = (a :: pr₁ (va, vb), b :: pr₂ (va, vb)) : {unzip_zip va vb}
... = (a :: va, b :: vb) : rfl
theorem zip_unzip : ∀ {n : nat} (v : vector (A × B) n), zip (pr₁ (unzip v)) (pr₂ (unzip v)) = v,
@zip_unzip 0 nil := rfl,
@zip_unzip (succ n) ((a, b) :: v) := calc
zip (pr₁ (unzip ((a, b) :: v))) (pr₂ (unzip ((a, b) :: v)))
= (a, b) :: zip (pr₁ (unzip v)) (pr₂ (unzip v)) : rfl
... = (a, b) :: v : {zip_unzip v}
/- Concat -/
definition concat : Π {n : nat}, vector A n → A → vector A (succ n),
concat nil a := a :: nil,
concat (b::v) a := b :: concat v a
theorem concat_nil (a : A) : concat nil a = a :: nil :=
rfl
theorem concat_cons {n : nat} (b : A) (v : vector A n) (a : A) : concat (b :: v) a = b :: concat v a :=
rfl
theorem last_concat : ∀ {n : nat} (v : vector A n) (a : A), last (concat v a) = a,
@last_concat 0 nil a := rfl,
@last_concat (succ n) (b::v) a := calc
last (concat (b::v) a) = last (concat v a) : rfl
... = a : last_concat v a
end vector
|
6d2c5b5d7c7c8d3ae82ee20087adf17e07626bcd | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/data/zmod/quotient.lean | 123bcc2d128bd213019ddede8316424fd3e13121 | [
"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 | 7,166 | lean | /-
Copyright (c) 2021 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import data.zmod.basic
import group_theory.group_action.quotient
import ring_theory.int.basic
/-!
# `zmod n` and quotient groups / rings
This file relates `zmod n` to the quotient group
`quotient_add_group.quotient (add_subgroup.zmultiples n)` and to the quotient ring
`(ideal.span {n}).quotient`.
## Main definitions
- `zmod.quotient_zmultiples_nat_equiv_zmod` and `zmod.quotient_zmultiples_equiv_zmod`:
`zmod n` is the group quotient of `ℤ` by `n ℤ := add_subgroup.zmultiples (n)`,
(where `n : ℕ` and `n : ℤ` respectively)
- `zmod.quotient_span_nat_equiv_zmod` and `zmod.quotient_span_equiv_zmod`:
`zmod n` is the ring quotient of `ℤ` by `n ℤ : ideal.span {n}`
(where `n : ℕ` and `n : ℤ` respectively)
- `zmod.lift n f` is the map from `zmod n` induced by `f : ℤ →+ A` that maps `n` to `0`.
## Tags
zmod, quotient group, quotient ring, ideal quotient
-/
open quotient_add_group
open zmod
variables (n : ℕ) {A R : Type*} [add_group A] [ring R]
namespace int
/-- `ℤ` modulo multiples of `n : ℕ` is `zmod n`. -/
def quotient_zmultiples_nat_equiv_zmod :
ℤ ⧸ add_subgroup.zmultiples (n : ℤ) ≃+ zmod n :=
(quotient_add_equiv_of_eq (zmod.ker_int_cast_add_hom _)).symm.trans $
quotient_ker_equiv_of_right_inverse (int.cast_add_hom (zmod n)) coe int_cast_zmod_cast
/-- `ℤ` modulo multiples of `a : ℤ` is `zmod a.nat_abs`. -/
def quotient_zmultiples_equiv_zmod (a : ℤ) :
ℤ ⧸ add_subgroup.zmultiples a ≃+ zmod a.nat_abs :=
(quotient_add_equiv_of_eq (zmultiples_nat_abs a)).symm.trans
(quotient_zmultiples_nat_equiv_zmod a.nat_abs)
/-- `ℤ` modulo the ideal generated by `n : ℕ` is `zmod n`. -/
def quotient_span_nat_equiv_zmod :
ℤ ⧸ ideal.span {↑n} ≃+* zmod n :=
(ideal.quot_equiv_of_eq (zmod.ker_int_cast_ring_hom _)).symm.trans $
ring_hom.quotient_ker_equiv_of_right_inverse $
show function.right_inverse coe (int.cast_ring_hom (zmod n)),
from int_cast_zmod_cast
/-- `ℤ` modulo the ideal generated by `a : ℤ` is `zmod a.nat_abs`. -/
def quotient_span_equiv_zmod (a : ℤ) :
ℤ ⧸ ideal.span ({a} : set ℤ) ≃+* zmod a.nat_abs :=
(ideal.quot_equiv_of_eq (span_nat_abs a)).symm.trans
(quotient_span_nat_equiv_zmod a.nat_abs)
end int
namespace add_action
open add_subgroup add_monoid_hom add_equiv function
variables {α β : Type*} [add_group α] (a : α) [add_action α β] (b : β)
/-- The quotient `(ℤ ∙ a) ⧸ (stabilizer b)` is cyclic of order `minimal_period ((+ᵥ) a) b`. -/
noncomputable def zmultiples_quotient_stabilizer_equiv :
zmultiples a ⧸ stabilizer (zmultiples a) b ≃+ zmod (minimal_period ((+ᵥ) a) b) :=
(of_bijective (map _ (stabilizer (zmultiples a) b)
(zmultiples_hom (zmultiples a) ⟨a, mem_zmultiples a⟩) (by
{ rw [zmultiples_le, mem_comap, mem_stabilizer_iff,
zmultiples_hom_apply, coe_nat_zsmul, ←vadd_iterate],
exact is_periodic_pt_minimal_period ((+ᵥ) a) b })) ⟨by
{ rw [←ker_eq_bot_iff, eq_bot_iff],
refine λ q, induction_on' q (λ n hn, _),
rw [mem_bot, eq_zero_iff, int.mem_zmultiples_iff, ←zsmul_vadd_eq_iff_minimal_period_dvd],
exact (eq_zero_iff _).mp hn },
λ q, induction_on' q (λ ⟨_, n, rfl⟩, ⟨n, rfl⟩)⟩).symm.trans
(int.quotient_zmultiples_nat_equiv_zmod (minimal_period ((+ᵥ) a) b))
lemma zmultiples_quotient_stabilizer_equiv_symm_apply (n : zmod (minimal_period ((+ᵥ) a) b)) :
(zmultiples_quotient_stabilizer_equiv a b).symm n =
(n : ℤ) • (⟨a, mem_zmultiples a⟩ : zmultiples a) :=
rfl
end add_action
namespace mul_action
open add_action subgroup add_subgroup function
variables {α β : Type*} [group α] (a : α) [mul_action α β] (b : β)
local attribute [semireducible] mul_opposite
/-- The quotient `(a ^ ℤ) ⧸ (stabilizer b)` is cyclic of order `minimal_period ((•) a) b`. -/
noncomputable def zpowers_quotient_stabilizer_equiv :
zpowers a ⧸ stabilizer (zpowers a) b ≃* multiplicative (zmod (minimal_period ((•) a) b)) :=
let f := zmultiples_quotient_stabilizer_equiv (additive.of_mul a) b in
⟨f.to_fun, f.inv_fun, f.left_inv, f.right_inv, f.map_add'⟩
lemma zpowers_quotient_stabilizer_equiv_symm_apply (n : zmod (minimal_period ((•) a) b)) :
(zpowers_quotient_stabilizer_equiv a b).symm n = (⟨a, mem_zpowers a⟩ : zpowers a) ^ (n : ℤ) :=
rfl
/-- The orbit `(a ^ ℤ) • b` is a cycle of order `minimal_period ((•) a) b`. -/
noncomputable def orbit_zpowers_equiv : orbit (zpowers a) b ≃ zmod (minimal_period ((•) a) b) :=
(orbit_equiv_quotient_stabilizer _ b).trans (zpowers_quotient_stabilizer_equiv a b).to_equiv
/-- The orbit `(ℤ • a) +ᵥ b` is a cycle of order `minimal_period ((+ᵥ) a) b`. -/
noncomputable def _root_.add_action.orbit_zmultiples_equiv
{α β : Type*} [add_group α] (a : α) [add_action α β] (b : β) :
add_action.orbit (zmultiples a) b ≃ zmod (minimal_period ((+ᵥ) a) b) :=
(add_action.orbit_equiv_quotient_stabilizer (zmultiples a) b).trans
(zmultiples_quotient_stabilizer_equiv a b).to_equiv
attribute [to_additive orbit_zmultiples_equiv] orbit_zpowers_equiv
@[to_additive orbit_zmultiples_equiv_symm_apply]
lemma orbit_zpowers_equiv_symm_apply (k : zmod (minimal_period ((•) a) b)) :
(orbit_zpowers_equiv a b).symm k =
(⟨a, mem_zpowers a⟩ : zpowers a) ^ (k : ℤ) • ⟨b, mem_orbit_self b⟩ :=
rfl
lemma orbit_zpowers_equiv_symm_apply' (k : ℤ) :
(orbit_zpowers_equiv a b).symm k =
(⟨a, mem_zpowers a⟩ : zpowers a) ^ k • ⟨b, mem_orbit_self b⟩ :=
begin
rw [orbit_zpowers_equiv_symm_apply, zmod.coe_int_cast],
exact subtype.ext (zpow_smul_mod_minimal_period _ _ k),
end
lemma _root_.add_action.orbit_zmultiples_equiv_symm_apply'
{α β : Type*} [add_group α] (a : α) [add_action α β] (b : β) (k : ℤ) :
(add_action.orbit_zmultiples_equiv a b).symm k =
(k • (⟨a, mem_zmultiples a⟩ : zmultiples a)) +ᵥ ⟨b, add_action.mem_orbit_self b⟩ :=
begin
rw [add_action.orbit_zmultiples_equiv_symm_apply, zmod.coe_int_cast],
exact subtype.ext (zsmul_vadd_mod_minimal_period _ _ k),
end
attribute [to_additive orbit_zmultiples_equiv_symm_apply'] orbit_zpowers_equiv_symm_apply'
@[to_additive] lemma minimal_period_eq_card [fintype (orbit (zpowers a) b)] :
minimal_period ((•) a) b = fintype.card (orbit (zpowers a) b) :=
by rw [←fintype.of_equiv_card (orbit_zpowers_equiv a b), zmod.card]
@[to_additive] instance minimal_period_pos [fintype $ orbit (zpowers a) b] :
ne_zero $ minimal_period ((•) a) b :=
⟨begin
haveI : nonempty (orbit (zpowers a) b) := (orbit_nonempty b).to_subtype,
rw minimal_period_eq_card,
exact fintype.card_ne_zero,
end⟩
/-- See also `order_eq_card_zpowers`. -/
@[to_additive add_order_eq_card_zmultiples' "See also `add_order_eq_card_zmultiples`."]
lemma _root_.order_eq_card_zpowers' : order_of a = nat.card (zpowers a) :=
begin
have := nat.card_congr (mul_action.orbit_zpowers_equiv a (1 : α)),
rwa [nat.card_zmod, orbit_subgroup_one_eq_self, eq_comm] at this,
end
end mul_action
|
f2a11fa7b62b3a3dc55181b778575470f20fe577 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/control/fix.lean | 96c8aac24a7a090c9f9d3da09c1e7f3781f709d9 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 3,309 | lean | /-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Simon Hudon
-/
import data.nat.upto
import data.stream.basic
import data.pfun
/-!
# Fixed point
This module defines a generic `fix` operator for defining recursive
computations that are not necessarily well-founded or productive.
An instance is defined for `roption`.
## Main definition
* class `has_fix`
* `roption.fix`
-/
universes u v
open_locale classical
variables {α : Type*} {β : α → Type*}
/-- `has_fix α` gives us a way to calculate the fixed point
of function of type `α → α`. -/
class has_fix (α : Type*) :=
(fix : (α → α) → α)
namespace roption
open roption nat nat.upto
section basic
variables (f : (Π a, roption $ β a) → (Π a, roption $ β a))
/-- A series of successive, finite approximation of the fixed point of `f`, defined by
`approx f n = f^[n] ⊥`. The limit of this chain is the fixed point of `f`. -/
def fix.approx : stream $ Π a, roption $ β a
| 0 := ⊥
| (nat.succ i) := f (fix.approx i)
/-- loop body for finding the fixed point of `f` -/
def fix_aux {p : ℕ → Prop} (i : nat.upto p)
(g : Π j : nat.upto p, i < j → Π a, roption $ β a) : Π a, roption $ β a :=
f $ λ x : α,
assert (¬p (i.val)) $ λ h : ¬ p (i.val),
g (i.succ h) (nat.lt_succ_self _) x
/-- The least fixed point of `f`.
If `f` is a continuous function (according to complete partial orders),
it satisfies the equations:
1. `fix f = f (fix f)` (is a fixed point)
2. `∀ X, f X ≤ X → fix f ≤ X` (least fixed point)
-/
protected def fix (x : α) : roption $ β x :=
roption.assert (∃ i, (fix.approx f i x).dom) $ λ h,
well_founded.fix.{1} (nat.upto.wf h) (fix_aux f) nat.upto.zero x
protected lemma fix_def {x : α} (h' : ∃ i, (fix.approx f i x).dom) :
roption.fix f x = fix.approx f (nat.succ $ nat.find h') x :=
begin
let p := λ (i : ℕ), (fix.approx f i x).dom,
have : p (nat.find h') := nat.find_spec h',
generalize hk : nat.find h' = k,
replace hk : nat.find h' = k + (@upto.zero p).val := hk,
rw hk at this,
revert hk,
dsimp [roption.fix], rw assert_pos h', revert this,
generalize : upto.zero = z, intros,
suffices : ∀ x', well_founded.fix (fix._proof_1 f x h') (fix_aux f) z x' = fix.approx f (succ k) x',
from this _,
induction k generalizing z; intro,
{ rw [fix.approx,well_founded.fix_eq,fix_aux],
congr, ext : 1, rw assert_neg, refl,
rw nat.zero_add at this,
simpa only [not_not, subtype.val_eq_coe] },
{ rw [fix.approx,well_founded.fix_eq,fix_aux],
congr, ext : 1,
have hh : ¬(fix.approx f (z.val) x).dom,
{ apply nat.find_min h',
rw [hk,nat.succ_add,← nat.add_succ],
apply nat.lt_of_succ_le,
apply nat.le_add_left },
rw succ_add_eq_succ_add at this hk,
rw [assert_pos hh, k_ih (upto.succ z hh) this hk] }
end
lemma fix_def' {x : α} (h' : ¬ ∃ i, (fix.approx f i x).dom) :
roption.fix f x = none :=
by dsimp [roption.fix]; rw assert_neg h'
end basic
end roption
namespace roption
instance : has_fix (roption α) :=
⟨λ f, roption.fix (λ x u, f (x u)) ()⟩
end roption
open sigma
namespace pi
instance roption.has_fix {β} : has_fix (α → roption β) := ⟨roption.fix⟩
end pi
|
3a0c7be7782eb96f51b8f428368777097a9831d5 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/task_test_io.lean | de2ffb6439998cf15aa8724d55ffbbd52f8052b0 | [
"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 | 910 | lean | #eval id (α := IO _) do
let t1 ← IO.asTask $ Nat.forM 10 fun _ => IO.println "hi";
let t2 ← IO.asTask $ Nat.forM 10 fun _ => IO.println "ho";
IO.ofExcept t1.get
#eval id (α := IO _) do
let t1 ← IO.mapTask IO.println (Task.spawn fun _ => "ha");
pure ()
#eval id (α := IO _) do
let t1 ← IO.bindTask (Task.spawn fun _ => "hu") fun s =>
IO.asTask (IO.println s);
pure ()
#eval id (α := IO _) do
let t1 ← IO.asTask do {
let c ← IO.checkCanceled;
IO.println (if c then "canceled!" else "done!")
};
pure ()
#eval id (α := IO _) do
let t1 ← IO.asTask do {
let c ← IO.checkCanceled;
IO.println (if c then "canceled! 2" else "done! 2")
};
IO.cancel t1;
discard $ IO.wait t1;
pure ()
#eval IO.waitAny [
Task.spawn fun _ => dbgSleep 2 fun _ => "A",
Task.spawn fun _ => dbgSleep 3 fun _ => "B",
Task.spawn fun _ => dbgSleep 1 fun _ => "C"
]
|
329010a4c9ba5a798a0dcfac02e5e81b6fc06b1d | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/lie/non_unital_non_assoc_algebra.lean | d9f1769f972f816ca433fd43dfc43609daf497ce | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 2,844 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.basic
import algebra.non_unital_alg_hom
/-!
# Lie algebras as non-unital, non-associative algebras
The definition of Lie algebras uses the `has_bracket` typeclass for multiplication whereas we have a
separate `has_mul` typeclass used for general algebras.
It is useful to have a special typeclass for Lie algebras because:
* it enables us to use the traditional notation `⁅x, y⁆` for the Lie multiplication,
* associative algebras carry a natural Lie algebra structure via the ring commutator and so we need
them to carry both `has_mul` and `has_bracket` simultaneously,
* more generally, Poisson algebras (not yet defined) need both typeclasses.
However there are times when it is convenient to be able to regard a Lie algebra as a general
algebra and we provide some basic definitions for doing so here.
## Main definitions
* `lie_ring.to_non_unital_non_assoc_semiring`
* `lie_hom.to_non_unital_alg_hom`
## Tags
lie algebra, non-unital, non-associative
-/
universes u v w
variables (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L]
/-- A `lie_ring` can be regarded as a `non_unital_non_assoc_semiring` by turning its
`has_bracket` (denoted `⁅, ⁆`) into a `has_mul` (denoted `*`). -/
def lie_ring.to_non_unital_non_assoc_semiring : non_unital_non_assoc_semiring L :=
{ mul := has_bracket.bracket,
left_distrib := lie_add,
right_distrib := add_lie,
zero_mul := zero_lie,
mul_zero := lie_zero,
.. (infer_instance : add_comm_monoid L) }
local attribute [instance] lie_ring.to_non_unital_non_assoc_semiring
namespace lie_algebra
/-- Regarding the `lie_ring` of a `lie_algebra` as a `non_unital_non_assoc_semiring`, we can
reinterpret the `smul_lie` law as an `is_scalar_tower`. -/
instance is_scalar_tower : is_scalar_tower R L L := ⟨smul_lie⟩
/-- Regarding the `lie_ring` of a `lie_algebra` as a `non_unital_non_assoc_semiring`, we can
reinterpret the `lie_smul` law as an `smul_comm_class`. -/
instance smul_comm_class : smul_comm_class R L L := ⟨λ t x y, (lie_smul t x y).symm⟩
end lie_algebra
namespace lie_hom
variables {R L} {L₂ : Type w} [lie_ring L₂] [lie_algebra R L₂]
/-- Regarding the `lie_ring` of a `lie_algebra` as a `non_unital_non_assoc_semiring`, we can
regard a `lie_hom` as a `non_unital_alg_hom`. -/
@[simps]
def to_non_unital_alg_hom (f : L →ₗ⁅R⁆ L₂) : non_unital_alg_hom R L L₂ :=
{ to_fun := f,
map_zero' := f.map_zero,
map_mul' := f.map_lie,
..f }
lemma to_non_unital_alg_hom_injective :
function.injective (to_non_unital_alg_hom : _ → non_unital_alg_hom R L L₂) :=
λ f g h, ext $ non_unital_alg_hom.congr_fun h
end lie_hom
|
de03f1d3f82870fa63a7e8c69e2a0a5bee763812 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /06_Inductive_Types.org.17.lean | 939e36c8c4f04d5750498961db29cea24d5a673a | [] | 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 | 174 | lean | /- page 82 -/
import standard
open nat
-- BEGIN
record color := (red : nat) (green : nat) (blue : nat)
definition yellow := color.mk 255 255 0
eval color.red yellow
-- END
|
7657f49afccc7194424e227db3701bf4f7259b8e | c777c32c8e484e195053731103c5e52af26a25d1 | /src/geometry/manifold/charted_space.lean | 519ab352e53167ce3ba8bf8c34f656a4984cc065 | [
"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 | 50,758 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import topology.local_homeomorph
/-!
# Charted spaces
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
A smooth manifold is a topological space `M` locally modelled on a euclidean space (or a euclidean
half-space for manifolds with boundaries, or an infinite dimensional vector space for more general
notions of manifolds), i.e., the manifold is covered by open subsets on which there are local
homeomorphisms (the charts) going to a model space `H`, and the changes of charts should be smooth
maps.
In this file, we introduce a general framework describing these notions, where the model space is an
arbitrary topological space. We avoid the word *manifold*, which should be reserved for the
situation where the model space is a (subset of a) vector space, and use the terminology
*charted space* instead.
If the changes of charts satisfy some additional property (for instance if they are smooth), then
`M` inherits additional structure (it makes sense to talk about smooth manifolds). There are
therefore two different ingredients in a charted space:
* the set of charts, which is data
* the fact that changes of charts belong to some group (in fact groupoid), which is additional Prop.
We separate these two parts in the definition: the charted space structure is just the set of
charts, and then the different smoothness requirements (smooth manifold, orientable manifold,
contact manifold, and so on) are additional properties of these charts. These properties are
formalized through the notion of structure groupoid, i.e., a set of local homeomorphisms stable
under composition and inverse, to which the change of coordinates should belong.
## Main definitions
* `structure_groupoid H` : a subset of local homeomorphisms of `H` stable under composition,
inverse and restriction (ex: local diffeos).
* `continuous_groupoid H` : the groupoid of all local homeomorphisms of `H`
* `charted_space H M` : charted space structure on `M` modelled on `H`, given by an atlas of
local homeomorphisms from `M` to `H` whose sources cover `M`. This is a type class.
* `has_groupoid M G` : when `G` is a structure groupoid on `H` and `M` is a charted space
modelled on `H`, require that all coordinate changes belong to `G`. This is a type class.
* `atlas H M` : when `M` is a charted space modelled on `H`, the atlas of this charted
space structure, i.e., the set of charts.
* `G.maximal_atlas M` : when `M` is a charted space modelled on `H` and admitting `G` as a
structure groupoid, one can consider all the local homeomorphisms from `M` to `H` such that
changing coordinate from any chart to them belongs to `G`. This is a larger atlas, called the
maximal atlas (for the groupoid `G`).
* `structomorph G M M'` : the type of diffeomorphisms between the charted spaces `M` and `M'` for
the groupoid `G`. We avoid the word diffeomorphism, keeping it for the smooth category.
As a basic example, we give the instance
`instance charted_space_model_space (H : Type*) [topological_space H] : charted_space H H`
saying that a topological space is a charted space over itself, with the identity as unique chart.
This charted space structure is compatible with any groupoid.
Additional useful definitions:
* `pregroupoid H` : a subset of local mas of `H` stable under composition and
restriction, but not inverse (ex: smooth maps)
* `groupoid_of_pregroupoid` : construct a groupoid from a pregroupoid, by requiring that a map and
its inverse both belong to the pregroupoid (ex: construct diffeos from smooth maps)
* `chart_at H x` is a preferred chart at `x : M` when `M` has a charted space structure modelled on
`H`.
* `G.compatible he he'` states that, for any two charts `e` and `e'` in the atlas, the composition
of `e.symm` and `e'` belongs to the groupoid `G` when `M` admits `G` as a structure groupoid.
* `G.compatible_of_mem_maximal_atlas he he'` states that, for any two charts `e` and `e'` in the
maximal atlas associated to the groupoid `G`, the composition of `e.symm` and `e'` belongs to the
`G` if `M` admits `G` as a structure groupoid.
* `charted_space_core.to_charted_space`: consider a space without a topology, but endowed with a set
of charts (which are local equivs) for which the change of coordinates are local homeos. Then
one can construct a topology on the space for which the charts become local homeos, defining
a genuine charted space structure.
## Implementation notes
The atlas in a charted space is *not* a maximal atlas in general: the notion of maximality depends
on the groupoid one considers, and changing groupoids changes the maximal atlas. With the current
formalization, it makes sense first to choose the atlas, and then to ask whether this precise atlas
defines a smooth manifold, an orientable manifold, and so on. A consequence is that structomorphisms
between `M` and `M'` do *not* induce a bijection between the atlases of `M` and `M'`: the
definition is only that, read in charts, the structomorphism locally belongs to the groupoid under
consideration. (This is equivalent to inducing a bijection between elements of the maximal atlas).
A consequence is that the invariance under structomorphisms of properties defined in terms of the
atlas is not obvious in general, and could require some work in theory (amounting to the fact
that these properties only depend on the maximal atlas, for instance). In practice, this does not
create any real difficulty.
We use the letter `H` for the model space thinking of the case of manifolds with boundary, where the
model space is a half space.
Manifolds are sometimes defined as topological spaces with an atlas of local diffeomorphisms, and
sometimes as spaces with an atlas from which a topology is deduced. We use the former approach:
otherwise, there would be an instance from manifolds to topological spaces, which means that any
instance search for topological spaces would try to find manifold structures involving a yet
unknown model space, leading to problems. However, we also introduce the latter approach,
through a structure `charted_space_core` making it possible to construct a topology out of a set of
local equivs with compatibility conditions (but we do not register it as an instance).
In the definition of a charted space, the model space is written as an explicit parameter as there
can be several model spaces for a given topological space. For instance, a complex manifold
(modelled over `ℂ^n`) will also be seen sometimes as a real manifold modelled over `ℝ^(2n)`.
## Notations
In the locale `manifold`, we denote the composition of local homeomorphisms with `≫ₕ`, and the
composition of local equivs with `≫`.
-/
noncomputable theory
open_locale classical topology
open filter
universes u
variables {H : Type u} {H' : Type*} {M : Type*} {M' : Type*} {M'' : Type*}
/- Notational shortcut for the composition of local homeomorphisms and local equivs, i.e.,
`local_homeomorph.trans` and `local_equiv.trans`.
Note that, as is usual for equivs, the composition is from left to right, hence the direction of
the arrow. -/
localized "infixr (name := local_homeomorph.trans)
` ≫ₕ `:100 := local_homeomorph.trans" in manifold
localized "infixr (name := local_equiv.trans)
` ≫ `:100 := local_equiv.trans" in manifold
open set local_homeomorph
/-! ### Structure groupoids-/
section groupoid
/-! One could add to the definition of a structure groupoid the fact that the restriction of an
element of the groupoid to any open set still belongs to the groupoid.
(This is in Kobayashi-Nomizu.)
I am not sure I want this, for instance on `H × E` where `E` is a vector space, and the groupoid is
made of functions respecting the fibers and linear in the fibers (so that a charted space over this
groupoid is naturally a vector bundle) I prefer that the members of the groupoid are always
defined on sets of the form `s × E`. There is a typeclass `closed_under_restriction` for groupoids
which have the restriction property.
The only nontrivial requirement is locality: if a local homeomorphism belongs to the groupoid
around each point in its domain of definition, then it belongs to the groupoid. Without this
requirement, the composition of structomorphisms does not have to be a structomorphism. Note that
this implies that a local homeomorphism with empty source belongs to any structure groupoid, as
it trivially satisfies this condition.
There is also a technical point, related to the fact that a local homeomorphism is by definition a
global map which is a homeomorphism when restricted to its source subset (and its values outside
of the source are not relevant). Therefore, we also require that being a member of the groupoid only
depends on the values on the source.
We use primes in the structure names as we will reformulate them below (without primes) using a
`has_mem` instance, writing `e ∈ G` instead of `e ∈ G.members`.
-/
/-- A structure groupoid is a set of local homeomorphisms of a topological space stable under
composition and inverse. They appear in the definition of the smoothness class of a manifold. -/
structure structure_groupoid (H : Type u) [topological_space H] :=
(members : set (local_homeomorph H H))
(trans' : ∀e e' : local_homeomorph H H, e ∈ members → e' ∈ members → e ≫ₕ e' ∈ members)
(symm' : ∀e : local_homeomorph H H, e ∈ members → e.symm ∈ members)
(id_mem' : local_homeomorph.refl H ∈ members)
(locality' : ∀e : local_homeomorph H H, (∀x ∈ e.source, ∃s, is_open s ∧
x ∈ s ∧ e.restr s ∈ members) → e ∈ members)
(eq_on_source' : ∀ e e' : local_homeomorph H H, e ∈ members → e' ≈ e → e' ∈ members)
variable [topological_space H]
instance : has_mem (local_homeomorph H H) (structure_groupoid H) :=
⟨λ(e : local_homeomorph H H) (G : structure_groupoid H), e ∈ G.members⟩
lemma structure_groupoid.trans (G : structure_groupoid H) {e e' : local_homeomorph H H}
(he : e ∈ G) (he' : e' ∈ G) : e ≫ₕ e' ∈ G :=
G.trans' e e' he he'
lemma structure_groupoid.symm (G : structure_groupoid H) {e : local_homeomorph H H} (he : e ∈ G) :
e.symm ∈ G :=
G.symm' e he
lemma structure_groupoid.id_mem (G : structure_groupoid H) :
local_homeomorph.refl H ∈ G :=
G.id_mem'
lemma structure_groupoid.locality (G : structure_groupoid H) {e : local_homeomorph H H}
(h : ∀x ∈ e.source, ∃s, is_open s ∧ x ∈ s ∧ e.restr s ∈ G) :
e ∈ G :=
G.locality' e h
lemma structure_groupoid.eq_on_source (G : structure_groupoid H) {e e' : local_homeomorph H H}
(he : e ∈ G) (h : e' ≈ e) : e' ∈ G :=
G.eq_on_source' e e' he h
/-- Partial order on the set of groupoids, given by inclusion of the members of the groupoid -/
instance structure_groupoid.partial_order : partial_order (structure_groupoid H) :=
partial_order.lift structure_groupoid.members
(λa b h, by { cases a, cases b, dsimp at h, induction h, refl })
lemma structure_groupoid.le_iff {G₁ G₂ : structure_groupoid H} :
G₁ ≤ G₂ ↔ ∀ e, e ∈ G₁ → e ∈ G₂ :=
iff.rfl
/-- The trivial groupoid, containing only the identity (and maps with empty source, as this is
necessary from the definition) -/
def id_groupoid (H : Type u) [topological_space H] : structure_groupoid H :=
{ members := {local_homeomorph.refl H} ∪ {e : local_homeomorph H H | e.source = ∅},
trans' := λe e' he he', begin
cases he; simp at he he',
{ simpa only [he, refl_trans]},
{ have : (e ≫ₕ e').source ⊆ e.source := sep_subset _ _,
rw he at this,
have : (e ≫ₕ e') ∈ {e : local_homeomorph H H | e.source = ∅} := eq_bot_iff.2 this,
exact (mem_union _ _ _).2 (or.inr this) },
end,
symm' := λe he, begin
cases (mem_union _ _ _).1 he with E E,
{ simp [mem_singleton_iff.mp E] },
{ right,
simpa only [e.to_local_equiv.image_source_eq_target.symm] with mfld_simps using E},
end,
id_mem' := mem_union_left _ rfl,
locality' := λe he, begin
cases e.source.eq_empty_or_nonempty with h h,
{ right, exact h },
{ left,
rcases h with ⟨x, hx⟩,
rcases he x hx with ⟨s, open_s, xs, hs⟩,
have x's : x ∈ (e.restr s).source,
{ rw [restr_source, open_s.interior_eq],
exact ⟨hx, xs⟩ },
cases hs,
{ replace hs : local_homeomorph.restr e s = local_homeomorph.refl H,
by simpa only using hs,
have : (e.restr s).source = univ, by { rw hs, simp },
change (e.to_local_equiv).source ∩ interior s = univ at this,
have : univ ⊆ interior s, by { rw ← this, exact inter_subset_right _ _ },
have : s = univ, by rwa [open_s.interior_eq, univ_subset_iff] at this,
simpa only [this, restr_univ] using hs },
{ exfalso,
rw mem_set_of_eq at hs,
rwa hs at x's } },
end,
eq_on_source' := λe e' he he'e, begin
cases he,
{ left,
have : e = e',
{ refine eq_of_eq_on_source_univ (setoid.symm he'e) _ _;
rw set.mem_singleton_iff.1 he ; refl },
rwa ← this },
{ right,
change (e.to_local_equiv).source = ∅ at he,
rwa [set.mem_set_of_eq, he'e.source_eq] }
end }
/-- Every structure groupoid contains the identity groupoid -/
instance : order_bot (structure_groupoid H) :=
{ bot := id_groupoid H,
bot_le := begin
assume u f hf,
change f ∈ {local_homeomorph.refl H} ∪ {e : local_homeomorph H H | e.source = ∅} at hf,
simp only [singleton_union, mem_set_of_eq, mem_insert_iff] at hf,
cases hf,
{ rw hf,
apply u.id_mem },
{ apply u.locality,
assume x hx,
rw [hf, mem_empty_iff_false] at hx,
exact hx.elim }
end }
instance (H : Type u) [topological_space H] : inhabited (structure_groupoid H) :=
⟨id_groupoid H⟩
/-- To construct a groupoid, one may consider classes of local homeos such that both the function
and its inverse have some property. If this property is stable under composition,
one gets a groupoid. `pregroupoid` bundles the properties needed for this construction, with the
groupoid of smooth functions with smooth inverses as an application. -/
structure pregroupoid (H : Type*) [topological_space H] :=
(property : (H → H) → (set H) → Prop)
(comp : ∀{f g u v}, property f u → property g v → is_open u → is_open v → is_open (u ∩ f ⁻¹' v)
→ property (g ∘ f) (u ∩ f ⁻¹' v))
(id_mem : property id univ)
(locality : ∀{f u}, is_open u → (∀x∈u, ∃v, is_open v ∧ x ∈ v ∧ property f (u ∩ v)) → property f u)
(congr : ∀{f g : H → H} {u}, is_open u → (∀x∈u, g x = f x) → property f u → property g u)
/-- Construct a groupoid of local homeos for which the map and its inverse have some property,
from a pregroupoid asserting that this property is stable under composition. -/
def pregroupoid.groupoid (PG : pregroupoid H) : structure_groupoid H :=
{ members := {e : local_homeomorph H H | PG.property e e.source ∧ PG.property e.symm e.target},
trans' := λe e' he he', begin
split,
{ apply PG.comp he.1 he'.1 e.open_source e'.open_source,
apply e.continuous_to_fun.preimage_open_of_open e.open_source e'.open_source },
{ apply PG.comp he'.2 he.2 e'.open_target e.open_target,
apply e'.continuous_inv_fun.preimage_open_of_open e'.open_target e.open_target }
end,
symm' := λe he, ⟨he.2, he.1⟩,
id_mem' := ⟨PG.id_mem, PG.id_mem⟩,
locality' := λe he, begin
split,
{ apply PG.locality e.open_source (λx xu, _),
rcases he x xu with ⟨s, s_open, xs, hs⟩,
refine ⟨s, s_open, xs, _⟩,
convert hs.1 using 1,
dsimp [local_homeomorph.restr], rw s_open.interior_eq },
{ apply PG.locality e.open_target (λx xu, _),
rcases he (e.symm x) (e.map_target xu) with ⟨s, s_open, xs, hs⟩,
refine ⟨e.target ∩ e.symm ⁻¹' s, _, ⟨xu, xs⟩, _⟩,
{ exact continuous_on.preimage_open_of_open e.continuous_inv_fun e.open_target s_open },
{ rw [← inter_assoc, inter_self],
convert hs.2 using 1,
dsimp [local_homeomorph.restr], rw s_open.interior_eq } },
end,
eq_on_source' := λe e' he ee', begin
split,
{ apply PG.congr e'.open_source ee'.2,
simp only [ee'.1, he.1] },
{ have A := ee'.symm',
apply PG.congr e'.symm.open_source A.2,
convert he.2,
rw A.1,
refl }
end }
lemma mem_groupoid_of_pregroupoid {PG : pregroupoid H} {e : local_homeomorph H H} :
e ∈ PG.groupoid ↔ PG.property e e.source ∧ PG.property e.symm e.target :=
iff.rfl
lemma groupoid_of_pregroupoid_le (PG₁ PG₂ : pregroupoid H)
(h : ∀f s, PG₁.property f s → PG₂.property f s) : PG₁.groupoid ≤ PG₂.groupoid :=
begin
refine structure_groupoid.le_iff.2 (λ e he, _),
rw mem_groupoid_of_pregroupoid at he ⊢,
exact ⟨h _ _ he.1, h _ _ he.2⟩
end
lemma mem_pregroupoid_of_eq_on_source (PG : pregroupoid H) {e e' : local_homeomorph H H}
(he' : e ≈ e') (he : PG.property e e.source) : PG.property e' e'.source :=
begin
rw ← he'.1,
exact PG.congr e.open_source he'.eq_on.symm he,
end
/-- The pregroupoid of all local maps on a topological space `H` -/
@[reducible] def continuous_pregroupoid (H : Type*) [topological_space H] : pregroupoid H :=
{ property := λf s, true,
comp := λf g u v hf hg hu hv huv, trivial,
id_mem := trivial,
locality := λf u u_open h, trivial,
congr := λf g u u_open hcongr hf, trivial }
instance (H : Type*) [topological_space H] : inhabited (pregroupoid H) :=
⟨continuous_pregroupoid H⟩
/-- The groupoid of all local homeomorphisms on a topological space `H` -/
def continuous_groupoid (H : Type*) [topological_space H] : structure_groupoid H :=
pregroupoid.groupoid (continuous_pregroupoid H)
/-- Every structure groupoid is contained in the groupoid of all local homeomorphisms -/
instance : order_top (structure_groupoid H) :=
{ top := continuous_groupoid H,
le_top := λ u f hf, by { split; exact dec_trivial } }
/-- A groupoid is closed under restriction if it contains all restrictions of its element local
homeomorphisms to open subsets of the source. -/
class closed_under_restriction (G : structure_groupoid H) : Prop :=
(closed_under_restriction : ∀ {e : local_homeomorph H H}, e ∈ G → ∀ (s : set H), is_open s →
e.restr s ∈ G)
lemma closed_under_restriction' {G : structure_groupoid H} [closed_under_restriction G]
{e : local_homeomorph H H} (he : e ∈ G) {s : set H} (hs : is_open s) :
e.restr s ∈ G :=
closed_under_restriction.closed_under_restriction he s hs
/-- The trivial restriction-closed groupoid, containing only local homeomorphisms equivalent to the
restriction of the identity to the various open subsets. -/
def id_restr_groupoid : structure_groupoid H :=
{ members := {e | ∃ {s : set H} (h : is_open s), e ≈ local_homeomorph.of_set s h},
trans' := begin
rintros e e' ⟨s, hs, hse⟩ ⟨s', hs', hse'⟩,
refine ⟨s ∩ s', is_open.inter hs hs', _⟩,
have := local_homeomorph.eq_on_source.trans' hse hse',
rwa local_homeomorph.of_set_trans_of_set at this,
end,
symm' := begin
rintros e ⟨s, hs, hse⟩,
refine ⟨s, hs, _⟩,
rw [← of_set_symm],
exact local_homeomorph.eq_on_source.symm' hse,
end,
id_mem' := ⟨univ, is_open_univ, by simp only with mfld_simps⟩,
locality' := begin
intros e h,
refine ⟨e.source, e.open_source, by simp only with mfld_simps, _⟩,
intros x hx,
rcases h x hx with ⟨s, hs, hxs, s', hs', hes'⟩,
have hes : x ∈ (e.restr s).source,
{ rw e.restr_source, refine ⟨hx, _⟩,
rw hs.interior_eq, exact hxs },
simpa only with mfld_simps using local_homeomorph.eq_on_source.eq_on hes' hes,
end,
eq_on_source' := begin
rintros e e' ⟨s, hs, hse⟩ hee',
exact ⟨s, hs, setoid.trans hee' hse⟩,
end }
lemma id_restr_groupoid_mem {s : set H} (hs : is_open s) :
of_set s hs ∈ @id_restr_groupoid H _ := ⟨s, hs, by refl⟩
/-- The trivial restriction-closed groupoid is indeed `closed_under_restriction`. -/
instance closed_under_restriction_id_restr_groupoid :
closed_under_restriction (@id_restr_groupoid H _) :=
⟨ begin
rintros e ⟨s', hs', he⟩ s hs,
use [s' ∩ s, is_open.inter hs' hs],
refine setoid.trans (local_homeomorph.eq_on_source.restr he s) _,
exact ⟨by simp only [hs.interior_eq] with mfld_simps, by simp only with mfld_simps⟩,
end ⟩
/-- A groupoid is closed under restriction if and only if it contains the trivial restriction-closed
groupoid. -/
lemma closed_under_restriction_iff_id_le (G : structure_groupoid H) :
closed_under_restriction G ↔ id_restr_groupoid ≤ G :=
begin
split,
{ introsI _i,
apply structure_groupoid.le_iff.mpr,
rintros e ⟨s, hs, hes⟩,
refine G.eq_on_source _ hes,
convert closed_under_restriction' G.id_mem hs,
change s = _ ∩ _,
rw hs.interior_eq,
simp only with mfld_simps },
{ intros h,
split,
intros e he s hs,
rw ← of_set_trans (e : local_homeomorph H H) hs,
refine G.trans _ he,
apply structure_groupoid.le_iff.mp h,
exact id_restr_groupoid_mem hs },
end
/-- The groupoid of all local homeomorphisms on a topological space `H` is closed under restriction.
-/
instance : closed_under_restriction (continuous_groupoid H) :=
(closed_under_restriction_iff_id_le _).mpr (by convert le_top)
end groupoid
/-! ### Charted spaces -/
/-- A charted space is a topological space endowed with an atlas, i.e., a set of local
homeomorphisms taking value in a model space `H`, called charts, such that the domains of the charts
cover the whole space. We express the covering property by chosing for each `x` a member
`chart_at H x` of the atlas containing `x` in its source: in the smooth case, this is convenient to
construct the tangent bundle in an efficient way.
The model space is written as an explicit parameter as there can be several model spaces for a
given topological space. For instance, a complex manifold (modelled over `ℂ^n`) will also be seen
sometimes as a real manifold over `ℝ^(2n)`.
-/
@[ext]
class charted_space (H : Type*) [topological_space H] (M : Type*) [topological_space M] :=
(atlas [] : set (local_homeomorph M H))
(chart_at [] : M → local_homeomorph M H)
(mem_chart_source [] : ∀x, x ∈ (chart_at x).source)
(chart_mem_atlas [] : ∀x, chart_at x ∈ atlas)
export charted_space
attribute [simp, mfld_simps] mem_chart_source chart_mem_atlas
section charted_space
/-- Any space is a charted_space modelled over itself, by just using the identity chart -/
instance charted_space_self (H : Type*) [topological_space H] : charted_space H H :=
{ atlas := {local_homeomorph.refl H},
chart_at := λx, local_homeomorph.refl H,
mem_chart_source := λx, mem_univ x,
chart_mem_atlas := λx, mem_singleton _ }
/-- In the trivial charted_space structure of a space modelled over itself through the identity, the
atlas members are just the identity -/
@[simp, mfld_simps] lemma charted_space_self_atlas
{H : Type*} [topological_space H] {e : local_homeomorph H H} :
e ∈ atlas H H ↔ e = local_homeomorph.refl H :=
by simp [atlas, charted_space.atlas]
/-- In the model space, chart_at is always the identity -/
lemma chart_at_self_eq {H : Type*} [topological_space H] {x : H} :
chart_at H x = local_homeomorph.refl H :=
by simpa using chart_mem_atlas H x
section
variables (H) [topological_space H] [topological_space M] [charted_space H M]
lemma mem_chart_target (x : M) : chart_at H x x ∈ (chart_at H x).target :=
(chart_at H x).map_source (mem_chart_source _ _)
lemma chart_source_mem_nhds (x : M) : (chart_at H x).source ∈ 𝓝 x :=
(chart_at H x).open_source.mem_nhds $ mem_chart_source H x
lemma chart_target_mem_nhds (x : M) : (chart_at H x).target ∈ 𝓝 (chart_at H x x) :=
(chart_at H x).open_target.mem_nhds $ mem_chart_target H x
/-- `achart H x` is the chart at `x`, considered as an element of the atlas.
Especially useful for working with `basic_smooth_vector_bundle_core` -/
def achart (x : M) : atlas H M := ⟨chart_at H x, chart_mem_atlas H x⟩
lemma achart_def (x : M) : achart H x = ⟨chart_at H x, chart_mem_atlas H x⟩ := rfl
@[simp, mfld_simps]
lemma coe_achart (x : M) : (achart H x : local_homeomorph M H) = chart_at H x := rfl
@[simp, mfld_simps]
lemma achart_val (x : M) : (achart H x).1 = chart_at H x := rfl
lemma mem_achart_source (x : M) : x ∈ (achart H x).1.source :=
mem_chart_source H x
open topological_space
lemma charted_space.second_countable_of_countable_cover [second_countable_topology H]
{s : set M} (hs : (⋃ x (hx : x ∈ s), (chart_at H x).source) = univ)
(hsc : s.countable) :
second_countable_topology M :=
begin
haveI : ∀ x : M, second_countable_topology (chart_at H x).source :=
λ x, (chart_at H x).second_countable_topology_source,
haveI := hsc.to_encodable,
rw bUnion_eq_Union at hs,
exact second_countable_topology_of_countable_cover (λ x : s, (chart_at H (x : M)).open_source) hs
end
variable (M)
lemma charted_space.second_countable_of_sigma_compact [second_countable_topology H]
[sigma_compact_space M] :
second_countable_topology M :=
begin
obtain ⟨s, hsc, hsU⟩ : ∃ s, set.countable s ∧ (⋃ x (hx : x ∈ s), (chart_at H x).source) = univ :=
countable_cover_nhds_of_sigma_compact (λ x : M, chart_source_mem_nhds H x),
exact charted_space.second_countable_of_countable_cover H hsU hsc
end
/-- If a topological space admits an atlas with locally compact charts, then the space itself
is locally compact. -/
lemma charted_space.locally_compact [locally_compact_space H] : locally_compact_space M :=
begin
have : ∀ (x : M), (𝓝 x).has_basis
(λ s, s ∈ 𝓝 (chart_at H x x) ∧ is_compact s ∧ s ⊆ (chart_at H x).target)
(λ s, (chart_at H x).symm '' s),
{ intro x,
rw [← (chart_at H x).symm_map_nhds_eq (mem_chart_source H x)],
exact ((compact_basis_nhds (chart_at H x x)).has_basis_self_subset
(chart_target_mem_nhds H x)).map _ },
refine locally_compact_space_of_has_basis this _,
rintro x s ⟨h₁, h₂, h₃⟩,
exact h₂.image_of_continuous_on ((chart_at H x).continuous_on_symm.mono h₃)
end
/-- If a topological space admits an atlas with locally connected charts, then the space itself is
locally connected. -/
lemma charted_space.locally_connected_space [locally_connected_space H] :
locally_connected_space M :=
begin
let E : M → local_homeomorph M H := chart_at H,
refine locally_connected_space_of_connected_bases
(λ x s, (E x).symm '' s)
(λ x s, (is_open s ∧ E x x ∈ s ∧ is_connected s) ∧ s ⊆ (E x).target) _ _,
{ intros x,
simpa only [local_homeomorph.symm_map_nhds_eq, mem_chart_source] using
((locally_connected_space.open_connected_basis (E x x)).restrict_subset
((E x).open_target.mem_nhds (mem_chart_target H x))).map (E x).symm },
{ rintros x s ⟨⟨-, -, hsconn⟩, hssubset⟩,
exact hsconn.is_preconnected.image _ ((E x).continuous_on_symm.mono hssubset) },
end
/-- If `M` is modelled on `H'` and `H'` is itself modelled on `H`, then we can consider `M` as being
modelled on `H`. -/
def charted_space.comp (H : Type*) [topological_space H] (H' : Type*) [topological_space H']
(M : Type*) [topological_space M] [charted_space H H'] [charted_space H' M] :
charted_space H M :=
{ atlas := image2 local_homeomorph.trans (atlas H' M) (atlas H H'),
chart_at := λ p : M, (chart_at H' p).trans (chart_at H (chart_at H' p p)),
mem_chart_source := λ p, by simp only with mfld_simps,
chart_mem_atlas :=
λ p, ⟨chart_at H' p, chart_at H _, chart_mem_atlas H' p, chart_mem_atlas H _, rfl⟩ }
end
/-- For technical reasons we introduce two type tags:
* `model_prod H H'` is the same as `H × H'`;
* `model_pi H` is the same as `Π i, H i`, where `H : ι → Type*` and `ι` is a finite type.
In both cases the reason is the same, so we explain it only in the case of the product. A charted
space `M` with model `H` is a set of local charts from `M` to `H` covering the space. Every space is
registered as a charted space over itself, using the only chart `id`, in `manifold_model_space`. You
can also define a product of charted space `M` and `M'` (with model space `H × H'`) by taking the
products of the charts. Now, on `H × H'`, there are two charted space structures with model space
`H × H'` itself, the one coming from `manifold_model_space`, and the one coming from the product of
the two `manifold_model_space` on each component. They are equal, but not defeq (because the product
of `id` and `id` is not defeq to `id`), which is bad as we know. This expedient of renaming `H × H'`
solves this problem. -/
library_note "Manifold type tags"
/-- Same thing as `H × H'` We introduce it for technical reasons,
see note [Manifold type tags]. -/
def model_prod (H : Type*) (H' : Type*) := H × H'
/-- Same thing as `Π i, H i` We introduce it for technical reasons,
see note [Manifold type tags]. -/
def model_pi {ι : Type*} (H : ι → Type*) := Π i, H i
section
local attribute [reducible] model_prod
instance model_prod_inhabited [inhabited H] [inhabited H'] :
inhabited (model_prod H H') :=
prod.inhabited
instance (H : Type*) [topological_space H] (H' : Type*) [topological_space H'] :
topological_space (model_prod H H') :=
prod.topological_space
/- Next lemma shows up often when dealing with derivatives, register it as simp. -/
@[simp, mfld_simps] lemma model_prod_range_prod_id
{H : Type*} {H' : Type*} {α : Type*} (f : H → α) :
range (λ (p : model_prod H H'), (f p.1, p.2)) = range f ×ˢ (univ : set H') :=
by rw prod_range_univ_eq
end
section
variables {ι : Type*} {Hi : ι → Type*}
instance model_pi_inhabited [Π i, inhabited (Hi i)] :
inhabited (model_pi Hi) :=
pi.inhabited _
instance [Π i, topological_space (Hi i)] :
topological_space (model_pi Hi) :=
Pi.topological_space
end
/-- The product of two charted spaces is naturally a charted space, with the canonical
construction of the atlas of product maps. -/
instance prod_charted_space (H : Type*) [topological_space H]
(M : Type*) [topological_space M] [charted_space H M]
(H' : Type*) [topological_space H']
(M' : Type*) [topological_space M'] [charted_space H' M'] :
charted_space (model_prod H H') (M × M') :=
{ atlas := image2 local_homeomorph.prod (atlas H M) (atlas H' M'),
chart_at := λ x : M × M', (chart_at H x.1).prod (chart_at H' x.2),
mem_chart_source := λ x, ⟨mem_chart_source _ _, mem_chart_source _ _⟩,
chart_mem_atlas := λ x, mem_image2_of_mem (chart_mem_atlas _ _) (chart_mem_atlas _ _) }
section prod_charted_space
variables [topological_space H] [topological_space M] [charted_space H M]
[topological_space H'] [topological_space M'] [charted_space H' M'] {x : M×M'}
@[simp, mfld_simps] lemma prod_charted_space_chart_at :
(chart_at (model_prod H H') x) = (chart_at H x.fst).prod (chart_at H' x.snd) := rfl
lemma charted_space_self_prod : prod_charted_space H H H' H' = charted_space_self (H × H') :=
by { ext1, { simp [prod_charted_space, atlas] }, { ext1, simp [chart_at_self_eq], refl } }
end prod_charted_space
/-- The product of a finite family of charted spaces is naturally a charted space, with the
canonical construction of the atlas of finite product maps. -/
instance pi_charted_space {ι : Type*} [fintype ι] (H : ι → Type*) [Π i, topological_space (H i)]
(M : ι → Type*) [Π i, topological_space (M i)] [Π i, charted_space (H i) (M i)] :
charted_space (model_pi H) (Π i, M i) :=
{ atlas := local_homeomorph.pi '' (set.pi univ $ λ i, atlas (H i) (M i)),
chart_at := λ f, local_homeomorph.pi $ λ i, chart_at (H i) (f i),
mem_chart_source := λ f i hi, mem_chart_source (H i) (f i),
chart_mem_atlas := λ f, mem_image_of_mem _ $ λ i hi, chart_mem_atlas (H i) (f i) }
@[simp, mfld_simps] lemma pi_charted_space_chart_at {ι : Type*} [fintype ι] (H : ι → Type*)
[Π i, topological_space (H i)] (M : ι → Type*) [Π i, topological_space (M i)]
[Π i, charted_space (H i) (M i)] (f : Π i, M i) :
chart_at (model_pi H) f = local_homeomorph.pi (λ i, chart_at (H i) (f i)) := rfl
end charted_space
/-! ### Constructing a topology from an atlas -/
/-- Sometimes, one may want to construct a charted space structure on a space which does not yet
have a topological structure, where the topology would come from the charts. For this, one needs
charts that are only local equivs, and continuity properties for their composition.
This is formalised in `charted_space_core`. -/
@[nolint has_nonempty_instance]
structure charted_space_core (H : Type*) [topological_space H] (M : Type*) :=
(atlas : set (local_equiv M H))
(chart_at : M → local_equiv M H)
(mem_chart_source : ∀x, x ∈ (chart_at x).source)
(chart_mem_atlas : ∀x, chart_at x ∈ atlas)
(open_source : ∀e e' : local_equiv M H, e ∈ atlas → e' ∈ atlas → is_open (e.symm.trans e').source)
(continuous_to_fun : ∀e e' : local_equiv M H, e ∈ atlas → e' ∈ atlas →
continuous_on (e.symm.trans e') (e.symm.trans e').source)
namespace charted_space_core
variables [topological_space H] (c : charted_space_core H M) {e : local_equiv M H}
/-- Topology generated by a set of charts on a Type. -/
protected def to_topological_space : topological_space M :=
topological_space.generate_from $ ⋃ (e : local_equiv M H) (he : e ∈ c.atlas)
(s : set H) (s_open : is_open s), {e ⁻¹' s ∩ e.source}
lemma open_source' (he : e ∈ c.atlas) : is_open[c.to_topological_space] e.source :=
begin
apply topological_space.generate_open.basic,
simp only [exists_prop, mem_Union, mem_singleton_iff],
refine ⟨e, he, univ, is_open_univ, _⟩,
simp only [set.univ_inter, set.preimage_univ]
end
lemma open_target (he : e ∈ c.atlas) : is_open e.target :=
begin
have E : e.target ∩ e.symm ⁻¹' e.source = e.target :=
subset.antisymm (inter_subset_left _ _) (λx hx, ⟨hx,
local_equiv.target_subset_preimage_source _ hx⟩),
simpa [local_equiv.trans_source, E] using c.open_source e e he he
end
/-- An element of the atlas in a charted space without topology becomes a local homeomorphism
for the topology constructed from this atlas. The `local_homeomorph` version is given in this
definition. -/
protected def local_homeomorph (e : local_equiv M H) (he : e ∈ c.atlas) :
@local_homeomorph M H c.to_topological_space _ :=
{ open_source := by convert c.open_source' he,
open_target := by convert c.open_target he,
continuous_to_fun := begin
letI : topological_space M := c.to_topological_space,
rw continuous_on_open_iff (c.open_source' he),
assume s s_open,
rw inter_comm,
apply topological_space.generate_open.basic,
simp only [exists_prop, mem_Union, mem_singleton_iff],
exact ⟨e, he, ⟨s, s_open, rfl⟩⟩
end,
continuous_inv_fun := begin
letI : topological_space M := c.to_topological_space,
apply continuous_on_open_of_generate_from (c.open_target he),
assume t ht,
simp only [exists_prop, mem_Union, mem_singleton_iff] at ht,
rcases ht with ⟨e', e'_atlas, s, s_open, ts⟩,
rw ts,
let f := e.symm.trans e',
have : is_open (f ⁻¹' s ∩ f.source),
by simpa [inter_comm] using (continuous_on_open_iff (c.open_source e e' he e'_atlas)).1
(c.continuous_to_fun e e' he e'_atlas) s s_open,
have A : e' ∘ e.symm ⁻¹' s ∩ (e.target ∩ e.symm ⁻¹' e'.source) =
e.target ∩ (e' ∘ e.symm ⁻¹' s ∩ e.symm ⁻¹' e'.source),
by { rw [← inter_assoc, ← inter_assoc], congr' 1, exact inter_comm _ _ },
simpa [local_equiv.trans_source, preimage_inter, preimage_comp.symm, A] using this
end,
..e }
/-- Given a charted space without topology, endow it with a genuine charted space structure with
respect to the topology constructed from the atlas. -/
def to_charted_space : @charted_space H _ M c.to_topological_space :=
{ atlas := ⋃ (e : local_equiv M H) (he : e ∈ c.atlas), {c.local_homeomorph e he},
chart_at := λx, c.local_homeomorph (c.chart_at x) (c.chart_mem_atlas x),
mem_chart_source := λx, c.mem_chart_source x,
chart_mem_atlas := λx, begin
simp only [mem_Union, mem_singleton_iff],
exact ⟨c.chart_at x, c.chart_mem_atlas x, rfl⟩,
end }
end charted_space_core
/-! ### Charted space with a given structure groupoid -/
section has_groupoid
variables [topological_space H] [topological_space M] [charted_space H M]
/-- A charted space has an atlas in a groupoid `G` if the change of coordinates belong to the
groupoid -/
class has_groupoid {H : Type*} [topological_space H] (M : Type*) [topological_space M]
[charted_space H M] (G : structure_groupoid H) : Prop :=
(compatible [] : ∀{e e' : local_homeomorph M H}, e ∈ atlas H M → e' ∈ atlas H M → e.symm ≫ₕ e' ∈ G)
/-- Reformulate in the `structure_groupoid` namespace the compatibility condition of charts in a
charted space admitting a structure groupoid, to make it more easily accessible with dot
notation. -/
lemma structure_groupoid.compatible {H : Type*} [topological_space H] (G : structure_groupoid H)
{M : Type*} [topological_space M] [charted_space H M] [has_groupoid M G]
{e e' : local_homeomorph M H} (he : e ∈ atlas H M) (he' : e' ∈ atlas H M) :
e.symm ≫ₕ e' ∈ G :=
has_groupoid.compatible G he he'
lemma has_groupoid_of_le {G₁ G₂ : structure_groupoid H} (h : has_groupoid M G₁) (hle : G₁ ≤ G₂) :
has_groupoid M G₂ :=
⟨λ e e' he he', hle (h.compatible he he')⟩
lemma has_groupoid_of_pregroupoid (PG : pregroupoid H)
(h : ∀{e e' : local_homeomorph M H}, e ∈ atlas H M → e' ∈ atlas H M
→ PG.property (e.symm ≫ₕ e') (e.symm ≫ₕ e').source) :
has_groupoid M (PG.groupoid) :=
⟨assume e e' he he', mem_groupoid_of_pregroupoid.mpr ⟨h he he', h he' he⟩⟩
/-- The trivial charted space structure on the model space is compatible with any groupoid -/
instance has_groupoid_model_space (H : Type*) [topological_space H] (G : structure_groupoid H) :
has_groupoid H G :=
{ compatible := λe e' he he', begin
replace he : e ∈ atlas H H := he,
replace he' : e' ∈ atlas H H := he',
rw charted_space_self_atlas at he he',
simp [he, he', structure_groupoid.id_mem]
end }
/-- Any charted space structure is compatible with the groupoid of all local homeomorphisms -/
instance has_groupoid_continuous_groupoid : has_groupoid M (continuous_groupoid H) :=
⟨begin
assume e e' he he',
rw [continuous_groupoid, mem_groupoid_of_pregroupoid],
simp only [and_self]
end⟩
section maximal_atlas
variables (M) (G : structure_groupoid H)
/-- Given a charted space admitting a structure groupoid, the maximal atlas associated to this
structure groupoid is the set of all local charts that are compatible with the atlas, i.e., such
that changing coordinates with an atlas member gives an element of the groupoid. -/
def structure_groupoid.maximal_atlas : set (local_homeomorph M H) :=
{e | ∀ e' ∈ atlas H M, e.symm ≫ₕ e' ∈ G ∧ e'.symm ≫ₕ e ∈ G}
variable {M}
/-- The elements of the atlas belong to the maximal atlas for any structure groupoid -/
lemma structure_groupoid.subset_maximal_atlas [has_groupoid M G] :
atlas H M ⊆ G.maximal_atlas M :=
λ e he e' he', ⟨G.compatible he he', G.compatible he' he⟩
lemma structure_groupoid.chart_mem_maximal_atlas [has_groupoid M G]
(x : M) : chart_at H x ∈ G.maximal_atlas M :=
G.subset_maximal_atlas (chart_mem_atlas H x)
variable {G}
lemma mem_maximal_atlas_iff {e : local_homeomorph M H} :
e ∈ G.maximal_atlas M ↔ ∀ e' ∈ atlas H M, e.symm ≫ₕ e' ∈ G ∧ e'.symm ≫ₕ e ∈ G :=
iff.rfl
/-- Changing coordinates between two elements of the maximal atlas gives rise to an element
of the structure groupoid. -/
lemma structure_groupoid.compatible_of_mem_maximal_atlas {e e' : local_homeomorph M H}
(he : e ∈ G.maximal_atlas M) (he' : e' ∈ G.maximal_atlas M) : e.symm ≫ₕ e' ∈ G :=
begin
apply G.locality (λ x hx, _),
set f := chart_at H (e.symm x) with hf,
let s := e.target ∩ (e.symm ⁻¹' f.source),
have hs : is_open s,
{ apply e.symm.continuous_to_fun.preimage_open_of_open; apply open_source },
have xs : x ∈ s, by { dsimp at hx, simp [s, hx] },
refine ⟨s, hs, xs, _⟩,
have A : e.symm ≫ₕ f ∈ G := (mem_maximal_atlas_iff.1 he f (chart_mem_atlas _ _)).1,
have B : f.symm ≫ₕ e' ∈ G := (mem_maximal_atlas_iff.1 he' f (chart_mem_atlas _ _)).2,
have C : (e.symm ≫ₕ f) ≫ₕ (f.symm ≫ₕ e') ∈ G := G.trans A B,
have D : (e.symm ≫ₕ f) ≫ₕ (f.symm ≫ₕ e') ≈ (e.symm ≫ₕ e').restr s := calc
(e.symm ≫ₕ f) ≫ₕ (f.symm ≫ₕ e') = e.symm ≫ₕ (f ≫ₕ f.symm) ≫ₕ e' : by simp [trans_assoc]
... ≈ e.symm ≫ₕ (of_set f.source f.open_source) ≫ₕ e' :
by simp [eq_on_source.trans', trans_self_symm]
... ≈ (e.symm ≫ₕ (of_set f.source f.open_source)) ≫ₕ e' : by simp [trans_assoc]
... ≈ (e.symm.restr s) ≫ₕ e' : by simp [s, trans_of_set']
... ≈ (e.symm ≫ₕ e').restr s : by simp [restr_trans],
exact G.eq_on_source C (setoid.symm D),
end
variable (G)
/-- In the model space, the identity is in any maximal atlas. -/
lemma structure_groupoid.id_mem_maximal_atlas : local_homeomorph.refl H ∈ G.maximal_atlas H :=
G.subset_maximal_atlas $ by simp
/-- In the model space, any element of the groupoid is in the maximal atlas. -/
lemma structure_groupoid.mem_maximal_atlas_of_mem_groupoid {f : local_homeomorph H H} (hf : f ∈ G) :
f ∈ G.maximal_atlas H :=
begin
rintros e (rfl : e = local_homeomorph.refl H),
exact ⟨G.trans (G.symm hf) G.id_mem, G.trans (G.symm G.id_mem) hf⟩,
end
end maximal_atlas
section singleton
variables {α : Type*} [topological_space α]
namespace local_homeomorph
variable (e : local_homeomorph α H)
/-- If a single local homeomorphism `e` from a space `α` into `H` has source covering the whole
space `α`, then that local homeomorphism induces an `H`-charted space structure on `α`.
(This condition is equivalent to `e` being an open embedding of `α` into `H`; see
`open_embedding.singleton_charted_space`.) -/
def singleton_charted_space (h : e.source = set.univ) : charted_space H α :=
{ atlas := {e},
chart_at := λ _, e,
mem_chart_source := λ _, by simp only [h] with mfld_simps,
chart_mem_atlas := λ _, by tauto }
@[simp, mfld_simps] lemma singleton_charted_space_chart_at_eq (h : e.source = set.univ) {x : α} :
@chart_at H _ α _ (e.singleton_charted_space h) x = e := rfl
lemma singleton_charted_space_chart_at_source
(h : e.source = set.univ) {x : α} :
(@chart_at H _ α _ (e.singleton_charted_space h) x).source = set.univ := h
lemma singleton_charted_space_mem_atlas_eq (h : e.source = set.univ)
(e' : local_homeomorph α H) (h' : e' ∈ (e.singleton_charted_space h).atlas) : e' = e := h'
/-- Given a local homeomorphism `e` from a space `α` into `H`, if its source covers the whole
space `α`, then the induced charted space structure on `α` is `has_groupoid G` for any structure
groupoid `G` which is closed under restrictions. -/
lemma singleton_has_groupoid (h : e.source = set.univ) (G : structure_groupoid H)
[closed_under_restriction G] : @has_groupoid _ _ _ _ (e.singleton_charted_space h) G :=
{ compatible := begin
intros e' e'' he' he'',
rw e.singleton_charted_space_mem_atlas_eq h e' he',
rw e.singleton_charted_space_mem_atlas_eq h e'' he'',
refine G.eq_on_source _ e.trans_symm_self,
have hle : id_restr_groupoid ≤ G := (closed_under_restriction_iff_id_le G).mp (by assumption),
exact structure_groupoid.le_iff.mp hle _ (id_restr_groupoid_mem _),
end }
end local_homeomorph
namespace open_embedding
variable [nonempty α]
/-- An open embedding of `α` into `H` induces an `H`-charted space structure on `α`.
See `local_homeomorph.singleton_charted_space` -/
def singleton_charted_space {f : α → H} (h : open_embedding f) :
charted_space H α := (h.to_local_homeomorph f).singleton_charted_space (by simp)
lemma singleton_charted_space_chart_at_eq {f : α → H} (h : open_embedding f) {x : α} :
⇑(@chart_at H _ α _ (h.singleton_charted_space) x) = f := rfl
lemma singleton_has_groupoid {f : α → H} (h : open_embedding f)
(G : structure_groupoid H) [closed_under_restriction G] :
@has_groupoid _ _ _ _ h.singleton_charted_space G :=
(h.to_local_homeomorph f).singleton_has_groupoid (by simp) G
end open_embedding
end singleton
namespace topological_space.opens
open topological_space
variables (G : structure_groupoid H) [has_groupoid M G]
variables (s : opens M)
/-- An open subset of a charted space is naturally a charted space. -/
instance : charted_space H s :=
{ atlas := ⋃ (x : s), {@local_homeomorph.subtype_restr _ _ _ _ (chart_at H x.1) s ⟨x⟩},
chart_at := λ x, @local_homeomorph.subtype_restr _ _ _ _ (chart_at H x.1) s ⟨x⟩,
mem_chart_source := λ x, by { simp only with mfld_simps, exact (mem_chart_source H x.1) },
chart_mem_atlas := λ x, by { simp only [mem_Union, mem_singleton_iff], use x } }
/-- If a groupoid `G` is `closed_under_restriction`, then an open subset of a space which is
`has_groupoid G` is naturally `has_groupoid G`. -/
instance [closed_under_restriction G] : has_groupoid s G :=
{ compatible := begin
rintros e e' ⟨_, ⟨x, hc⟩, he⟩ ⟨_, ⟨x', hc'⟩, he'⟩,
haveI : nonempty s := ⟨x⟩,
simp only [hc.symm, mem_singleton_iff, subtype.val_eq_coe] at he,
simp only [hc'.symm, mem_singleton_iff, subtype.val_eq_coe] at he',
rw [he, he'],
convert G.eq_on_source _
(subtype_restr_symm_trans_subtype_restr s (chart_at H x) (chart_at H x')),
apply closed_under_restriction',
{ exact G.compatible (chart_mem_atlas H x) (chart_mem_atlas H x') },
{ exact preimage_open_of_open_symm (chart_at H x) s.2 },
end }
end topological_space.opens
/-! ### Structomorphisms -/
/-- A `G`-diffeomorphism between two charted spaces is a homeomorphism which, when read in the
charts, belongs to `G`. We avoid the word diffeomorph as it is too related to the smooth category,
and use structomorph instead. -/
@[nolint has_nonempty_instance]
structure structomorph (G : structure_groupoid H) (M : Type*) (M' : Type*)
[topological_space M] [topological_space M'] [charted_space H M] [charted_space H M']
extends homeomorph M M' :=
(mem_groupoid : ∀c : local_homeomorph M H, ∀c' : local_homeomorph M' H,
c ∈ atlas H M → c' ∈ atlas H M' → c.symm ≫ₕ to_homeomorph.to_local_homeomorph ≫ₕ c' ∈ G)
variables [topological_space M'] [topological_space M'']
{G : structure_groupoid H} [charted_space H M'] [charted_space H M'']
/-- The identity is a diffeomorphism of any charted space, for any groupoid. -/
def structomorph.refl (M : Type*) [topological_space M] [charted_space H M]
[has_groupoid M G] : structomorph G M M :=
{ mem_groupoid := λc c' hc hc', begin
change (local_homeomorph.symm c) ≫ₕ (local_homeomorph.refl M) ≫ₕ c' ∈ G,
rw local_homeomorph.refl_trans,
exact has_groupoid.compatible G hc hc'
end,
..homeomorph.refl M }
/-- The inverse of a structomorphism is a structomorphism -/
def structomorph.symm (e : structomorph G M M') : structomorph G M' M :=
{ mem_groupoid := begin
assume c c' hc hc',
have : (c'.symm ≫ₕ e.to_homeomorph.to_local_homeomorph ≫ₕ c).symm ∈ G :=
G.symm (e.mem_groupoid c' c hc' hc),
rwa [trans_symm_eq_symm_trans_symm, trans_symm_eq_symm_trans_symm, symm_symm, trans_assoc]
at this,
end,
..e.to_homeomorph.symm}
/-- The composition of structomorphisms is a structomorphism -/
def structomorph.trans (e : structomorph G M M') (e' : structomorph G M' M'') :
structomorph G M M'' :=
{ mem_groupoid := begin
/- Let c and c' be two charts in M and M''. We want to show that e' ∘ e is smooth in these
charts, around any point x. For this, let y = e (c⁻¹ x), and consider a chart g around y.
Then g ∘ e ∘ c⁻¹ and c' ∘ e' ∘ g⁻¹ are both smooth as e and e' are structomorphisms, so
their composition is smooth, and it coincides with c' ∘ e' ∘ e ∘ c⁻¹ around x. -/
assume c c' hc hc',
refine G.locality (λx hx, _),
let f₁ := e.to_homeomorph.to_local_homeomorph,
let f₂ := e'.to_homeomorph.to_local_homeomorph,
let f := (e.to_homeomorph.trans e'.to_homeomorph).to_local_homeomorph,
have feq : f = f₁ ≫ₕ f₂ := homeomorph.trans_to_local_homeomorph _ _,
-- define the atlas g around y
let y := (c.symm ≫ₕ f₁) x,
let g := chart_at H y,
have hg₁ := chart_mem_atlas H y,
have hg₂ := mem_chart_source H y,
let s := (c.symm ≫ₕ f₁).source ∩ (c.symm ≫ₕ f₁) ⁻¹' g.source,
have open_s : is_open s,
by apply (c.symm ≫ₕ f₁).continuous_to_fun.preimage_open_of_open; apply open_source,
have : x ∈ s,
{ split,
{ simp only [trans_source, preimage_univ, inter_univ, homeomorph.to_local_homeomorph_source],
rw trans_source at hx,
exact hx.1 },
{ exact hg₂ } },
refine ⟨s, open_s, this, _⟩,
let F₁ := (c.symm ≫ₕ f₁ ≫ₕ g) ≫ₕ (g.symm ≫ₕ f₂ ≫ₕ c'),
have A : F₁ ∈ G := G.trans (e.mem_groupoid c g hc hg₁) (e'.mem_groupoid g c' hg₁ hc'),
let F₂ := (c.symm ≫ₕ f ≫ₕ c').restr s,
have : F₁ ≈ F₂ := calc
F₁ ≈ c.symm ≫ₕ f₁ ≫ₕ (g ≫ₕ g.symm) ≫ₕ f₂ ≫ₕ c' : by simp [F₁, trans_assoc]
... ≈ c.symm ≫ₕ f₁ ≫ₕ (of_set g.source g.open_source) ≫ₕ f₂ ≫ₕ c' :
by simp [eq_on_source.trans', trans_self_symm g]
... ≈ ((c.symm ≫ₕ f₁) ≫ₕ (of_set g.source g.open_source)) ≫ₕ (f₂ ≫ₕ c') :
by simp [trans_assoc]
... ≈ ((c.symm ≫ₕ f₁).restr s) ≫ₕ (f₂ ≫ₕ c') : by simp [s, trans_of_set']
... ≈ ((c.symm ≫ₕ f₁) ≫ₕ (f₂ ≫ₕ c')).restr s : by simp [restr_trans]
... ≈ (c.symm ≫ₕ (f₁ ≫ₕ f₂) ≫ₕ c').restr s : by simp [eq_on_source.restr, trans_assoc]
... ≈ F₂ : by simp [F₂, feq],
have : F₂ ∈ G := G.eq_on_source A (setoid.symm this),
exact this
end,
..homeomorph.trans e.to_homeomorph e'.to_homeomorph }
end has_groupoid
|
4e74d8c1de7d26d39d05c2f74f2d09cd1790bb83 | c3f2fcd060adfa2ca29f924839d2d925e8f2c685 | /tests/lean/cls_err.lean | 7f5b3132d0f18c482b292c3be56b1d99792fe48f | [
"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 | 206 | lean | import logic
inductive H [class] (A : Type) :=
mk : A → H A
definition foo {A : Type} [h : H A] : A :=
H.rec (λa, a) h
context
variable A : Type
variable h : H A
definition tst : A :=
foo
end
|
0c4ac81660329993554000561a68e02b68daca36 | aa2345b30d710f7e75f13157a35845ee6d48c017 | /tactic/basic.lean | fc347ce3d262e2609c633bf889839117be26cc18 | [
"Apache-2.0"
] | permissive | CohenCyril/mathlib | 5241b20a3fd0ac0133e48e618a5fb7761ca7dcbe | a12d5a192f5923016752f638d19fc1a51610f163 | refs/heads/master | 1,586,031,957,957 | 1,541,432,824,000 | 1,541,432,824,000 | 156,246,337 | 0 | 0 | Apache-2.0 | 1,541,434,514,000 | 1,541,434,513,000 | null | UTF-8 | Lean | false | false | 25,621 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek
-/
import data.dlist.basic category.basic
namespace name
meta def deinternalize_field : name → name
| (name.mk_string s name.anonymous) :=
let i := s.mk_iterator in
if i.curr = '_' then i.next.next_to_string else s
| n := n
end name
namespace name_set
meta def filter (s : name_set) (P : name → bool) : name_set :=
s.fold s (λ a m, if P a then m else m.erase a)
meta def mfilter {m} [monad m] (s : name_set) (P : name → m bool) : m name_set :=
s.fold (pure s) (λ a m,
do x ← m,
mcond (P a) (pure x) (pure $ x.erase a))
meta def union (s t : name_set) : name_set :=
s.fold t (λ a t, t.insert a)
end name_set
namespace expr
open tactic
attribute [derive has_reflect] binder_info
protected meta def to_pos_nat : expr → option ℕ
| `(has_one.one _) := some 1
| `(bit0 %%e) := bit0 <$> e.to_pos_nat
| `(bit1 %%e) := bit1 <$> e.to_pos_nat
| _ := none
protected meta def to_nat : expr → option ℕ
| `(has_zero.zero _) := some 0
| e := e.to_pos_nat
protected meta def to_int : expr → option ℤ
| `(has_neg.neg %%e) := do n ← e.to_nat, some (-n)
| e := coe <$> e.to_nat
protected meta def of_nat (α : expr) : ℕ → tactic expr :=
nat.binary_rec
(tactic.mk_mapp ``has_zero.zero [some α, none])
(λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else
do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e])
protected meta def of_int (α : expr) : ℤ → tactic expr
| (n : ℕ) := expr.of_nat α n
| -[1+ n] := do
e ← expr.of_nat α (n+1),
tactic.mk_app ``has_neg.neg [e]
meta def is_meta_var : expr → bool
| (mvar _ _ _) := tt
| e := ff
meta def is_sort : expr → bool
| (sort _) := tt
| e := ff
meta def list_local_consts (e : expr) : list expr :=
e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es)
meta def list_constant (e : expr) : name_set :=
e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es)
meta def list_meta_vars (e : expr) : list expr :=
e.fold [] (λ e' _ es, if e'.is_meta_var then insert e' es else es)
meta def list_names_with_prefix (pre : name) (e : expr) : name_set :=
e.fold mk_name_set $ λ e' _ l,
match e' with
| expr.const n _ := if n.get_prefix = pre then l.insert n else l
| _ := l
end
/- only traverses the direct descendents -/
meta def {u} traverse {m : Type → Type u} [applicative m]
{elab elab' : bool} (f : expr elab → m (expr elab')) :
expr elab → m (expr elab')
| (var v) := pure $ var v
| (sort l) := pure $ sort l
| (const n ls) := pure $ const n ls
| (mvar n n' e) := mvar n n' <$> f e
| (local_const n n' bi e) := local_const n n' bi <$> f e
| (app e₀ e₁) := app <$> f e₀ <*> f e₁
| (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁
| (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁
| (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂
| (macro mac es) := macro mac <$> list.traverse f es
meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α
| x e := prod.snd <$> (state_t.run (e.traverse $ λ e',
(get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _)
end expr
namespace environment
meta def in_current_file' (env : environment) (n : name) : bool :=
env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind])
meta def is_structure_like (env : environment) (n : name) : option (nat × name) :=
do guardb (env.is_inductive n),
d ← (env.get n).to_option,
[intro] ← pure (env.constructors_of n) | none,
guard (env.inductive_num_indices n = 0),
some (env.inductive_num_params n, intro)
meta def is_structure (env : environment) (n : name) : bool :=
option.is_some $ do
(nparams, intro) ← env.is_structure_like n,
di ← (env.get intro).to_option,
expr.pi x _ _ _ ← nparams.iterate
(λ e : option expr, do expr.pi _ _ _ body ← e | none, some body)
(some di.type) | none,
env.is_projection (n ++ x.deinternalize_field)
end environment
namespace interaction_monad
open result
meta def get_result {σ α} (tac : interaction_monad σ α) :
interaction_monad σ (interaction_monad.result σ α) | s :=
match tac s with
| r@(success _ s') := success r s'
| r@(exception _ _ s') := success r s'
end
end interaction_monad
namespace lean.parser
open lean interaction_monad.result
meta def of_tactic' {α} (tac : tactic α) : parser α :=
do r ← of_tactic (interaction_monad.get_result tac),
match r with
| (success a _) := return a
| (exception f pos _) := exception f pos
end
end lean.parser
namespace tactic
meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α :=
mk_app ``id [e] >>= eval_expr α
meta def is_simp_lemma : name → tactic bool :=
succeeds ∘ tactic.has_attribute `simp
meta def local_decls : tactic (name_map declaration) :=
do e ← tactic.get_env,
let xs := e.fold native.mk_rb_map
(λ d s, if environment.in_current_file' e d.to_name
then s.insert d.to_name d else s),
pure xs
meta def simp_lemmas_from_file : tactic name_set :=
do s ← local_decls,
let s := s.map (expr.list_constant ∘ declaration.value),
xs ← s.to_list.mmap ((<$>) name_set.of_list ∘ mfilter tactic.is_simp_lemma ∘ name_set.to_list ∘ prod.snd),
return $ name_set.filter (xs.foldl name_set.union mk_name_set) (λ x, ¬ s.contains x)
meta def file_simp_attribute_decl (attr : name) : tactic unit :=
do s ← simp_lemmas_from_file,
trace format!"run_cmd mk_simp_attr `{attr}",
let lmms := format.join $ list.intersperse " " $ s.to_list.map to_fmt,
trace format!"local attribute [{attr}] {lmms}"
meta def mk_local (n : name) : expr :=
expr.local_const n n binder_info.default (expr.const n [])
meta def local_def_value (e : expr) : tactic expr := do
do (v,_) ← solve_aux `(true) (do
(expr.elet n t v _) ← (revert e >> target)
| fail format!"{e} is not a local definition",
return v),
return v
meta def check_defn (n : name) (e : pexpr) : tactic unit :=
do (declaration.defn _ _ _ d _ _) ← get_decl n,
e' ← to_expr e,
guard (d =ₐ e') <|> trace d >> failed
-- meta def compile_eqn (n : name) (univ : list name) (args : list expr) (val : expr) (num : ℕ) : tactic unit :=
-- do let lhs := (expr.const n $ univ.map level.param).mk_app args,
-- stmt ← mk_app `eq [lhs,val],
-- let vs := stmt.list_local_const,
-- let stmt := stmt.pis vs,
-- (_,pr) ← solve_aux stmt (tactic.intros >> reflexivity),
-- add_decl $ declaration.thm (n <.> "equations" <.> to_string (format!"_eqn_{num}")) univ stmt (pure pr)
meta def to_implicit : expr → expr
| (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t
| e := e
meta def pis : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← pis es f,
pure $ expr.pi pp info t (expr.abstract_local f' uniq)
| _ f := pure f
meta def lambdas : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← lambdas es f,
pure $ expr.lam pp info t (expr.abstract_local f' uniq)
| _ f := pure f
meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit :=
do cxt ← list.map to_implicit <$> local_context,
t ← target,
(eqns,d) ← solve_aux t elab_def,
d ← instantiate_mvars d,
t' ← pis cxt t,
d' ← lambdas cxt d,
let univ := t'.collect_univ_params,
add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted,
applyc n
meta def exact_dec_trivial : tactic unit := `[exact dec_trivial]
/-- Runs a tactic for a result, reverting the state after completion -/
meta def retrieve {α} (tac : tactic α) : tactic α :=
λ s, result.cases_on (tac s)
(λ a s', result.success a s)
result.exception
/-- Repeat a tactic at least once, calling it recursively on all subgoals,
until it fails. This tactic fails if the first invocation fails. -/
meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t
/-- `iterate_range m n t`: Repeat the given tactic at least `m` times and
at most `n` times or until `t` fails. Fails if `t` does not run at least m times. -/
meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit
| 0 0 t := skip
| 0 (n+1) t := try (t >> iterate_range 0 n t)
| (m+1) n t := t >> iterate_range m (n-1) t
meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) : tactic bool :=
do to_remove ← hs.mfilter $ λ h, do {
h_type ← infer_type h,
succeeds $ do
(new_h_type, pr) ← tac h_type,
assert h.local_pp_name new_h_type,
mk_eq_mp pr h >>= tactic.exact },
goal_simplified ← succeeds $ do {
guard tgt,
(new_t, pr) ← target >>= tac,
replace_target new_t pr },
to_remove.mmap' (λ h, try (clear h)),
return (¬ to_remove.empty ∨ goal_simplified)
meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) :=
prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg
meta structure instance_cache :=
(α : expr)
(univ : level)
(inst : name_map expr)
meta def mk_instance_cache (α : expr) : tactic instance_cache :=
do u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
return ⟨α, u, mk_name_map⟩
namespace instance_cache
meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) :=
match c.inst.find n with
| some i := return (c, i)
| none := do e ← mk_app n [c.α] >>= mk_instance,
return (⟨c.α, c.univ, c.inst.insert n e⟩, e)
end
open expr
meta def append_typeclasses : expr → instance_cache → list expr →
tactic (instance_cache × list expr)
| (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l :=
do (c, p) ← c.get n, return (c, p :: l)
| _ c l := return (c, l)
meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) :=
do d ← get_decl n,
(c, l) ← append_typeclasses d.type.binding_body c l,
return (c, (expr.const n [c.univ]).mk_app (c.α :: l))
end instance_cache
/-- Reset the instance cache for the main goal. -/
meta def reset_instance_cache : tactic unit := unfreeze_local_instances
meta def match_head (e : expr) : expr → tactic unit
| e' :=
unify e e'
<|> do `(_ → %%e') ← whnf e',
v ← mk_mvar,
match_head (e'.instantiate_var v)
meta def find_matching_head : expr → list expr → tactic (list expr)
| e [] := return []
| e (H :: Hs) :=
do t ← infer_type H,
((::) H <$ match_head e t <|> pure id) <*> find_matching_head e Hs
meta def subst_locals (s : list (expr × expr)) (e : expr) : expr :=
(e.abstract_locals (s.map (expr.local_uniq_name ∘ prod.fst)).reverse).instantiate_vars (s.map prod.snd)
meta def set_binder : expr → list binder_info → expr
| e [] := e
| (expr.pi v _ d b) (bi :: bs) := expr.pi v bi d (set_binder b bs)
| e _ := e
meta def last_explicit_arg : expr → tactic expr
| (expr.app f e) :=
do t ← infer_type f >>= whnf,
if t.binding_info = binder_info.default
then pure e
else last_explicit_arg f
| e := pure e
private meta def get_expl_pi_arity_aux : expr → tactic nat
| (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
new_b ← whnf (expr.instantiate_var b l),
r ← get_expl_pi_arity_aux new_b,
if bi = binder_info.default then
return (r + 1)
else
return r
| e := return 0
/-- Compute the arity of explicit arguments of the given (Pi-)type -/
meta def get_expl_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_expl_pi_arity_aux
/-- Compute the arity of explicit arguments of the given function -/
meta def get_expl_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_expl_pi_arity
/-- variation on `assert` where a (possibly incomplete)
proof of the assertion is provided as a parameter.
``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and
use `tac` to (partially) construct a proof for it. `gs` is the
list of remaining goals in the proof of `h`.
The benefits over assert are:
- unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`;
- when `tac` does not complete the proof of `h`, returning the list
of goals allows one to write a tactic using `h` and with the confidence
that a proof will not boil over to goals left over from the proof of `h`,
unlike what would be the case when using `tactic.swap`.
-/
meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) :
tactic (expr × list expr) :=
focus1 $
do h' ← assert h p,
[g₀,g₁] ← get_goals,
set_goals [g₀], tac₀,
gs ← get_goals,
set_goals [g₁],
return (h', gs)
meta def var_names : expr → list name
| (expr.pi n _ _ b) := n :: var_names b
| _ := []
meta def drop_binders : expr → tactic expr
| (expr.pi n bi t b) := b.instantiate_var <$> mk_local' n bi t >>= drop_binders
| e := pure e
meta def subobject_names (struct_n : name) : tactic (list name × list name) :=
do env ← get_env,
[c] ← pure $ env.constructors_of struct_n | fail "too many constructors",
vs ← var_names <$> (mk_const c >>= infer_type),
fields ← env.structure_fields struct_n,
return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs)
meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n :=
do (so,fs) ← subobject_names struct_n,
ts ← so.mmap (λ n, do
e ← mk_const (n.update_prefix struct_n) >>= infer_type >>= drop_binders,
expanded_field_list' $ e.get_app_fn.const_name),
return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n)
open functor function
meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) :=
dlist.to_list <$> expanded_field_list' struct_n
meta def get_classes (e : expr) : tactic (list name) :=
attribute.get_instances `class >>= list.mfilter (λ n,
succeeds $ mk_app n [e] >>= mk_instance)
open nat
meta def mk_mvar_list : ℕ → tactic (list expr)
| 0 := pure []
| (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n
/--`iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals,
or until it fails. Always succeeds. -/
meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := tactic.all_goals $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip
/--`iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first
goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on
current goal. -/
meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac)
/--`apply_list l`: try to apply the tactics in the list `l` on the first goal, and
fail if none succeeds -/
meta def apply_list_expr : list expr → tactic unit
| [] := fail "no matching rule"
| (h::t) := do interactive.concat_tags (apply h) <|> apply_list_expr t
/-- constructs a list of expressions given a list of p-expressions, as follows:
- if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it
- if the p-expression is a user attribute, add all the theorems with this attribute
to the list.-/
meta def build_list_expr_for_apply : list pexpr → tactic (list expr)
| [] := return []
| (h::t) := do
tail ← build_list_expr_for_apply t,
a ← i_to_expr_for_apply h,
(do l ← attribute.get_instances (expr.const_name a),
m ← list.mmap mk_const l,
return (m.append tail))
<|> return (a::tail)
/--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the
first goal and the resulting subgoals, iteratively, at most `n` times -/
meta def apply_rules (hs : list pexpr) (n : nat) : tactic unit :=
do l ← build_list_expr_for_apply hs,
iterate_at_most_on_subgoals n (assumption <|> apply_list_expr l)
meta def replace (h : name) (p : pexpr) : tactic unit :=
do h' ← get_local h,
p ← to_expr p,
note h none p,
clear h'
meta def symm_apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) :=
tactic.apply e cfg <|> (symmetry >> tactic.apply e cfg)
meta def apply_assumption
(asms : tactic (list expr) := local_context)
(tac : tactic unit := skip) : tactic unit :=
do { ctx ← asms,
ctx.any_of (λ H, symm_apply H >> tac) } <|>
do { exfalso,
ctx ← asms,
ctx.any_of (λ H, symm_apply H >> tac) }
<|> fail "assumption tactic failed"
open nat
meta def solve_by_elim_aux (discharger : tactic unit) (asms : tactic (list expr)) : ℕ → tactic unit
| 0 := done
| (succ n) := discharger <|> (apply_assumption asms $ solve_by_elim_aux n)
meta structure by_elim_opt :=
(discharger : tactic unit := done)
(assumptions : tactic (list expr) := local_context)
(max_rep : ℕ := 3)
meta def solve_by_elim (opt : by_elim_opt := { }) : tactic unit :=
do
tactic.fail_if_no_goals,
focus1 $
solve_by_elim_aux opt.discharger opt.assumptions opt.max_rep
meta def metavariables : tactic (list expr) :=
do r ← result,
pure (r.list_meta_vars)
/-- Succeeds only if the current goal is a proposition. -/
meta def propositional_goal : tactic unit :=
do goals ← get_goals,
p ← is_proof goals.head,
guard p
variable {α : Type}
private meta def iterate_aux (t : tactic α) : list α → tactic (list α)
| L := (do r ← t, iterate_aux (r :: L)) <|> return L
/-- Apply a tactic as many times as possible, collecting the results in a list. -/
meta def iterate' (t : tactic α) : tactic (list α) :=
list.reverse <$> iterate_aux t []
/-- Like iterate', but fail if the tactic does not succeed at least once. -/
meta def iterate1 (t : tactic α) : tactic (α × list α) :=
do r ← decorate_ex "iterate1 failed: tactic did not succeed" t,
L ← iterate' t,
return (r, L)
meta def intros1 : tactic (list expr) :=
iterate1 intro1 >>= λ p, return (p.1 :: p.2)
/-- `successes` invokes each tactic in turn, returning the list of successful results. -/
meta def successes (tactics : list (tactic α)) : tactic (list α) :=
list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t))
/-- Return target after instantiating metavars and whnf -/
private meta def target' : tactic expr :=
target >>= instantiate_mvars >>= whnf
/--
Just like `split`, `fsplit` applies the constructor when the type of the target is an inductive data type with one constructor.
However it does not reorder goals or invoke `auto_param` tactics.
-/
-- FIXME check if we can remove `auto_param := ff`
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 >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip
run_cmd add_interactive [`fsplit]
/-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection`
succeeds, clears the old hypothesis. -/
meta def injections_and_clear : tactic unit :=
do l ← local_context,
results ← successes $ l.map $ λ e, injection e >> clear e,
when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis")
run_cmd add_interactive [`injections_and_clear]
meta def note_anon (e : expr) : tactic unit :=
do n ← get_unused_name "lh",
note n none e, skip
meta def find_local (t : pexpr) : tactic expr :=
do t' ← to_expr t,
prod.snd <$> solve_aux t' assumption
/-- `dependent_pose_core l`: introduce dependent hypothesis, where the proofs depend on the values
of the previous local constants. `l` is a list of local constants and their values. -/
meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do
let lc := l.map prod.fst,
let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)),
t ← target,
new_goal ← mk_meta_var (t.pis lc),
old::other_goals ← get_goals,
set_goals (old :: new_goal :: other_goals),
exact ((new_goal.mk_app lc).instantiate_locals lm),
return ()
/-- like `mk_local_pis` but translating into weak head normal form before checking if it is a Π. -/
meta def mk_local_pis_whnf : expr → tactic (list expr × expr) | e := do
(expr.pi n bi d b) ← whnf e | return ([], e),
p ← mk_local' n bi d,
(ps, r) ← mk_local_pis (expr.instantiate_var b p),
return ((p :: ps), r)
/-- Changes `(h : ∀xs, ∃a:α, p a) ⊢ g` to `(d : ∀xs, a) (s : ∀xs, p (d xs) ⊢ g` -/
meta def choose1 (h : expr) (data : name) (spec : name) : tactic expr := do
t ← infer_type h,
(ctxt, t) ← mk_local_pis_whnf t,
`(@Exists %%α %%p) ← whnf t transparency.all | fail "expected a term of the shape ∀xs, ∃a, p xs a",
α_t ← infer_type α,
expr.sort u ← whnf α_t transparency.all,
value ← mk_local_def data (α.pis ctxt),
t' ← head_beta (p.app (value.mk_app ctxt)),
spec ← mk_local_def spec (t'.pis ctxt),
dependent_pose_core [
(value, ((((expr.const `classical.some [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt),
(spec, ((((expr.const `classical.some_spec [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt)],
try (tactic.clear h),
intro1,
intro1
/-- Changes `(h : ∀xs, ∃as, p as) ⊢ g` to a list of functions `as`, an a final hypothesis on `p as` -/
meta def choose : expr → list name → tactic unit
| h [] := fail "expect list of variables"
| h [n] := do
cnt ← revert h,
intro n,
intron (cnt - 1),
return ()
| h (n::ns) := do
v ← get_unused_name >>= choose1 h n,
choose v ns
/-- This makes sure that the execution of the tactic does not change the tactic state.
This can be helpful while using rewrite, apply, or expr munging.
Remember to instantiate your metavariables before you're done! -/
meta def lock_tactic_state {α} (t : tactic α) : tactic α
| s := match t s with
| result.success a s' := result.success a s
| result.exception msg pos s' := result.exception msg pos s
end
/--
Hole command used to fill in a structure's field when specifying an instance.
In the following:
```
instance : monad id :=
{! !}
```
invoking hole command `Instance Stub` produces:
```
instance : monad id :=
{ map := _,
map_const := _,
pure := _,
seq := _,
seq_left := _,
seq_right := _,
bind := _ }
```
-/
@[hole_command] meta def instance_stub : hole_command :=
{ name := "Instance Stub",
descr := "Generate a skeleton for the structure under construction.",
action := λ _,
do tgt ← target,
let cl := tgt.get_app_fn.const_name,
env ← get_env,
fs ← expanded_field_list cl,
let fs := fs.map prod.snd,
let fs := list.intersperse (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"),
let out := format.to_string format!"{{ {format.join fs} }",
return [(out,"")] }
meta def classical : tactic unit :=
do h ← get_unused_name `_inst,
mk_const `classical.prop_decidable >>= note h none,
reset_instance_cache
open expr
meta def add_prime : name → name
| (name.mk_string s p) := name.mk_string (s ++ "'") p
| n := (name.mk_string "x'" n)
meta def mk_comp (v : expr) : expr → tactic expr
| (app f e) :=
if e = v then pure f
else do
guard (¬ v.occurs f) <|> fail "bad guard",
e' ← mk_comp e >>= instantiate_mvars,
f ← instantiate_mvars f,
mk_mapp ``function.comp [none,none,none,f,e']
| e :=
do guard (e = v),
t ← infer_type e,
mk_mapp ``id [t]
meta def mk_higher_order_type : expr → tactic expr
| (pi n bi d b@(pi _ _ _ _)) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b'
| (pi n bi d b) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(l,r) ← match_eq b' <|> fail format!"not an equality {b'}",
l' ← mk_comp v l,
r' ← mk_comp v r,
mk_app ``eq [l',r']
| e := failed
open lean.parser interactive.types
@[user_attribute]
meta def higher_order_attr : user_attribute unit (option name) :=
{ name := `higher_order,
parser := optional ident,
descr :=
"From a lemma of the shape `f (g x) = h x` derive an auxiliary lemma of the
form `f ∘ g = h` for reasoning about higher-order functions.",
after_set := some $ λ lmm _ _,
do env ← get_env,
decl ← env.get lmm,
let num := decl.univ_params.length,
let lvls := (list.iota num).map (`l).append_after,
let l : expr := expr.const lmm $ lvls.map level.param,
t ← infer_type l >>= instantiate_mvars,
t' ← mk_higher_order_type t,
(_,pr) ← solve_aux t' $ do {
intros, applyc ``_root_.funext, intro1, applyc lmm; assumption },
pr ← instantiate_mvars pr,
lmm' ← higher_order_attr.get_param lmm,
lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure (add_prime lmm),
add_decl $ declaration.thm lmm' lvls t' (pure pr),
copy_attribute `simp lmm tt lmm',
copy_attribute `functor_norm lmm tt lmm' }
attribute [higher_order map_comp_pure] map_pure
end tactic
|
39a7fc3df2739970634584dac24a36307606f0ad | 5bf112cf7101c6c6303dc3fd0b3179c860e61e56 | /lean/problems/algebra/imo_2018_sl.lean | 589650465640f03e7abf4c19c6a16cf7faaaa167 | [
"Apache-2.0"
] | permissive | fredfeng/formal-encoding | 7ab645f49a553dfad2af03fcb4289e40fc679759 | 024efcf58672ac6b817caa10dfe8cd9708b07f1b | refs/heads/master | 1,597,236,551,123 | 1,568,832,149,000 | 1,568,832,149,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,099 | lean | import background
namespace IMOGrandChallenge
namespace Problems
namespace Algebra
def IMO_2018_SL_A1 : Type :=
-- note: subtype for `Q_{>0}`; want better notation, e.g. `ℚgt0`
-- note: doesn't typecheck, need support for operations on subtypes, e.g. `(x : ℚgt0) * (y : ℚgt0)`
determine $ λ (f : ℚgt0 → ℚgt0) => ∀ (x y : ℚgt0), f (x^2 * (f y)^2) = (f x)^2 * (f y)
def IMO_2018_SL_A2 : Type :=
-- note: using `Vec _ n` for a sequence `a₁, ..., aₙ`
-- note: switched to 0-indexing, which arguably adds confusion
-- note: assuming `⊕` is defined for cyclic addition on `Fin n`
-- note: (still missing ∃ syntax support)
-- note: type-class inference may struggle with `HasOne (Fin n)`, since it needs to track `n ≥ 3`
determine $ λ (n : ℕ) => n ≥ 3 ∧ ∃ (a : Vec ℝ n),
∀ (i : Fin n), a[i] * a[i ⊕ 1] + 1 = a[i ⊕ 2]
def IMO_2018_SL_A3 : Prop :=
-- note: made `FiniteSet` a type instead of a condition
-- note: assuming elaborator can handle `<FiniteSet T> ⊆ <Set T>`
-- note: using `F ≠ G` for distinct from, which wouldn't work if they were `Set`s
-- note: still missing `⊆` support
-- note: let-binding the conditions
∀ (S : Set ℤgt0),
let C1 : Prop :=
∃ (F G : FiniteSet ℤgt0), F ⊆ S ∧ G ⊆ S ∧ F ≠ G ∧ F.sum (λ x => 1/x) = G.sum (λ x => 1/x);
let C2 : Prop :=
∃ (r : ℚgt0), r < 1 ∧ ∀ (F : FiniteSet ℤgt0), F ⊆ S ∧ F.sum (λ x => 1/x) ≠ r;
C1 ∨ C2
def IMO_2018_SL_A4 : Type :=
-- note: let-binded the predicate
-- note: `range1 k` means `[1, ... , k]`
-- note: the quantifier structure is subtle; we never introduce a sequence `a`
-- note: `max : ∀ {X Y : Type} [TotalOrder Y], Set X → (X → Y) → Y`
-- note: `compute {X : Type} (target : X) : Type := { x : X // x = target }`
-- is just the 1-element version of `determine`.
-- (Recall that under the current proposal, the witness must be human-checked)
let goodSequence : Set (ℕ → ℝ) :=
λ (a : ℕ → ℝ),
a 0 = 1 ∧ a 1 = 1
∧ ∀ (n : ℕ), n ≥ 2 → ∃ (k : ℕ), 1 ≤ k ∧ k ≤ n ∧ a n = avg (map (λ i => a (n - i)) (range1 k));
compute $ max goodSequence (λ a => a 2018 - a 2017)
def IMO_2018_SL_A5 : Type :=
-- note: straightforward, though curry-syntax is a real downer
determine $ λ (f : ℝgt0 → ℝ) => ∀ (x y : ℝgt0), (x + 1/x) * f y = f (x * y) + f (y / x)
def IMO_2018_SL_A6 : Prop :=
-- note: question says `m` and `n` are `ℤ` and `≥ 2`
-- note: assumes a formulation of multivariate polynomials, that take `Vec`s
-- note: `x ∈ range m` is problematic, and would require tricky coercions.
∀ (m n : ℕ), m ≥ 2 → n ≥ 2 →
∀ (f : Poly ℝ n),
∀ (xs : Vec ℝ n), xs.all (λ x => x ∈ range m) →
totalDegree f ≥ n
def IMO_2018_SL_A7 : Prop :=
-- note: `ℝ≥` likely problematic
-- note: awkward to bind cyclicSum with the same name
compute $ max (λ (cs : Vec ℝ≥ 4) => cs.sum = 100)
(λ (cs : Vec ℝ≥ 4) => cs.cyclicSum (λ cs => ((cs.get 0) / ((cs.get 1) + 7)) ^ (1/3)))
end Algebra
end Problems
end IMOGrandChallenge
|
6d01dc8e3331aad84b0030d5b99ab1b715b9f28b | 5749d8999a76f3a8fddceca1f6941981e33aaa96 | /src/topology/stone_cech.lean | 8953debce2d861577ef0357332bc1366f3259a5f | [
"Apache-2.0"
] | permissive | jdsalchow/mathlib | 13ab43ef0d0515a17e550b16d09bd14b76125276 | 497e692b946d93906900bb33a51fd243e7649406 | refs/heads/master | 1,585,819,143,348 | 1,580,072,892,000 | 1,580,072,892,000 | 154,287,128 | 0 | 0 | Apache-2.0 | 1,540,281,610,000 | 1,540,281,609,000 | null | UTF-8 | Lean | false | false | 11,243 | lean | /-
Copyright (c) 2018 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton
-/
import topology.bases topology.dense_embedding
/-! # Stone-Čech compactification
Construction of the Stone-Čech compactification using ultrafilters.
Parts of the formalization are based on "Ultrafilters and Topology"
by Marius Stekelenburg, particularly section 5.
-/
noncomputable theory
open filter lattice set
open_locale topological_space
universes u v
section ultrafilter
/- The set of ultrafilters on α carries a natural topology which makes
it the Stone-Čech compactification of α (viewed as a discrete space). -/
/-- Basis for the topology on `ultrafilter α`. -/
def ultrafilter_basis (α : Type u) : set (set (ultrafilter α)) :=
{t | ∃ (s : set α), t = {u | s ∈ u.val}}
variables {α : Type u}
instance : topological_space (ultrafilter α) :=
topological_space.generate_from (ultrafilter_basis α)
lemma ultrafilter_basis_is_basis :
topological_space.is_topological_basis (ultrafilter_basis α) :=
⟨begin
rintros _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ u ⟨ua, ub⟩,
refine ⟨_, ⟨a ∩ b, rfl⟩, u.val.inter_sets ua ub, assume v hv, ⟨_, _⟩⟩;
apply v.val.sets_of_superset hv; simp
end,
eq_univ_of_univ_subset $ subset_sUnion_of_mem $
⟨univ, eq.symm (eq_univ_of_forall (λ u, u.val.univ_sets))⟩,
rfl⟩
/-- The basic open sets for the topology on ultrafilters are open. -/
lemma ultrafilter_is_open_basic (s : set α) :
is_open {u : ultrafilter α | s ∈ u.val} :=
topological_space.is_open_of_is_topological_basis ultrafilter_basis_is_basis ⟨s, rfl⟩
/-- The basic open sets for the topology on ultrafilters are also closed. -/
lemma ultrafilter_is_closed_basic (s : set α) :
is_closed {u : ultrafilter α | s ∈ u.val} :=
begin
change is_open (- _),
convert ultrafilter_is_open_basic (-s),
ext u,
exact (ultrafilter_iff_compl_mem_iff_not_mem.mp u.property s).symm
end
/-- Every ultrafilter `u` on `ultrafilter α` converges to a unique
point of `ultrafilter α`, namely `mjoin u`. -/
lemma ultrafilter_converges_iff {u : ultrafilter (ultrafilter α)} {x : ultrafilter α} :
u.val ≤ 𝓝 x ↔ x = mjoin u :=
begin
rw [eq_comm, ultrafilter.eq_iff_val_le_val],
change u.val ≤ 𝓝 x ↔ x.val.sets ⊆ {a | {v : ultrafilter α | a ∈ v.val} ∈ u.val},
simp only [topological_space.nhds_generate_from, lattice.le_infi_iff, ultrafilter_basis,
le_principal_iff],
split; intro h,
{ intros a ha, exact h _ ⟨ha, a, rfl⟩ },
{ rintros _ ⟨xi, a, rfl⟩, exact h xi }
end
instance ultrafilter_compact : compact_space (ultrafilter α) :=
⟨compact_iff_ultrafilter_le_nhds.mpr $ assume f uf _,
⟨mjoin ⟨f, uf⟩, trivial, ultrafilter_converges_iff.mpr rfl⟩⟩
instance ultrafilter.t2_space : t2_space (ultrafilter α) :=
t2_iff_ultrafilter.mpr $ assume f x y u fx fy,
have hx : x = mjoin ⟨f, u⟩, from ultrafilter_converges_iff.mp fx,
have hy : y = mjoin ⟨f, u⟩, from ultrafilter_converges_iff.mp fy,
hx.trans hy.symm
lemma ultrafilter_comap_pure_nhds (b : ultrafilter α) : comap pure (𝓝 b) ≤ b.val :=
begin
rw topological_space.nhds_generate_from,
simp only [comap_infi, comap_principal],
intros s hs,
rw ←le_principal_iff,
refine lattice.infi_le_of_le {u | s ∈ u.val} _,
refine lattice.infi_le_of_le ⟨hs, ⟨s, rfl⟩⟩ _,
exact principal_mono.2 (λ a, id)
end
section embedding
lemma ultrafilter_pure_injective : function.injective (pure : α → ultrafilter α) :=
begin
intros x y h,
have : {x} ∈ (pure x : ultrafilter α).val := singleton_mem_pure_sets,
rw h at this,
exact (mem_singleton_iff.mp (mem_pure_sets.mp this)).symm
end
open topological_space
/-- `pure : α → ultrafilter α` defines a dense inducing of `α` in `ultrafilter α`. -/
lemma dense_inducing_pure : @dense_inducing _ _ ⊥ _ (pure : α → ultrafilter α) :=
by letI : topological_space α := ⊥; exact
dense_inducing.mk' pure continuous_bot
(assume x, mem_closure_iff_ultrafilter.mpr
⟨x.map ultrafilter.pure, range_mem_map,
ultrafilter_converges_iff.mpr (bind_pure x).symm⟩)
(assume a s as,
⟨{u | s ∈ u.val},
mem_nhds_sets (ultrafilter_is_open_basic s) (mem_of_nhds as : a ∈ s),
assume b hb, mem_pure_sets.mp hb⟩)
-- The following refined version will never be used
/-- `pure : α → ultrafilter α` defines a dense embedding of `α` in `ultrafilter α`. -/
lemma dense_embedding_pure : @dense_embedding _ _ ⊥ _ (pure : α → ultrafilter α) :=
by letI : topological_space α := ⊥ ;
exact { inj := ultrafilter_pure_injective, ..dense_inducing_pure }
end embedding
section extension
/- Goal: Any function `α → γ` to a compact Hausdorff space `γ` has a
unique extension to a continuous function `ultrafilter α → γ`. We
already know it must be unique because `α → ultrafilter α` is a
dense embedding and `γ` is Hausdorff. For existence, we will invoke
`dense_embedding.continuous_extend`. -/
variables {γ : Type*} [topological_space γ]
/-- The extension of a function `α → γ` to a function `ultrafilter α → γ`.
When `γ` is a compact Hausdorff space it will be continuous. -/
def ultrafilter.extend (f : α → γ) : ultrafilter α → γ :=
by letI : topological_space α := ⊥; exact dense_inducing_pure.extend f
variables [t2_space γ]
lemma ultrafilter_extend_extends (f : α → γ) : ultrafilter.extend f ∘ pure = f :=
begin
letI : topological_space α := ⊥,
letI : discrete_topology α := ⟨rfl⟩,
exact funext (dense_inducing_pure.extend_eq_of_cont continuous_of_discrete_topology)
end
variables [compact_space γ]
lemma continuous_ultrafilter_extend (f : α → γ) : continuous (ultrafilter.extend f) :=
have ∀ (b : ultrafilter α), ∃ c, tendsto f (comap ultrafilter.pure (𝓝 b)) (𝓝 c) := assume b,
-- b.map f is an ultrafilter on γ, which is compact, so it converges to some c in γ.
let ⟨c, _, h⟩ := compact_iff_ultrafilter_le_nhds.mp compact_univ (b.map f).val (b.map f).property
(by rw [le_principal_iff]; exact univ_mem_sets) in
⟨c, le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h⟩,
begin
letI : topological_space α := ⊥,
letI : normal_space γ := normal_of_compact_t2,
exact dense_inducing_pure.continuous_extend this
end
/-- The value of `ultrafilter.extend f` on an ultrafilter `b` is the
unique limit of the ultrafilter `b.map f` in `γ`. -/
lemma ultrafilter_extend_eq_iff {f : α → γ} {b : ultrafilter α} {c : γ} :
ultrafilter.extend f b = c ↔ b.val.map f ≤ 𝓝 c :=
⟨assume h, begin
-- Write b as an ultrafilter limit of pure ultrafilters, and use
-- the facts that ultrafilter.extend is a continuous extension of f.
let b' : ultrafilter (ultrafilter α) := b.map pure,
have t : b'.val ≤ 𝓝 b,
from ultrafilter_converges_iff.mpr (bind_pure _).symm,
rw ←h,
have := (continuous_ultrafilter_extend f).tendsto b,
refine le_trans _ (le_trans (map_mono t) this),
change _ ≤ map (ultrafilter.extend f ∘ pure) b.val,
rw ultrafilter_extend_extends,
exact le_refl _
end,
assume h, by letI : topological_space α := ⊥; exact
dense_inducing_pure.extend_eq (le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h)⟩
end extension
end ultrafilter
section stone_cech
/- Now, we start with a (not necessarily discrete) topological space α
and we want to construct its Stone-Čech compactification. We can
build it as a quotient of `ultrafilter α` by the relation which
identifies two points if the extension of every continuous function
α → γ to a compact Hausdorff space sends the two points to the same
point of γ. -/
variables (α : Type u) [topological_space α]
instance stone_cech_setoid : setoid (ultrafilter α) :=
{ r := λ x y, ∀ (γ : Type u) [topological_space γ], by exactI
∀ [t2_space γ] [compact_space γ] (f : α → γ) (hf : continuous f),
ultrafilter.extend f x = ultrafilter.extend f y,
iseqv :=
⟨assume x γ tγ h₁ h₂ f hf, rfl,
assume x y xy γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).symm,
assume x y z xy yz γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).trans (yz γ f hf)⟩ }
/-- The Stone-Čech compactification of a topological space. -/
def stone_cech : Type u := quotient (stone_cech_setoid α)
variables {α}
instance : topological_space (stone_cech α) := by unfold stone_cech; apply_instance
/-- The natural map from α to its Stone-Čech compactification. -/
def stone_cech_unit (x : α) : stone_cech α := ⟦pure x⟧
/-- The image of stone_cech_unit is dense. (But stone_cech_unit need
not be an embedding, for example if α is not Hausdorff.) -/
lemma stone_cech_unit_dense : closure (range (@stone_cech_unit α _)) = univ :=
begin
convert quotient_dense_of_dense (eq_univ_iff_forall.mp dense_inducing_pure.closure_range),
rw [←range_comp], refl
end
section extension
variables {γ : Type u} [topological_space γ] [t2_space γ] [compact_space γ]
variables {f : α → γ} (hf : continuous f)
local attribute [elab_with_expected_type] quotient.lift
/-- The extension of a continuous function from α to a compact
Hausdorff space γ to the Stone-Čech compactification of α. -/
def stone_cech_extend : stone_cech α → γ :=
quotient.lift (ultrafilter.extend f) (λ x y xy, xy γ f hf)
lemma stone_cech_extend_extends : stone_cech_extend hf ∘ stone_cech_unit = f :=
ultrafilter_extend_extends f
lemma continuous_stone_cech_extend : continuous (stone_cech_extend hf) :=
continuous_quot_lift _ (continuous_ultrafilter_extend f)
end extension
lemma convergent_eqv_pure {u : ultrafilter α} {x : α} (ux : u.val ≤ 𝓝 x) : u ≈ pure x :=
assume γ tγ h₁ h₂ f hf, begin
resetI,
transitivity f x, swap, symmetry,
all_goals { refine ultrafilter_extend_eq_iff.mpr (le_trans (map_mono _) (hf.tendsto _)) },
{ apply pure_le_nhds }, { exact ux }
end
lemma continuous_stone_cech_unit : continuous (stone_cech_unit : α → stone_cech α) :=
continuous_iff_ultrafilter.mpr $ λ x g u gx,
let g' : ultrafilter α := ⟨g, u⟩ in
have (g'.map ultrafilter.pure).val ≤ 𝓝 g',
by rw ultrafilter_converges_iff; exact (bind_pure _).symm,
have (g'.map stone_cech_unit).val ≤ 𝓝 ⟦g'⟧, from
(continuous_at_iff_ultrafilter g').mp
(continuous_quotient_mk.tendsto g') _ (ultrafilter_map u) this,
by rwa (show ⟦g'⟧ = ⟦pure x⟧, from quotient.sound $ convergent_eqv_pure gx) at this
instance stone_cech.t2_space : t2_space (stone_cech α) :=
begin
rw t2_iff_ultrafilter,
rintros g ⟨x⟩ ⟨y⟩ u gx gy,
apply quotient.sound,
intros γ tγ h₁ h₂ f hf,
resetI,
let ff := stone_cech_extend hf,
change ff ⟦x⟧ = ff ⟦y⟧,
have lim : ∀ z : ultrafilter α, g ≤ 𝓝 ⟦z⟧ → tendsto ff g (𝓝 (ff ⟦z⟧)) :=
assume z gz,
calc map ff g ≤ map ff (𝓝 ⟦z⟧) : map_mono gz
... ≤ 𝓝 (ff ⟦z⟧) : (continuous_stone_cech_extend hf).tendsto _,
exact tendsto_nhds_unique u.1 (lim x gx) (lim y gy)
end
instance stone_cech.compact_space : compact_space (stone_cech α) :=
quotient.compact_space
end stone_cech
|
a432d10a8df5cbd71acbf8aac934f64accdf85ef | 42610cc2e5db9c90269470365e6056df0122eaa0 | /hott/homotopy/homotopy_group.hlean | 6b768b4056268d1f0762390873e63bd1e05b7899 | [
"Apache-2.0"
] | permissive | tomsib2001/lean | 2ab59bfaebd24a62109f800dcf4a7139ebd73858 | eb639a7d53fb40175bea5c8da86b51d14bb91f76 | refs/heads/master | 1,586,128,387,740 | 1,468,968,950,000 | 1,468,968,950,000 | 61,027,234 | 0 | 0 | null | 1,465,813,585,000 | 1,465,813,585,000 | null | UTF-8 | Lean | false | false | 6,286 | hlean | /-
Copyright (c) 2016 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Clive Newstead
-/
import .LES_of_homotopy_groups .sphere .complex_hopf
open eq is_trunc trunc_index pointed algebra trunc nat is_conn fiber pointed
namespace is_trunc
-- Lemma 8.3.1
theorem trivial_homotopy_group_of_is_trunc (A : Type*) (n k : ℕ) [is_trunc n A] (H : n ≤ k)
: is_contr (πg[k+1] A) :=
begin
apply is_trunc_trunc_of_is_trunc,
apply is_contr_loop_of_is_trunc,
apply @is_trunc_of_le A n _,
rewrite [succ_sub_two_succ k],
exact of_nat_le_of_nat H,
end
-- Lemma 8.3.2
theorem trivial_homotopy_group_of_is_conn (A : Type*) {k n : ℕ} (H : k ≤ n) [is_conn n A]
: is_contr (π[k] A) :=
begin
have H3 : is_contr (ptrunc k A), from is_conn_of_le A (of_nat_le_of_nat H),
have H4 : is_contr (Ω[k](ptrunc k A)), from !is_trunc_loop_of_is_trunc,
apply is_trunc_equiv_closed_rev,
{ apply equiv_of_pequiv (phomotopy_group_pequiv_loop_ptrunc k A)}
end
-- Corollary 8.3.3
section
open sphere sphere.ops sphere_index
theorem homotopy_group_sphere_le (n k : ℕ) (H : k < n) : is_contr (π[k] (S. n)) :=
begin
cases n with n,
{ exfalso, apply not_lt_zero, exact H},
{ have H2 : k ≤ n, from le_of_lt_succ H,
apply @(trivial_homotopy_group_of_is_conn _ H2) }
end
end
theorem is_contr_HG_fiber_of_is_connected {A B : Type*} (k n : ℕ) (f : A →* B)
[H : is_conn_fun n f] (H2 : k ≤ n) : is_contr (π[k] (pfiber f)) :=
@(trivial_homotopy_group_of_is_conn (pfiber f) H2) (H pt)
/- Corollaries of the LES of homotopy groups -/
local attribute comm_group.to_group [coercion]
local attribute is_equiv_tinverse [instance]
open prod chain_complex group fin equiv function is_equiv lift
/-
Because of the construction of the LES this proof only gives us this result when
A and B live in the same universe (because Lean doesn't have universe cumulativity).
However, below we also proof that it holds for A and B in arbitrary universes.
-/
theorem is_equiv_π_of_is_connected'.{u} {A B : pType.{u}} {n k : ℕ} (f : A →* B)
(H2 : k ≤ n) [H : is_conn_fun n f] : is_equiv (π→[k] f) :=
begin
cases k with k,
{ /- k = 0 -/
change (is_equiv (trunc_functor 0 f)), apply is_equiv_trunc_functor_of_is_conn_fun,
refine is_conn_fun_of_le f (zero_le_of_nat n)},
{ /- k > 0 -/
have H2' : k ≤ n, from le.trans !self_le_succ H2,
exact
@is_equiv_of_trivial _
(LES_of_homotopy_groups f) _
(is_exact_LES_of_homotopy_groups f (k, 2))
(is_exact_LES_of_homotopy_groups f (succ k, 0))
(@is_contr_HG_fiber_of_is_connected A B k n f H H2')
(@is_contr_HG_fiber_of_is_connected A B (succ k) n f H H2)
(@pgroup_of_group _ (group_LES_of_homotopy_groups f k 0) idp)
(@pgroup_of_group _ (group_LES_of_homotopy_groups f k 1) idp)
(homomorphism.struct (homomorphism_LES_of_homotopy_groups_fun f (k, 0)))},
end
theorem is_equiv_π_of_is_connected.{u v} {A : pType.{u}} {B : pType.{v}} {n k : ℕ} (f : A →* B)
(H2 : k ≤ n) [H : is_conn_fun n f] : is_equiv (π→[k] f) :=
begin
have π→*[k] pdown.{v u} ∘* π→*[k] (plift_functor f) ∘* π→*[k] pup.{u v} ~* π→*[k] f,
begin
refine pwhisker_left _ !phomotopy_group_functor_compose⁻¹* ⬝* _,
refine !phomotopy_group_functor_compose⁻¹* ⬝* _,
apply phomotopy_group_functor_phomotopy, apply plift_functor_phomotopy
end,
have π→[k] pdown.{v u} ∘ π→[k] (plift_functor f) ∘ π→[k] pup.{u v} ~ π→[k] f, from this,
apply is_equiv.homotopy_closed, rotate 1,
{ exact this},
{ do 2 apply is_equiv_compose,
{ apply is_equiv_homotopy_group_functor, apply to_is_equiv !equiv_lift},
{ refine @(is_equiv_π_of_is_connected' _ H2) _, apply is_conn_fun_lift_functor},
{ apply is_equiv_homotopy_group_functor, apply to_is_equiv !equiv_lift⁻¹ᵉ}}
end
definition π_equiv_π_of_is_connected {A B : Type*} {n k : ℕ} (f : A →* B)
(H2 : k ≤ n) [H : is_conn_fun n f] : π*[k] A ≃* π*[k] B :=
pequiv_of_pmap (π→*[k] f) (is_equiv_π_of_is_connected f H2)
-- TODO: prove this for A and B in different universe levels
theorem is_surjective_π_of_is_connected.{u} {A B : pType.{u}} (n : ℕ) (f : A →* B)
[H : is_conn_fun n f] : is_surjective (π→[n + 1] f) :=
@is_surjective_of_trivial _
(LES_of_homotopy_groups f) _
(is_exact_LES_of_homotopy_groups f (n, 2))
(@is_contr_HG_fiber_of_is_connected A B n n f H !le.refl)
/-
Theorem 8.8.3: Whitehead's principle
-/
definition whiteheads_principle (n : ℕ₋₂) {A B : Type}
[HA : is_trunc n A] [HB : is_trunc n B] (f : A → B) (H' : is_equiv (trunc_functor 0 f))
(H : Πa k, is_equiv (π→*[k + 1] (pmap_of_map f a))) : is_equiv f :=
begin
revert A B HA HB f H' H, induction n with n IH: intros,
{ apply is_equiv_of_is_contr},
have Πa, is_equiv (Ω→ (pmap_of_map f a)),
begin
intro a,
apply IH, do 2 (esimp; exact _),
{ rexact H a 0},
intro p k,
have is_equiv (π→*[k + 1] (Ω→(pmap_of_map f a))),
from is_equiv_phomotopy_group_functor_ap1 (k+1) (pmap_of_map f a),
have Π(b : A) (p : a = b),
is_equiv (pmap.to_fun (π→*[k + 1] (pmap_of_map (ap f) p))),
begin
intro b p, induction p, apply is_equiv.homotopy_closed, exact this,
refine phomotopy_group_functor_phomotopy _ _,
apply ap1_pmap_of_map
end,
have is_equiv (phomotopy_group_pequiv _
(pequiv_of_eq_pt (!idp_con⁻¹ : ap f p = Ω→ (pmap_of_map f a) p)) ∘
pmap.to_fun (π→*[k + 1] (pmap_of_map (ap f) p))),
begin
apply is_equiv_compose, exact this a p,
end,
apply is_equiv.homotopy_closed, exact this,
refine !phomotopy_group_functor_compose⁻¹* ⬝* _,
apply phomotopy_group_functor_phomotopy,
fapply phomotopy.mk,
{ esimp, intro q, refine !idp_con⁻¹},
{ esimp, refine !idp_con⁻¹},
end,
apply is_equiv_of_is_equiv_ap1_of_is_equiv_trunc
end
end is_trunc
|
647000c956a4dfd4dd5ac2925e61a1b44e0ea46e | 5e3548e65f2c037cb94cd5524c90c623fbd6d46a | /src_icannos_totilas/reduction/cpge_reduction_013.lean | e9cc2449819e82c61ee1a085ced9ed055b150449 | [] | no_license | ahayat16/lean_exos | d4f08c30adb601a06511a71b5ffb4d22d12ef77f | 682f2552d5b04a8c8eb9e4ab15f875a91b03845c | refs/heads/main | 1,693,101,073,585 | 1,636,479,336,000 | 1,636,479,336,000 | 415,000,441 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 321 | lean | import data.real.basic
import data.polynomial.derivative
-- Soit D : P → P' l'endomorphisme de dérivation sur R[X] . Existe-t-il un
-- endomorphisme ∆ de R[X] tel que ∆^2 = D ?
theorem exo: forall (Delta: polynomial real →ₗ[real] polynomial real), Delta.comp Delta = polynomial.derivative -> false := sorry
|
866e186e18704c1780eeceb117a57db0830c69b8 | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/algebra/order/with_zero.lean | 19bc6254206714dc6131ba2d6dfc45cf8f99c721 | [
"Apache-2.0"
] | permissive | jumpy4/mathlib | d3829e75173012833e9f15ac16e481e17596de0f | af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13 | refs/heads/master | 1,693,508,842,818 | 1,636,203,271,000 | 1,636,203,271,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,705 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Johan Commelin, Patrick Massot
-/
import algebra.order.group
import algebra.group_with_zero
import algebra.group_with_zero.power
import tactic.abel
/-!
# Linearly ordered commutative groups and monoids with a zero element adjoined
This file sets up a special class of linearly ordered commutative monoids
that show up as the target of so-called “valuations” in algebraic number theory.
Usually, in the informal literature, these objects are constructed
by taking a linearly ordered commutative group Γ and formally adjoining a zero element: Γ ∪ {0}.
The disadvantage is that a type such as `nnreal` is not of that form,
whereas it is a very common target for valuations.
The solutions is to use a typeclass, and that is exactly what we do in this file.
Note that to avoid issues with import cycles, `linear_ordered_comm_monoid_with_zero` is defined
in another file. However, the lemmas about it are stated here.
-/
set_option old_structure_cmd true
/-- A linearly ordered commutative group with a zero element. -/
class linear_ordered_comm_group_with_zero (α : Type*)
extends linear_ordered_comm_monoid_with_zero α, comm_group_with_zero α
variables {α : Type*}
variables {a b c d x y z : α}
instance [linear_ordered_add_comm_monoid_with_top α] :
linear_ordered_comm_monoid_with_zero (multiplicative (order_dual α)) :=
{ zero := multiplicative.of_add (⊤ : α),
zero_mul := top_add,
mul_zero := add_top,
zero_le_one := (le_top : (0 : α) ≤ ⊤),
..multiplicative.ordered_comm_monoid,
..multiplicative.linear_order }
instance [linear_ordered_add_comm_group_with_top α] :
linear_ordered_comm_group_with_zero (multiplicative (order_dual α)) :=
{ inv_zero := linear_ordered_add_comm_group_with_top.neg_top,
mul_inv_cancel := linear_ordered_add_comm_group_with_top.add_neg_cancel,
..multiplicative.div_inv_monoid,
..multiplicative.linear_ordered_comm_monoid_with_zero,
..multiplicative.nontrivial }
instance [linear_ordered_comm_monoid α] :
linear_ordered_comm_monoid_with_zero (with_zero α) :=
{ mul_le_mul_left := λ x y, mul_le_mul_left',
zero_le_one := with_zero.zero_le _,
..with_zero.linear_order,
..with_zero.comm_monoid_with_zero }
instance [linear_ordered_comm_group α] :
linear_ordered_comm_group_with_zero (with_zero α) :=
{ ..with_zero.linear_ordered_comm_monoid_with_zero,
..with_zero.comm_group_with_zero }
section linear_ordered_comm_monoid
variables [linear_ordered_comm_monoid_with_zero α]
/-
The following facts are true more generally in a (linearly) ordered commutative monoid.
-/
/-- Pullback a `linear_ordered_comm_monoid_with_zero` under an injective map.
See note [reducible non-instances]. -/
@[reducible]
def function.injective.linear_ordered_comm_monoid_with_zero {β : Type*}
[has_zero β] [has_one β] [has_mul β]
(f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
linear_ordered_comm_monoid_with_zero β :=
{ zero_le_one := show f 0 ≤ f 1, by simp only [zero, one,
linear_ordered_comm_monoid_with_zero.zero_le_one],
..linear_order.lift f hf,
..hf.ordered_comm_monoid f one mul,
..hf.comm_monoid_with_zero f zero one mul }
lemma zero_le_one' : (0 : α) ≤ 1 :=
linear_ordered_comm_monoid_with_zero.zero_le_one
@[simp] lemma zero_le' : 0 ≤ a :=
by simpa only [mul_zero, mul_one] using mul_le_mul_left' (@zero_le_one' α _) a
@[simp] lemma not_lt_zero' : ¬a < 0 :=
not_lt_of_le zero_le'
@[simp] lemma le_zero_iff : a ≤ 0 ↔ a = 0 :=
⟨λ h, le_antisymm h zero_le', λ h, h ▸ le_refl _⟩
lemma zero_lt_iff : 0 < a ↔ a ≠ 0 :=
⟨ne_of_gt, λ h, lt_of_le_of_ne zero_le' h.symm⟩
lemma ne_zero_of_lt (h : b < a) : a ≠ 0 :=
λ h1, not_lt_zero' $ show b < 0, from h1 ▸ h
lemma pow_pos_iff [no_zero_divisors α] {n : ℕ} (hn : 0 < n) : 0 < a ^ n ↔ 0 < a :=
by simp_rw [zero_lt_iff, pow_ne_zero_iff hn]
instance : linear_ordered_add_comm_monoid_with_top (additive (order_dual α)) :=
{ top := (0 : α),
top_add' := λ a, (zero_mul a : (0 : α) * a = 0),
le_top := λ _, zero_le',
..additive.ordered_add_comm_monoid,
..additive.linear_order }
end linear_ordered_comm_monoid
variables [linear_ordered_comm_group_with_zero α]
lemma zero_lt_one₀ : (0 : α) < 1 :=
lt_of_le_of_ne zero_le_one' zero_ne_one
lemma le_of_le_mul_right (h : c ≠ 0) (hab : a * c ≤ b * c) : a ≤ b :=
by simpa only [mul_inv_cancel_right₀ h] using (mul_le_mul_right' hab c⁻¹)
lemma le_mul_inv_of_mul_le (h : c ≠ 0) (hab : a * c ≤ b) : a ≤ b * c⁻¹ :=
le_of_le_mul_right h (by simpa [h] using hab)
lemma mul_inv_le_of_le_mul (h : c ≠ 0) (hab : a ≤ b * c) : a * c⁻¹ ≤ b :=
le_of_le_mul_right h (by simpa [h] using hab)
lemma div_le_div₀ (a b c d : α) (hb : b ≠ 0) (hd : d ≠ 0) :
a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b :=
if ha : a = 0 then by simp [ha] else
if hc : c = 0 then by simp [inv_ne_zero hb, hc, hd] else
show (units.mk0 a ha) * (units.mk0 b hb)⁻¹ ≤ (units.mk0 c hc) * (units.mk0 d hd)⁻¹ ↔
(units.mk0 a ha) * (units.mk0 d hd) ≤ (units.mk0 c hc) * (units.mk0 b hb),
from mul_inv_le_mul_inv_iff'
@[simp] lemma units.zero_lt (u : units α) : (0 : α) < u :=
zero_lt_iff.2 $ u.ne_zero
lemma mul_lt_mul_of_lt_of_le₀ (hab : a ≤ b) (hb : b ≠ 0) (hcd : c < d) : a * c < b * d :=
have hd : d ≠ 0 := ne_zero_of_lt hcd,
if ha : a = 0 then by { rw [ha, zero_mul, zero_lt_iff], exact mul_ne_zero hb hd } else
if hc : c = 0 then by { rw [hc, mul_zero, zero_lt_iff], exact mul_ne_zero hb hd } else
show (units.mk0 a ha) * (units.mk0 c hc) < (units.mk0 b hb) * (units.mk0 d hd),
from mul_lt_mul_of_le_of_lt hab hcd
lemma mul_lt_mul₀ (hab : a < b) (hcd : c < d) : a * c < b * d :=
mul_lt_mul_of_lt_of_le₀ hab.le (ne_zero_of_lt hab) hcd
lemma mul_inv_lt_of_lt_mul₀ (h : x < y * z) : x * z⁻¹ < y :=
have hz : z ≠ 0 := (mul_ne_zero_iff.1 $ ne_zero_of_lt h).2,
by { contrapose! h, simpa only [inv_inv₀] using mul_inv_le_of_le_mul (inv_ne_zero hz) h }
lemma inv_mul_lt_of_lt_mul₀ (h : x < y * z) : y⁻¹ * x < z :=
by { rw mul_comm at *, exact mul_inv_lt_of_lt_mul₀ h }
lemma mul_lt_right₀ (c : α) (h : a < b) (hc : c ≠ 0) : a * c < b * c :=
by { contrapose! h, exact le_of_le_mul_right hc h }
lemma pow_lt_pow_succ {x : α} {n : ℕ} (hx : 1 < x) : x ^ n < x ^ n.succ :=
by { rw [← one_mul (x ^ n), pow_succ],
exact mul_lt_right₀ _ hx (pow_ne_zero _ $ ne_of_gt (lt_trans zero_lt_one₀ hx)) }
lemma pow_lt_pow₀ {x : α} {m n : ℕ} (hx : 1 < x) (hmn : m < n) : x ^ m < x ^ n :=
by { induction hmn with n hmn ih, exacts [pow_lt_pow_succ hx, lt_trans ih (pow_lt_pow_succ hx)] }
lemma inv_lt_inv₀ (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ < b⁻¹ ↔ b < a :=
show (units.mk0 a ha)⁻¹ < (units.mk0 b hb)⁻¹ ↔ (units.mk0 b hb) < (units.mk0 a ha),
from inv_lt_inv_iff
lemma inv_le_inv₀ (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a :=
show (units.mk0 a ha)⁻¹ ≤ (units.mk0 b hb)⁻¹ ↔ (units.mk0 b hb) ≤ (units.mk0 a ha),
from inv_le_inv_iff
lemma lt_of_mul_lt_mul_of_le₀ (h : a * b < c * d) (hc : 0 < c) (hh : c ≤ a) : b < d :=
begin
have ha : a ≠ 0 := ne_of_gt (lt_of_lt_of_le hc hh),
simp_rw ← inv_le_inv₀ ha (ne_of_gt hc) at hh,
have := mul_lt_mul_of_lt_of_le₀ hh (inv_ne_zero (ne_of_gt hc)) h,
simpa [inv_mul_cancel_left₀ ha, inv_mul_cancel_left₀ (ne_of_gt hc)] using this,
end
instance : linear_ordered_add_comm_group_with_top (additive (order_dual α)) :=
{ neg_top := inv_zero,
add_neg_cancel := λ a ha, mul_inv_cancel ha,
..additive.sub_neg_monoid,
..additive.linear_ordered_add_comm_monoid_with_top,
..additive.nontrivial }
namespace monoid_hom
variables {R : Type*} [ring R] (f : R →* α)
theorem map_neg_one : f (-1) = 1 :=
(pow_eq_one_iff (nat.succ_ne_zero 1)).1 $
calc f (-1) ^ 2 = f (-1) * f(-1) : sq _
... = f ((-1) * - 1) : (f.map_mul _ _).symm
... = f ( - - 1) : congr_arg _ (neg_one_mul _)
... = f 1 : congr_arg _ (neg_neg _)
... = 1 : map_one f
@[simp] lemma map_neg (x : R) : f (-x) = f x :=
calc f (-x) = f (-1 * x) : congr_arg _ (neg_one_mul _).symm
... = f (-1) * f x : map_mul _ _ _
... = 1 * f x : _root_.congr_arg (λ g, g * (f x)) (map_neg_one f)
... = f x : one_mul _
lemma map_sub_swap (x y : R) : f (x - y) = f (y - x) :=
calc f (x - y) = f (-(y - x)) : congr_arg _ (neg_sub _ _).symm
... = _ : map_neg _ _
end monoid_hom
|
fbd533fca3b2132a7b0822403c69370c14d5057f | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Compiler/IR/NormIds.lean | 624e34982b69fe443ca0f7b21da971059364e38a | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 7,451 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Compiler.IR.Basic
namespace Lean.IR.UniqueIds
abbrev M := StateT IndexSet Id
def checkId (id : Index) : M Bool :=
modifyGet fun s =>
if s.contains id then (false, s)
else (true, s.insert id)
def checkParams (ps : Array Param) : M Bool :=
ps.allM fun p => checkId p.x.idx
partial def checkFnBody : FnBody → M Bool
| .vdecl x _ _ b => checkId x.idx <&&> checkFnBody b
| .jdecl j ys _ b => checkId j.idx <&&> checkParams ys <&&> checkFnBody b
| .case _ _ _ alts => alts.allM fun alt => checkFnBody alt.body
| b => if b.isTerminal then pure true else checkFnBody b.body
partial def checkDecl : Decl → M Bool
| .fdecl (xs := xs) (body := b) .. => checkParams xs <&&> checkFnBody b
| .extern (xs := xs) .. => checkParams xs
end UniqueIds
/-- Return true if variable, parameter and join point ids are unique -/
def Decl.uniqueIds (d : Decl) : Bool :=
(UniqueIds.checkDecl d).run' {}
namespace NormalizeIds
abbrev M := ReaderT IndexRenaming Id
def normIndex (x : Index) : M Index := fun m =>
match m.find? x with
| some y => y
| none => x
def normVar (x : VarId) : M VarId :=
VarId.mk <$> normIndex x.idx
def normJP (x : JoinPointId) : M JoinPointId :=
JoinPointId.mk <$> normIndex x.idx
def normArg : Arg → M Arg
| Arg.var x => Arg.var <$> normVar x
| other => pure other
def normArgs (as : Array Arg) : M (Array Arg) := fun m =>
as.map fun a => normArg a m
def normExpr : Expr → M Expr
| Expr.ctor c ys, m => Expr.ctor c (normArgs ys m)
| Expr.reset n x, m => Expr.reset n (normVar x m)
| Expr.reuse x c u ys, m => Expr.reuse (normVar x m) c u (normArgs ys m)
| Expr.proj i x, m => Expr.proj i (normVar x m)
| Expr.uproj i x, m => Expr.uproj i (normVar x m)
| Expr.sproj n o x, m => Expr.sproj n o (normVar x m)
| Expr.fap c ys, m => Expr.fap c (normArgs ys m)
| Expr.pap c ys, m => Expr.pap c (normArgs ys m)
| Expr.ap x ys, m => Expr.ap (normVar x m) (normArgs ys m)
| Expr.box t x, m => Expr.box t (normVar x m)
| Expr.unbox x, m => Expr.unbox (normVar x m)
| Expr.isShared x, m => Expr.isShared (normVar x m)
| e@(Expr.lit _), _ => e
abbrev N := ReaderT IndexRenaming (StateM Nat)
@[inline] def withVar {α : Type} (x : VarId) (k : VarId → N α) : N α := fun m => do
let n ← getModify (fun n => n + 1)
k { idx := n } (m.insert x.idx n)
@[inline] def withJP {α : Type} (x : JoinPointId) (k : JoinPointId → N α) : N α := fun m => do
let n ← getModify (fun n => n + 1)
k { idx := n } (m.insert x.idx n)
@[inline] def withParams {α : Type} (ps : Array Param) (k : Array Param → N α) : N α := fun m => do
let m ← ps.foldlM (init := m) fun m p => do
let n ← getModify fun n => n + 1
return m.insert p.x.idx n
let ps := ps.map fun p => { p with x := normVar p.x m }
k ps m
instance : MonadLift M N :=
⟨fun x m => return x m⟩
partial def normFnBody : FnBody → N FnBody
| FnBody.vdecl x t v b => do let v ← normExpr v; withVar x fun x => return FnBody.vdecl x t v (← normFnBody b)
| FnBody.jdecl j ys v b => do
let (ys, v) ← withParams ys fun ys => do let v ← normFnBody v; pure (ys, v)
withJP j fun j => return FnBody.jdecl j ys v (← normFnBody b)
| FnBody.set x i y b => return FnBody.set (← normVar x) i (← normArg y) (← normFnBody b)
| FnBody.uset x i y b => return FnBody.uset (← normVar x) i (← normVar y) (← normFnBody b)
| FnBody.sset x i o y t b => return FnBody.sset (← normVar x) i o (← normVar y) t (← normFnBody b)
| FnBody.setTag x i b => return FnBody.setTag (← normVar x) i (← normFnBody b)
| FnBody.inc x n c p b => return FnBody.inc (← normVar x) n c p (← normFnBody b)
| FnBody.dec x n c p b => return FnBody.dec (← normVar x) n c p (← normFnBody b)
| FnBody.del x b => return FnBody.del (← normVar x) (← normFnBody b)
| FnBody.mdata d b => return FnBody.mdata d (← normFnBody b)
| FnBody.case tid x xType alts => do
let x ← normVar x
let alts ← alts.mapM fun alt => alt.mmodifyBody normFnBody
return FnBody.case tid x xType alts
| FnBody.jmp j ys => return FnBody.jmp (← normJP j) (← normArgs ys)
| FnBody.ret x => return FnBody.ret (← normArg x)
| FnBody.unreachable => pure FnBody.unreachable
def normDecl (d : Decl) : N Decl :=
match d with
| Decl.fdecl (xs := xs) (body := b) .. => withParams xs fun _ => return d.updateBody! (← normFnBody b)
| other => pure other
end NormalizeIds
/-- Create a declaration equivalent to `d` s.t. `d.normalizeIds.uniqueIds == true` -/
def Decl.normalizeIds (d : Decl) : Decl :=
(NormalizeIds.normDecl d {}).run' 1
/-! Apply a function `f : VarId → VarId` to variable occurrences.
The following functions assume the IR code does not have variable shadowing. -/
namespace MapVars
@[inline] def mapArg (f : VarId → VarId) : Arg → Arg
| Arg.var x => Arg.var (f x)
| a => a
def mapArgs (f : VarId → VarId) (as : Array Arg) : Array Arg :=
as.map (mapArg f)
def mapExpr (f : VarId → VarId) : Expr → Expr
| Expr.ctor c ys => Expr.ctor c (mapArgs f ys)
| Expr.reset n x => Expr.reset n (f x)
| Expr.reuse x c u ys => Expr.reuse (f x) c u (mapArgs f ys)
| Expr.proj i x => Expr.proj i (f x)
| Expr.uproj i x => Expr.uproj i (f x)
| Expr.sproj n o x => Expr.sproj n o (f x)
| Expr.fap c ys => Expr.fap c (mapArgs f ys)
| Expr.pap c ys => Expr.pap c (mapArgs f ys)
| Expr.ap x ys => Expr.ap (f x) (mapArgs f ys)
| Expr.box t x => Expr.box t (f x)
| Expr.unbox x => Expr.unbox (f x)
| Expr.isShared x => Expr.isShared (f x)
| e@(Expr.lit _) => e
partial def mapFnBody (f : VarId → VarId) : FnBody → FnBody
| FnBody.vdecl x t v b => FnBody.vdecl x t (mapExpr f v) (mapFnBody f b)
| FnBody.jdecl j ys v b => FnBody.jdecl j ys (mapFnBody f v) (mapFnBody f b)
| FnBody.set x i y b => FnBody.set (f x) i (mapArg f y) (mapFnBody f b)
| FnBody.setTag x i b => FnBody.setTag (f x) i (mapFnBody f b)
| FnBody.uset x i y b => FnBody.uset (f x) i (f y) (mapFnBody f b)
| FnBody.sset x i o y t b => FnBody.sset (f x) i o (f y) t (mapFnBody f b)
| FnBody.inc x n c p b => FnBody.inc (f x) n c p (mapFnBody f b)
| FnBody.dec x n c p b => FnBody.dec (f x) n c p (mapFnBody f b)
| FnBody.del x b => FnBody.del (f x) (mapFnBody f b)
| FnBody.mdata d b => FnBody.mdata d (mapFnBody f b)
| FnBody.case tid x xType alts => FnBody.case tid (f x) xType (alts.map fun alt => alt.modifyBody (mapFnBody f))
| FnBody.jmp j ys => FnBody.jmp j (mapArgs f ys)
| FnBody.ret x => FnBody.ret (mapArg f x)
| FnBody.unreachable => FnBody.unreachable
end MapVars
@[inline] def FnBody.mapVars (f : VarId → VarId) (b : FnBody) : FnBody :=
MapVars.mapFnBody f b
/-- Replace `x` with `y` in `b`. This function assumes `b` does not shadow `x` -/
def FnBody.replaceVar (x y : VarId) (b : FnBody) : FnBody :=
b.mapVars fun z => if x == z then y else z
end Lean.IR
|
49f59818330f652da5e2295c3ed8d46e535002bb | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/group_theory/submonoid/pointwise.lean | db1c25a50e1176d8e3aa2b7a411594bfc5f6a2ad | [
"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 | 21,058 | lean | /-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import data.set.pointwise.smul
import group_theory.submonoid.membership
import order.well_founded_set
/-! # Pointwise instances on `submonoid`s and `add_submonoid`s
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file provides:
* `submonoid.has_inv`
* `add_submonoid.has_neg`
and the actions
* `submonoid.pointwise_mul_action`
* `add_submonoid.pointwise_mul_action`
which matches the action of `mul_action_set`.
These are all available in the `pointwise` locale.
Additionally, it provides various degrees of monoid structure:
* `add_submonoid.has_one`
* `add_submonoid.has_mul`
* `add_submonoid.mul_one_class`
* `add_submonoid.semigroup`
* `add_submonoid.monoid`
which is available globally to match the monoid structure implied by `submodule.idem_semiring`.
## Implementation notes
Most of the lemmas in this file are direct copies of lemmas from `algebra/pointwise.lean`.
While the statements of these lemmas are defeq, we repeat them here due to them not being
syntactically equal. Before adding new lemmas here, consider if they would also apply to the action
on `set`s.
-/
open set
variables {α : Type*} {G : Type*} {M : Type*} {R : Type*} {A : Type*}
variables [monoid M] [add_monoid A]
/-! Some lemmas about pointwise multiplication and submonoids. Ideally we put these in
`group_theory.submonoid.basic`, but currently we cannot because that file is imported by this. -/
namespace submonoid
open_locale pointwise
variables {s t u : set M}
@[to_additive]
lemma mul_subset {S : submonoid M} (hs : s ⊆ S) (ht : t ⊆ S) : s * t ⊆ S :=
by { rintro _ ⟨p, q, hp, hq, rfl⟩, exact submonoid.mul_mem _ (hs hp) (ht hq) }
@[to_additive]
lemma mul_subset_closure (hs : s ⊆ u) (ht : t ⊆ u) : s * t ⊆ submonoid.closure u :=
mul_subset (subset.trans hs submonoid.subset_closure) (subset.trans ht submonoid.subset_closure)
@[to_additive]
lemma coe_mul_self_eq (s : submonoid M) : (s : set M) * s = s :=
begin
ext x,
refine ⟨_, λ h, ⟨x, 1, h, s.one_mem, mul_one x⟩⟩,
rintro ⟨a, b, ha, hb, rfl⟩,
exact s.mul_mem ha hb
end
@[to_additive]
lemma closure_mul_le (S T : set M) : closure (S * T) ≤ closure S ⊔ closure T :=
Inf_le $ λ x ⟨s, t, hs, ht, hx⟩, hx ▸ (closure S ⊔ closure T).mul_mem
(set_like.le_def.mp le_sup_left $ subset_closure hs)
(set_like.le_def.mp le_sup_right $ subset_closure ht)
@[to_additive]
lemma sup_eq_closure (H K : submonoid M) : H ⊔ K = closure (H * K) :=
le_antisymm
(sup_le
(λ h hh, subset_closure ⟨h, 1, hh, K.one_mem, mul_one h⟩)
(λ k hk, subset_closure ⟨1, k, H.one_mem, hk, one_mul k⟩))
(by conv_rhs { rw [← closure_eq H, ← closure_eq K] }; apply closure_mul_le)
@[to_additive]
lemma pow_smul_mem_closure_smul {N : Type*} [comm_monoid N] [mul_action M N]
[is_scalar_tower M N N] (r : M) (s : set N) {x : N} (hx : x ∈ closure s) :
∃ n : ℕ, r ^ n • x ∈ closure (r • s) :=
begin
apply @closure_induction N _ s
(λ (x : N), ∃ n : ℕ, r ^ n • x ∈ closure (r • s)) _ hx,
{ intros x hx,
exact ⟨1, subset_closure ⟨_, hx, by rw pow_one⟩⟩ },
{ exact ⟨0, by simpa using one_mem _⟩ },
{ rintro x y ⟨nx, hx⟩ ⟨ny, hy⟩,
use nx + ny,
convert mul_mem hx hy,
rw [pow_add, smul_mul_assoc, mul_smul, mul_comm, ← smul_mul_assoc, mul_comm] }
end
variables [group G]
open_locale pointwise
/-- The submonoid with every element inverted. -/
@[to_additive /-" The additive submonoid with every element negated. "-/]
protected def has_inv : has_inv (submonoid G) :=
{ inv := λ S,
{ carrier := (S : set G)⁻¹,
one_mem' := show (1 : G)⁻¹ ∈ S, by { rw inv_one, exact S.one_mem },
mul_mem' := λ a b (ha : a⁻¹ ∈ S) (hb : b⁻¹ ∈ S), show (a * b)⁻¹ ∈ S,
by { rw mul_inv_rev, exact S.mul_mem hb ha } } }
localized "attribute [instance] submonoid.has_inv" in pointwise
open_locale pointwise
@[simp, to_additive] lemma coe_inv (S : submonoid G) : ↑(S⁻¹) = (S : set G)⁻¹ := rfl
@[simp, to_additive] lemma mem_inv {g : G} {S : submonoid G} : g ∈ S⁻¹ ↔ g⁻¹ ∈ S := iff.rfl
@[to_additive] instance : has_involutive_inv (submonoid G) :=
set_like.coe_injective.has_involutive_inv _ $ λ _, rfl
@[simp, to_additive] lemma inv_le_inv (S T : submonoid G) : S⁻¹ ≤ T⁻¹ ↔ S ≤ T :=
set_like.coe_subset_coe.symm.trans set.inv_subset_inv
@[to_additive] lemma inv_le (S T : submonoid G) : S⁻¹ ≤ T ↔ S ≤ T⁻¹ :=
set_like.coe_subset_coe.symm.trans set.inv_subset
/-- `submonoid.has_inv` as an order isomorphism. -/
@[to_additive /-" `add_submonoid.has_neg` as an order isomorphism "-/, simps]
def inv_order_iso : submonoid G ≃o submonoid G :=
{ to_equiv := equiv.inv _,
map_rel_iff' := inv_le_inv }
@[to_additive] lemma closure_inv (s : set G) : closure s⁻¹ = (closure s)⁻¹ :=
begin
apply le_antisymm,
{ rw [closure_le, coe_inv, ←set.inv_subset, inv_inv],
exact subset_closure },
{ rw [inv_le, closure_le, coe_inv, ←set.inv_subset],
exact subset_closure }
end
@[simp, to_additive]
lemma inv_inf (S T : submonoid G) : (S ⊓ T)⁻¹ = S⁻¹ ⊓ T⁻¹ :=
set_like.coe_injective set.inter_inv
@[simp, to_additive]
lemma inv_sup (S T : submonoid G) : (S ⊔ T)⁻¹ = S⁻¹ ⊔ T⁻¹ :=
(inv_order_iso : submonoid G ≃o submonoid G).map_sup S T
@[simp, to_additive]
lemma inv_bot : (⊥ : submonoid G)⁻¹ = ⊥ :=
set_like.coe_injective $ (set.inv_singleton 1).trans $ congr_arg _ inv_one
@[simp, to_additive]
lemma inv_top : (⊤ : submonoid G)⁻¹ = ⊤ :=
set_like.coe_injective $ set.inv_univ
@[simp, to_additive]
lemma inv_infi {ι : Sort*} (S : ι → submonoid G) : (⨅ i, S i)⁻¹ = ⨅ i, (S i)⁻¹ :=
(inv_order_iso : submonoid G ≃o submonoid G).map_infi _
@[simp, to_additive]
lemma inv_supr {ι : Sort*} (S : ι → submonoid G) : (⨆ i, S i)⁻¹ = ⨆ i, (S i)⁻¹ :=
(inv_order_iso : submonoid G ≃o submonoid G).map_supr _
end submonoid
namespace submonoid
section monoid
variables [monoid α] [mul_distrib_mul_action α M]
/-- The action on a submonoid corresponding to applying the action to every element.
This is available as an instance in the `pointwise` locale. -/
protected def pointwise_mul_action : mul_action α (submonoid M) :=
{ smul := λ a S, S.map (mul_distrib_mul_action.to_monoid_End _ M a),
one_smul := λ S, by { ext, simp, },
mul_smul := λ a₁ a₂ S,
(congr_arg (λ f : monoid.End M, S.map f) (monoid_hom.map_mul _ _ _)).trans
(S.map_map _ _).symm,}
localized "attribute [instance] submonoid.pointwise_mul_action" in pointwise
open_locale pointwise
@[simp] lemma coe_pointwise_smul (a : α) (S : submonoid M) : ↑(a • S) = a • (S : set M) := rfl
lemma smul_mem_pointwise_smul (m : M) (a : α) (S : submonoid M) : m ∈ S → a • m ∈ a • S :=
(set.smul_mem_smul_set : _ → _ ∈ a • (S : set M))
lemma mem_smul_pointwise_iff_exists (m : M) (a : α) (S : submonoid M) :
m ∈ a • S ↔ ∃ (s : M), s ∈ S ∧ a • s = m :=
(set.mem_smul_set : m ∈ a • (S : set M) ↔ _)
@[simp] lemma smul_bot (a : α) : a • (⊥ : submonoid M) = ⊥ := map_bot _
lemma smul_sup (a : α) (S T : submonoid M) : a • (S ⊔ T) = a • S ⊔ a • T := map_sup _ _ _
lemma smul_closure (a : α) (s : set M) : a • closure s = closure (a • s) :=
monoid_hom.map_mclosure _ _
instance pointwise_central_scalar [mul_distrib_mul_action αᵐᵒᵖ M] [is_central_scalar α M] :
is_central_scalar α (submonoid M) :=
⟨λ a S, congr_arg (λ f : monoid.End M, S.map f) $ monoid_hom.ext $ by exact op_smul_eq_smul _⟩
end monoid
section group
variables [group α] [mul_distrib_mul_action α M]
open_locale pointwise
@[simp] lemma smul_mem_pointwise_smul_iff {a : α} {S : submonoid M} {x : M} :
a • x ∈ a • S ↔ x ∈ S :=
smul_mem_smul_set_iff
lemma mem_pointwise_smul_iff_inv_smul_mem {a : α} {S : submonoid M} {x : M} :
x ∈ a • S ↔ a⁻¹ • x ∈ S :=
mem_smul_set_iff_inv_smul_mem
lemma mem_inv_pointwise_smul_iff {a : α} {S : submonoid M} {x : M} : x ∈ a⁻¹ • S ↔ a • x ∈ S :=
mem_inv_smul_set_iff
@[simp] lemma pointwise_smul_le_pointwise_smul_iff {a : α} {S T : submonoid M} :
a • S ≤ a • T ↔ S ≤ T :=
set_smul_subset_set_smul_iff
lemma pointwise_smul_subset_iff {a : α} {S T : submonoid M} : a • S ≤ T ↔ S ≤ a⁻¹ • T :=
set_smul_subset_iff
lemma subset_pointwise_smul_iff {a : α} {S T : submonoid M} : S ≤ a • T ↔ a⁻¹ • S ≤ T :=
subset_set_smul_iff
end group
section group_with_zero
variables [group_with_zero α] [mul_distrib_mul_action α M]
open_locale pointwise
@[simp] lemma smul_mem_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) (S : submonoid M)
(x : M) : a • x ∈ a • S ↔ x ∈ S :=
smul_mem_smul_set_iff₀ ha (S : set M) x
lemma mem_pointwise_smul_iff_inv_smul_mem₀ {a : α} (ha : a ≠ 0) (S : submonoid M) (x : M) :
x ∈ a • S ↔ a⁻¹ • x ∈ S :=
mem_smul_set_iff_inv_smul_mem₀ ha (S : set M) x
lemma mem_inv_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) (S : submonoid M) (x : M) :
x ∈ a⁻¹ • S ↔ a • x ∈ S :=
mem_inv_smul_set_iff₀ ha (S : set M) x
@[simp] lemma pointwise_smul_le_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) {S T : submonoid M} :
a • S ≤ a • T ↔ S ≤ T :=
set_smul_subset_set_smul_iff₀ ha
lemma pointwise_smul_le_iff₀ {a : α} (ha : a ≠ 0) {S T : submonoid M} : a • S ≤ T ↔ S ≤ a⁻¹ • T :=
set_smul_subset_iff₀ ha
lemma le_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) {S T : submonoid M} : S ≤ a • T ↔ a⁻¹ • S ≤ T :=
subset_set_smul_iff₀ ha
end group_with_zero
open_locale pointwise
@[to_additive]
lemma mem_closure_inv {G : Type*} [group G] (S : set G) (x : G) :
x ∈ submonoid.closure S⁻¹ ↔ x⁻¹ ∈ submonoid.closure S :=
by rw [closure_inv, mem_inv]
end submonoid
namespace add_submonoid
section monoid
variables [monoid α] [distrib_mul_action α A]
/-- The action on an additive submonoid corresponding to applying the action to every element.
This is available as an instance in the `pointwise` locale. -/
protected def pointwise_mul_action : mul_action α (add_submonoid A) :=
{ smul := λ a S, S.map (distrib_mul_action.to_add_monoid_End _ A a),
one_smul := λ S, (congr_arg (λ f : add_monoid.End A, S.map f)
(monoid_hom.map_one _)).trans S.map_id,
mul_smul := λ a₁ a₂ S,
(congr_arg (λ f : add_monoid.End A, S.map f) (monoid_hom.map_mul _ _ _)).trans
(S.map_map _ _).symm,}
localized "attribute [instance] add_submonoid.pointwise_mul_action" in pointwise
open_locale pointwise
@[simp] lemma coe_pointwise_smul (a : α) (S : add_submonoid A) : ↑(a • S) = a • (S : set A) := rfl
lemma smul_mem_pointwise_smul (m : A) (a : α) (S : add_submonoid A) : m ∈ S → a • m ∈ a • S :=
(set.smul_mem_smul_set : _ → _ ∈ a • (S : set A))
lemma mem_smul_pointwise_iff_exists (m : A) (a : α) (S : add_submonoid A) :
m ∈ a • S ↔ ∃ (s : A), s ∈ S ∧ a • s = m :=
(set.mem_smul_set : m ∈ a • (S : set A) ↔ _)
@[simp] lemma smul_bot (a : α) : a • (⊥ : add_submonoid A) = ⊥ := map_bot _
lemma smul_sup (a : α) (S T : add_submonoid A) : a • (S ⊔ T) = a • S ⊔ a • T := map_sup _ _ _
@[simp] lemma smul_closure (a : α) (s : set A) : a • closure s = closure (a • s) :=
add_monoid_hom.map_mclosure _ _
instance pointwise_central_scalar [distrib_mul_action αᵐᵒᵖ A] [is_central_scalar α A] :
is_central_scalar α (add_submonoid A) :=
⟨λ a S, congr_arg (λ f : add_monoid.End A, S.map f) $
add_monoid_hom.ext $ by exact op_smul_eq_smul _⟩
end monoid
section group
variables [group α] [distrib_mul_action α A]
open_locale pointwise
@[simp] lemma smul_mem_pointwise_smul_iff {a : α} {S : add_submonoid A} {x : A} :
a • x ∈ a • S ↔ x ∈ S :=
smul_mem_smul_set_iff
lemma mem_pointwise_smul_iff_inv_smul_mem {a : α} {S : add_submonoid A} {x : A} :
x ∈ a • S ↔ a⁻¹ • x ∈ S :=
mem_smul_set_iff_inv_smul_mem
lemma mem_inv_pointwise_smul_iff {a : α} {S : add_submonoid A} {x : A} : x ∈ a⁻¹ • S ↔ a • x ∈ S :=
mem_inv_smul_set_iff
@[simp] lemma pointwise_smul_le_pointwise_smul_iff {a : α} {S T : add_submonoid A} :
a • S ≤ a • T ↔ S ≤ T :=
set_smul_subset_set_smul_iff
lemma pointwise_smul_le_iff {a : α} {S T : add_submonoid A} : a • S ≤ T ↔ S ≤ a⁻¹ • T :=
set_smul_subset_iff
lemma le_pointwise_smul_iff {a : α} {S T : add_submonoid A} : S ≤ a • T ↔ a⁻¹ • S ≤ T :=
subset_set_smul_iff
end group
section group_with_zero
variables [group_with_zero α] [distrib_mul_action α A]
open_locale pointwise
@[simp] lemma smul_mem_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) (S : add_submonoid A)
(x : A) : a • x ∈ a • S ↔ x ∈ S :=
smul_mem_smul_set_iff₀ ha (S : set A) x
lemma mem_pointwise_smul_iff_inv_smul_mem₀ {a : α} (ha : a ≠ 0) (S : add_submonoid A) (x : A) :
x ∈ a • S ↔ a⁻¹ • x ∈ S :=
mem_smul_set_iff_inv_smul_mem₀ ha (S : set A) x
lemma mem_inv_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) (S : add_submonoid A) (x : A) :
x ∈ a⁻¹ • S ↔ a • x ∈ S :=
mem_inv_smul_set_iff₀ ha (S : set A) x
@[simp] lemma pointwise_smul_le_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) {S T : add_submonoid A} :
a • S ≤ a • T ↔ S ≤ T :=
set_smul_subset_set_smul_iff₀ ha
lemma pointwise_smul_le_iff₀ {a : α} (ha : a ≠ 0) {S T : add_submonoid A} :
a • S ≤ T ↔ S ≤ a⁻¹ • T :=
set_smul_subset_iff₀ ha
lemma le_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) {S T : add_submonoid A} :
S ≤ a • T ↔ a⁻¹ • S ≤ T :=
subset_set_smul_iff₀ ha
end group_with_zero
end add_submonoid
/-! ### Elementwise monoid structure of additive submonoids
These definitions are a cut-down versions of the ones around `submodule.has_mul`, as that API is
usually more useful. -/
namespace add_submonoid
open_locale pointwise
section add_monoid_with_one
variables [add_monoid_with_one R]
instance : has_one (add_submonoid R) :=
⟨(nat.cast_add_monoid_hom R).mrange⟩
theorem one_eq_mrange :
(1 : add_submonoid R) = (nat.cast_add_monoid_hom R).mrange := rfl
lemma nat_cast_mem_one (n : ℕ) : (n : R) ∈ (1 : add_submonoid R) := ⟨_, rfl⟩
@[simp] lemma mem_one {x : R} : x ∈ (1 : add_submonoid R) ↔ ∃ n : ℕ, ↑n = x := iff.rfl
theorem one_eq_closure : (1 : add_submonoid R) = closure {1} :=
begin
simp only [closure_singleton_eq, mul_one, one_eq_mrange],
congr' 1 with n,
simp,
end
theorem one_eq_closure_one_set : (1 : add_submonoid R) = closure 1 := one_eq_closure
end add_monoid_with_one
section non_unital_non_assoc_semiring
variables [non_unital_non_assoc_semiring R]
/-- Multiplication of additive submonoids of a semiring R. The additive submonoid `S * T` is the
smallest R-submodule of `R` containing the elements `s * t` for `s ∈ S` and `t ∈ T`. -/
instance : has_mul (add_submonoid R) :=
⟨λ M N, ⨆ s : M, N.map $ add_monoid_hom.mul s.1⟩
theorem mul_mem_mul {M N : add_submonoid R} {m n : R} (hm : m ∈ M) (hn : n ∈ N) : m * n ∈ M * N :=
(le_supr _ ⟨m, hm⟩ : _ ≤ M * N) ⟨n, hn, rfl⟩
theorem mul_le {M N P : add_submonoid R} : M * N ≤ P ↔ ∀ (m ∈ M) (n ∈ N), m * n ∈ P :=
⟨λ H m hm n hn, H $ mul_mem_mul hm hn,
λ H, supr_le $ λ ⟨m, hm⟩, map_le_iff_le_comap.2 $ λ n hn, H m hm n hn⟩
@[elab_as_eliminator] protected theorem mul_induction_on
{M N : add_submonoid R}
{C : R → Prop} {r : R} (hr : r ∈ M * N)
(hm : ∀ (m ∈ M) (n ∈ N), C (m * n))
(ha : ∀ x y, C x → C y → C (x + y)) : C r :=
(@mul_le _ _ _ _ ⟨C, ha, by simpa only [zero_mul] using hm _ (zero_mem _) _ (zero_mem _)⟩).2 hm hr
open_locale pointwise
-- this proof is copied directly from `submodule.span_mul_span`
theorem closure_mul_closure (S T : set R) : closure S * closure T = closure (S * T) :=
begin
apply le_antisymm,
{ rw mul_le, intros a ha b hb,
apply closure_induction ha,
work_on_goal 1 { intros, apply closure_induction hb,
work_on_goal 1 { intros, exact subset_closure ⟨_, _, ‹_›, ‹_›, rfl⟩ } },
all_goals { intros, simp only [mul_zero, zero_mul, zero_mem,
left_distrib, right_distrib, mul_smul_comm, smul_mul_assoc];
solve_by_elim [add_mem _ _, zero_mem _]
{ max_depth := 4, discharger := tactic.interactive.apply_instance } } },
{ rw closure_le, rintros _ ⟨a, b, ha, hb, rfl⟩,
exact mul_mem_mul (subset_closure ha) (subset_closure hb) }
end
lemma mul_eq_closure_mul_set (M N : add_submonoid R) : M * N = closure (M * N) :=
by rw [←closure_mul_closure, closure_eq, closure_eq]
@[simp] theorem mul_bot (S : add_submonoid R) : S * ⊥ = ⊥ :=
eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [add_submonoid.mem_bot] at hn ⊢; rw [hn, mul_zero]
@[simp] theorem bot_mul (S : add_submonoid R) : ⊥ * S = ⊥ :=
eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [add_submonoid.mem_bot] at hm ⊢; rw [hm, zero_mul]
@[mono] theorem mul_le_mul {M N P Q : add_submonoid R} (hmp : M ≤ P) (hnq : N ≤ Q) :
M * N ≤ P * Q :=
mul_le.2 $ λ m hm n hn, mul_mem_mul (hmp hm) (hnq hn)
theorem mul_le_mul_left {M N P : add_submonoid R} (h : M ≤ N) : M * P ≤ N * P :=
mul_le_mul h (le_refl P)
theorem mul_le_mul_right {M N P : add_submonoid R} (h : N ≤ P) : M * N ≤ M * P :=
mul_le_mul (le_refl M) h
lemma mul_subset_mul {M N : add_submonoid R} : (↑M : set R) * (↑N : set R) ⊆ (↑(M * N) : set R) :=
by { rintros _ ⟨i, j, hi, hj, rfl⟩, exact mul_mem_mul hi hj }
end non_unital_non_assoc_semiring
section non_unital_non_assoc_ring
variables [non_unital_non_assoc_ring R]
/-- `add_submonoid.has_pointwise_neg` distributes over multiplication.
This is available as an instance in the `pointwise` locale. -/
protected def has_distrib_neg : has_distrib_neg (add_submonoid R) :=
{ neg := has_neg.neg,
neg_mul := λ x y, begin
refine le_antisymm
(mul_le.2 $ λ m hm n hn, _)
((add_submonoid.neg_le _ _).2 $ mul_le.2 $ λ m hm n hn, _);
simp only [add_submonoid.mem_neg, ←neg_mul] at *,
{ exact mul_mem_mul hm hn },
{ exact mul_mem_mul (neg_mem_neg.2 hm) hn },
end,
mul_neg := λ x y, begin
refine le_antisymm
(mul_le.2 $ λ m hm n hn, _)
((add_submonoid.neg_le _ _).2 $ mul_le.2 $ λ m hm n hn, _);
simp only [add_submonoid.mem_neg, ←mul_neg] at *,
{ exact mul_mem_mul hm hn,},
{ exact mul_mem_mul hm (neg_mem_neg.2 hn) },
end,
..add_submonoid.has_involutive_neg }
localized "attribute [instance] add_submonoid.has_distrib_neg" in pointwise
end non_unital_non_assoc_ring
section non_assoc_semiring
variables [non_assoc_semiring R]
instance : mul_one_class (add_submonoid R) :=
{ one := 1,
mul := (*),
one_mul := λ M, by rw [one_eq_closure_one_set, ←closure_eq M, closure_mul_closure, one_mul],
mul_one := λ M, by rw [one_eq_closure_one_set, ←closure_eq M, closure_mul_closure, mul_one] }
end non_assoc_semiring
section non_unital_semiring
variables [non_unital_semiring R]
instance : semigroup (add_submonoid R) :=
{ mul := (*),
mul_assoc := λ M N P,
le_antisymm (mul_le.2 $ λ mn hmn p hp,
suffices M * N ≤ (M * (N * P)).comap (add_monoid_hom.mul_right p), from this hmn,
mul_le.2 $ λ m hm n hn, show m * n * p ∈ M * (N * P), from
(mul_assoc m n p).symm ▸ mul_mem_mul hm (mul_mem_mul hn hp))
(mul_le.2 $ λ m hm np hnp,
suffices N * P ≤ (M * N * P).comap (add_monoid_hom.mul_left m), from this hnp,
mul_le.2 $ λ n hn p hp, show m * (n * p) ∈ M * N * P, from
mul_assoc m n p ▸ mul_mem_mul (mul_mem_mul hm hn) hp) }
end non_unital_semiring
section semiring
variables [semiring R]
instance : monoid (add_submonoid R) :=
{ one := 1,
mul := (*),
..add_submonoid.semigroup,
..add_submonoid.mul_one_class }
lemma closure_pow (s : set R) : ∀ n : ℕ, closure s ^ n = closure (s ^ n)
| 0 := by rw [pow_zero, pow_zero, one_eq_closure_one_set]
| (n + 1) := by rw [pow_succ, pow_succ, closure_pow, closure_mul_closure]
lemma pow_eq_closure_pow_set (s : add_submonoid R) (n : ℕ) : s ^ n = closure ((s : set R) ^ n) :=
by rw [←closure_pow, closure_eq]
lemma pow_subset_pow {s : add_submonoid R} {n : ℕ} : (↑s : set R)^n ⊆ ↑(s^n) :=
(pow_eq_closure_pow_set s n).symm ▸ subset_closure
end semiring
end add_submonoid
namespace set.is_pwo
variables [ordered_cancel_comm_monoid α] {s : set α}
@[to_additive]
lemma submonoid_closure (hpos : ∀ x : α, x ∈ s → 1 ≤ x) (h : s.is_pwo) :
is_pwo ((submonoid.closure s) : set α) :=
begin
rw submonoid.closure_eq_image_prod,
refine (h.partially_well_ordered_on_sublist_forall₂ (≤)).image_of_monotone_on _,
exact λ l1 hl1 l2 hl2 h12, h12.prod_le_prod' (λ x hx, hpos x $ hl2 x hx)
end
end set.is_pwo
|
ce1d7c7afef8d19b021385ddf7bdb6ac3ba0f8c4 | 737dc4b96c97368cb66b925eeea3ab633ec3d702 | /stage0/src/Lean/Meta/DiscrTree.lean | 2f1ff9180e6f20beba10002ce6d5ea03140a63ea | [
"Apache-2.0"
] | permissive | Bioye97/lean4 | 1ace34638efd9913dc5991443777b01a08983289 | bc3900cbb9adda83eed7e6affeaade7cfd07716d | refs/heads/master | 1,690,589,820,211 | 1,631,051,000,000 | 1,631,067,598,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 20,183 | 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.Basic
import Lean.Meta.FunInfo
import Lean.Meta.InferType
import Lean.Meta.WHNF
namespace Lean.Meta.DiscrTree
/-
(Imperfect) discrimination trees.
We use a hybrid representation.
- A `PersistentHashMap` for the root node which usually contains many children.
- A sorted array of key/node pairs for inner nodes.
The edges are labeled by keys:
- Constant names (and arity). Universe levels are ignored.
- Free variables (and arity). Thus, an entry in the discrimination tree
may reference hypotheses from the local context.
- Literals
- Star/Wildcard. We use them to represent metavariables and terms
we want to ignore. We ignore implicit arguments and proofs.
- Other. We use to represent other kinds of terms (e.g., nested lambda, forall, sort, etc).
We reduce terms using `TransparencyMode.reducible`. Thus, all reducible
definitions in an expression `e` are unfolded before we insert it into the
discrimination tree.
Recall that projections from classes are **NOT** reducible.
For example, the expressions `Add.add α (ringAdd ?α ?s) ?x ?x`
and `Add.add Nat Nat.hasAdd a b` generates paths with the following keys
respctively
```
⟨Add.add, 4⟩, *, *, *, *
⟨Add.add, 4⟩, *, *, ⟨a,0⟩, ⟨b,0⟩
```
That is, we don't reduce `Add.add Nat inst a b` into `Nat.add a b`.
We say the `Add.add` applications are the de-facto canonical forms in
the metaprogramming framework.
Moreover, it is the metaprogrammer's responsibility to re-pack applications such as
`Nat.add a b` into `Add.add Nat inst a b`.
Remark: we store the arity in the keys
1- To be able to implement the "skip" operation when retrieving "candidate"
unifiers.
2- Distinguish partial applications `f a`, `f a b`, and `f a b c`.
-/
def Key.ctorIdx : Key → Nat
| Key.star => 0
| Key.other => 1
| Key.lit .. => 2
| Key.fvar .. => 3
| Key.const .. => 4
| Key.arrow => 5
| Key.proj .. => 6
def Key.lt : Key → Key → Bool
| Key.lit v₁, Key.lit v₂ => v₁ < v₂
| Key.fvar n₁ a₁, Key.fvar n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂)
| Key.const n₁ a₁, Key.const n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂)
| Key.proj s₁ i₁, Key.proj s₂ i₂ => Name.quickLt s₁ s₂ || (s₁ == s₂ && i₁ < i₂)
| k₁, k₂ => k₁.ctorIdx < k₂.ctorIdx
instance : LT Key := ⟨fun a b => Key.lt a b⟩
instance (a b : Key) : Decidable (a < b) := inferInstanceAs (Decidable (Key.lt a b))
def Key.format : Key → Format
| Key.star => "*"
| Key.other => "◾"
| Key.lit (Literal.natVal v) => Std.format v
| Key.lit (Literal.strVal v) => repr v
| Key.const k _ => Std.format k
| Key.proj s i => Std.format s ++ "." ++ Std.format i
| Key.fvar k _ => Std.format k
| Key.arrow => "→"
instance : ToFormat Key := ⟨Key.format⟩
def Key.arity : Key → Nat
| Key.const _ a => a
| Key.fvar _ a => a
| Key.arrow => 2
| Key.proj .. => 1
| _ => 0
instance : Inhabited (Trie α) := ⟨Trie.node #[] #[]⟩
def empty : DiscrTree α := { root := {} }
partial def Trie.format [ToFormat α] : Trie α → Format
| Trie.node vs cs => Format.group $ Format.paren $
"node" ++ (if vs.isEmpty then Format.nil else " " ++ Std.format vs)
++ Format.join (cs.toList.map $ fun ⟨k, c⟩ => Format.line ++ Format.paren (Std.format k ++ " => " ++ format c))
instance [ToFormat α] : ToFormat (Trie α) := ⟨Trie.format⟩
partial def format [ToFormat α] (d : DiscrTree α) : Format :=
let (_, r) := d.root.foldl
(fun (p : Bool × Format) k c =>
(false, p.2 ++ (if p.1 then Format.nil else Format.line) ++ Format.paren (Std.format k ++ " => " ++ Std.format c)))
(true, Format.nil)
Format.group r
instance [ToFormat α] : ToFormat (DiscrTree α) := ⟨format⟩
/- The discrimination tree ignores implicit arguments and proofs.
We use the following auxiliary id as a "mark". -/
private def tmpMVarId : MVarId := `_discr_tree_tmp
private def tmpStar := mkMVar tmpMVarId
instance : Inhabited (DiscrTree α) where
default := {}
/--
Return true iff the argument should be treated as a "wildcard" by the discrimination tree.
- We ignore proofs because of proof irrelevance. It doesn't make sense to try to
index their structure.
- We ignore instance implicit arguments (e.g., `[Add α]`) because they are "morally" canonical.
Moreover, we may have many definitionally equal terms floating around.
Example: `Ring.hasAdd Int Int.isRing` and `Int.hasAdd`.
- We considered ignoring implicit arguments (e.g., `{α : Type}`) since users don't "see" them,
and may not even understand why some simplification rule is not firing.
However, in type class resolution, we have instance such as `Decidable (@Eq Nat x y)`,
where `Nat` is an implicit argument. Thus, we would add the path
```
Decidable -> Eq -> * -> * -> * -> [Nat.decEq]
```
to the discrimination tree IF we ignored the implict `Nat` argument.
This would be BAD since **ALL** decidable equality instances would be in the same path.
So, we index implicit arguments if they are types.
This setting seems sensible for simplification lemmas such as:
```
forall (x y : Unit), (@Eq Unit x y) = true
```
If we ignore the implicit argument `Unit`, the `DiscrTree` will say it is a candidate
simplification lemma for any equality in our goal.
Remark: if users have problems with the solution above, we may provide a `noIndexing` annotation,
and `ignoreArg` would return true for any term of the form `noIndexing t`.
-/
private def ignoreArg (a : Expr) (i : Nat) (infos : Array ParamInfo) : MetaM Bool := do
if h : i < infos.size then
let info := infos.get ⟨i, h⟩
if info.isInstImplicit then
return true
else if info.isImplicit || info.isStrictImplicit then
return not (← isType a)
else
isProof a
else
isProof a
private partial def pushArgsAux (infos : Array ParamInfo) : Nat → Expr → Array Expr → MetaM (Array Expr)
| i, Expr.app f a _, todo => do
if (← ignoreArg a i infos) then
pushArgsAux infos (i-1) f (todo.push tmpStar)
else
pushArgsAux infos (i-1) f (todo.push a)
| _, _, todo => return todo
/--
Return true if `e` is one of the following
- A nat literal (numeral)
- `Nat.zero`
- `Nat.succ x` where `isNumeral x`
- `OfNat.ofNat _ x _` where `isNumeral x` -/
private partial def isNumeral (e : Expr) : Bool :=
if e.isNatLit then true
else
let f := e.getAppFn
if !f.isConst then false
else
let fName := f.constName!
if fName == ``Nat.succ && e.getAppNumArgs == 1 then isNumeral e.appArg!
else if fName == ``OfNat.ofNat && e.getAppNumArgs == 3 then isNumeral (e.getArg! 1)
else if fName == ``Nat.zero && e.getAppNumArgs == 0 then true
else false
private def isNatType (e : Expr) : MetaM Bool :=
return (← whnf e).isConstOf ``Nat
/--
Return true if `e` is one of the following
- `Nat.add _ k` where `isNumeral k`
- `Add.add Nat _ _ k` where `isNumeral k`
- `HAdd.hAdd _ Nat _ _ k` where `isNumeral k`
- `Nat.succ _`
This function assumes `e.isAppOf fName`
-/
private def isOffset (fName : Name) (e : Expr) : MetaM Bool := do
if fName == ``Nat.add && e.getAppNumArgs == 2 then
return isNumeral e.appArg!
else if fName == ``Add.add && e.getAppNumArgs == 4 then
if (← isNatType (e.getArg! 0)) then return isNumeral e.appArg! else return false
else if fName == ``HAdd.hAdd && e.getAppNumArgs == 6 then
if (← isNatType (e.getArg! 1)) then return isNumeral e.appArg! else return false
else
return fName == ``Nat.succ && e.getAppNumArgs == 1
/-
TODO: add hook for users adding their own functions for controlling `shouldAddAsStar`
Different `DiscrTree` users may populate this set using, for example, attributes.
Remark: we currently tag `Nat.zero` and "offset" terms to avoid having to add special
support for `Expr.lit` and offset terms.
Example, suppose the discrimination tree contains the entry
`Nat.succ ?m |-> v`, and we are trying to retrieve the matches for `Expr.lit (Literal.natVal 1) _`.
In this scenario, we want to retrieve `Nat.succ ?m |-> v` -/
private def shouldAddAsStar (fName : Name) (e : Expr) : MetaM Bool := do
if fName == `Nat.zero then
return true
else
isOffset fName e
def mkNoindexAnnotation (e : Expr) : Expr :=
mkAnnotation `noindex e
def hasNoindexAnnotation (e : Expr) : Bool :=
annotation? `noindex e |>.isSome
private partial def whnfEta (e : Expr) : MetaM Expr := do
let e ← whnf e
match e.etaExpandedStrict? with
| some e => whnfEta e
| none => return e
/--
Return `true` if `fn` is a "bad" key. That is, `pushArgs` would add `Key.other` or `Key.star`.
We use this function when processing "root terms, and will avoid unfolding terms.
Note that without this trick the pattern `List.map f ∘ List.map g` would be mapped into the key `Key.other`
since the function composition `∘` would be unfolded and we would get `fun x => List.map g (List.map f x)`
-/
private def isBadKey (fn : Expr) : Bool :=
match fn with
| Expr.lit .. => false
| Expr.const .. => false
| Expr.fvar .. => false
| Expr.proj .. => false
| Expr.forallE _ d b _ => b.hasLooseBVars
| _ => true
/--
Reduce `e` until we get an irreducible term (modulo current reducibility setting) or the resulting term
is a bad key (see comment at `isBadKey`).
We use this method instead of `whnfEta` for root terms at `pushArgs`. -/
private partial def whnfUntilBadKey (e : Expr) : MetaM Expr := do
let e ← step e
match e.etaExpandedStrict? with
| some e => whnfUntilBadKey e
| none => return e
where
step (e : Expr) := do
let e ← whnfCore e
match (← unfoldDefinition? e) with
| some e' => if isBadKey e' then return e else step e'
| none => return e
/-- whnf for the discrimination tree module -/
private def whnfDT (e : Expr) (root : Bool) : MetaM Expr :=
if root then whnfUntilBadKey e else whnfEta e
/- Remark: we use `shouldAddAsStar` only for nested terms, and `root == false` for nested terms -/
private def pushArgs (root : Bool) (todo : Array Expr) (e : Expr) : MetaM (Key × Array Expr) := do
if hasNoindexAnnotation e then
return (Key.star, todo)
else
let e ← whnfDT e root
let fn := e.getAppFn
let push (k : Key) (nargs : Nat) : MetaM (Key × Array Expr) := do
let info ← getFunInfoNArgs fn nargs
let todo ← pushArgsAux info.paramInfo (nargs-1) e todo
return (k, todo)
match fn with
| Expr.lit v _ => return (Key.lit v, todo)
| Expr.const c _ _ =>
unless root do
if (← shouldAddAsStar c e) then
return (Key.star, todo)
let nargs := e.getAppNumArgs
push (Key.const c nargs) nargs
| Expr.proj s i a .. =>
return (Key.proj s i, todo.push a)
| Expr.fvar fvarId _ =>
let nargs := e.getAppNumArgs
push (Key.fvar fvarId nargs) nargs
| Expr.mvar mvarId _ =>
if mvarId == tmpMVarId then
-- We use `tmp to mark implicit arguments and proofs
return (Key.star, todo)
else if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then
return (Key.other, todo)
else
return (Key.star, todo)
| Expr.forallE _ d b _ =>
if b.hasLooseBVars then
return (Key.other, todo)
else
return (Key.arrow, todo.push d |>.push b)
| _ =>
return (Key.other, todo)
partial def mkPathAux (root : Bool) (todo : Array Expr) (keys : Array Key) : MetaM (Array Key) := do
if todo.isEmpty then
return keys
else
let e := todo.back
let todo := todo.pop
let (k, todo) ← pushArgs root todo e
mkPathAux false todo (keys.push k)
private def initCapacity := 8
def mkPath (e : Expr) : MetaM (Array Key) := do
withReducible do
let todo : Array Expr := Array.mkEmpty initCapacity
let keys : Array Key := Array.mkEmpty initCapacity
mkPathAux (root := true) (todo.push e) keys
private partial def createNodes (keys : Array Key) (v : α) (i : Nat) : Trie α :=
if h : i < keys.size then
let k := keys.get ⟨i, h⟩
let c := createNodes keys v (i+1)
Trie.node #[] #[(k, c)]
else
Trie.node #[v] #[]
private def insertVal [BEq α] (vs : Array α) (v : α) : Array α :=
if vs.contains v then vs else vs.push v
private partial def insertAux [BEq α] (keys : Array Key) (v : α) : Nat → Trie α → Trie α
| i, Trie.node vs cs =>
if h : i < keys.size then
let k := keys.get ⟨i, h⟩
let c := Id.run $ cs.binInsertM
(fun a b => a.1 < b.1)
(fun ⟨_, s⟩ => let c := insertAux keys v (i+1) s; (k, c)) -- merge with existing
(fun _ => let c := createNodes keys v (i+1); (k, c))
(k, arbitrary)
Trie.node vs c
else
Trie.node (insertVal vs v) cs
def insertCore [BEq α] (d : DiscrTree α) (keys : Array Key) (v : α) : DiscrTree α :=
if keys.isEmpty then panic! "invalid key sequence"
else
let k := keys[0]
match d.root.find? k with
| none =>
let c := createNodes keys v 1
{ root := d.root.insert k c }
| some c =>
let c := insertAux keys v 1 c
{ root := d.root.insert k c }
def insert [BEq α] (d : DiscrTree α) (e : Expr) (v : α) : MetaM (DiscrTree α) := do
let keys ← mkPath e
return d.insertCore keys v
private def getKeyArgs (e : Expr) (isMatch root : Bool) : MetaM (Key × Array Expr) := do
let e ← whnfDT e root
match e.getAppFn with
| Expr.lit v _ => return (Key.lit v, #[])
| Expr.const c _ _ =>
let nargs := e.getAppNumArgs
return (Key.const c nargs, e.getAppRevArgs)
| Expr.fvar fvarId _ =>
let nargs := e.getAppNumArgs
return (Key.fvar fvarId nargs, e.getAppRevArgs)
| Expr.mvar mvarId _ =>
if isMatch then
return (Key.other, #[])
else do
let ctx ← read
if ctx.config.isDefEqStuckEx then
/-
When the configuration flag `isDefEqStuckEx` is set to true,
we want `isDefEq` to throw an exception whenever it tries to assign
a read-only metavariable.
This feature is useful for type class resolution where
we may want to notify the caller that the TC problem may be solveable
later after it assigns `?m`.
The method `DiscrTree.getUnify e` returns candidates `c` that may "unify" with `e`.
That is, `isDefEq c e` may return true. Now, consider `DiscrTree.getUnify d (Add ?m)`
where `?m` is a read-only metavariable, and the discrimination tree contains the keys
`HadAdd Nat` and `Add Int`. If `isDefEqStuckEx` is set to true, we must treat `?m` as
a regular metavariable here, otherwise we return the empty set of candidates.
This is incorrect because it is equivalent to saying that there is no solution even if
the caller assigns `?m` and try again. -/
return (Key.star, #[])
else if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then
return (Key.other, #[])
else
return (Key.star, #[])
| Expr.proj s i a .. =>
return (Key.proj s i, #[a])
| Expr.forallE _ d b _ =>
if b.hasLooseBVars then
return (Key.other, #[])
else
return (Key.arrow, #[d, b])
| _ =>
return (Key.other, #[])
private abbrev getMatchKeyArgs (e : Expr) (root : Bool) : MetaM (Key × Array Expr) :=
getKeyArgs e (isMatch := true) (root := root)
private abbrev getUnifyKeyArgs (e : Expr) (root : Bool) : MetaM (Key × Array Expr) :=
getKeyArgs e (isMatch := false) (root := root)
private def getStarResult (d : DiscrTree α) : Array α :=
let result : Array α := Array.mkEmpty initCapacity
match d.root.find? Key.star with
| none => result
| some (Trie.node vs _) => result ++ vs
private abbrev findKey (cs : Array (Key × Trie α)) (k : Key) : Option (Key × Trie α) :=
cs.binSearch (k, arbitrary) (fun a b => a.1 < b.1)
partial def getMatch (d : DiscrTree α) (e : Expr) : MetaM (Array α) :=
withReducible do
let result := getStarResult d
let (k, args) ← getMatchKeyArgs e (root := true)
match k with
| Key.star => return result
| _ =>
match d.root.find? k with
| none => return result
| some c => process args c result
where
process (todo : Array Expr) (c : Trie α) (result : Array α) : MetaM (Array α) := do
match c with
| Trie.node vs cs =>
if todo.isEmpty then
return result ++ vs
else if cs.isEmpty then
return result
else
let e := todo.back
let todo := todo.pop
let first := cs[0] /- Recall that `Key.star` is the minimal key -/
let (k, args) ← getMatchKeyArgs e (root := false)
/- We must always visit `Key.star` edges since they are wildcards.
Thus, `todo` is not used linearly when there is `Key.star` edge
and there is an edge for `k` and `k != Key.star`. -/
let visitStar (result : Array α) : MetaM (Array α) :=
if first.1 == Key.star then
process todo first.2 result
else
return result
let visitNonStar (k : Key) (args : Array Expr) (result : Array α) : MetaM (Array α) :=
match findKey cs k with
| none => result
| some c => process (todo ++ args) c.2 result
let result ← visitStar result
match k with
| Key.star => result
/-
Recall that dependent arrows are `(Key.other, #[])`, and non-dependent arrows are `(Key.arrow, #[a, b])`.
A non-dependent arrow may be an instance of a dependent arrow (stored at `DiscrTree`). Thus, we also visit the `Key.other` child.
-/
| Key.arrow => visitNonStar Key.other #[] (← visitNonStar k args result)
| _ => visitNonStar k args result
partial def getUnify (d : DiscrTree α) (e : Expr) : MetaM (Array α) :=
withReducible do
let (k, args) ← getUnifyKeyArgs e (root := true)
match k with
| Key.star => d.root.foldlM (init := #[]) fun result k c => process k.arity #[] c result
| _ =>
let result := getStarResult d
match d.root.find? k with
| none => return result
| some c => process 0 args c result
where
process (skip : Nat) (todo : Array Expr) (c : Trie α) (result : Array α) : MetaM (Array α) := do
match skip, c with
| skip+1, Trie.node vs cs =>
if cs.isEmpty then
return result
else
cs.foldlM (init := result) fun result ⟨k, c⟩ => process (skip + k.arity) todo c result
| 0, Trie.node vs cs => do
if todo.isEmpty then
return result ++ vs
else if cs.isEmpty then
return result
else
let e := todo.back
let todo := todo.pop
let (k, args) ← getUnifyKeyArgs e (root := false)
let visitStar (result : Array α) : MetaM (Array α) :=
let first := cs[0]
if first.1 == Key.star then
process 0 todo first.2 result
else
return result
let visitNonStar (k : Key) (args : Array Expr) (result : Array α) : MetaM (Array α) :=
match findKey cs k with
| none => result
| some c => process 0 (todo ++ args) c.2 result
match k with
| Key.star => cs.foldlM (init := result) fun result ⟨k, c⟩ => process k.arity todo c result
-- See comment a `getMatch` regarding non-dependent arrows vs dependent arrows
| Key.arrow => visitNonStar Key.other #[] (← visitNonStar k args (← visitStar result))
| _ => visitNonStar k args (← visitStar result)
end Lean.Meta.DiscrTree
|
91a8c2a6a152b533cfb3e9bacaa5560afa0e024e | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/analysis/locally_convex/bounded.lean | dfdb88768c29a314f1527c00012c89a87d7db928 | [
"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 | 11,779 | lean | /-
Copyright (c) 2022 Moritz Doll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Moritz Doll
-/
import analysis.locally_convex.basic
import analysis.seminorm
import topology.bornology.basic
import topology.algebra.uniform_group
import analysis.locally_convex.balanced_core_hull
/-!
# Von Neumann Boundedness
This file defines natural or von Neumann bounded sets and proves elementary properties.
## Main declarations
* `bornology.is_vonN_bounded`: A set `s` is von Neumann-bounded if every neighborhood of zero
absorbs `s`.
* `bornology.vonN_bornology`: The bornology made of the von Neumann-bounded sets.
## Main results
* `bornology.is_vonN_bounded_of_topological_space_le`: A coarser topology admits more
von Neumann-bounded sets.
## References
* [Bourbaki, *Topological Vector Spaces*][bourbaki1987]
-/
variables {𝕜 E F ι : Type*}
open filter
open_locale topological_space pointwise
namespace bornology
section semi_normed_ring
section has_zero
variables (𝕜)
variables [semi_normed_ring 𝕜] [has_smul 𝕜 E] [has_zero E]
variables [topological_space E]
/-- A set `s` is von Neumann bounded if every neighborhood of 0 absorbs `s`. -/
def is_vonN_bounded (s : set E) : Prop := ∀ ⦃V⦄, V ∈ 𝓝 (0 : E) → absorbs 𝕜 V s
variables (E)
@[simp] lemma is_vonN_bounded_empty : is_vonN_bounded 𝕜 (∅ : set E) :=
λ _ _, absorbs_empty
variables {𝕜 E}
lemma is_vonN_bounded_iff (s : set E) : is_vonN_bounded 𝕜 s ↔ ∀ V ∈ 𝓝 (0 : E), absorbs 𝕜 V s :=
iff.rfl
lemma _root_.filter.has_basis.is_vonN_bounded_basis_iff {q : ι → Prop} {s : ι → set E} {A : set E}
(h : (𝓝 (0 : E)).has_basis q s) :
is_vonN_bounded 𝕜 A ↔ ∀ i (hi : q i), absorbs 𝕜 (s i) A :=
begin
refine ⟨λ hA i hi, hA (h.mem_of_mem hi), λ hA V hV, _⟩,
rcases h.mem_iff.mp hV with ⟨i, hi, hV⟩,
exact (hA i hi).mono_left hV,
end
/-- Subsets of bounded sets are bounded. -/
lemma is_vonN_bounded.subset {s₁ s₂ : set E} (h : s₁ ⊆ s₂) (hs₂ : is_vonN_bounded 𝕜 s₂) :
is_vonN_bounded 𝕜 s₁ :=
λ V hV, (hs₂ hV).mono_right h
/-- The union of two bounded sets is bounded. -/
lemma is_vonN_bounded.union {s₁ s₂ : set E} (hs₁ : is_vonN_bounded 𝕜 s₁)
(hs₂ : is_vonN_bounded 𝕜 s₂) :
is_vonN_bounded 𝕜 (s₁ ∪ s₂) :=
λ V hV, (hs₁ hV).union (hs₂ hV)
end has_zero
end semi_normed_ring
section multiple_topologies
variables [semi_normed_ring 𝕜] [add_comm_group E] [module 𝕜 E]
/-- If a topology `t'` is coarser than `t`, then any set `s` that is bounded with respect to
`t` is bounded with respect to `t'`. -/
lemma is_vonN_bounded.of_topological_space_le {t t' : topological_space E} (h : t ≤ t') {s : set E}
(hs : @is_vonN_bounded 𝕜 E _ _ _ t s) : @is_vonN_bounded 𝕜 E _ _ _ t' s :=
λ V hV, hs $ (le_iff_nhds t t').mp h 0 hV
end multiple_topologies
section image
variables {𝕜₁ 𝕜₂ : Type*} [normed_division_ring 𝕜₁] [normed_division_ring 𝕜₂]
[add_comm_group E] [module 𝕜₁ E] [add_comm_group F] [module 𝕜₂ F]
[topological_space E] [topological_space F]
/-- A continuous linear image of a bounded set is bounded. -/
lemma is_vonN_bounded.image {σ : 𝕜₁ →+* 𝕜₂} [ring_hom_surjective σ] [ring_hom_isometric σ]
{s : set E} (hs : is_vonN_bounded 𝕜₁ s) (f : E →SL[σ] F) :
is_vonN_bounded 𝕜₂ (f '' s) :=
begin
let σ' := ring_equiv.of_bijective σ ⟨σ.injective, σ.is_surjective⟩,
have σ_iso : isometry σ := add_monoid_hom_class.isometry_of_norm σ
(λ x, ring_hom_isometric.is_iso),
have σ'_symm_iso : isometry σ'.symm := σ_iso.right_inv σ'.right_inv,
have f_tendsto_zero := f.continuous.tendsto 0,
rw map_zero at f_tendsto_zero,
intros V hV,
rcases hs (f_tendsto_zero hV) with ⟨r, hrpos, hr⟩,
refine ⟨r, hrpos, λ a ha, _⟩,
rw ← σ'.apply_symm_apply a,
have hanz : a ≠ 0 := norm_pos_iff.mp (hrpos.trans_le ha),
have : σ'.symm a ≠ 0 := (map_ne_zero σ'.symm.to_ring_hom).mpr hanz,
change _ ⊆ σ _ • _,
rw [set.image_subset_iff, preimage_smul_setₛₗ _ _ _ f this.is_unit],
refine hr (σ'.symm a) _,
rwa σ'_symm_iso.norm_map_of_map_zero (map_zero _)
end
end image
section normed_field
variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E]
variables [topological_space E] [has_continuous_smul 𝕜 E]
/-- Singletons are bounded. -/
lemma is_vonN_bounded_singleton (x : E) : is_vonN_bounded 𝕜 ({x} : set E) :=
λ V hV, (absorbent_nhds_zero hV).absorbs
/-- The union of all bounded set is the whole space. -/
lemma is_vonN_bounded_covers : ⋃₀ (set_of (is_vonN_bounded 𝕜)) = (set.univ : set E) :=
set.eq_univ_iff_forall.mpr (λ x, set.mem_sUnion.mpr
⟨{x}, is_vonN_bounded_singleton _, set.mem_singleton _⟩)
variables (𝕜 E)
/-- The von Neumann bornology defined by the von Neumann bounded sets.
Note that this is not registered as an instance, in order to avoid diamonds with the
metric bornology.-/
@[reducible] -- See note [reducible non-instances]
def vonN_bornology : bornology E :=
bornology.of_bounded (set_of (is_vonN_bounded 𝕜)) (is_vonN_bounded_empty 𝕜 E)
(λ _ hs _ ht, hs.subset ht) (λ _ hs _, hs.union) is_vonN_bounded_singleton
variables {E}
@[simp] lemma is_bounded_iff_is_vonN_bounded {s : set E} :
@is_bounded _ (vonN_bornology 𝕜 E) s ↔ is_vonN_bounded 𝕜 s :=
is_bounded_of_bounded_iff _
end normed_field
end bornology
section uniform_add_group
variables (𝕜) [nontrivially_normed_field 𝕜] [add_comm_group E] [module 𝕜 E]
variables [uniform_space E] [uniform_add_group E] [has_continuous_smul 𝕜 E]
lemma totally_bounded.is_vonN_bounded {s : set E} (hs : totally_bounded s) :
bornology.is_vonN_bounded 𝕜 s :=
begin
rw totally_bounded_iff_subset_finite_Union_nhds_zero at hs,
intros U hU,
have h : filter.tendsto (λ (x : E × E), x.fst + x.snd) (𝓝 (0,0)) (𝓝 ((0 : E) + (0 : E))) :=
tendsto_add,
rw add_zero at h,
have h' := (nhds_basis_balanced 𝕜 E).prod (nhds_basis_balanced 𝕜 E),
simp_rw [←nhds_prod_eq, id.def] at h',
rcases h.basis_left h' U hU with ⟨x, hx, h''⟩,
rcases hs x.snd hx.2.1 with ⟨t, ht, hs⟩,
refine absorbs.mono_right _ hs,
rw ht.absorbs_Union,
have hx_fstsnd : x.fst + x.snd ⊆ U,
{ intros z hz,
rcases set.mem_add.mp hz with ⟨z1, z2, hz1, hz2, hz⟩,
have hz' : (z1, z2) ∈ x.fst ×ˢ x.snd := ⟨hz1, hz2⟩,
simpa only [hz] using h'' hz' },
refine λ y hy, absorbs.mono_left _ hx_fstsnd,
rw [←set.singleton_vadd, vadd_eq_add],
exact (absorbent_nhds_zero hx.1.1).absorbs.add hx.2.2.absorbs_self,
end
end uniform_add_group
section continuous_linear_map
variables [nontrivially_normed_field 𝕜]
variables [add_comm_group E] [module 𝕜 E]
variables [uniform_space E] [uniform_add_group E] [has_continuous_smul 𝕜 E]
variables [add_comm_group F] [module 𝕜 F]
variables [uniform_space F] [uniform_add_group F]
/-- Construct a continuous linear map from a linear map `f : E →ₗ[𝕜] F` and the existence of a
neighborhood of zero that gets mapped into a bounded set in `F`. -/
def linear_map.clm_of_exists_bounded_image (f : E →ₗ[𝕜] F)
(h : ∃ (V : set E) (hV : V ∈ 𝓝 (0 : E)), bornology.is_vonN_bounded 𝕜 (f '' V)) : E →L[𝕜] F :=
⟨f, begin
-- It suffices to show that `f` is continuous at `0`.
refine continuous_of_continuous_at_zero f _,
rw [continuous_at_def, f.map_zero],
intros U hU,
-- Continuity means that `U ∈ 𝓝 0` implies that `f ⁻¹' U ∈ 𝓝 0`.
rcases h with ⟨V, hV, h⟩,
rcases h hU with ⟨r, hr, h⟩,
rcases normed_field.exists_lt_norm 𝕜 r with ⟨x, hx⟩,
specialize h x hx.le,
-- After unfolding all the definitions, we know that `f '' V ⊆ x • U`. We use this to show the
-- inclusion `x⁻¹ • V ⊆ f⁻¹' U`.
have x_ne := norm_pos_iff.mp (hr.trans hx),
have : x⁻¹ • V ⊆ f⁻¹' U :=
calc x⁻¹ • V ⊆ x⁻¹ • (f⁻¹' (f '' V)) : set.smul_set_mono (set.subset_preimage_image ⇑f V)
... ⊆ x⁻¹ • (f⁻¹' (x • U)) : set.smul_set_mono (set.preimage_mono h)
... = f⁻¹' (x⁻¹ • (x • U)) :
by ext; simp only [set.mem_inv_smul_set_iff₀ x_ne, set.mem_preimage, linear_map.map_smul]
... ⊆ f⁻¹' U : by rw inv_smul_smul₀ x_ne _,
-- Using this inclusion, it suffices to show that `x⁻¹ • V` is in `𝓝 0`, which is trivial.
refine mem_of_superset _ this,
convert set_smul_mem_nhds_smul hV (inv_ne_zero x_ne),
exact (smul_zero _).symm,
end⟩
lemma linear_map.clm_of_exists_bounded_image_coe {f : E →ₗ[𝕜] F}
{h : ∃ (V : set E) (hV : V ∈ 𝓝 (0 : E)), bornology.is_vonN_bounded 𝕜 (f '' V)} :
(f.clm_of_exists_bounded_image h : E →ₗ[𝕜] F) = f := rfl
@[simp] lemma linear_map.clm_of_exists_bounded_image_apply {f : E →ₗ[𝕜] F}
{h : ∃ (V : set E) (hV : V ∈ 𝓝 (0 : E)), bornology.is_vonN_bounded 𝕜 (f '' V)} {x : E} :
f.clm_of_exists_bounded_image h x = f x := rfl
end continuous_linear_map
section vonN_bornology_eq_metric
variables (𝕜 E) [nontrivially_normed_field 𝕜] [seminormed_add_comm_group E] [normed_space 𝕜 E]
namespace normed_space
lemma is_vonN_bounded_ball (r : ℝ) :
bornology.is_vonN_bounded 𝕜 (metric.ball (0 : E) r) :=
begin
rw [metric.nhds_basis_ball.is_vonN_bounded_basis_iff, ← ball_norm_seminorm 𝕜 E],
exact λ ε hε, (norm_seminorm 𝕜 E).ball_zero_absorbs_ball_zero hε
end
lemma is_vonN_bounded_closed_ball (r : ℝ) :
bornology.is_vonN_bounded 𝕜 (metric.closed_ball (0 : E) r) :=
(is_vonN_bounded_ball 𝕜 E (r+1)).subset (metric.closed_ball_subset_ball $ by linarith)
lemma is_vonN_bounded_iff (s : set E) :
bornology.is_vonN_bounded 𝕜 s ↔ bornology.is_bounded s :=
begin
rw [← metric.bounded_iff_is_bounded, metric.bounded_iff_subset_ball (0 : E)],
split,
{ intros h,
rcases h (metric.ball_mem_nhds 0 zero_lt_one) with ⟨ρ, hρ, hρball⟩,
rcases normed_field.exists_lt_norm 𝕜 ρ with ⟨a, ha⟩,
specialize hρball a ha.le,
rw [← ball_norm_seminorm 𝕜 E, seminorm.smul_ball_zero (hρ.trans ha),
ball_norm_seminorm, mul_one] at hρball,
exact ⟨∥a∥, hρball.trans metric.ball_subset_closed_ball⟩ },
{ exact λ ⟨C, hC⟩, (is_vonN_bounded_closed_ball 𝕜 E C).subset hC }
end
/-- In a normed space, the von Neumann bornology (`bornology.vonN_bornology`) is equal to the
metric bornology. -/
lemma vonN_bornology_eq : bornology.vonN_bornology 𝕜 E = pseudo_metric_space.to_bornology :=
begin
rw bornology.ext_iff_is_bounded,
intro s,
rw bornology.is_bounded_iff_is_vonN_bounded,
exact is_vonN_bounded_iff 𝕜 E s
end
variable (𝕜)
lemma is_bounded_iff_subset_smul_ball {s : set E} :
bornology.is_bounded s ↔ ∃ a : 𝕜, s ⊆ a • metric.ball 0 1 :=
begin
rw ← is_vonN_bounded_iff 𝕜,
split,
{ intros h,
rcases h (metric.ball_mem_nhds 0 zero_lt_one) with ⟨ρ, hρ, hρball⟩,
rcases normed_field.exists_lt_norm 𝕜 ρ with ⟨a, ha⟩,
exact ⟨a, hρball a ha.le⟩ },
{ rintros ⟨a, ha⟩,
exact ((is_vonN_bounded_ball 𝕜 E 1).image (a • 1 : E →L[𝕜] E)).subset ha }
end
lemma is_bounded_iff_subset_smul_closed_ball {s : set E} :
bornology.is_bounded s ↔ ∃ a : 𝕜, s ⊆ a • metric.closed_ball 0 1 :=
begin
split,
{ rw is_bounded_iff_subset_smul_ball 𝕜,
exact exists_imp_exists
(λ a ha, ha.trans $ set.smul_set_mono $ metric.ball_subset_closed_ball) },
{ rw ← is_vonN_bounded_iff 𝕜,
rintros ⟨a, ha⟩,
exact ((is_vonN_bounded_closed_ball 𝕜 E 1).image (a • 1 : E →L[𝕜] E)).subset ha }
end
end normed_space
end vonN_bornology_eq_metric
|
cdc79ef3b0b4f83842787a7cfb2f551f5155191d | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /stage0/src/Lean/Compiler/LCNF/Simp/JpCases.lean | 3cfcb517efe471fbfe7054e9c9aacb1e3c3e83c4 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 9,451 | 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.LCNF.DependsOn
import Lean.Compiler.LCNF.InferType
import Lean.Compiler.LCNF.Simp.Basic
namespace Lean.Compiler.LCNF
namespace Simp
/--
Given the function declaration `decl`, return `true` if it is of the form
```
f y :=
... /- This part is not bigger than smallThreshold. -/
cases y
| ... => ...
...
```
-/
def isJpCases (decl : FunDecl) : CompilerM Bool := do
if decl.params.size != 1 then
return false
else
let param := decl.params[0]!
let small := (← getConfig).smallThreshold
let rec go (code : Code) (prefixSize : Nat) : Bool :=
prefixSize <= small &&
match code with
| .let _ k => go k (prefixSize + 1) /- TODO: we should have uniform heuristics for estimating the size. -/
| .cases c => c.discr == param.fvarId
| _ => false
return go decl.value 0
abbrev JpCasesInfo := FVarIdMap NameSet
/-- Return `true` if the collected information suggests opportunities for the `JpCases` optimization. -/
def JpCasesInfo.isCandidate (info : JpCasesInfo) : Bool :=
info.any fun _ s => !s.isEmpty
/--
Return a map containing entries `jpFVarId ↦ ctorNames` where `jpFVarId` is the id of join point
in code that satisfies `isJpCases`, and `ctorNames` is a set of constructor names such that
there is a jump `.jmp jpFVarId #[x]` in `code` and `x` is a constructor application.
-/
partial def collectJpCasesInfo (code : Code) : CompilerM JpCasesInfo := do
let (_, s) ← go code |>.run {}
return s
where
go (code : Code) : StateRefT JpCasesInfo CompilerM Unit := do
match code with
| .let _ k => go k
| .fun decl k => go decl.value; go k
| .jp decl k =>
if (← isJpCases decl) then
modify fun s => s.insert decl.fvarId {}
go decl.value; go k
| .cases c => c.alts.forM fun alt => go alt.getCode
| .return .. | .unreach .. => return ()
| .jmp fvarId args =>
if args.size == 1 then
if let some ctorNames := (← get).find? fvarId then
let arg ← findExpr args[0]!
let some (cval, _) := arg.constructorApp? (← getEnv) | return ()
modify fun s => s.insert fvarId <| ctorNames.insert cval.name
/--
Extract the let-declarations and `cases` for a join point body that satisfies `isJpCases`.
-/
private def extractJpCases (code : Code) : Array CodeDecl × Cases :=
go code #[]
where
go (code : Code) (decls : Array CodeDecl) :=
match code with
| .let decl k => go k <| decls.push (.let decl)
| .cases c => (decls, c)
| _ => unreachable! -- `code` is not the body of a join point that satisfies `isJpCases`
structure JpCasesAlt where
decl : FunDecl
default : Bool
dependsOnDiscr : Bool
abbrev Ctor2JpCasesAlt := FVarIdMap (NameMap JpCasesAlt)
open Internalize in
private def mkJpAlt (decls : Array CodeDecl) (discr : Param) (fields : Array Param) (k : Code) (default : Bool) : CompilerM JpCasesAlt := do
go |>.run' {}
where
go : InternalizeM JpCasesAlt := do
let s : FVarIdSet := {}
let mut paramsNew := #[]
let dependsOnDiscr := k.dependsOn (s.insert discr.fvarId)
if dependsOnDiscr then
paramsNew := paramsNew.push (← internalizeParam discr)
paramsNew := paramsNew ++ (← fields.mapM internalizeParam)
let decls ← decls.mapM internalizeCodeDecl
let k ← internalizeCode k
let value := LCNF.attachCodeDecls decls k
return { decl := (← mkAuxJpDecl paramsNew value), default, dependsOnDiscr }
/--
Try to optimize `jpCases` join points.
We say a join point is a `jpCases` when it satifies the predicate `isJpCases`.
If we have a jump to `jpCases` with a constructor, then we can optimize the code by creating an new join point for
the constructor.
Example: suppose we have
```lean
jp _jp.1 y :=
let x.1 := true
cases y
| nil => let x.2 := g x.1; return x.2
| cons h t => let x.3 := h x.1; return x.3
...
cases x.4
| ctor1 =>
let x.5 := cons z.1 z.2
jmp _jp.1 x.5
| ctor2 =>
let x.6 := f x.4
jmp _jp.1 x.6
```
This `simpJpCases?` converts it to
```lean
jp _jp.2 h t :=
let x.1 := true
let x.3 := h x.1
return x.3
jp _jp.1 y :=
let x.1 := true
cases y
| nil => let x.2 := g x.1; return x.2
| cons h t => jmp _jp.2 h t
...
cases x.4
| ctor1 =>
-- The constructor has been eliminated here
jmp _jp.2 z.1 z.2
| ctor2 =>
let x.6 := f x.4
jmp _jp.1 x.6
```
Note that if all jumps to the join point are with constructors,
then the join point is eliminated as dead code.
-/
partial def simpJpCases? (code : Code) : CompilerM (Option Code) := do
let info ← collectJpCasesInfo code
unless info.isCandidate do return none
traceM `Compiler.simp.jpCases do
let mut msg : MessageData := "candidates"
for (fvarId, ctorName) in info.toList do
msg := msg ++ indentD m!"{mkFVar fvarId} ↦ {ctorName.toList}"
return msg
visit code info |>.run' {}
where
visit (code : Code) : ReaderT JpCasesInfo (StateRefT Ctor2JpCasesAlt CompilerM) Code := do
match code with
| .let decl k =>
return code.updateLet! decl (← visit k)
| .fun decl k =>
let value ← visit decl.value
let decl ← decl.updateValue value
return code.updateFun! decl (← visit k)
| .jp decl k =>
if let some code ← visitJp? decl k then
return code
else
let value ← visit decl.value
let decl ← decl.updateValue value
return code.updateFun! decl (← visit k)
| .cases c =>
let alts ← c.alts.mapMonoM fun alt => return alt.updateCode (← visit alt.getCode)
return code.updateAlts! alts
| .return _ | .unreach _ => return code
| .jmp fvarId args =>
let some code ← visitJmp? fvarId args | return code
return code
visitJp? (decl : FunDecl) (k : Code) : ReaderT JpCasesInfo (StateRefT Ctor2JpCasesAlt CompilerM) (Option Code) := do
let some s := (← read).find? decl.fvarId | return none
if s.isEmpty then return none
-- This join point satisfies `isJp` and there jumps with constructors in `s` to it.
let p := decl.params[0]!
let (decls, cases) := extractJpCases decl.value
let mut jpAltMap := {}
let mut jpAltDecls := #[]
let mut altsNew := #[]
for alt in cases.alts do
match alt with
| .default k =>
let k ← visit k
let explicitCtorNames := cases.getCtorNames
if s.any fun ctorNameInJump => !explicitCtorNames.contains ctorNameInJump then
let jpAlt ← mkJpAlt decls p #[] k (default := true)
jpAltDecls := jpAltDecls.push (.jp jpAlt.decl)
eraseCode k
for ctorNameInJmp in s do
unless explicitCtorNames.contains ctorNameInJmp do
jpAltMap := jpAltMap.insert ctorNameInJmp jpAlt
let args := if jpAlt.dependsOnDiscr then #[.fvar p.fvarId] else #[]
altsNew := altsNew.push (alt.updateCode (.jmp jpAlt.decl.fvarId args))
else
altsNew := altsNew.push (alt.updateCode k)
| .alt ctorName fields k =>
let k ← visit k
if s.contains ctorName then
let jpAlt ← mkJpAlt decls p fields k (default := false)
jpAltDecls := jpAltDecls.push (.jp jpAlt.decl)
jpAltMap := jpAltMap.insert ctorName jpAlt
let mut args := fields.map (mkFVar ·.fvarId)
if jpAlt.dependsOnDiscr then
args := #[mkFVar p.fvarId] ++ args
eraseCode k
altsNew := altsNew.push (alt.updateCode (.jmp jpAlt.decl.fvarId args))
else
altsNew := altsNew.push (alt.updateCode k)
modify fun s => s.insert decl.fvarId jpAltMap
let value := LCNF.attachCodeDecls decls (.cases { cases with alts := altsNew })
let decl ← decl.updateValue value
let code := .jp decl (← visit k)
return LCNF.attachCodeDecls jpAltDecls code
visitJmp? (fvarId : FVarId) (args : Array Expr) : ReaderT JpCasesInfo (StateRefT Ctor2JpCasesAlt CompilerM) (Option Code) := do
let some ctorJpAltMap := (← get).find? fvarId | return none
assert! args.size == 1
let arg ← findExpr args[0]!
let some (ctorVal, ctorArgs) := arg.constructorApp? (← getEnv) (useRaw := true) | return none
let some jpAlt := ctorJpAltMap.find? ctorVal.name | return none
if jpAlt.default then
if jpAlt.dependsOnDiscr then
return some <| .jmp jpAlt.decl.fvarId args
else
return some <| .jmp jpAlt.decl.fvarId #[]
else
let fields := ctorArgs[ctorVal.numParams:]
-- Recall that if `arg` is a `Nat` literal, then `ctorArgs` is a literal too.
-- We use a for-loop because we may have other special cases in the future.
let mut auxDecls := #[]
let mut fieldsNew := #[]
for field in fields do
if field.isFVar then
fieldsNew := fieldsNew.push field
else
let letDecl ← mkAuxLetDecl field
auxDecls := auxDecls.push (CodeDecl.let letDecl)
fieldsNew := fieldsNew.push (.fvar letDecl.fvarId)
let code ← if jpAlt.dependsOnDiscr then
pure <| .jmp jpAlt.decl.fvarId (args ++ fieldsNew)
else
pure <| .jmp jpAlt.decl.fvarId fieldsNew
return some <| LCNF.attachCodeDecls auxDecls code
end Simp
builtin_initialize
registerTraceClass `Compiler.simp.jpCases
end Lean.Compiler.LCNF
|
0c8084f45f376a576c8a1a8f957db063b6fca36c | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Meta/Tactic/Generalize.lean | ff3993ba39f226375edb3fff94aac167a924c43a | [
"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 | 4,440 | 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.KAbstract
import Lean.Meta.Tactic.Util
import Lean.Meta.Tactic.Intro
import Lean.Meta.Tactic.FVarSubst
import Lean.Meta.Tactic.Revert
namespace Lean.Meta
/-- The `generalize` tactic takes arguments of the form `h : e = x` -/
structure GeneralizeArg where
expr : Expr
xName? : Option Name := none
hName? : Option Name := none
deriving Inhabited
/--
Telescopic `generalize` tactic. It can simultaneously generalize many terms.
It uses `kabstract` to occurrences of the terms that need to be generalized.
-/
private partial def generalizeCore (mvarId : MVarId) (args : Array GeneralizeArg) : MetaM (Array FVarId × MVarId) :=
mvarId.withContext do
mvarId.checkNotAssigned `generalize
let tag ← mvarId.getTag
let target ← instantiateMVars (← mvarId.getType)
let rec go (i : Nat) : MetaM Expr := do
if _h : i < args.size then
let arg := args[i]
let e ← instantiateMVars arg.expr
let eType ← instantiateMVars (← inferType e)
let type ← go (i+1)
let xName ← if let some xName := arg.xName? then pure xName else mkFreshUserName `x
return Lean.mkForall xName BinderInfo.default eType (← kabstract type e)
else
return target
let targetNew ← go 0
unless (← isTypeCorrect targetNew) do
throwTacticEx `generalize mvarId m!"result is not type correct{indentExpr targetNew}"
let es := args.map (·.expr)
if !args.any fun arg => arg.hName?.isSome then
let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew tag
mvarId.assign (mkAppN mvarNew es)
mvarNew.mvarId!.introNP args.size
else
let (rfls, targetNew) ← forallBoundedTelescope targetNew args.size fun xs type => do
let rec go' (i : Nat) : MetaM (List Expr × Expr) := do
if _h : i < xs.size then
let arg := args[i]!
if let some hName := arg.hName? then
let xType ← inferType xs[i]
let e ← instantiateMVars arg.expr
let eType ← instantiateMVars (← inferType e)
let (hType, r) ← if (← isDefEq xType eType) then
pure (← mkEq e xs[i], ← mkEqRefl e)
else
pure (← mkHEq e xs[i], ← mkHEqRefl e)
let (rs, type) ← go' (i+1)
return (r :: rs, mkForall hName BinderInfo.default hType type)
else
go' (i+1)
else
return ([], type)
let (rfls, type) ← go' 0
return (rfls, ← mkForallFVars xs type)
let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew tag
mvarId.assign (mkAppN (mkAppN mvarNew es) rfls.toArray)
mvarNew.mvarId!.introNP (args.size + rfls.length)
@[inherit_doc generalizeCore]
def _root_.Lean.MVarId.generalize (mvarId : MVarId) (args : Array GeneralizeArg) : MetaM (Array FVarId × MVarId) :=
generalizeCore mvarId args
@[inherit_doc generalizeCore, deprecated MVarId.generalize]
def generalize (mvarId : MVarId) (args : Array GeneralizeArg) : MetaM (Array FVarId × MVarId) :=
generalizeCore mvarId args
/--
Extension of `generalize` to support generalizing within specified hypotheses.
The `hyps` array contains the list of hypotheses within which to look for occurrences
of the generalizing expressions.
-/
def _root_.Lean.MVarId.generalizeHyp (mvarId : MVarId) (args : Array GeneralizeArg) (hyps : Array FVarId := #[])
(fvarSubst : FVarSubst := {}) : MetaM (FVarSubst × Array FVarId × MVarId) := do
if hyps.isEmpty then
-- trivial case
return (fvarSubst, ← mvarId.generalize args)
let args ← args.mapM fun arg => return { arg with expr := ← instantiateMVars arg.expr }
let hyps ← hyps.filterM fun h => do
let type ← instantiateMVars (← h.getType)
args.anyM fun arg => return (← kabstract type arg.expr).hasLooseBVars
let (reverted, mvarId) ← mvarId.revert hyps true
let (newVars, mvarId) ← mvarId.generalize args
let (reintros, mvarId) ← mvarId.introNP reverted.size
let fvarSubst := Id.run do
let mut subst : FVarSubst := fvarSubst
for h in reverted, reintro in reintros do
subst := subst.insert h (mkFVar reintro)
pure subst
return (fvarSubst, newVars, mvarId)
end Lean.Meta
|
81264cf93cfb1923a6aa71bed7c086c64089b7f4 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/set_theory/game/domineering.lean | 43958be820b700415d2d18e329c2510ac36dd620 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 7,651 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import set_theory.game.state
/-!
# Domineering as a combinatorial game.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define the game of Domineering, played on a chessboard of arbitrary shape
(possibly even disconnected).
Left moves by placing a domino vertically, while Right moves by placing a domino horizontally.
This is only a fragment of a full development;
in order to successfully analyse positions we would need some more theorems.
Most importantly, we need a general statement that allows us to discard irrelevant moves.
Specifically to domineering, we need the fact that
disjoint parts of the chessboard give sums of games.
-/
namespace pgame
namespace domineering
open function
/-- The equivalence `(x, y) ↦ (x, y+1)`. -/
@[simps]
def shift_up : ℤ × ℤ ≃ ℤ × ℤ :=
(equiv.refl ℤ).prod_congr (equiv.add_right (1 : ℤ))
/-- The equivalence `(x, y) ↦ (x+1, y)`. -/
@[simps]
def shift_right : ℤ × ℤ ≃ ℤ × ℤ :=
(equiv.add_right (1 : ℤ)).prod_congr (equiv.refl ℤ)
/-- A Domineering board is an arbitrary finite subset of `ℤ × ℤ`. -/
@[derive inhabited]
def board := finset (ℤ × ℤ)
local attribute [reducible] board
/-- Left can play anywhere that a square and the square below it are open. -/
def left (b : board) : finset (ℤ × ℤ) := b ∩ b.map shift_up
/-- Right can play anywhere that a square and the square to the left are open. -/
def right (b : board) : finset (ℤ × ℤ) := b ∩ b.map shift_right
lemma mem_left {b : board} (x : ℤ × ℤ) : x ∈ left b ↔ x ∈ b ∧ (x.1, x.2 - 1) ∈ b :=
finset.mem_inter.trans (and_congr iff.rfl finset.mem_map_equiv)
lemma mem_right {b : board} (x : ℤ × ℤ) : x ∈ right b ↔ x ∈ b ∧ (x.1 - 1, x.2) ∈ b :=
finset.mem_inter.trans (and_congr iff.rfl finset.mem_map_equiv)
/-- After Left moves, two vertically adjacent squares are removed from the board. -/
def move_left (b : board) (m : ℤ × ℤ) : board :=
(b.erase m).erase (m.1, m.2 - 1)
/-- After Left moves, two horizontally adjacent squares are removed from the board. -/
def move_right (b : board) (m : ℤ × ℤ) : board :=
(b.erase m).erase (m.1 - 1, m.2)
lemma fst_pred_mem_erase_of_mem_right {b : board} {m : ℤ × ℤ} (h : m ∈ right b) :
(m.1 - 1, m.2) ∈ b.erase m :=
begin
rw mem_right at h,
apply finset.mem_erase_of_ne_of_mem _ h.2,
exact ne_of_apply_ne prod.fst (pred_ne_self m.1),
end
lemma snd_pred_mem_erase_of_mem_left {b : board} {m : ℤ × ℤ} (h : m ∈ left b) :
(m.1, m.2 - 1) ∈ b.erase m :=
begin
rw mem_left at h,
apply finset.mem_erase_of_ne_of_mem _ h.2,
exact ne_of_apply_ne prod.snd (pred_ne_self m.2),
end
lemma card_of_mem_left {b : board} {m : ℤ × ℤ} (h : m ∈ left b) : 2 ≤ finset.card b :=
begin
have w₁ : m ∈ b := (finset.mem_inter.1 h).1,
have w₂ : (m.1, m.2 - 1) ∈ b.erase m := snd_pred_mem_erase_of_mem_left h,
have i₁ := finset.card_erase_lt_of_mem w₁,
have i₂ := nat.lt_of_le_of_lt (nat.zero_le _) (finset.card_erase_lt_of_mem w₂),
exact nat.lt_of_le_of_lt i₂ i₁,
end
lemma card_of_mem_right {b : board} {m : ℤ × ℤ} (h : m ∈ right b) : 2 ≤ finset.card b :=
begin
have w₁ : m ∈ b := (finset.mem_inter.1 h).1,
have w₂ := fst_pred_mem_erase_of_mem_right h,
have i₁ := finset.card_erase_lt_of_mem w₁,
have i₂ := nat.lt_of_le_of_lt (nat.zero_le _) (finset.card_erase_lt_of_mem w₂),
exact nat.lt_of_le_of_lt i₂ i₁,
end
lemma move_left_card {b : board} {m : ℤ × ℤ} (h : m ∈ left b) :
finset.card (move_left b m) + 2 = finset.card b :=
begin
dsimp [move_left],
rw finset.card_erase_of_mem (snd_pred_mem_erase_of_mem_left h),
rw finset.card_erase_of_mem (finset.mem_of_mem_inter_left h),
exact tsub_add_cancel_of_le (card_of_mem_left h),
end
lemma move_right_card {b : board} {m : ℤ × ℤ} (h : m ∈ right b) :
finset.card (move_right b m) + 2 = finset.card b :=
begin
dsimp [move_right],
rw finset.card_erase_of_mem (fst_pred_mem_erase_of_mem_right h),
rw finset.card_erase_of_mem (finset.mem_of_mem_inter_left h),
exact tsub_add_cancel_of_le (card_of_mem_right h),
end
lemma move_left_smaller {b : board} {m : ℤ × ℤ} (h : m ∈ left b) :
finset.card (move_left b m) / 2 < finset.card b / 2 :=
by simp [←move_left_card h, lt_add_one]
lemma move_right_smaller {b : board} {m : ℤ × ℤ} (h : m ∈ right b) :
finset.card (move_right b m) / 2 < finset.card b / 2 :=
by simp [←move_right_card h, lt_add_one]
/-- The instance describing allowed moves on a Domineering board. -/
instance state : state board :=
{ turn_bound := λ s, s.card / 2,
L := λ s, (left s).image (move_left s),
R := λ s, (right s).image (move_right s),
left_bound := λ s t m,
begin
simp only [finset.mem_image, prod.exists] at m,
rcases m with ⟨_, _, ⟨h, rfl⟩⟩,
exact move_left_smaller h
end,
right_bound := λ s t m,
begin
simp only [finset.mem_image, prod.exists] at m,
rcases m with ⟨_, _, ⟨h, rfl⟩⟩,
exact move_right_smaller h
end, }
end domineering
/-- Construct a pre-game from a Domineering board. -/
def domineering (b : domineering.board) : pgame := pgame.of_state b
/-- All games of Domineering are short, because each move removes two squares. -/
instance short_domineering (b : domineering.board) : short (domineering b) :=
by { dsimp [domineering], apply_instance }
/-- The Domineering board with two squares arranged vertically, in which Left has the only move. -/
def domineering.one := domineering ([(0,0), (0,1)].to_finset)
/-- The `L` shaped Domineering board, in which Left is exactly half a move ahead. -/
def domineering.L := domineering ([(0,2), (0,1), (0,0), (1,0)].to_finset)
instance short_one : short domineering.one := by { dsimp [domineering.one], apply_instance }
instance short_L : short domineering.L := by { dsimp [domineering.L], apply_instance }
-- The VM can play small games successfully:
-- #eval to_bool (domineering.one ≈ 1)
-- #eval to_bool (domineering.L + domineering.L ≈ 1)
-- The following no longer works since Lean 3.29, since definitions by well-founded
-- recursion no longer reduce definitionally.
-- We can check that `decidable` instances reduce as expected,
-- and so our implementation of domineering is computable.
-- run_cmd tactic.whnf `(by apply_instance : decidable (domineering.one ≤ 1)) >>= tactic.trace
-- dec_trivial can handle most of the dictionary of small games described in [conway2001]
-- example : domineering.one ≈ 1 := dec_trivial
-- example : domineering.L + domineering.L ≈ 1 := dec_trivial
-- example : domineering.L ≈ pgame.of_lists [0] [1] := dec_trivial
-- example : (domineering ([(0,0), (0,1), (0,2), (0,3)].to_finset) ≈ 2) := dec_trivial
-- example : (domineering ([(0,0), (0,1), (1,0), (1,1)].to_finset) ≈ pgame.of_lists [1] [-1]) :=
-- dec_trivial.
-- The 3x3 grid is doable, but takes a minute...
-- example :
-- (domineering ([(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)].to_finset) ≈
-- pgame.of_lists [1] [-1]) := dec_trivial
-- The 5x5 grid is actually 0, but brute-forcing this is too challenging even for the VM.
-- #eval to_bool (domineering ([
-- (0,0), (0,1), (0,2), (0,3), (0,4),
-- (1,0), (1,1), (1,2), (1,3), (1,4),
-- (2,0), (2,1), (2,2), (2,3), (2,4),
-- (3,0), (3,1), (3,2), (3,3), (3,4),
-- (4,0), (4,1), (4,2), (4,3), (4,4)
-- ].to_finset) ≈ 0)
end pgame
|
f5c929b205214ac00b53ee5b22ae0de9c09ba5ca | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/data/int/gcd.lean | 079dda2a431ca451b43960c05a3f401ed20e9837 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 4,709 | lean | /-
Copyright (c) 2018 Guy Leroy. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sangwoo Jo (aka Jason), Guy Leroy, Johannes Hölzl
Greatest common divisor (gcd) and least common multiple (lcm) for integers.
This sets up ℤ to be a GCD domain, and introduces rules about `int.gcd`, as well as `int.lcm`.
NOTE: If you add rules to this theory, check that the corresponding rules are available for
`gcd_domain`.
-/
import data.int.basic data.nat.prime
/- Extended Euclidean algorithm -/
namespace nat
def xgcd_aux : ℕ → ℤ → ℤ → ℕ → ℤ → ℤ → ℕ × ℤ × ℤ
| 0 s t r' s' t' := (r', s', t')
| r@(succ _) s t r' s' t' :=
have r' % r < r, from mod_lt _ $ succ_pos _,
let q := r' / r in xgcd_aux (r' % r) (s' - q * s) (t' - q * t) r s t
@[simp] theorem xgcd_zero_left {s t r' s' t'} : xgcd_aux 0 s t r' s' t' = (r', s', t') :=
by simp [xgcd_aux]
@[simp] theorem xgcd_aux_rec {r s t r' s' t'} (h : 0 < r) : xgcd_aux r s t r' s' t' = xgcd_aux (r' % r) (s' - (r' / r) * s) (t' - (r' / r) * t) r s t :=
by cases r; [exact absurd h (lt_irrefl _), {simp only [xgcd_aux], refl}]
/-- Use the extended GCD algorithm to generate the `a` and `b` values
satisfying `gcd x y = x * a + y * b`. -/
def xgcd (x y : ℕ) : ℤ × ℤ := (xgcd_aux x 1 0 y 0 1).2
/-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/
def gcd_a (x y : ℕ) : ℤ := (xgcd x y).1
/-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/
def gcd_b (x y : ℕ) : ℤ := (xgcd x y).2
@[simp] theorem xgcd_aux_fst (x y) : ∀ s t s' t',
(xgcd_aux x s t y s' t').1 = gcd x y :=
gcd.induction x y (by simp) (λ x y h IH s t s' t', by simp [h, IH]; rw ← gcd_rec)
theorem xgcd_aux_val (x y) : xgcd_aux x 1 0 y 0 1 = (gcd x y, xgcd x y) :=
by rw [xgcd, ← xgcd_aux_fst x y 1 0 0 1]; cases xgcd_aux x 1 0 y 0 1; refl
theorem xgcd_val (x y) : xgcd x y = (gcd_a x y, gcd_b x y) :=
by unfold gcd_a gcd_b; cases xgcd x y; refl
section
parameters (a b : ℕ)
private def P : ℕ × ℤ × ℤ → Prop | (r, s, t) := (r : ℤ) = a * s + b * t
theorem xgcd_aux_P {r r'} : ∀ {s t s' t'}, P (r, s, t) → P (r', s', t') → P (xgcd_aux r s t r' s' t') :=
gcd.induction r r' (by simp) $ λ x y h IH s t s' t' p p', begin
rw [xgcd_aux_rec h], refine IH _ p, dsimp [P] at *,
rw [int.mod_def], generalize : (y / x : ℤ) = k,
rw [p, p'], simp [mul_add, mul_comm, mul_left_comm]
end
theorem gcd_eq_gcd_ab : (gcd a b : ℤ) = a * gcd_a a b + b * gcd_b a b :=
by have := @xgcd_aux_P a b a b 1 0 0 1 (by simp [P]) (by simp [P]);
rwa [xgcd_aux_val, xgcd_val] at this
end
end nat
namespace int
theorem nat_abs_div (a b : ℤ) (H : b ∣ a) : nat_abs (a / b) = (nat_abs a) / (nat_abs b) :=
begin
cases (nat.eq_zero_or_pos (nat_abs b)),
rw eq_zero_of_nat_abs_eq_zero h,
simp,
calc
nat_abs (a / b) = nat_abs (a / b) * 1 : by rw mul_one
... = nat_abs (a / b) * (nat_abs b / nat_abs b) : by rw nat.div_self h
... = nat_abs (a / b) * nat_abs b / nat_abs b : by rw (nat.mul_div_assoc _ (dvd_refl _))
... = nat_abs (a / b * b) / nat_abs b : by rw (nat_abs_mul (a / b) b)
... = nat_abs a / nat_abs b : by rw int.div_mul_cancel H,
end
theorem nat_abs_dvd_abs_iff {i j : ℤ} : i.nat_abs ∣ j.nat_abs ↔ i ∣ j :=
⟨assume (H : i.nat_abs ∣ j.nat_abs), dvd_nat_abs.mp (nat_abs_dvd.mp (coe_nat_dvd.mpr H)),
assume H : (i ∣ j), coe_nat_dvd.mp (dvd_nat_abs.mpr (nat_abs_dvd.mpr H))⟩
lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : nat.prime p) {m n : ℤ} {k l : ℕ}
(hpm : ↑(p ^ k) ∣ m)
(hpn : ↑(p ^ l) ∣ n) (hpmn : ↑(p ^ (k+l+1)) ∣ m*n) : ↑(p ^ (k+1)) ∣ m ∨ ↑(p ^ (l+1)) ∣ n :=
have hpm' : p ^ k ∣ m.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpm,
have hpn' : p ^ l ∣ n.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpn,
have hpmn' : (p ^ (k+l+1)) ∣ m.nat_abs*n.nat_abs,
by rw ←int.nat_abs_mul; apply (int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpmn),
let hsd := nat.succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul p_prime hpm' hpn' hpmn' in
hsd.elim
(λ hsd1, or.inl begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd1 end)
(λ hsd2, or.inr begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd2 end)
theorem dvd_of_mul_dvd_mul_left {i j k : ℤ} (k_non_zero : k ≠ 0) (H : k * i ∣ k * j) : i ∣ j :=
dvd.elim H (λl H1, by rw mul_assoc at H1; exact ⟨_, eq_of_mul_eq_mul_left k_non_zero H1⟩)
theorem dvd_of_mul_dvd_mul_right {i j k : ℤ} (k_non_zero : k ≠ 0) (H : i * k ∣ j * k) : i ∣ j :=
by rw [mul_comm i k, mul_comm j k] at H; exact dvd_of_mul_dvd_mul_left k_non_zero H
end int
|
e7243e4b350231f555ee07e95b3404ec30f5fea5 | ee8cdbabf07f77e7be63a449b8483ce308d37218 | /lean/src/valid/mathd-algebra-119.lean | 7566467ebeacd76a42e6e56cf6adaa939ae1eecd | [
"MIT",
"Apache-2.0"
] | permissive | zeta1999/miniF2F | 6d66c75d1c18152e224d07d5eed57624f731d4b7 | c1ba9629559c5273c92ec226894baa0c1ce27861 | refs/heads/main | 1,681,897,460,642 | 1,620,646,361,000 | 1,620,646,361,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 272 | lean | /-
Copyright (c) 2021 OpenAI. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kunhao Zheng
-/
import data.real.basic
example (d e : ℝ) (h₀ : 2 * d = 17 * e - 8) (h₁ : 2 * e = d - 9) : e = 2 :=
begin
linarith,
end
|
8a39e50d89976b91a5ce3840829497e603ed37ac | 26bff4ed296b8373c92b6b025f5d60cdf02104b9 | /tests/lean/run/fold.lean | 061d9a2f2999e48a83934f8b4da5dfc6f2ff39bb | [
"Apache-2.0"
] | permissive | guiquanz/lean | b8a878ea24f237b84b0e6f6be2f300e8bf028229 | 242f8ba0486860e53e257c443e965a82ee342db3 | refs/heads/master | 1,526,680,092,098 | 1,427,492,833,000 | 1,427,493,281,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 257 | lean | definition id {A : Type} (a : A) := a
example (a b c : nat) : id a = id b → a = b :=
begin
intro H,
fold {id a, id b},
assumption
end
example (a b c : nat) : id a = id b → a = b :=
begin
intro H,
fold (id a),
fold (id b),
assumption
end
|
09ae90079dd1a7c793fe182cc02b3162756b16bf | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/inj_tac.lean | ac8b1625ce2e4edbca8b01f5c65ac69cea0ba0e4 | [
"Apache-2.0"
] | permissive | soonhokong/lean | cb8aa01055ffe2af0fb99a16b4cda8463b882cd1 | 38607e3eb57f57f77c0ac114ad169e9e4262e24f | refs/heads/master | 1,611,187,284,081 | 1,450,766,737,000 | 1,476,122,547,000 | 11,513,992 | 2 | 0 | null | 1,401,763,102,000 | 1,374,182,235,000 | C++ | UTF-8 | Lean | false | false | 1,254 | lean | import data.examples.vector
open nat vector
example (a b : nat) : succ a = succ b → a + 2 = b + 2 :=
begin
intro H,
injection H with aeqb,
rewrite aeqb
end
example (A : Type) (n : nat) (v w : vector A n) (a : A) (b : A) :
a :: v = a :: w → b :: v = b :: w :=
begin
intro H, injection H with veqw,
rewrite veqw
end
example (A : Type) (n : nat) (v w : vector A n) (a : A) (b : A) :
a :: v = b :: w → b :: v = a :: w :=
begin
intro H, injection H with aeqb veqw,
rewrite [aeqb, veqw]
end
example (A : Type) (a₁ a₂ a₃ b₁ b₂ b₃ : A) : (a₁, a₂, a₃) = (b₁, b₂, b₃) → b₁ = a₁ :=
begin
intro H, injection H with a₁b₁ a₂b₂ a₃b₃,
rewrite a₁b₁
end
example (A : Type) (a₁ a₂ a₃ b₁ b₂ b₃ : A) : (a₁ :: [], a₂, a₃) = (b₁ :: [], b₂, b₃) → b₁ = a₁ :=
begin
intro H, injection H with a₁b₁ a₂b₂ a₃b₃,
rewrite a₁b₁
end
example (a₁ a₂ a₃ b₁ b₂ b₃ : nat) : (a₁+2, a₂+3, a₃+1) = (b₁+2, b₂+2, b₃+2) → b₁ = a₁ ∧ a₃ = b₃+1 ∧ b₂ = succ a₂ :=
begin
intro H, injection H with a₁b₁ sa₂b₂ a₃sb₃,
esimp at *,
krewrite [a₁b₁, a₃sb₃, -sa₂b₂],
repeat (split | esimp)
end
|
c249a9b19ab257d6be38beca30c085db42f2e3d1 | 7b89826c26634aa18c0110f1634f73027851edfe | /logic_and_proof/src/04-01.lean | 32e30046cc44efb237dfc1f471104700bbbea45d | [
"MIT"
] | permissive | marcofavorito/leanings | b7642344d8c9012a1cec74a804c5884297880c4d | 581b83be66ff4f8dd946fb6a1bb045d2ddf91076 | refs/heads/master | 1,672,310,991,244 | 1,603,031,766,000 | 1,603,031,766,000 | 279,163,004 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 47 | lean | variables A B C : Prop
#check A ∧ ¬ B → C |
9a0dcd1fcb6e758a84eee2696183e1c5c8136ce4 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/field_theory/krull_topology.lean | 2fd5df4c58e10b1cde8669f527a4634fb9b84e6f | [
"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 | 8,839 | lean | /-
Copyright (c) 2022 Sebastian Monnet. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Monnet
-/
import field_theory.galois
import topology.algebra.filter_basis
import algebra.algebra.subalgebra
/-!
# Krull topology
We define the Krull topology on `L ≃ₐ[K] L` for an arbitrary field extension `L/K`. In order to do
this, we first define a `group_filter_basis` on `L ≃ₐ[K] L`, whose sets are `E.fixing_subgroup` for
all intermediate fields `E` with `E/K` finite dimensional.
## Main Definitions
- `finite_exts K L`. Given a field extension `L/K`, this is the set of intermediate fields that are
finite-dimensional over `K`.
- `fixed_by_finite K L`. Given a field extension `L/K`, `fixed_by_finite K L` is the set of
subsets `Gal(L/E)` of `Gal(L/K)`, where `E/K` is finite
- `gal_basis K L`. Given a field extension `L/K`, this is the filter basis on `L ≃ₐ[K] L` whose
sets are `Gal(L/E)` for intermediate fields `E` with `E/K` finite.
- `gal_group_basis K L`. This is the same as `gal_basis K L`, but with the added structure
that it is a group filter basis on `L ≃ₐ[K] L`, rather than just a filter basis.
- `krull_topology K L`. Given a field extension `L/K`, this is the topology on `L ≃ₐ[K] L`, induced
by the group filter basis `gal_group_basis K L`.
## Notations
- In docstrings, we will write `Gal(L/E)` to denote the fixing subgroup of an intermediate field
`E`. That is, `Gal(L/E)` is the subgroup of `L ≃ₐ[K] L` consisting of automorphisms that fix
every element of `E`. In particular, we distinguish between `L ≃ₐ[E] L` and `Gal(L/E)`, since the
former is defined to be a subgroup of `L ≃ₐ[K] L`, while the latter is a group in its own right.
## Implementation Notes
- `krull_topology K L` is defined as an instance for type class inference.
-/
open_locale classical
/-- Mapping intermediate fields along algebra equivalences preserves the partial order -/
lemma intermediate_field.map_mono {K L M : Type*} [field K] [field L] [field M]
[algebra K L] [algebra K M] {E1 E2 : intermediate_field K L}
(e : L ≃ₐ[K] M) (h12 : E1 ≤ E2) : E1.map e.to_alg_hom ≤ E2.map e.to_alg_hom :=
set.image_subset e h12
/-- Mapping intermediate fields along the identity does not change them -/
lemma intermediate_field.map_id {K L : Type*} [field K] [field L] [algebra K L]
(E : intermediate_field K L) :
E.map (alg_hom.id K L) = E :=
set_like.coe_injective $ set.image_id _
/-- Mapping a finite dimensional intermediate field along an algebra equivalence gives
a finite-dimensional intermediate field. -/
instance im_finite_dimensional {K L : Type*} [field K] [field L] [algebra K L]
{E : intermediate_field K L} (σ : L ≃ₐ[K] L) [finite_dimensional K E]:
finite_dimensional K (E.map σ.to_alg_hom) :=
linear_equiv.finite_dimensional (intermediate_field.intermediate_field_map σ E).to_linear_equiv
/-- Given a field extension `L/K`, `finite_exts K L` is the set of
intermediate field extensions `L/E/K` such that `E/K` is finite -/
def finite_exts (K : Type*) [field K] (L : Type*) [field L] [algebra K L] :
set (intermediate_field K L) :=
{E | finite_dimensional K E}
/-- Given a field extension `L/K`, `fixed_by_finite K L` is the set of
subsets `Gal(L/E)` of `L ≃ₐ[K] L`, where `E/K` is finite -/
def fixed_by_finite (K L : Type*) [field K] [field L] [algebra K L]: set (subgroup (L ≃ₐ[K] L)) :=
intermediate_field.fixing_subgroup '' (finite_exts K L)
/-- For an field extension `L/K`, the intermediate field `K` is finite-dimensional over `K` -/
lemma intermediate_field.finite_dimensional_bot (K L : Type*) [field K]
[field L] [algebra K L] : finite_dimensional K (⊥ : intermediate_field K L) :=
finite_dimensional_of_dim_eq_one intermediate_field.dim_bot
/-- This lemma says that `Gal(L/K) = L ≃ₐ[K] L` -/
lemma intermediate_field.fixing_subgroup.bot {K L : Type*} [field K]
[field L] [algebra K L] :
intermediate_field.fixing_subgroup (⊥ : intermediate_field K L) = ⊤ :=
begin
ext f,
refine ⟨λ _, subgroup.mem_top _, λ _, _⟩,
rintro ⟨x, hx⟩,
rw intermediate_field.mem_bot at hx,
rcases hx with ⟨y, rfl⟩,
exact f.commutes y,
end
/-- If `L/K` is a field extension, then we have `Gal(L/K) ∈ fixed_by_finite K L` -/
lemma top_fixed_by_finite {K L : Type*} [field K] [field L] [algebra K L] :
⊤ ∈ fixed_by_finite K L :=
⟨⊥, intermediate_field.finite_dimensional_bot K L, intermediate_field.fixing_subgroup.bot⟩
/-- If `E1` and `E2` are finite-dimensional intermediate fields, then so is their compositum.
This rephrases a result already in mathlib so that it is compatible with our type classes -/
lemma finite_dimensional_sup {K L: Type*} [field K] [field L] [algebra K L]
(E1 E2 : intermediate_field K L) (h1 : finite_dimensional K E1)
(h2 : finite_dimensional K E2) : finite_dimensional K ↥(E1 ⊔ E2) :=
by exactI intermediate_field.finite_dimensional_sup E1 E2
/-- An element of `L ≃ₐ[K] L` is in `Gal(L/E)` if and only if it fixes every element of `E`-/
lemma mem_fixing_subgroup_iff {K L : Type*} [field K] [field L] [algebra K L]
(E : intermediate_field K L) (σ : (L ≃ₐ[K] L)) :
σ ∈ E.fixing_subgroup ↔∀ (x : L), x ∈ E → σ x = x :=
⟨λ hσ x hx, hσ ⟨x, hx⟩, λ h ⟨x, hx⟩, h x hx⟩
/-- The map `E ↦ Gal(L/E)` is inclusion-reversing -/
lemma intermediate_field.fixing_subgroup.antimono {K L : Type*} [field K] [field L] [algebra K L]
{E1 E2 : intermediate_field K L} (h12 : E1 ≤ E2) : E2.fixing_subgroup ≤ E1.fixing_subgroup :=
begin
rintro σ hσ ⟨x, hx⟩,
exact hσ ⟨x, h12 hx⟩,
end
/-- Given a field extension `L/K`, `gal_basis K L` is the filter basis on `L ≃ₐ[K] L` whose sets
are `Gal(L/E)` for intermediate fields `E` with `E/K` finite dimensional -/
def gal_basis (K L : Type*) [field K] [field L] [algebra K L] : filter_basis (L ≃ₐ[K] L) :=
{ sets := subgroup.carrier '' (fixed_by_finite K L),
nonempty := ⟨⊤, ⊤, top_fixed_by_finite, rfl⟩,
inter_sets :=
begin
rintros X Y ⟨H1, ⟨E1, h_E1, rfl⟩, rfl⟩ ⟨H2, ⟨E2, h_E2, rfl⟩, rfl⟩,
use (intermediate_field.fixing_subgroup (E1 ⊔ E2)).carrier,
refine ⟨⟨_, ⟨_, finite_dimensional_sup E1 E2 h_E1 h_E2, rfl⟩, rfl⟩, _⟩,
rw set.subset_inter_iff,
exact ⟨intermediate_field.fixing_subgroup.antimono le_sup_left,
intermediate_field.fixing_subgroup.antimono le_sup_right⟩,
end }
/-- A subset of `L ≃ₐ[K] L` is a member of `gal_basis K L` if and only if it is the underlying set
of `Gal(L/E)` for some finite subextension `E/K`-/
lemma mem_gal_basis_iff (K L : Type*) [field K] [field L] [algebra K L]
(U : set (L ≃ₐ[K] L)) : U ∈ gal_basis K L ↔ U ∈ subgroup.carrier '' (fixed_by_finite K L) :=
iff.rfl
/-- For a field extension `L/K`, `gal_group_basis K L` is the group filter basis on `L ≃ₐ[K] L`
whose sets are `Gal(L/E)` for finite subextensions `E/K` -/
def gal_group_basis (K L : Type*) [field K] [field L] [algebra K L] :
group_filter_basis (L ≃ₐ[K] L) :=
{ to_filter_basis := gal_basis K L,
one' := λ U ⟨H, hH, h2⟩, h2 ▸ H.one_mem,
mul' := λ U hU, ⟨U, hU, begin
rcases hU with ⟨H, hH, rfl⟩,
rintros x ⟨a, b, haH, hbH, rfl⟩,
exact H.mul_mem haH hbH,
end⟩,
inv' := λ U hU, ⟨U, hU, begin
rcases hU with ⟨H, hH, rfl⟩,
exact H.inv_mem',
end⟩,
conj' :=
begin
rintros σ U ⟨H, ⟨E, hE, rfl⟩, rfl⟩,
let F : intermediate_field K L := E.map (σ.symm.to_alg_hom),
refine ⟨F.fixing_subgroup.carrier, ⟨⟨F.fixing_subgroup, ⟨F,
_, rfl⟩, rfl⟩, λ g hg, _⟩⟩,
{ apply im_finite_dimensional σ.symm,
exact hE },
change σ * g * σ⁻¹ ∈ E.fixing_subgroup,
rw mem_fixing_subgroup_iff,
intros x hx,
change σ(g(σ⁻¹ x)) = x,
have h_in_F : σ⁻¹ x ∈ F := ⟨x, hx, by {dsimp, rw ← alg_equiv.inv_fun_eq_symm, refl }⟩,
have h_g_fix : g (σ⁻¹ x) = (σ⁻¹ x),
{ rw [subgroup.mem_carrier, mem_fixing_subgroup_iff F g] at hg,
exact hg (σ⁻¹ x) h_in_F },
rw h_g_fix,
change σ(σ⁻¹ x) = x,
exact alg_equiv.apply_symm_apply σ x,
end }
/-- For a field extension `L/K`, `krull_topology K L` is the topological space structure on
`L ≃ₐ[K] L` induced by the group filter basis `gal_group_basis K L` -/
instance krull_topology (K L : Type*) [field K] [field L] [algebra K L] :
topological_space (L ≃ₐ[K] L) :=
group_filter_basis.topology (gal_group_basis K L)
/-- For a field extension `L/K`, the Krull topology on `L ≃ₐ[K] L` makes it a topological group. -/
instance (K L : Type*) [field K] [field L] [algebra K L] :
topological_group (L ≃ₐ[K] L) :=
group_filter_basis.is_topological_group (gal_group_basis K L)
|
f5bd566688efa6c59c6d06a59a6d816c8d2842cd | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Parser/Extension.lean | 70fecd0ee62af6fa36bbaf545b2a8a03b1b90451 | [
"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 | 32,904 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Parser.Basic
import Lean.Compiler.InitAttr
import Lean.ScopedEnvExtension
import Lean.DocString
/-! Extensible parsing via attributes -/
namespace Lean
namespace Parser
builtin_initialize builtinTokenTable : IO.Ref TokenTable ← IO.mkRef {}
/- Global table with all SyntaxNodeKind's -/
builtin_initialize builtinSyntaxNodeKindSetRef : IO.Ref SyntaxNodeKindSet ← IO.mkRef {}
def registerBuiltinNodeKind (k : SyntaxNodeKind) : IO Unit :=
builtinSyntaxNodeKindSetRef.modify fun s => s.insert k
builtin_initialize
registerBuiltinNodeKind choiceKind
registerBuiltinNodeKind identKind
registerBuiltinNodeKind strLitKind
registerBuiltinNodeKind numLitKind
registerBuiltinNodeKind scientificLitKind
registerBuiltinNodeKind charLitKind
registerBuiltinNodeKind nameLitKind
builtin_initialize builtinParserCategoriesRef : IO.Ref ParserCategories ← IO.mkRef {}
private def throwParserCategoryAlreadyDefined {α} (catName : Name) : ExceptT String Id α :=
throw s!"parser category '{catName}' has already been defined"
private def addParserCategoryCore (categories : ParserCategories) (catName : Name) (initial : ParserCategory) : Except String ParserCategories :=
if categories.contains catName then
throwParserCategoryAlreadyDefined catName
else
pure $ categories.insert catName initial
/-- All builtin parser categories are Pratt's parsers -/
private def addBuiltinParserCategory (catName declName : Name) (behavior : LeadingIdentBehavior) : IO Unit := do
let categories ← builtinParserCategoriesRef.get
let categories ← IO.ofExcept $ addParserCategoryCore categories catName { declName, behavior }
builtinParserCategoriesRef.set categories
namespace ParserExtension
inductive OLeanEntry where
| token (val : Token) : OLeanEntry
| kind (val : SyntaxNodeKind) : OLeanEntry
| category (catName : Name) (declName : Name) (behavior : LeadingIdentBehavior)
| parser (catName : Name) (declName : Name) (prio : Nat) : OLeanEntry
deriving Inhabited
inductive Entry where
| token (val : Token) : Entry
| kind (val : SyntaxNodeKind) : Entry
| category (catName : Name) (declName : Name) (behavior : LeadingIdentBehavior)
| parser (catName : Name) (declName : Name) (leading : Bool) (p : Parser) (prio : Nat) : Entry
deriving Inhabited
def Entry.toOLeanEntry : Entry → OLeanEntry
| token v => OLeanEntry.token v
| kind v => OLeanEntry.kind v
| category c d b => OLeanEntry.category c d b
| parser c d _ _ prio => OLeanEntry.parser c d prio
structure State where
tokens : TokenTable := {}
kinds : SyntaxNodeKindSet := {}
categories : ParserCategories := {}
deriving Inhabited
end ParserExtension
open ParserExtension in
abbrev ParserExtension := ScopedEnvExtension OLeanEntry Entry State
private def ParserExtension.mkInitial : IO ParserExtension.State := do
let tokens ← builtinTokenTable.get
let kinds ← builtinSyntaxNodeKindSetRef.get
let categories ← builtinParserCategoriesRef.get
pure { tokens := tokens, kinds := kinds, categories := categories }
private def addTokenConfig (tokens : TokenTable) (tk : Token) : Except String TokenTable := do
if tk == "" then throw "invalid empty symbol"
else match tokens.find? tk with
| none => pure $ tokens.insert tk tk
| some _ => pure tokens
def throwUnknownParserCategory {α} (catName : Name) : ExceptT String Id α :=
throw s!"unknown parser category '{catName}'"
abbrev getCategory (categories : ParserCategories) (catName : Name) : Option ParserCategory :=
categories.find? catName
def addLeadingParser (categories : ParserCategories) (catName declName : Name) (p : Parser) (prio : Nat) : Except String ParserCategories :=
match getCategory categories catName with
| none =>
throwUnknownParserCategory catName
| some cat =>
let kinds := cat.kinds.insert declName
let addTokens (tks : List Token) : Except String ParserCategories :=
let tks := tks.map Name.mkSimple
let tables := tks.eraseDups.foldl (init := cat.tables) fun tables tk =>
{ tables with leadingTable := tables.leadingTable.insert tk (p, prio) }
pure $ categories.insert catName { cat with kinds, tables }
match p.info.firstTokens with
| FirstTokens.tokens tks => addTokens tks
| FirstTokens.optTokens tks => addTokens tks
| _ =>
let tables := { cat.tables with leadingParsers := (p, prio) :: cat.tables.leadingParsers }
pure $ categories.insert catName { cat with kinds, tables }
private def addTrailingParserAux (tables : PrattParsingTables) (p : TrailingParser) (prio : Nat) : PrattParsingTables :=
let addTokens (tks : List Token) : PrattParsingTables :=
let tks := tks.map fun tk => Name.mkSimple tk
tks.eraseDups.foldl (init := tables) fun tables tk =>
{ tables with trailingTable := tables.trailingTable.insert tk (p, prio) }
match p.info.firstTokens with
| FirstTokens.tokens tks => addTokens tks
| FirstTokens.optTokens tks => addTokens tks
| _ => { tables with trailingParsers := (p, prio) :: tables.trailingParsers }
def addTrailingParser (categories : ParserCategories) (catName declName : Name) (p : TrailingParser) (prio : Nat) : Except String ParserCategories :=
match getCategory categories catName with
| none => throwUnknownParserCategory catName
| some cat =>
let kinds := cat.kinds.insert declName
let tables := addTrailingParserAux cat.tables p prio
pure $ categories.insert catName { cat with kinds, tables }
def addParser (categories : ParserCategories) (catName declName : Name)
(leading : Bool) (p : Parser) (prio : Nat) : Except String ParserCategories := do
match leading, p with
| true, p => addLeadingParser categories catName declName p prio
| false, p => addTrailingParser categories catName declName p prio
def addParserTokens (tokenTable : TokenTable) (info : ParserInfo) : Except String TokenTable :=
let newTokens := info.collectTokens []
newTokens.foldlM addTokenConfig tokenTable
private def updateBuiltinTokens (info : ParserInfo) (declName : Name) : IO Unit := do
let tokenTable ← builtinTokenTable.swap {}
match addParserTokens tokenTable info with
| Except.ok tokenTable => builtinTokenTable.set tokenTable
| Except.error msg => throw (IO.userError s!"invalid builtin parser '{declName}', {msg}")
def ParserExtension.addEntryImpl (s : State) (e : Entry) : State :=
match e with
| Entry.token tk =>
match addTokenConfig s.tokens tk with
| Except.ok tokens => { s with tokens }
| _ => unreachable!
| Entry.kind k =>
{ s with kinds := s.kinds.insert k }
| Entry.category catName declName behavior =>
if s.categories.contains catName then s
else { s with
categories := s.categories.insert catName { declName, behavior } }
| Entry.parser catName declName leading parser prio =>
match addParser s.categories catName declName leading parser prio with
| Except.ok categories => { s with categories }
| _ => unreachable!
/-- Parser aliases for making `ParserDescr` extensible -/
inductive AliasValue (α : Type) where
| const (p : α)
| unary (p : α → α)
| binary (p : α → α → α)
abbrev AliasTable (α) := NameMap (AliasValue α)
def registerAliasCore {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) (value : AliasValue α) : IO Unit := do
unless (← initializing) do throw ↑"aliases can only be registered during initialization"
if (← mapRef.get).contains aliasName then
throw ↑s!"alias '{aliasName}' has already been declared"
mapRef.modify (·.insert aliasName value)
def getAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO (Option (AliasValue α)) := do
return (← mapRef.get).find? aliasName
def getConstAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO α := do
match (← getAlias mapRef aliasName) with
| some (AliasValue.const v) => pure v
| some (AliasValue.unary _) => throw ↑s!"parser '{aliasName}' is not a constant, it takes one argument"
| some (AliasValue.binary _) => throw ↑s!"parser '{aliasName}' is not a constant, it takes two arguments"
| none => throw ↑s!"parser '{aliasName}' was not found"
def getUnaryAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO (α → α) := do
match (← getAlias mapRef aliasName) with
| some (AliasValue.unary v) => pure v
| some _ => throw ↑s!"parser '{aliasName}' does not take one argument"
| none => throw ↑s!"parser '{aliasName}' was not found"
def getBinaryAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO (α → α → α) := do
match (← getAlias mapRef aliasName) with
| some (AliasValue.binary v) => pure v
| some _ => throw ↑s!"parser '{aliasName}' does not take two arguments"
| none => throw ↑s!"parser '{aliasName}' was not found"
abbrev ParserAliasValue := AliasValue Parser
structure ParserAliasInfo where
declName : Name := .anonymous
/-- Number of syntax nodes produced by this parser. `none` means "sum of input sizes". -/
stackSz? : Option Nat := some 1
/-- Whether arguments should be wrapped in `group(·)` if they do not produce exactly one syntax node. -/
autoGroupArgs : Bool := stackSz?.isSome
builtin_initialize parserAliasesRef : IO.Ref (NameMap ParserAliasValue) ← IO.mkRef {}
builtin_initialize parserAlias2kindRef : IO.Ref (NameMap SyntaxNodeKind) ← IO.mkRef {}
builtin_initialize parserAliases2infoRef : IO.Ref (NameMap ParserAliasInfo) ← IO.mkRef {}
def getParserAliasInfo (aliasName : Name) : IO ParserAliasInfo := do
return (← parserAliases2infoRef.get).findD aliasName {}
-- Later, we define macro `register_parser_alias` which registers a parser, formatter and parenthesizer
def registerAlias (aliasName declName : Name) (p : ParserAliasValue) (kind? : Option SyntaxNodeKind := none) (info : ParserAliasInfo := {}) : IO Unit := do
registerAliasCore parserAliasesRef aliasName p
if let some kind := kind? then
parserAlias2kindRef.modify (·.insert aliasName kind)
parserAliases2infoRef.modify (·.insert aliasName { info with declName })
instance : Coe Parser ParserAliasValue := { coe := AliasValue.const }
instance : Coe (Parser → Parser) ParserAliasValue := { coe := AliasValue.unary }
instance : Coe (Parser → Parser → Parser) ParserAliasValue := { coe := AliasValue.binary }
def isParserAlias (aliasName : Name) : IO Bool := do
match (← getAlias parserAliasesRef aliasName) with
| some _ => pure true
| _ => pure false
def getSyntaxKindOfParserAlias? (aliasName : Name) : IO (Option SyntaxNodeKind) :=
return (← parserAlias2kindRef.get).find? aliasName
def ensureUnaryParserAlias (aliasName : Name) : IO Unit :=
discard $ getUnaryAlias parserAliasesRef aliasName
def ensureBinaryParserAlias (aliasName : Name) : IO Unit :=
discard $ getBinaryAlias parserAliasesRef aliasName
def ensureConstantParserAlias (aliasName : Name) : IO Unit :=
discard $ getConstAlias parserAliasesRef aliasName
unsafe def mkParserOfConstantUnsafe (constName : Name) (compileParserDescr : ParserDescr → ImportM Parser) : ImportM (Bool × Parser) := do
let env := (← read).env
let opts := (← read).opts
match env.find? constName with
| none => throw ↑s!"unknown constant '{constName}'"
| some info =>
match info.type with
| Expr.const `Lean.Parser.TrailingParser _ =>
let p ← IO.ofExcept $ env.evalConst Parser opts constName
pure ⟨false, p⟩
| Expr.const `Lean.Parser.Parser _ =>
let p ← IO.ofExcept $ env.evalConst Parser opts constName
pure ⟨true, p⟩
| Expr.const `Lean.ParserDescr _ =>
let d ← IO.ofExcept $ env.evalConst ParserDescr opts constName
let p ← compileParserDescr d
pure ⟨true, p⟩
| Expr.const `Lean.TrailingParserDescr _ =>
let d ← IO.ofExcept $ env.evalConst TrailingParserDescr opts constName
let p ← compileParserDescr d
pure ⟨false, p⟩
| _ => throw ↑s!"unexpected parser type at '{constName}' (`ParserDescr`, `TrailingParserDescr`, `Parser` or `TrailingParser` expected)"
@[implemented_by mkParserOfConstantUnsafe]
opaque mkParserOfConstantAux (constName : Name) (compileParserDescr : ParserDescr → ImportM Parser) : ImportM (Bool × Parser)
partial def compileParserDescr (categories : ParserCategories) (d : ParserDescr) : ImportM Parser :=
let rec visit : ParserDescr → ImportM Parser
| ParserDescr.const n => getConstAlias parserAliasesRef n
| ParserDescr.unary n d => return (← getUnaryAlias parserAliasesRef n) (← visit d)
| ParserDescr.binary n d₁ d₂ => return (← getBinaryAlias parserAliasesRef n) (← visit d₁) (← visit d₂)
| ParserDescr.node k prec d => return leadingNode k prec (← visit d)
| ParserDescr.nodeWithAntiquot n k d => return withCache k (nodeWithAntiquot n k (← visit d) (anonymous := true))
| ParserDescr.sepBy p sep psep trail => return sepBy (← visit p) sep (← visit psep) trail
| ParserDescr.sepBy1 p sep psep trail => return sepBy1 (← visit p) sep (← visit psep) trail
| ParserDescr.trailingNode k prec lhsPrec d => return trailingNode k prec lhsPrec (← visit d)
| ParserDescr.symbol tk => return symbol tk
| ParserDescr.nonReservedSymbol tk includeIdent => return nonReservedSymbol tk includeIdent
| ParserDescr.parser constName => do
let (_, p) ← mkParserOfConstantAux constName visit;
pure p
| ParserDescr.cat catName prec =>
match getCategory categories catName with
| some _ => pure $ categoryParser catName prec
| none => IO.ofExcept $ throwUnknownParserCategory catName
visit d
def mkParserOfConstant (categories : ParserCategories) (constName : Name) : ImportM (Bool × Parser) :=
mkParserOfConstantAux constName (compileParserDescr categories)
structure ParserAttributeHook where
/-- Called after a parser attribute is applied to a declaration. -/
postAdd (catName : Name) (declName : Name) (builtin : Bool) : AttrM Unit
builtin_initialize parserAttributeHooks : IO.Ref (List ParserAttributeHook) ← IO.mkRef {}
def registerParserAttributeHook (hook : ParserAttributeHook) : IO Unit := do
parserAttributeHooks.modify fun hooks => hook::hooks
def runParserAttributeHooks (catName : Name) (declName : Name) (builtin : Bool) : AttrM Unit := do
let hooks ← parserAttributeHooks.get
hooks.forM fun hook => hook.postAdd catName declName builtin
builtin_initialize
registerBuiltinAttribute {
name := `run_builtin_parser_attribute_hooks
descr := "explicitly run hooks normally activated by builtin parser attributes"
add := fun decl stx _ => do
Attribute.Builtin.ensureNoArgs stx
runParserAttributeHooks Name.anonymous decl (builtin := true)
}
builtin_initialize
registerBuiltinAttribute {
name := `run_parser_attribute_hooks
descr := "explicitly run hooks normally activated by parser attributes"
add := fun decl stx _ => do
Attribute.Builtin.ensureNoArgs stx
runParserAttributeHooks Name.anonymous decl (builtin := false)
}
private def ParserExtension.OLeanEntry.toEntry (s : State) : OLeanEntry → ImportM Entry
| token tk => return Entry.token tk
| kind k => return Entry.kind k
| category c d l => return Entry.category c d l
| parser catName declName prio => do
let (leading, p) ← mkParserOfConstant s.categories declName
return Entry.parser catName declName leading p prio
builtin_initialize parserExtension : ParserExtension ←
registerScopedEnvExtension {
mkInitial := ParserExtension.mkInitial
addEntry := ParserExtension.addEntryImpl
toOLeanEntry := ParserExtension.Entry.toOLeanEntry
ofOLeanEntry := ParserExtension.OLeanEntry.toEntry
}
def isParserCategory (env : Environment) (catName : Name) : Bool :=
(parserExtension.getState env).categories.contains catName
def addParserCategory (env : Environment) (catName declName : Name) (behavior : LeadingIdentBehavior) : Except String Environment := do
if isParserCategory env catName then
throwParserCategoryAlreadyDefined catName
else
return parserExtension.addEntry env <| ParserExtension.Entry.category catName declName behavior
def leadingIdentBehavior (env : Environment) (catName : Name) : LeadingIdentBehavior :=
match getCategory (parserExtension.getState env).categories catName with
| none => LeadingIdentBehavior.default
| some cat => cat.behavior
unsafe def evalParserConstUnsafe (declName : Name) : ParserFn := fun ctx s => unsafeBaseIO do
let categories := (parserExtension.getState ctx.env).categories
match (← (mkParserOfConstant categories declName { env := ctx.env, opts := ctx.options }).toBaseIO) with
| .ok (_, p) =>
-- We should manually register `p`'s tokens before invoking it as it might not be part of any syntax category (yet)
return adaptUncacheableContextFn (fun ctx => { ctx with tokens := p.info.collectTokens [] |>.foldl (fun tks tk => tks.insert tk tk) ctx.tokens }) p.fn ctx s
| .error e => return s.mkUnexpectedError e.toString
@[implemented_by evalParserConstUnsafe]
opaque evalParserConst (declName : Name) : ParserFn
register_builtin_option internal.parseQuotWithCurrentStage : Bool := {
defValue := false
group := "internal"
descr := "(Lean bootstrapping) use parsers from the current stage inside quotations"
}
/-- Run `declName` if possible and inside a quotation, or else `p`. The `ParserInfo` will always be taken from `p`. -/
def evalInsideQuot (declName : Name) : Parser → Parser := withFn fun f c s =>
if c.quotDepth > 0 && !c.suppressInsideQuot && internal.parseQuotWithCurrentStage.get c.options && c.env.contains declName then
evalParserConst declName c s
else
f c s
def addBuiltinParser (catName : Name) (declName : Name) (leading : Bool) (p : Parser) (prio : Nat) : IO Unit := do
let p := evalInsideQuot declName p
let categories ← builtinParserCategoriesRef.get
let categories ← IO.ofExcept $ addParser categories catName declName leading p prio
builtinParserCategoriesRef.set categories
builtinSyntaxNodeKindSetRef.modify p.info.collectKinds
updateBuiltinTokens p.info declName
def addBuiltinLeadingParser (catName : Name) (declName : Name) (p : Parser) (prio : Nat) : IO Unit :=
addBuiltinParser catName declName true p prio
def addBuiltinTrailingParser (catName : Name) (declName : Name) (p : TrailingParser) (prio : Nat) : IO Unit :=
addBuiltinParser catName declName false p prio
def mkCategoryAntiquotParser (kind : Name) : Parser :=
mkAntiquot kind.toString kind (isPseudoKind := true)
-- helper decl to work around inlining issue https://github.com/leanprover/lean4/commit/3f6de2af06dd9a25f62294129f64bc05a29ea912#r41340377
@[inline] private def mkCategoryAntiquotParserFn (kind : Name) : ParserFn :=
(mkCategoryAntiquotParser kind).fn
def categoryParserFnImpl (catName : Name) : ParserFn := fun ctx s =>
let catName := if catName == `syntax then `stx else catName -- temporary Hack
let categories := (parserExtension.getState ctx.env).categories
match getCategory categories catName with
| some cat =>
prattParser catName cat.tables cat.behavior (mkCategoryAntiquotParserFn catName) ctx s
| none => s.mkUnexpectedError ("unknown parser category '" ++ toString catName ++ "'")
builtin_initialize
categoryParserFnRef.set categoryParserFnImpl
def addToken (tk : Token) (kind : AttributeKind) : AttrM Unit := do
-- Recall that `ParserExtension.addEntry` is pure, and assumes `addTokenConfig` does not fail.
-- So, we must run it here to handle exception.
discard <| ofExcept <| addTokenConfig (parserExtension.getState (← getEnv)).tokens tk
parserExtension.add (ParserExtension.Entry.token tk) kind
def addSyntaxNodeKind (env : Environment) (k : SyntaxNodeKind) : Environment :=
parserExtension.addEntry env <| ParserExtension.Entry.kind k
def isValidSyntaxNodeKind (env : Environment) (k : SyntaxNodeKind) : Bool :=
let kinds := (parserExtension.getState env).kinds
-- accept any constant in stage 1 (i.e. when compiled by stage 0) so that
-- we can add a built-in parser and its elaborator in the same stage
kinds.contains k || (Internal.isStage0 () && env.contains k)
def getSyntaxNodeKinds (env : Environment) : List SyntaxNodeKind :=
let kinds := (parserExtension.getState env).kinds
kinds.foldl (fun ks k _ => k::ks) []
def getTokenTable (env : Environment) : TokenTable :=
(parserExtension.getState env).tokens
def mkInputContext (input : String) (fileName : String) : InputContext := {
input := input,
fileName := fileName,
fileMap := input.toFileMap
}
def mkParserState (input : String) : ParserState :=
{ cache := initCacheForInput input }
/-- convenience function for testing -/
def runParserCategory (env : Environment) (catName : Name) (input : String) (fileName := "<input>") : Except String Syntax :=
let p := andthenFn whitespace (categoryParserFnImpl catName)
let ictx := mkInputContext input fileName
let s := p.run ictx { env, options := {} } (getTokenTable env) (mkParserState input)
if s.hasError then
Except.error (s.toErrorMsg ictx)
else if input.atEnd s.pos then
Except.ok s.stxStack.back
else
Except.error ((s.mkError "end of input").toErrorMsg ictx)
def declareBuiltinParser (addFnName : Name) (catName : Name) (declName : Name) (prio : Nat) : CoreM Unit :=
let val := mkAppN (mkConst addFnName) #[toExpr catName, toExpr declName, mkConst declName, mkRawNatLit prio]
declareBuiltin declName val
def declareLeadingBuiltinParser (catName : Name) (declName : Name) (prio : Nat) : CoreM Unit :=
declareBuiltinParser `Lean.Parser.addBuiltinLeadingParser catName declName prio
def declareTrailingBuiltinParser (catName : Name) (declName : Name) (prio : Nat) : CoreM Unit :=
declareBuiltinParser `Lean.Parser.addBuiltinTrailingParser catName declName prio
def getParserPriority (args : Syntax) : Except String Nat :=
match args.getNumArgs with
| 0 => pure 0
| 1 => match (args.getArg 0).isNatLit? with
| some prio => pure prio
| none => throw "invalid parser attribute, numeral expected"
| _ => throw "invalid parser attribute, no argument or numeral expected"
private def BuiltinParserAttribute.add (attrName : Name) (catName : Name)
(declName : Name) (stx : Syntax) (kind : AttributeKind) : AttrM Unit := do
let prio ← Attribute.Builtin.getPrio stx
unless kind == AttributeKind.global do throwError "invalid attribute '{attrName}', must be global"
let decl ← getConstInfo declName
match decl.type with
| Expr.const `Lean.Parser.TrailingParser _ =>
declareTrailingBuiltinParser catName declName prio
| Expr.const `Lean.Parser.Parser _ =>
declareLeadingBuiltinParser catName declName prio
| _ => throwError "unexpected parser type at '{declName}' (`Parser` or `TrailingParser` expected)"
if let some doc ← findDocString? (← getEnv) declName (includeBuiltin := false) then
declareBuiltin (declName ++ `docString) (mkAppN (mkConst ``addBuiltinDocString) #[toExpr declName, toExpr doc])
if let some declRanges ← findDeclarationRanges? declName then
declareBuiltin (declName ++ `declRange) (mkAppN (mkConst ``addBuiltinDeclarationRanges) #[toExpr declName, toExpr declRanges])
runParserAttributeHooks catName declName (builtin := true)
/--
The parsing tables for builtin parsers are "stored" in the extracted source code.
-/
def registerBuiltinParserAttribute (attrName declName : Name)
(behavior := LeadingIdentBehavior.default) : IO Unit := do
let .str ``Lean.Parser.Category s := declName
| throw (IO.userError "`declName` should be in Lean.Parser.Category")
let catName := Name.mkSimple s
addBuiltinParserCategory catName declName behavior
registerBuiltinAttribute {
ref := declName
name := attrName
descr := "Builtin parser"
add := fun declName stx kind => liftM $ BuiltinParserAttribute.add attrName catName declName stx kind
applicationTime := AttributeApplicationTime.afterCompilation
}
private def ParserAttribute.add (_attrName : Name) (catName : Name) (declName : Name) (stx : Syntax) (attrKind : AttributeKind) : AttrM Unit := do
let prio ← Attribute.Builtin.getPrio stx
let env ← getEnv
let categories := (parserExtension.getState env).categories
let p ← mkParserOfConstant categories declName
let leading := p.1
let parser := p.2
let tokens := parser.info.collectTokens []
tokens.forM fun token => do
try
addToken token attrKind
catch
| Exception.error _ msg => throwError "invalid parser '{declName}', {msg}"
| ex => throw ex
let kinds := parser.info.collectKinds {}
kinds.forM fun kind _ => modifyEnv fun env => addSyntaxNodeKind env kind
let entry := ParserExtension.Entry.parser catName declName leading parser prio
match addParser categories catName declName leading parser prio with
| Except.error ex => throwError ex
| Except.ok _ => parserExtension.add entry attrKind
runParserAttributeHooks catName declName (builtin := false)
def mkParserAttributeImpl (attrName catName : Name) (ref : Name := by exact decl_name%) : AttributeImpl where
ref := ref
name := attrName
descr := "parser"
add declName stx attrKind := ParserAttribute.add attrName catName declName stx attrKind
applicationTime := AttributeApplicationTime.afterCompilation
/-- A builtin parser attribute that can be extended by users. -/
def registerBuiltinDynamicParserAttribute (attrName catName : Name) (ref : Name := by exact decl_name%) : IO Unit := do
registerBuiltinAttribute (mkParserAttributeImpl attrName catName ref)
builtin_initialize
registerAttributeImplBuilder `parserAttr fun ref args =>
match args with
| [DataValue.ofName attrName, DataValue.ofName catName] => pure $ mkParserAttributeImpl attrName catName ref
| _ => throw "invalid parser attribute implementation builder arguments"
def registerParserCategory (env : Environment) (attrName catName : Name)
(behavior := LeadingIdentBehavior.default) (ref : Name := by exact decl_name%) : IO Environment := do
let env ← IO.ofExcept $ addParserCategory env catName ref behavior
registerAttributeOfBuilder env `parserAttr ref [DataValue.ofName attrName, DataValue.ofName catName]
-- declare `term_parser` here since it is used everywhere via antiquotations
builtin_initialize registerBuiltinParserAttribute `builtin_term_parser ``Category.term
builtin_initialize registerBuiltinDynamicParserAttribute `term_parser `term
-- declare `command_parser` to break cyclic dependency
builtin_initialize registerBuiltinParserAttribute `builtin_command_parser ``Category.command
builtin_initialize registerBuiltinDynamicParserAttribute `command_parser `command
@[inline] def commandParser (rbp : Nat := 0) : Parser :=
categoryParser `command rbp
private def withNamespaces (ids : Array Name) (addOpenSimple : Bool) : ParserFn → ParserFn := adaptUncacheableContextFn fun c =>
let c := ids.foldl (init := c) fun c id =>
let nss := ResolveName.resolveNamespace c.env c.currNamespace c.openDecls id
let (env, openDecls) := nss.foldl (init := (c.env, c.openDecls)) fun (env, openDecls) ns =>
let openDecls := if addOpenSimple then OpenDecl.simple ns [] :: openDecls else openDecls
let env := parserExtension.activateScoped env ns
(env, openDecls)
{ c with env, openDecls }
let tokens := parserExtension.getState c.env |>.tokens
{ c with tokens }
def withOpenDeclFnCore (openDeclStx : Syntax) (p : ParserFn) : ParserFn := fun c s =>
if openDeclStx.getKind == `Lean.Parser.Command.openSimple then
withNamespaces (openDeclStx[0].getArgs.map fun stx => stx.getId) (addOpenSimple := true) p c s
else if openDeclStx.getKind == `Lean.Parser.Command.openScoped then
withNamespaces (openDeclStx[1].getArgs.map fun stx => stx.getId) (addOpenSimple := false) p c s
else if openDeclStx.getKind == `Lean.Parser.Command.openOnly then
-- It does not activate scoped attributes, nor affects namespace resolution
p c s
else if openDeclStx.getKind == `Lean.Parser.Command.openHiding then
-- TODO: it does not activate scoped attributes, but it affects namespaces resolution of open decls parsed by `p`.
p c s
else
p c s
/-- If the parsing stack is of the form `#[.., openCommand]`, we process the open command, and execute `p` -/
def withOpenFn (p : ParserFn) : ParserFn := fun c s =>
if s.stxStack.size > 0 then
let stx := s.stxStack.back
if stx.getKind == `Lean.Parser.Command.open then
withOpenDeclFnCore stx[1] p c s
else
p c s
else
p c s
@[inline] def withOpen : Parser → Parser := withFn withOpenFn
/-- If the parsing stack is of the form `#[.., openDecl]`, we process the open declaration, and execute `p` -/
def withOpenDeclFn (p : ParserFn) : ParserFn := fun c s =>
if s.stxStack.size > 0 then
let stx := s.stxStack.back
withOpenDeclFnCore stx p c s
else
p c s
@[inline] def withOpenDecl : Parser → Parser := withFn withOpenDeclFn
inductive ParserName
| category (cat : Name)
| parser (decl : Name) (isDescr : Bool)
-- TODO(gabriel): add parser aliases (this is blocked on doing IO in parsers)
deriving Repr
/-- Resolve the given parser name and return a list of candidates. -/
def resolveParserNameCore (env : Environment) (currNamespace : Name)
(openDecls : List OpenDecl) (ident : Ident) : List ParserName := Id.run do
let ⟨.ident (val := val) (preresolved := pre) ..⟩ := ident | return []
let rec isParser (name : Name) : Option Bool :=
(env.find? name).bind fun ci =>
match ci.type with
| .const ``Parser _ | .const ``TrailingParser _ => some false
| .const ``ParserDescr _ | .const ``TrailingParserDescr _ => some true
| _ => none
for pre in pre do
if let .decl n [] := pre then
if let some isDescr := isParser n then
return [.parser n isDescr]
let erased := val.eraseMacroScopes
if isParserCategory env erased then
return [.category erased]
ResolveName.resolveGlobalName env currNamespace openDecls val |>.filterMap fun
| (name, []) => (isParser name).map fun isDescr => .parser name isDescr
| _ => none
/-- Resolve the given parser name and return a list of candidates. -/
def ParserContext.resolveParserName (ctx : ParserContext) (id : Ident) : List ParserName :=
Parser.resolveParserNameCore ctx.env ctx.currNamespace ctx.openDecls id
/-- Resolve the given parser name and return a list of candidates. -/
def resolveParserName (id : Ident) : CoreM (List ParserName) :=
return resolveParserNameCore (← getEnv) (← getCurrNamespace) (← getOpenDecls) id
def parserOfStackFn (offset : Nat) : ParserFn := fun ctx s => Id.run do
let stack := s.stxStack
if stack.size < offset + 1 then
return s.mkUnexpectedError ("failed to determine parser using syntax stack, stack is too small")
let parserName@(.ident ..) := stack.get! (stack.size - offset - 1)
| s.mkUnexpectedError ("failed to determine parser using syntax stack, the specified element on the stack is not an identifier")
match ctx.resolveParserName ⟨parserName⟩ with
| [.category cat] =>
categoryParserFn cat ctx s
| [.parser parserName _] =>
let iniSz := s.stackSize
let s := adaptUncacheableContextFn (fun ctx =>
if !internal.parseQuotWithCurrentStage.get ctx.options then
-- static quotations such as `(e) do not use the interpreter unless the above option is set,
-- so for consistency neither should dynamic quotations using this function
{ ctx with options := ctx.options.setBool `interpreter.prefer_native true }
else ctx) (evalParserConst parserName) ctx s
if !s.hasError && s.stackSize != iniSz + 1 then
s.mkUnexpectedError "expected parser to return exactly one syntax object"
else
s
| _::_::_ => s.mkUnexpectedError s!"ambiguous parser name {parserName}"
| [] => s.mkUnexpectedError s!"unknown parser {parserName}"
def parserOfStack (offset : Nat) (prec : Nat := 0) : Parser where
fn := adaptCacheableContextFn ({ · with prec }) (parserOfStackFn offset)
end Parser
end Lean
|
36abba8379903b693bc0c3c518858f3d54470879 | 22e97a5d648fc451e25a06c668dc03ac7ed7bc25 | /src/algebra/big_operators.lean | a628e05b25b95ebfcd8db7b93922d675e29b41ca | [
"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 | 55,682 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import data.finset
import data.nat.enat
import tactic.omega
/-!
# Big operators
In this file we define products and sums indexed by finite sets (specifically, `finset`).
## Notation
We introduce the following notation, localized in `big_operators`.
To enable the notation, use `open_locale big_operators`.
Let `s` be a `finset α`, and `f : α → β` a function.
* `∏ x in s, f x` is notation for `finset.prod s f` (assuming `β` is a `comm_monoid`)
* `∑ x in s, f x` is notation for `finset.sum s f` (assuming `β` is an `add_comm_monoid`)
* `∏ x, f x` is notation for `finset.prod finset.univ f`
(assuming `α` is a `fintype` and `β` is a `comm_monoid`)
* `∑ x, f x` is notation for `finset.sum finset.univ f`
(assuming `α` is a `fintype` and `β` is an `add_comm_monoid`)
-/
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
theorem directed.finset_le {r : α → α → Prop} [is_trans α r]
{ι} (hι : nonempty ι) {f : ι → α} (D : directed r f) (s : finset ι) :
∃ z, ∀ i ∈ s, r (f i) (f z) :=
show ∃ z, ∀ i ∈ s.1, r (f i) (f z), from
multiset.induction_on s.1 (let ⟨z⟩ := hι in ⟨z, λ _, false.elim⟩) $
λ i s ⟨j, H⟩, let ⟨k, h₁, h₂⟩ := D i j in
⟨k, λ a h, or.cases_on (multiset.mem_cons.1 h)
(λ h, h.symm ▸ h₁)
(λ h, trans (H _ h) h₂)⟩
theorem finset.exists_le {α : Type u} [nonempty α] [directed_order α] (s : finset α) :
∃ M, ∀ i ∈ s, i ≤ M :=
directed.finset_le (by apply_instance) directed_order.directed s
namespace finset
/-- `∏ x in s, f x` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/
@[to_additive "`∑ x in s, f` is the sum of `f x` as `x` ranges over the elements
of the finite set `s`."]
protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod
end finset
/-
## Operator precedence of `∏` and `∑`
There is no established mathematical convention
for the operator precedence of big operators like `∏` and `∑`.
We will have to make a choice.
Online discussions, such as https://math.stackexchange.com/q/185538/30839
seem to suggest that `∏` and `∑` should have the same precedence,
and that this should be somewhere between `*` and `+`.
The latter have precedence levels `70` and `65` respectively,
and we therefore choose the level `67`.
In practice, this means that parentheses should be placed as follows:
```lean
∑ k in K, (a k + b k) = ∑ k in K, a k + ∑ k in K, b k →
∏ k in K, a k * b k = (∏ k in K, a k) * (∏ k in K, b k)
```
(Example taken from page 490 of Knuth's *Concrete Mathematics*.)
-/
localized "notation `∑` binders `, ` r:(scoped:67 f, finset.sum finset.univ f) := r" in big_operators
localized "notation `∏` binders `, ` r:(scoped:67 f, finset.prod finset.univ f) := r" in big_operators
localized "notation `∑` binders ` in ` s `, ` r:(scoped:67 f, finset.sum s f) := r" in big_operators
localized "notation `∏` binders ` in ` s `, ` r:(scoped:67 f, finset.prod s f) := r" in big_operators
open_locale big_operators
namespace finset
variables {s s₁ s₂ : finset α} {a : α} {f g : α → β}
@[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) :
∏ x in s, f x = (s.1.map f).prod := rfl
@[to_additive]
theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : (∏ x in s, f x) = s.fold (*) 1 f := rfl
end finset
@[to_additive]
lemma monoid_hom.map_prod [comm_monoid β] [comm_monoid γ] (g : β →* γ) (f : α → β) (s : finset α) :
g (∏ x in s, f x) = ∏ x in s, g (f x) :=
by simp only [finset.prod_eq_multiset_prod, g.map_multiset_prod, multiset.map_map]
lemma ring_hom.map_list_prod [semiring β] [semiring γ] (f : β →+* γ) (l : list β) :
f l.prod = (l.map f).prod :=
f.to_monoid_hom.map_list_prod l
lemma ring_hom.map_list_sum [semiring β] [semiring γ] (f : β →+* γ) (l : list β) :
f l.sum = (l.map f).sum :=
f.to_add_monoid_hom.map_list_sum l
lemma ring_hom.map_multiset_prod [comm_semiring β] [comm_semiring γ] (f : β →+* γ)
(s : multiset β) :
f s.prod = (s.map f).prod :=
f.to_monoid_hom.map_multiset_prod s
lemma ring_hom.map_multiset_sum [semiring β] [semiring γ] (f : β →+* γ) (s : multiset β) :
f s.sum = (s.map f).sum :=
f.to_add_monoid_hom.map_multiset_sum s
lemma ring_hom.map_prod [comm_semiring β] [comm_semiring γ]
(g : β →+* γ) (f : α → β) (s : finset α) :
g (∏ x in s, f x) = ∏ x in s, g (f x) :=
g.to_monoid_hom.map_prod f s
lemma ring_hom.map_sum [semiring β] [semiring γ]
(g : β →+* γ) (f : α → β) (s : finset α) :
g (∑ x in s, f x) = ∑ x in s, g (f x) :=
g.to_add_monoid_hom.map_sum f s
namespace finset
variables {s s₁ s₂ : finset α} {a : α} {f g : α → β}
section comm_monoid
variables [comm_monoid β]
@[simp, to_additive]
lemma prod_empty {α : Type u} {f : α → β} : (∏ x in (∅:finset α), f x) = 1 := rfl
@[simp, to_additive]
lemma prod_insert [decidable_eq α] :
a ∉ s → (∏ x in (insert a s), f x) = f a * ∏ x in s, f x := fold_insert
@[simp, to_additive]
lemma prod_singleton : (∏ x in (singleton a), f x) = f a :=
eq.trans fold_singleton $ mul_one _
@[to_additive]
lemma prod_pair [decidable_eq α] {a b : α} (h : a ≠ b) :
(∏ x in ({a, b} : finset α), f x) = f a * f b :=
by rw [prod_insert (not_mem_singleton.2 h), prod_singleton]
@[simp, priority 1100] lemma prod_const_one : (∏ x in s, (1 : β)) = 1 :=
by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow]
@[simp, priority 1100] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] :
(∑ x in s, (0 : β)) = 0 :=
@prod_const_one _ (multiplicative β) _ _
attribute [to_additive] prod_const_one
@[simp, to_additive]
lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} :
(∀x∈s, ∀y∈s, g x = g y → x = y) → (∏ x in (s.image g), f x) = ∏ x in s, f (g x) :=
fold_image
@[simp, to_additive]
lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) :
(∏ x in (s.map e), f x) = ∏ x in s, f (e x) :=
by rw [finset.prod, finset.map_val, multiset.map_map]; refl
@[congr, to_additive]
lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g :=
by rw [h]; exact fold_congr
attribute [congr] finset.sum_congr
@[to_additive]
lemma prod_union_inter [decidable_eq α] :
(∏ x in (s₁ ∪ s₂), f x) * (∏ x in (s₁ ∩ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) :=
fold_union_inter
@[to_additive]
lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) :
(∏ x in (s₁ ∪ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) :=
by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm
@[to_additive]
lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) :
(∏ x in (s₂ \ s₁), f x) * (∏ x in s₁, f x) = (∏ x in s₂, f x) :=
by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h]
@[simp, to_additive]
lemma prod_sum_elim [decidable_eq (α ⊕ γ)]
(s : finset α) (t : finset γ) (f : α → β) (g : γ → β) :
(s.image sum.inl ∪ t.image sum.inr).prod (sum.elim f g) = (∏ x in s, f x) * (∏ x in t, g x) :=
begin
rw [prod_union, prod_image, prod_image],
{ simp only [sum.elim_inl, sum.elim_inr] },
{ exact λ _ _ _ _, sum.inr.inj },
{ exact λ _ _ _ _, sum.inl.inj },
{ rintros i hi,
erw [finset.mem_inter, finset.mem_image, finset.mem_image] at hi,
rcases hi with ⟨⟨i, hi, rfl⟩, ⟨j, hj, H⟩⟩,
cases H }
end
@[to_additive]
lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} :
(∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y)) → (∏ x in (s.bind t), f x) = ∏ x in s, (t x).prod f :=
by haveI := classical.dec_eq γ; exact
finset.induction_on s (λ _, by simp only [bind_empty, prod_empty])
(assume x s hxs ih hd,
have hd' : ∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y),
from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy),
have ∀y∈s, x ≠ y,
from assume _ hy h, by rw [←h] at hy; contradiction,
have ∀y∈s, disjoint (t x) (t y),
from assume _ hy, hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hy) (this _ hy),
have disjoint (t x) (finset.bind s t),
from (disjoint_bind_right _ _ _).mpr this,
by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd'])
@[to_additive]
lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} :
(∏ x in s.product t, f x) = ∏ x in s, ∏ y in t, f (x, y) :=
begin
haveI := classical.dec_eq α, haveI := classical.dec_eq γ,
rw [product_eq_bind, prod_bind],
{ congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) },
simp only [disjoint_iff_ne, mem_image],
rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _,
apply h, cc
end
@[to_additive]
lemma prod_sigma {σ : α → Type*}
{s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} :
(∏ x in s.sigma t, f x) = ∏ a in s, ∏ s in (t a), f ⟨a, s⟩ :=
by haveI := classical.dec_eq α; haveI := (λ a, classical.dec_eq (σ a)); exact
calc (s.sigma t).prod f =
(s.bind (λa, (t a).image (λs, sigma.mk a s))).prod f : by rw sigma_eq_bind
... = s.prod (λa, ((t a).image (λs, sigma.mk a s)).prod f) :
prod_bind $ assume a₁ ha a₂ ha₂ h,
by simp only [disjoint_iff_ne, mem_image];
rintro ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩; apply h; cc
... = (s.prod $ λa, (t a).prod $ λs, f ⟨a, s⟩) :
prod_congr rfl $ λ _ _, prod_image $ λ _ _ _ _ _, by cc
@[to_additive]
lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β)
(eq : ∀c∈s, f (g c) = (s.filter (λc', g c' = g c)).prod h) :
(∏ x in s.image g, f x) = ∏ x in s, h x :=
begin
letI := classical.dec_eq γ,
rw [← image_bind_filter_eq s g] {occs := occurrences.pos [2]},
rw [finset.prod_bind],
{ refine finset.prod_congr rfl (assume a ha, _),
rcases finset.mem_image.1 ha with ⟨b, hb, rfl⟩,
exact eq b hb },
assume a₀ _ a₁ _ ne,
refine (disjoint_iff_ne.2 _),
assume c₀ h₀ c₁ h₁,
rcases mem_filter.1 h₀ with ⟨h₀, rfl⟩,
rcases mem_filter.1 h₁ with ⟨h₁, rfl⟩,
exact mt (congr_arg g) ne
end
@[to_additive]
lemma prod_mul_distrib : s.prod (λx, f x * g x) = (∏ x in s, f x) * (∏ x in s, g x) :=
eq.trans (by rw one_mul; refl) fold_op_distrib
@[to_additive]
lemma prod_comm {s : finset γ} {t : finset α} {f : γ → α → β} :
(∏ x in s, ∏ y in t, f x y) = (∏ y in t, ∏ x in s, f x y) :=
begin
classical,
apply finset.induction_on s,
{ simp only [prod_empty, prod_const_one] },
{ intros _ _ H ih,
simp only [prod_insert H, prod_mul_distrib, ih] }
end
@[to_additive]
lemma prod_hom [comm_monoid γ] (s : finset α) {f : α → β} (g : β → γ) [is_monoid_hom g] :
(∏ x in s, g (f x)) = g (∏ x in s, f x) :=
((monoid_hom.of g).map_prod f s).symm
@[to_additive]
lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α}
(h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (∏ x in s, f x) (∏ x in s, g x) :=
by { delta finset.prod, apply multiset.prod_hom_rel; assumption }
@[to_additive]
lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : (∏ x in s₁, f x) = ∏ x in s₂, f x :=
by haveI := classical.dec_eq α; exact
have (s₂ \ s₁).prod f = (s₂ \ s₁).prod (λx, 1),
from prod_congr rfl $ by simpa only [mem_sdiff, and_imp],
by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul]
-- If we use `[decidable_eq β]` here, some rewrites fail because they find a wrong `decidable`
-- instance first; `{∀x, decidable (f x ≠ 1)}` doesn't work with `rw ← prod_filter_ne_one`
@[to_additive]
lemma prod_filter_ne_one [∀ x, decidable (f x ≠ 1)] :
(∏ x in (s.filter $ λx, f x ≠ 1), f x) = (∏ x in s, f x) :=
prod_subset (filter_subset _) $ λ x,
by { classical, rw [not_imp_comm, mem_filter], exact and.intro }
@[to_additive]
lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) :
(∏ a in s.filter p, f a) = (∏ a in s, if p a then f a else 1) :=
calc (s.filter p).prod f = (s.filter p).prod (λa, if p a then f a else 1) :
prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2])
... = s.prod (λa, if p a then f a else 1) :
begin
refine prod_subset (filter_subset s) (assume x hs h, _),
rw [mem_filter, not_and] at h,
exact if_neg (h hs)
end
@[to_additive]
lemma prod_eq_single {s : finset α} {f : α → β} (a : α)
(h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : (∏ x in s, f x) = f a :=
by haveI := classical.dec_eq α;
from classical.by_cases
(assume : a ∈ s,
calc (∏ x in s, f x) = ({a} : finset α).prod f :
begin
refine (prod_subset _ _).symm,
{ intros _ H, rwa mem_singleton.1 H },
{ simpa only [mem_singleton] }
end
... = f a : prod_singleton)
(assume : a ∉ s,
(prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $
prod_const_one.trans (h₁ this).symm)
@[to_additive] lemma prod_apply_ite {s : finset α}
{p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) :
(∏ x in s, h (if p x then f x else g x)) =
(∏ x in s.filter p, h (f x)) * (∏ x in s.filter (λ x, ¬ p x), h (g x)) :=
by letI := classical.dec_eq α; exact
calc s.prod (λ x, h (if p x then f x else g x))
= (s.filter p ∪ s.filter (λ x, ¬ p x)).prod (λ x, h (if p x then f x else g x)) :
by rw [filter_union_filter_neg_eq]
... = (s.filter p).prod (λ x, h (if p x then f x else g x)) *
(s.filter (λ x, ¬ p x)).prod (λ x, h (if p x then f x else g x)) :
prod_union (by simp [disjoint_right] {contextual := tt})
... = (s.filter p).prod (λ x, h (f x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (g x)) :
congr_arg2 _
(prod_congr rfl (by simp {contextual := tt}))
(prod_congr rfl (by simp {contextual := tt}))
@[to_additive] lemma prod_ite {s : finset α}
{p : α → Prop} {hp : decidable_pred p} (f g : α → β) :
(∏ x in s, if p x then f x else g x) =
(s.filter p).prod (λ x, f x) * (s.filter (λ x, ¬ p x)).prod (λ x, g x) :=
by simp [prod_apply_ite _ _ (λ x, x)]
@[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : α → β) :
(∏ x in s, (ite (a = x) (b x) 1)) = ite (a ∈ s) (b a) 1 :=
begin
rw ←finset.prod_filter,
split_ifs;
simp only [filter_eq, if_true, if_false, h, prod_empty, prod_singleton],
end
/--
When a product is taken over a conditional whose condition is an equality test on the index
and whose alternative is 1, then the product's value is either the term at that index or `1`.
The difference with `prod_ite_eq` is that the arguments to `eq` are swapped.
-/
@[simp, to_additive] lemma prod_ite_eq' [decidable_eq α] (s : finset α) (a : α) (b : α → β) :
(∏ x in s, (ite (x = a) (b x) 1)) = ite (a ∈ s) (b a) 1 :=
begin
rw ←prod_ite_eq,
congr, ext x,
by_cases x = a; finish
end
@[to_additive]
lemma prod_attach {f : α → β} : (∏ x in s.attach, f x.val) = (∏ x in s, f x) :=
by haveI := classical.dec_eq α; exact
calc s.attach.prod (λx, f x.val) = ((s.attach).image subtype.val).prod f :
by rw [prod_image]; exact assume x _ y _, subtype.eq
... = _ : by rw [attach_image_val]
/--
Reorder a product.
The difference with `prod_bij'` is that the bijection is specified as a surjective injection,
rather than by an inverse function.
-/
@[to_additive]
lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β}
(i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha))
(i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) :
(∏ x in s, f x) = (∏ x in t, g x) :=
congr_arg multiset.prod
(multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj)
/--
Reorder a product.
The difference with `prod_bij` is that the bijection is specified with an inverse, rather than
as a surjective injection.
-/
@[to_additive]
lemma prod_bij' {s : finset α} {t : finset γ} {f : α → β} {g : γ → β}
(i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha))
(j : Πa∈t, α) (hj : ∀a ha, j a ha ∈ s) (left_inv : ∀ a ha, j (i a ha) (hi a ha) = a)
(right_inv : ∀ a ha, i (j a ha) (hj a ha) = a) :
(∏ x in s, f x) = (∏ x in t, g x) :=
begin
refine prod_bij i hi h _ _,
{intros a1 a2 h1 h2 eq, rw [←left_inv a1 h1, ←left_inv a2 h2], cc,},
{intros b hb, use j b hb, use hj b hb, exact (right_inv b hb).symm,},
end
@[to_additive]
lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β}
(i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t)
(hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂)
(hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂)
(h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) :
(∏ x in s, f x) = (∏ x in t, g x) :=
by classical; exact
calc (∏ x in s, f x) = (s.filter $ λx, f x ≠ 1).prod f : prod_filter_ne_one.symm
... = (t.filter $ λx, g x ≠ 1).prod g :
prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2)
(assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr
⟨hi₁ a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩)
(assume a ha, (mem_filter.mp ha).elim $ h a)
(assume a₁ a₂ ha₁ ha₂,
(mem_filter.mp ha₁).elim $ λha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λha₂₁ ha₂₂, hi₂ a₁ a₂ _ _ _ _)
(assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂,
let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩)
... = (∏ x in t, g x) : prod_filter_ne_one
@[to_additive]
lemma nonempty_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : s.nonempty :=
s.eq_empty_or_nonempty.elim (λ H, false.elim $ h $ H.symm ▸ prod_empty) id
@[to_additive]
lemma exists_ne_one_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : ∃a∈s, f a ≠ 1 :=
begin
classical,
rw ← prod_filter_ne_one at h,
rcases nonempty_of_prod_ne_one h with ⟨x, hx⟩,
exact ⟨x, (mem_filter.1 hx).1, (mem_filter.1 hx).2⟩
end
lemma sum_range_succ {β} [add_comm_monoid β] (f : ℕ → β) (n : ℕ) :
(∑ x in range (n + 1), f x) = f n + (∑ x in range n, f x) :=
by rw [range_succ, sum_insert not_mem_range_self]
@[to_additive]
lemma prod_range_succ (f : ℕ → β) (n : ℕ) :
(∏ x in range (n + 1), f x) = f n * (∏ x in range n, f x) :=
by rw [range_succ, prod_insert not_mem_range_self]
lemma prod_range_succ' (f : ℕ → β) :
∀ n : ℕ, (∏ k in range (n + 1), f k) = (∏ k in range n, f (k+1)) * f 0
| 0 := (prod_range_succ _ _).trans $ mul_comm _ _
| (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ'];
exact prod_range_succ _ _
lemma sum_Ico_add {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) (m n k : ℕ) :
(∑ l in Ico m n, f (k + l)) = (∑ l in Ico (m + k) (n + k), f l) :=
Ico.image_add m n k ▸ eq.symm $ sum_image $ λ x hx y hy h, nat.add_left_cancel h
@[to_additive]
lemma prod_Ico_add (f : ℕ → β) (m n k : ℕ) :
(∏ l in Ico m n, f (k + l)) = (∏ l in Ico (m + k) (n + k), f l) :=
@sum_Ico_add (additive β) _ f m n k
lemma sum_Ico_succ_top {δ : Type*} [add_comm_monoid δ] {a b : ℕ}
(hab : a ≤ b) (f : ℕ → δ) : (∑ k in Ico a (b + 1), f k) = (∑ k in Ico a b, f k) + f b :=
by rw [Ico.succ_top hab, sum_insert Ico.not_mem_top, add_comm]
@[to_additive]
lemma prod_Ico_succ_top {a b : ℕ} (hab : a ≤ b) (f : ℕ → β) :
(∏ k in Ico a (b + 1), f k) = (∏ k in Ico a b, f k) * f b :=
@sum_Ico_succ_top (additive β) _ _ _ hab _
lemma sum_eq_sum_Ico_succ_bot {δ : Type*} [add_comm_monoid δ] {a b : ℕ}
(hab : a < b) (f : ℕ → δ) : (∑ k in Ico a b, f k) = f a + (∑ k in Ico (a + 1) b, f k) :=
have ha : a ∉ Ico (a + 1) b, by simp,
by rw [← sum_insert ha, Ico.insert_succ_bot hab]
@[to_additive]
lemma prod_eq_prod_Ico_succ_bot {a b : ℕ} (hab : a < b) (f : ℕ → β) :
(∏ k in Ico a b, f k) = f a * (∏ k in Ico (a + 1) b, f k) :=
@sum_eq_sum_Ico_succ_bot (additive β) _ _ _ hab _
@[to_additive]
lemma prod_Ico_consecutive (f : ℕ → β) {m n k : ℕ} (hmn : m ≤ n) (hnk : n ≤ k) :
(∏ i in Ico m n, f i) * (∏ i in Ico n k, f i) = (∏ i in Ico m k, f i) :=
Ico.union_consecutive hmn hnk ▸ eq.symm $ prod_union $ Ico.disjoint_consecutive m n k
@[to_additive]
lemma prod_range_mul_prod_Ico (f : ℕ → β) {m n : ℕ} (h : m ≤ n) :
(∏ k in range m, f k) * (∏ k in Ico m n, f k) = (∏ k in range n, f k) :=
Ico.zero_bot m ▸ Ico.zero_bot n ▸ prod_Ico_consecutive f (nat.zero_le m) h
@[to_additive]
lemma prod_Ico_eq_mul_inv {δ : Type*} [comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) :
(∏ k in Ico m n, f k) = (∏ k in range n, f k) * (∏ k in range m, f k)⁻¹ :=
eq_mul_inv_iff_mul_eq.2 $ by rw [mul_comm]; exact prod_range_mul_prod_Ico f h
lemma sum_Ico_eq_sub {δ : Type*} [add_comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) :
(∑ k in Ico m n, f k) = (∑ k in range n, f k) - (∑ k in range m, f k) :=
sum_Ico_eq_add_neg f h
@[to_additive]
lemma prod_Ico_eq_prod_range (f : ℕ → β) (m n : ℕ) :
(∏ k in Ico m n, f k) = (∏ k in range (n - m), f (m + k)) :=
begin
by_cases h : m ≤ n,
{ rw [← Ico.zero_bot, prod_Ico_add, zero_add, nat.sub_add_cancel h] },
{ replace h : n ≤ m := le_of_not_ge h,
rw [Ico.eq_empty_of_le h, nat.sub_eq_zero_of_le h, range_zero, prod_empty, prod_empty] }
end
@[to_additive]
lemma prod_range_zero (f : ℕ → β) :
(∏ k in range 0, f k) = 1 :=
by rw [range_zero, prod_empty]
lemma prod_range_one (f : ℕ → β) :
(∏ k in range 1, f k) = f 0 :=
by { rw [range_one], apply @prod_singleton ℕ β 0 f }
lemma sum_range_one {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) :
(∑ k in range 1, f k) = f 0 :=
@prod_range_one (multiplicative δ) _ f
attribute [to_additive finset.sum_range_one] prod_range_one
/-- For any product along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that
it's equal to a different function just by checking ratios of adjacent terms.
This is a multiplicative discrete analogue of the fundamental theorem of calculus. -/
lemma prod_range_induction {M : Type*} [comm_monoid M]
(f s : ℕ → M) (h0 : s 0 = 1) (h : ∀ n, s (n + 1) = s n * f n) (n : ℕ) :
∏ k in finset.range n, f k = s n :=
begin
induction n with k hk,
{ simp only [h0, finset.prod_range_zero] },
{ simp only [hk, finset.prod_range_succ, h, mul_comm] }
end
/-- For any sum along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal
to a different function just by checking differences of adjacent terms. This is a discrete analogue
of the fundamental theorem of calculus. -/
lemma sum_range_induction {M : Type*} [add_comm_monoid M]
(f s : ℕ → M) (h0 : s 0 = 0) (h : ∀ n, s (n + 1) = s n + f n) (n : ℕ) :
∑ k in finset.range n, f k = s n :=
@prod_range_induction (multiplicative M) _ f s h0 h n
/-- A telescoping sum along `{0, ..., n-1}` of an `ℕ`-valued function reduces to the difference of
the last and first terms when the function we are summing is monotone. -/
lemma sum_range_sub_of_monotone {f : ℕ → ℕ} (h : monotone f) (n : ℕ) :
∑ i in range n, (f (i+1) - f i) = f n - f 0 :=
begin
refine sum_range_induction _ _ (nat.sub_self _) (λ n, _) _,
have : f n ≤ f (n+1) := h (nat.le_succ _),
have : f 0 ≤ f n := h (nat.zero_le _),
omega
end
lemma prod_Ico_reflect (f : ℕ → β) (k : ℕ) {m n : ℕ} (h : m ≤ n + 1) :
∏ j in Ico k m, f (n - j) = ∏ j in Ico (n + 1 - m) (n + 1 - k), f j :=
begin
have : ∀ i < m, i ≤ n,
{ intros i hi,
exact (add_le_add_iff_right 1).1 (le_trans (nat.lt_iff_add_one_le.1 hi) h) },
cases lt_or_le k m with hkm hkm,
{ rw [← finset.Ico.image_const_sub (this _ hkm)],
refine (prod_image _).symm,
simp only [Ico.mem],
rintros i ⟨ki, im⟩ j ⟨kj, jm⟩ Hij,
rw [← nat.sub_sub_self (this _ im), Hij, nat.sub_sub_self (this _ jm)] },
{ simp [Ico.eq_empty_of_le, nat.sub_le_sub_left, hkm] }
end
lemma sum_Ico_reflect {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) (k : ℕ) {m n : ℕ}
(h : m ≤ n + 1) :
∑ j in Ico k m, f (n - j) = ∑ j in Ico (n + 1 - m) (n + 1 - k), f j :=
@prod_Ico_reflect (multiplicative δ) _ f k m n h
lemma prod_range_reflect (f : ℕ → β) (n : ℕ) :
∏ j in range n, f (n - 1 - j) = ∏ j in range n, f j :=
begin
cases n,
{ simp },
{ simp only [range_eq_Ico, nat.succ_sub_succ_eq_sub, nat.sub_zero],
rw [prod_Ico_reflect _ _ (le_refl _)],
simp }
end
lemma sum_range_reflect {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) (n : ℕ) :
∑ j in range n, f (n - 1 - j) = ∑ j in range n, f j :=
@prod_range_reflect (multiplicative δ) _ f n
@[simp] lemma prod_const (b : β) : (∏ x in s, b) = b ^ s.card :=
by haveI := classical.dec_eq α; exact
finset.induction_on s rfl (λ a s has ih,
by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih])
lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) :
(∏ x in s, f x ^ n) = (∏ x in s, f x) ^ n :=
by haveI := classical.dec_eq α; exact
finset.induction_on s (by simp) (by simp [_root_.mul_pow] {contextual := tt})
lemma prod_nat_pow (s : finset α) (n : ℕ) (f : α → ℕ) :
(∏ x in s, f x ^ n) = (∏ x in s, f x) ^ n :=
by haveI := classical.dec_eq α; exact
finset.induction_on s (by simp) (by simp [nat.mul_pow] {contextual := tt})
-- `to_additive` fails on this lemma, so we prove it manually below
lemma prod_flip {n : ℕ} (f : ℕ → β) :
(∏ r in range (n + 1), f (n - r)) = (∏ k in range (n + 1), f k) :=
begin
induction n with n ih,
{ rw [prod_range_one, prod_range_one] },
{ rw [prod_range_succ', prod_range_succ _ (nat.succ n), mul_comm],
simp [← ih] }
end
@[to_additive]
lemma prod_involution {s : finset α} {f : α → β} :
∀ (g : Π a ∈ s, α)
(h₁ : ∀ a ha, f a * f (g a ha) = 1)
(h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a)
(h₃ : ∀ a ha, g a ha ∈ s)
(h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a),
(∏ x in s, f x) = 1 :=
by haveI := classical.dec_eq α;
haveI := classical.dec_eq β; exact
finset.strong_induction_on s
(λ s ih g h₁ h₂ h₃ h₄,
s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ rfl)
(λ ⟨x, hx⟩,
have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s,
from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)),
have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y,
from λ x hx y hy h, by rw [← h₄ x hx, ← h₄ y hy]; simp [h],
have ih': (erase (erase s x) (g x hx)).prod f = (1 : β) :=
ih ((s.erase x).erase (g x hx))
⟨subset.trans (erase_subset _ _) (erase_subset _ _),
λ h, not_mem_erase (g x hx) (s.erase x) (h (h₃ x hx))⟩
(λ y hy, g y (hmem y hy))
(λ y hy, h₁ y (hmem y hy))
(λ y hy, h₂ y (hmem y hy))
(λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy,
mem_erase.2 ⟨λ (h : g y _ = x),
have y = g x hx, from h₄ y (hmem y hy) ▸ by simp [h],
by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩)
(λ y hy, h₄ y (hmem y hy)),
if hx1 : f x = 1
then ih' ▸ eq.symm (prod_subset hmem
(λ y hy hy₁,
have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto,
this.elim (λ h, h.symm ▸ hx1)
(λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm)))
else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _),
← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩),
prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx]))
/-- The product of the composition of functions `f` and `g`, is the product
over `b ∈ s.image g` of `f b` to the power of the cardinality of the fibre of `b` -/
lemma prod_comp [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) :
∏ a in s, f (g a) = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card :=
calc ∏ a in s, f (g a)
= ∏ x in (s.image g).sigma (λ b : γ, s.filter (λ a, g a = b)), f (g x.2) :
prod_bij (λ a ha, ⟨g a, a⟩) (by simp; tauto) (λ _ _, rfl) (by simp) (by finish)
... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f (g a) : prod_sigma
... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f b :
prod_congr rfl (λ b hb, prod_congr rfl (by simp {contextual := tt}))
... = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card :
prod_congr rfl (λ _ _, prod_const _)
@[to_additive]
lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : (∏ x in s, f x) = 1 :=
calc (∏ x in s, f x) = s.prod (λx, 1) : finset.prod_congr rfl h
... = 1 : finset.prod_const_one
/-- A product over all subsets of `s ∪ {x}` is obtained by multiplying the product over all subsets
of `s`, and over all subsets of `s` to which one adds `x`. -/
@[to_additive]
lemma prod_powerset_insert [decidable_eq α] {s : finset α} {x : α} (h : x ∉ s) (f : finset α → β) :
(∏ a in (insert x s).powerset, f a) =
(∏ a in s.powerset, f a) * (∏ t in s.powerset, f (insert x t)) :=
begin
rw [powerset_insert, finset.prod_union, finset.prod_image],
{ assume t₁ h₁ t₂ h₂ heq,
rw [← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₁ h),
← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₂ h), heq] },
{ rw finset.disjoint_iff_ne,
assume t₁ h₁ t₂ h₂,
rcases finset.mem_image.1 h₂ with ⟨t₃, h₃, H₃₂⟩,
rw ← H₃₂,
exact ne_insert_of_not_mem _ _ (not_mem_of_mem_powerset_of_not_mem h₁ h) }
end
@[to_additive]
lemma prod_piecewise [decidable_eq α] (s t : finset α) (f g : α → β) :
(∏ x in s, (t.piecewise f g) x) = (∏ x in s ∩ t, f x) * (∏ x in s \ t, g x) :=
by { rw [piecewise, prod_ite, filter_mem_eq_inter, ← sdiff_eq_filter], }
/-- If we can partition a product into subsets that cancel out, then the whole product cancels. -/
@[to_additive]
lemma prod_cancels_of_partition_cancels (R : setoid α) [decidable_rel R.r]
(h : ∀ x ∈ s, (∏ a in s.filter (λy, y ≈ x), f a) = 1) : (∏ x in s, f x) = 1 :=
begin
suffices : (s.image quotient.mk).prod (λ xbar, (s.filter (λ y, ⟦y⟧ = xbar)).prod f) = (∏ x in s, f x),
{ rw [←this, ←finset.prod_eq_one],
intros xbar xbar_in_s,
rcases (mem_image).mp xbar_in_s with ⟨x, x_in_s, xbar_eq_x⟩,
rw [←xbar_eq_x, filter_congr (λ y _, @quotient.eq _ R y x)],
apply h x x_in_s },
apply finset.prod_image' f,
intros,
refl
end
@[to_additive]
lemma prod_update_of_not_mem [decidable_eq α] {s : finset α} {i : α}
(h : i ∉ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = (∏ x in s, f x) :=
begin
apply prod_congr rfl (λj hj, _),
have : j ≠ i, by { assume eq, rw eq at hj, exact h hj },
simp [this]
end
lemma prod_update_of_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) :
(∏ x in s, function.update f i b x) = b * (∏ x in s \ (singleton i), f x) :=
by { rw [update_eq_piecewise, prod_piecewise], simp [h] }
end comm_monoid
lemma sum_update_of_mem [add_comm_monoid β] [decidable_eq α] {s : finset α} {i : α}
(h : i ∈ s) (f : α → β) (b : β) :
(∑ x in s, function.update f i b x) = b + (∑ x in s \ (singleton i), f x) :=
by { rw [update_eq_piecewise, sum_piecewise], simp [h] }
attribute [to_additive] prod_update_of_mem
lemma sum_smul' [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) :
(∑ x in s, add_monoid.smul n (f x)) = add_monoid.smul n ((∑ x in s, f x)) :=
@prod_pow _ (multiplicative β) _ _ _ _
attribute [to_additive sum_smul'] prod_pow
@[simp] lemma sum_const [add_comm_monoid β] (b : β) :
(∑ x in s, b) = add_monoid.smul s.card b :=
@prod_const _ (multiplicative β) _ _ _
attribute [to_additive] prod_const
lemma sum_comp [add_comm_monoid β] [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) :
∑ a in s, f (g a) = ∑ b in s.image g, add_monoid.smul (s.filter (λ a, g a = b)).card (f b) :=
@prod_comp _ (multiplicative β) _ _ _ _ _ _
attribute [to_additive "The sum of the composition of functions `f` and `g`, is the sum
over `b ∈ s.image g` of `f b` times of the cardinality of the fibre of `b`"] prod_comp
lemma sum_const_nat {m : ℕ} {f : α → ℕ} (h₁ : ∀x ∈ s, f x = m) :
(∑ x in s, f x) = card s * m :=
begin
rw [← nat.smul_eq_mul, ← sum_const],
apply sum_congr rfl h₁
end
@[simp]
lemma sum_boole {s : finset α} {p : α → Prop} [semiring β] {hp : decidable_pred p} :
(∑ x in s, if p x then (1 : β) else (0 : β)) = (s.filter p).card :=
by simp [sum_ite]
lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) :
∀ n : ℕ, (∑ i in range (n + 1), f i) = (∑ i in range n, f (i + 1)) + f 0 :=
@prod_range_succ' (multiplicative β) _ _
attribute [to_additive] prod_range_succ'
lemma sum_flip [add_comm_monoid β] {n : ℕ} (f : ℕ → β) :
(∑ i in range (n + 1), f (n - i)) = (∑ i in range (n + 1), f i) :=
@prod_flip (multiplicative β) _ _ _
attribute [to_additive] prod_flip
@[norm_cast]
lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) :
↑(∑ x in s, f x : ℕ) = (∑ x in s, (f x : β)) :=
(nat.cast_add_monoid_hom β).map_sum f s
@[norm_cast]
lemma prod_nat_cast [comm_semiring β] (s : finset α) (f : α → ℕ) :
↑(∏ x in s, f x : ℕ) = (∏ x in s, (f x : β)) :=
(nat.cast_ring_hom β).map_prod f s
protected lemma sum_nat_coe_enat (s : finset α) (f : α → ℕ) :
(∑ x in s, (f x : enat)) = (∑ x in s, f x : ℕ) :=
begin
classical,
induction s using finset.induction with a s has ih h,
{ simp },
{ simp [has, ih] }
end
theorem dvd_sum [comm_semiring α] {a : α} {s : finset β} {f : β → α}
(h : ∀ x ∈ s, a ∣ f x) : a ∣ ∑ x in s, f x :=
multiset.dvd_sum (λ y hy, by rcases multiset.mem_map.1 hy with ⟨x, hx, rfl⟩; exact h x hx)
lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_add_comm_monoid β]
(f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) :
f (∑ x in s, g x) ≤ ∑ x in s, f (g x) :=
begin
refine le_trans (multiset.le_sum_of_subadditive f h_zero h_add _) _,
rw [multiset.map_map],
refl
end
lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {f : β → α} {s : finset β} :
abs (∑ x in s, f x) ≤ ∑ x in s, abs (f x) :=
le_sum_of_subadditive _ abs_zero abs_add s f
section comm_group
variables [comm_group β]
@[simp, to_additive]
lemma prod_inv_distrib : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ :=
s.prod_hom has_inv.inv
end comm_group
@[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) :
card (s.sigma t) = ∑ a in s, card (t a) :=
multiset.card_sigma _ _
lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β}
(h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) :
(s.bind t).card = ∑ u in s, card (t u) :=
calc (s.bind t).card = (s.bind t).sum (λ _, 1) : by simp
... = s.sum (λ a, (t a).sum (λ _, 1)) : finset.sum_bind h
... = s.sum (λ u, card (t u)) : by simp
lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} :
(s.bind t).card ≤ ∑ a in s, (t a).card :=
by haveI := classical.dec_eq α; exact
finset.induction_on s (by simp)
(λ a s has ih,
calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card :
by rw bind_insert; exact finset.card_union_le _ _
... ≤ (insert a s).sum (λ a, card (t a)) :
by rw sum_insert has; exact add_le_add_left ih _)
theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) :
s.card = ∑ a in s.image f, (s.filter (λ x, f x = a)).card :=
by letI := classical.dec_eq α; exact
calc s.card = ((s.image f).bind (λ a, s.filter (λ x, f x = a))).card :
congr_arg _ (finset.ext.2 $ λ x,
⟨λ hs, mem_bind.2 ⟨f x, mem_image_of_mem _ hs,
mem_filter.2 ⟨hs, rfl⟩⟩,
λ h, let ⟨a, ha₁, ha₂⟩ := mem_bind.1 h in by convert filter_subset s ha₂⟩)
... = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) :
card_bind (by simp [disjoint_left, finset.ext] {contextual := tt})
lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) :
gsmul z (∑ a in s, f a) = ∑ a in s, gsmul z (f a) :=
(s.sum_hom (gsmul z)).symm
end finset
namespace finset
variables {s s₁ s₂ : finset α} {f g : α → β} {b : β} {a : α}
@[simp] lemma sum_sub_distrib [add_comm_group β] :
∑ x in s, (f x - g x) = (∑ x in s, f x) - (∑ x in s, g x) :=
sum_add_distrib.trans $ congr_arg _ sum_neg_distrib
section comm_monoid
variables [comm_monoid β]
lemma prod_pow_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) :
(∏ x in s, (f x)^(ite (a = x) 1 0)) = ite (a ∈ s) (f a) 1 :=
by simp
end comm_monoid
section semiring
variables [semiring β]
lemma sum_mul : (∑ x in s, f x) * b = ∑ x in s, f x * b :=
(s.sum_hom (λ x, x * b)).symm
lemma mul_sum : b * (∑ x in s, f x) = ∑ x in s, b * f x :=
(s.sum_hom _).symm
lemma sum_mul_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) :
(∑ x in s, (f x * ite (a = x) 1 0)) = ite (a ∈ s) (f a) 0 :=
by simp
lemma sum_boole_mul [decidable_eq α] (s : finset α) (f : α → β) (a : α) :
(∑ x in s, (ite (a = x) 1 0) * f x) = ite (a ∈ s) (f a) 0 :=
by simp
end semiring
lemma sum_div [division_ring β] {s : finset α} {f : α → β} {b : β} :
(∑ x in s, f x) / b = ∑ x in s, f x / b :=
calc (∑ x in s, f x) / b = ∑ x in s, f x * (1 / b) : by rw [div_eq_mul_one_div, sum_mul]
... = ∑ x in s, f x / b : by { congr, ext, rw ← div_eq_mul_one_div (f x) b }
section comm_semiring
variables [comm_semiring β]
lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : (∏ x in s, f x) = 0 :=
by haveI := classical.dec_eq α;
calc (∏ x in s, f x) = ∏ x in insert a (erase s a), f x : by rw insert_erase ha
... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul]
/-- The product over a sum can be written as a sum over the product of sets, `finset.pi`.
`finset.prod_univ_sum` is an alternative statement when the product is over `univ`. -/
lemma prod_sum {δ : α → Type*} [decidable_eq α] [∀a, decidable_eq (δ a)]
{s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} :
(∏ a in s, ∑ b in (t a), f a b) =
∑ p in (s.pi t), ∏ x in s.attach, f x.1 (p x.1 x.2) :=
begin
induction s using finset.induction with a s ha ih,
{ rw [pi_empty, sum_singleton], refl },
{ have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y,
disjoint (image (pi.cons s a x) (pi s t)) (image (pi.cons s a y) (pi s t)),
{ assume x hx y hy h,
simp only [disjoint_iff_ne, mem_image],
rintros _ ⟨p₂, hp, eq₂⟩ _ ⟨p₃, hp₃, eq₃⟩ eq,
have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _),
{ rw [eq₂, eq₃, eq] },
rw [pi.cons_same, pi.cons_same] at this,
exact h this },
rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bind h₁],
refine sum_congr rfl (λ b _, _),
have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from
assume p₁ h₁ p₂ h₂ eq, injective_pi_cons ha eq,
rw [sum_image h₂, mul_sum],
refine sum_congr rfl (λ g _, _),
rw [attach_insert, prod_insert, prod_image],
{ simp only [pi.cons_same],
congr', ext ⟨v, hv⟩, congr',
exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm },
{ exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj },
{ simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } }
end
lemma sum_mul_sum {ι₁ : Type*} {ι₂ : Type*} (s₁ : finset ι₁) (s₂ : finset ι₂)
(f₁ : ι₁ → β) (f₂ : ι₂ → β) :
(∑ x₁ in s₁, f₁ x₁) * (∑ x₂ in s₂, f₂ x₂) = ∑ p in s₁.product s₂, f₁ p.1 * f₂ p.2 :=
by { rw [sum_product, sum_mul, sum_congr rfl], intros, rw mul_sum }
open_locale classical
/-- The product of `f a + g a` over all of `s` is the sum
over the powerset of `s` of the product of `f` over a subset `t` times
the product of `g` over the complement of `t` -/
lemma prod_add (f g : α → β) (s : finset α) :
∏ a in s, (f a + g a) = ∑ t in s.powerset, ((∏ a in t, f a) * (∏ a in (s \ t), g a)) :=
calc ∏ a in s, (f a + g a)
= ∏ a in s, ∑ p in ({true, false} : finset Prop), if p then f a else g a : by simp
... = ∑ p in (s.pi (λ _, {true, false}) : finset (Π a ∈ s, Prop)),
∏ a in s.attach, if p a.1 a.2 then f a.1 else g a.1 : prod_sum
... = ∑ t in s.powerset, (∏ a in t, f a) * (∏ a in (s \ t), g a) : begin
refine eq.symm (sum_bij (λ t _ a _, a ∈ t) _ _ _ _),
{ simp [subset_iff]; tauto },
{ intros t ht,
erw [prod_ite (λ a : {a // a ∈ s}, f a.1) (λ a : {a // a ∈ s}, g a.1)],
refine congr_arg2 _
(prod_bij (λ (a : α) (ha : a ∈ t), ⟨a, mem_powerset.1 ht ha⟩)
_ _ _
(λ b hb, ⟨b, by cases b; finish⟩))
(prod_bij (λ (a : α) (ha : a ∈ s \ t), ⟨a, by simp * at *⟩)
_ _ _
(λ b hb, ⟨b, by cases b; finish⟩));
intros; simp * at *; simp * at * },
{ finish [function.funext_iff, finset.ext, subset_iff] },
{ assume f hf,
exact ⟨s.filter (λ a : α, ∃ h : a ∈ s, f a h),
by simp, by funext; intros; simp *⟩ }
end
/-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a `finset`
gives `(a + b)^s.card`.-/
lemma sum_pow_mul_eq_add_pow
{α R : Type*} [comm_semiring R] (a b : R) (s : finset α) :
(∑ t in s.powerset, a ^ t.card * b ^ (s.card - t.card)) = (a + b) ^ s.card :=
begin
rw [← prod_const, prod_add],
refine finset.sum_congr rfl (λ t ht, _),
rw [prod_const, prod_const, ← card_sdiff (mem_powerset.1 ht)]
end
lemma prod_pow_eq_pow_sum {x : β} {f : α → ℕ} :
∀ {s : finset α}, (∏ i in s, x ^ (f i)) = x ^ (∑ x in s, f x) :=
begin
apply finset.induction,
{ simp },
{ assume a s has H,
rw [finset.prod_insert has, finset.sum_insert has, pow_add, H] }
end
end comm_semiring
section integral_domain /- add integral_semi_domain to support nat and ennreal -/
variables [integral_domain β]
lemma prod_eq_zero_iff : (∏ x in s, f x) = 0 ↔ (∃a∈s, f a = 0) :=
begin
classical,
apply finset.induction_on s,
exact ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩,
assume a s ha ih,
rw [prod_insert ha, mul_eq_zero_iff_eq_zero_or_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def]
end
end integral_domain
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β]
lemma sum_le_sum : (∀x∈s, f x ≤ g x) → (∑ x in s, f x) ≤ (∑ x in s, g x) :=
begin
classical,
apply finset.induction_on s,
exact (λ _, le_refl _),
assume a s ha ih h,
have : f a + (∑ x in s, f x) ≤ g a + (∑ x in s, g x),
from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx),
by simpa only [sum_insert ha]
end
lemma sum_nonneg (h : ∀x∈s, 0 ≤ f x) : 0 ≤ (∑ x in s, f x) :=
le_trans (by rw [sum_const_zero]) (sum_le_sum h)
lemma sum_nonpos (h : ∀x∈s, f x ≤ 0) : (∑ x in s, f x) ≤ 0 :=
le_trans (sum_le_sum h) (by rw [sum_const_zero])
lemma sum_le_sum_of_subset_of_nonneg
(h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) :=
by classical;
calc (∑ x in s₁, f x) ≤ (∑ x in s₂ \ s₁, f x) + (∑ x in s₁, f x) :
le_add_of_nonneg_left' $ sum_nonneg $ by simpa only [mem_sdiff, and_imp]
... = ∑ x in s₂ \ s₁ ∪ s₁, f x : (sum_union sdiff_disjoint).symm
... = (∑ x in s₂, f x) : by rw [sdiff_union_of_subset h]
lemma sum_mono_set_of_nonneg (hf : ∀ x, 0 ≤ f x) : monotone (λ s, ∑ x in s, f x) :=
λ s₁ s₂ hs, sum_le_sum_of_subset_of_nonneg hs $ λ x _ _, hf x
lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → ((∑ x in s, f x) = 0 ↔ ∀x∈s, f x = 0) :=
begin
classical,
apply finset.induction_on s,
exact λ _, ⟨λ _ _, false.elim, λ _, rfl⟩,
assume a s ha ih H,
have : ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem,
rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (sum_nonneg this),
forall_mem_insert, ih this]
end
lemma sum_eq_zero_iff_of_nonpos : (∀x∈s, f x ≤ 0) → ((∑ x in s, f x) = 0 ↔ ∀x∈s, f x = 0) :=
@sum_eq_zero_iff_of_nonneg _ (order_dual β) _ _ _
lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ (∑ x in s, f x) :=
have ({a} : finset α).sum f ≤ (∑ x in s, f x),
from sum_le_sum_of_subset_of_nonneg
(λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h),
by rwa sum_singleton at this
end ordered_add_comm_monoid
section canonically_ordered_add_monoid
variables [canonically_ordered_add_monoid β]
lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) :=
sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _
lemma sum_mono_set (f : α → β) : monotone (λ s, ∑ x in s, f x) :=
λ s₁ s₂ hs, sum_le_sum_of_subset hs
lemma sum_le_sum_of_ne_zero (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) :
(∑ x in s₁, f x) ≤ (∑ x in s₂, f x) :=
by classical;
calc (∑ x in s₁, f x) = (s₁.filter (λx, f x = 0)).sum f + (s₁.filter (λx, f x ≠ 0)).sum f :
by rw [←sum_union, filter_union_filter_neg_eq];
exact disjoint_filter.2 (assume _ _ h n_h, n_h h)
... ≤ (∑ x in s₂, f x) : add_le_of_nonpos_of_le'
(sum_nonpos $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq)
(sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp])
end canonically_ordered_add_monoid
section ordered_cancel_comm_monoid
variables [ordered_cancel_add_comm_monoid β]
theorem sum_lt_sum (Hle : ∀ i ∈ s, f i ≤ g i) (Hlt : ∃ i ∈ s, f i < g i) :
(∑ x in s, f x) < (∑ x in s, g x) :=
begin
classical,
rcases Hlt with ⟨i, hi, hlt⟩,
rw [← insert_erase hi, sum_insert (not_mem_erase _ _), sum_insert (not_mem_erase _ _)],
exact add_lt_add_of_lt_of_le hlt (sum_le_sum $ λ j hj, Hle j $ mem_of_mem_erase hj)
end
lemma sum_lt_sum_of_nonempty (hs : s.nonempty) (Hlt : ∀ x ∈ s, f x < g x) :
(∑ x in s, f x) < (∑ x in s, g x) :=
begin
apply sum_lt_sum,
{ intros i hi, apply le_of_lt (Hlt i hi) },
cases hs with i hi,
exact ⟨i, hi, Hlt i hi⟩,
end
lemma sum_lt_sum_of_subset [decidable_eq α]
(h : s₁ ⊆ s₂) {i : α} (hi : i ∈ s₂ \ s₁) (hpos : 0 < f i) (hnonneg : ∀ j ∈ s₂ \ s₁, 0 ≤ f j) :
(∑ x in s₁, f x) < (∑ x in s₂, f x) :=
calc (∑ x in s₁, f x) < (∑ x in insert i s₁, f x) :
begin
simp only [mem_sdiff] at hi,
rw sum_insert hi.2,
exact lt_add_of_pos_left (finset.sum s₁ f) hpos,
end
... ≤ (∑ x in s₂, f x) :
begin
simp only [mem_sdiff] at hi,
apply sum_le_sum_of_subset_of_nonneg,
{ simp [finset.insert_subset, h, hi.1] },
{ assume x hx h'x,
apply hnonneg x,
simp [mem_insert, not_or_distrib] at h'x,
rw mem_sdiff,
simp [hx, h'x] }
end
end ordered_cancel_comm_monoid
section decidable_linear_ordered_cancel_comm_monoid
variables [decidable_linear_ordered_cancel_add_comm_monoid β]
theorem exists_le_of_sum_le (hs : s.nonempty) (Hle : (∑ x in s, f x) ≤ s.sum g) :
∃ i ∈ s, f i ≤ g i :=
begin
classical,
contrapose! Hle with Hlt,
rcases hs with ⟨i, hi⟩,
exact sum_lt_sum (λ i hi, le_of_lt (Hlt i hi)) ⟨i, hi, Hlt i hi⟩
end
end decidable_linear_ordered_cancel_comm_monoid
section linear_ordered_comm_ring
variables [linear_ordered_comm_ring β]
open_locale classical
/- this is also true for a ordered commutative multiplicative monoid -/
lemma prod_nonneg {s : finset α} {f : α → β}
(h0 : ∀(x ∈ s), 0 ≤ f x) : 0 ≤ (∏ x in s, f x) :=
begin
induction s using finset.induction with a s has ih h,
{ simp [zero_le_one] },
{ simp [has], apply mul_nonneg, apply h0 a (mem_insert_self a s),
exact ih (λ x H, h0 x (mem_insert_of_mem H)) }
end
/- this is also true for a ordered commutative multiplicative monoid -/
lemma prod_pos {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 < f x) : 0 < (∏ x in s, f x) :=
begin
induction s using finset.induction with a s has ih h,
{ simp [zero_lt_one] },
{ simp [has], apply mul_pos, apply h0 a (mem_insert_self a s),
exact ih (λ x H, h0 x (mem_insert_of_mem H)) }
end
/- this is also true for a ordered commutative multiplicative monoid -/
lemma prod_le_prod {s : finset α} {f g : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x)
(h1 : ∀(x ∈ s), f x ≤ g x) : (∏ x in s, f x) ≤ (∏ x in s, g x) :=
begin
induction s using finset.induction with a s has ih h,
{ simp },
{ simp [has], apply mul_le_mul,
exact h1 a (mem_insert_self a s),
apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H),
apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)),
apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) }
end
end linear_ordered_comm_ring
section canonically_ordered_comm_semiring
variables [canonically_ordered_comm_semiring β]
lemma prod_le_prod' {s : finset α} {f g : α → β} (h : ∀ i ∈ s, f i ≤ g i) :
(∏ x in s, f x) ≤ (∏ x in s, g x) :=
begin
classical,
induction s using finset.induction with a s has ih h,
{ simp },
{ rw [finset.prod_insert has, finset.prod_insert has],
apply canonically_ordered_semiring.mul_le_mul,
{ exact h _ (finset.mem_insert_self a s) },
{ exact ih (λ i hi, h _ (finset.mem_insert_of_mem hi)) } }
end
end canonically_ordered_comm_semiring
@[simp] lemma card_pi [decidable_eq α] {δ : α → Type*}
(s : finset α) (t : Π a, finset (δ a)) :
(s.pi t).card = s.prod (λ a, card (t a)) :=
multiset.card_pi _ _
theorem card_le_mul_card_image [decidable_eq β] {f : α → β} (s : finset α)
(n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) :
s.card ≤ n * (s.image f).card :=
calc s.card = (∑ a in s.image f, (s.filter (λ x, f x = a)).card) :
card_eq_sum_card_image _ _
... ≤ (∑ _ in s.image f, n) : sum_le_sum hn
... = _ : by simp [mul_comm]
@[simp] lemma prod_Ico_id_eq_fact : ∀ n : ℕ, (Ico 1 (n + 1)).prod (λ x, x) = nat.fact n
| 0 := rfl
| (n+1) := by rw [prod_Ico_succ_top $ nat.succ_le_succ $ zero_le n,
nat.fact_succ, prod_Ico_id_eq_fact n, nat.succ_eq_add_one, mul_comm]
end finset
namespace finset
section gauss_sum
/-- Gauss' summation formula -/
lemma sum_range_id_mul_two (n : ℕ) :
(∑ i in range n, i) * 2 = n * (n - 1) :=
calc (∑ i in range n, i) * 2 = (∑ i in range n, i) + (∑ i in range n, (n - 1 - i)) :
by rw [sum_range_reflect (λ i, i) n, mul_two]
... = ∑ i in range n, (i + (n - 1 - i)) : sum_add_distrib.symm
... = ∑ i in range n, (n - 1) : sum_congr rfl $ λ i hi, nat.add_sub_cancel' $
nat.le_pred_of_lt $ mem_range.1 hi
... = n * (n - 1) : by rw [sum_const, card_range, nat.smul_eq_mul]
/-- Gauss' summation formula -/
lemma sum_range_id (n : ℕ) : (∑ i in range n, i) = (n * (n - 1)) / 2 :=
by rw [← sum_range_id_mul_two n, nat.mul_div_cancel]; exact dec_trivial
end gauss_sum
lemma card_eq_sum_ones (s : finset α) : s.card = ∑ _ in s, 1 :=
by simp
end finset
section group
open list
variables [group α] [group β]
theorem is_group_anti_hom.map_prod (f : α → β) [is_group_anti_hom f] (l : list α) :
f (prod l) = prod (map f (reverse l)) :=
by induction l with hd tl ih; [exact is_group_anti_hom.map_one f,
simp only [prod_cons, is_group_anti_hom.map_mul f, ih, reverse_cons, map_append, prod_append, map_singleton, prod_cons, prod_nil, mul_one]]
theorem inv_prod : ∀ l : list α, (prod l)⁻¹ = prod (map (λ x, x⁻¹) (reverse l)) :=
λ l, @is_group_anti_hom.map_prod _ _ _ _ _ inv_is_group_anti_hom l -- TODO there is probably a cleaner proof of this
end group
@[to_additive is_add_group_hom_finset_sum]
lemma is_group_hom_finset_prod {α β γ} [group α] [comm_group β] (s : finset γ)
(f : γ → α → β) [∀c, is_group_hom (f c)] : is_group_hom (λa, ∏ c in s, f c a) :=
{ map_mul := assume a b, by simp only [λc, is_mul_hom.map_mul (f c), finset.prod_mul_distrib] }
attribute [instance] is_group_hom_finset_prod is_add_group_hom_finset_sum
namespace multiset
variables [decidable_eq α]
@[simp] lemma to_finset_sum_count_eq (s : multiset α) :
(∑ a in s.to_finset, s.count a) = s.card :=
multiset.induction_on s rfl
(assume a s ih,
calc (∑ x in to_finset (a :: s), count x (a :: s)) =
(to_finset (a :: s)).sum (λx, (if x = a then 1 else 0) + count x s) :
finset.sum_congr rfl $ λ _ _, by split_ifs;
[simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]]
... = card (a :: s) :
begin
by_cases a ∈ s.to_finset,
{ have : (to_finset s).sum (λx, ite (x = a) 1 0) = ({a} : finset α).sum (λx, ite (x = a) 1 0),
{ apply (finset.sum_subset _ _).symm,
{ intros _ H, rwa mem_singleton.1 H },
{ exact λ _ _ H, if_neg (mt finset.mem_singleton.2 H) } },
rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] },
{ have ha : a ∉ s, by rwa mem_to_finset at h,
have : (to_finset s).sum (λx, ite (x = a) 1 0) = (to_finset s).sum (λx, 0), from
finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc),
rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] }
end)
end multiset
namespace with_top
open finset
open_locale classical
/-- sum of finite numbers is still finite -/
lemma sum_lt_top [ordered_add_comm_monoid β] {s : finset α} {f : α → with_top β} :
(∀a∈s, f a < ⊤) → (∑ x in s, f x) < ⊤ :=
finset.induction_on s (by { intro h, rw sum_empty, exact coe_lt_top _ })
(λa s ha ih h,
begin
rw [sum_insert ha, add_lt_top], split,
{ apply h, apply mem_insert_self },
{ apply ih, intros a ha, apply h, apply mem_insert_of_mem ha }
end)
/-- sum of finite numbers is still finite -/
lemma sum_lt_top_iff [canonically_ordered_add_monoid β] {s : finset α} {f : α → with_top β} :
(∑ x in s, f x) < ⊤ ↔ (∀a∈s, f a < ⊤) :=
iff.intro (λh a ha, lt_of_le_of_lt (single_le_sum (λa ha, zero_le _) ha) h) sum_lt_top
end with_top
|
c81372516ae7c306800167dfa06914f6d922b276 | 7c2dd01406c42053207061adb11703dc7ce0b5e5 | /src/solutions/07bis_abstract_negations.lean | ef6fa52489bacf8ab4b0f3146a455143288b5973 | [
"Apache-2.0"
] | permissive | leanprover-community/tutorials | 50ec79564cbf2ad1afd1ac43d8ee3c592c2883a8 | 79a6872a755c4ae0c2aca57e1adfdac38b1d8bb1 | refs/heads/master | 1,687,466,144,386 | 1,672,061,276,000 | 1,672,061,276,000 | 189,169,918 | 186 | 81 | Apache-2.0 | 1,686,350,300,000 | 1,559,113,678,000 | Lean | UTF-8 | Lean | false | false | 2,459 | lean | import data.real.basic
open_locale classical
/-
Theoretical negations.
This file is for people interested in logic who want to fully understand
negations.
Here we don't use `contrapose` or `push_neg`. The goal is to prove lemmas
that are used by those tactics. Of course we can use
`exfalso`, `by_contradiction` and `by_cases`.
If this doesn't sound like fun then skip ahead to the next file.
-/
section negation_prop
variables P Q : Prop
-- 0055
example : (P → Q) ↔ (¬ Q → ¬ P) :=
begin
-- sorry
split,
{ intros h hnQ hP,
exact hnQ (h hP) },
{ intros h hP,
by_contradiction hnQ,
exact h hnQ hP },
-- sorry
end
-- 0056
lemma non_imp (P Q : Prop) : ¬ (P → Q) ↔ P ∧ ¬ Q :=
begin
-- sorry
split,
{ intro h,
by_contradiction H,
apply h,
intro hP,
by_contradiction H',
apply H,
exact ⟨hP, H'⟩ },
{ intros h h',
cases h with hP hnQ,
exact hnQ (h' hP) },
-- sorry
end
-- In the next one, let's use the axiom
-- propext {P Q : Prop} : (P ↔ Q) → P = Q
-- 0057
example (P : Prop) : ¬ P ↔ P = false :=
begin
-- sorry
split,
{ intro h,
apply propext,
split,
{ intro h',
exact h h' },
{ intro h,
exfalso,
exact h } },
{ intro h,
rw h,
exact id },
-- sorry
end
end negation_prop
section negation_quantifiers
variables (X : Type) (P : X → Prop)
-- 0058
example : ¬ (∀ x, P x) ↔ ∃ x, ¬ P x :=
begin
-- sorry
split,
{ intro h,
by_contradiction H,
apply h,
intros x,
by_contradiction H',
apply H,
use [x, H'] },
{ rintros ⟨x, hx⟩ h',
exact hx (h' x) },
-- sorry
end
-- 0059
example : ¬ (∃ x, P x) ↔ ∀ x, ¬ P x :=
begin
-- sorry
split,
{ intros h x h',
apply h,
use [x, h'] },
{ rintros h ⟨x, hx⟩,
exact h x hx },
-- sorry
end
-- 0060
example (P : ℝ → Prop) : ¬ (∃ ε > 0, P ε) ↔ ∀ ε > 0, ¬ P ε :=
begin
-- sorry
split,
{ intros h ε ε_pos hP,
apply h,
use [ε, ε_pos, hP] },
{ rintros h ⟨ε, ε_pos, hP⟩,
exact h ε ε_pos hP },
-- sorry
end
-- 0061
example (P : ℝ → Prop) : ¬ (∀ x > 0, P x) ↔ ∃ x > 0, ¬ P x :=
begin
-- sorry
split,
{ intros h,
by_contradiction H,
apply h,
intros x x_pos,
by_contradiction HP,
apply H,
use [x, x_pos, HP] },
{ rintros ⟨x, xpos, hx⟩ h',
exact hx (h' x xpos) },
-- sorry
end
end negation_quantifiers
|
cebe1537ed16d55064b4510ec9ac4b9bdfd7bf78 | d1bbf1801b3dcb214451d48214589f511061da63 | /src/topology/local_homeomorph.lean | 4742cbc52fcb3bae32a68f1568af6a1bcd787db8 | [
"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 | 38,282 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import data.equiv.local_equiv
import topology.opens
/-!
# Local homeomorphisms
This file defines homeomorphisms between open subsets of topological spaces. An element `e` of
`local_homeomorph α β` is an extension of `local_equiv α β`, i.e., it is a pair of functions
`e.to_fun` and `e.inv_fun`, inverse of each other on the sets `e.source` and `e.target`.
Additionally, we require that these sets are open, and that the functions are continuous on them.
Equivalently, they are homeomorphisms there.
As in equivs, we register a coercion to functions, and we use `e x` and `e.symm x` throughout
instead of `e.to_fun x` and `e.inv_fun x`.
## Main definitions
`homeomorph.to_local_homeomorph`: associating a local homeomorphism to a homeomorphism, with
source = target = univ
`local_homeomorph.symm` : the inverse of a local homeomorphism
`local_homeomorph.trans` : the composition of two local homeomorphisms
`local_homeomorph.refl` : the identity local homeomorphism
`local_homeomorph.of_set`: the identity on a set `s`
`eq_on_source` : equivalence relation describing the "right" notion of equality for local
homeomorphisms
## Implementation notes
Most statements are copied from their local_equiv versions, although some care is required
especially when restricting to subsets, as these should be open subsets.
For design notes, see `local_equiv.lean`.
-/
open function set filter
open_locale topological_space
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
[topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
/-- local homeomorphisms, defined on open subsets of the space -/
@[nolint has_inhabited_instance]
structure local_homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β]
extends local_equiv α β :=
(open_source : is_open source)
(open_target : is_open target)
(continuous_to_fun : continuous_on to_fun source)
(continuous_inv_fun : continuous_on inv_fun target)
/-- A homeomorphism induces a local homeomorphism on the whole space -/
def homeomorph.to_local_homeomorph (e : homeomorph α β) :
local_homeomorph α β :=
{ open_source := is_open_univ,
open_target := is_open_univ,
continuous_to_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_to_fun },
continuous_inv_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_inv_fun },
..e.to_equiv.to_local_equiv }
namespace local_homeomorph
variables (e : local_homeomorph α β) (e' : local_homeomorph β γ)
instance : has_coe_to_fun (local_homeomorph α β) := ⟨_, λ e, e.to_local_equiv.to_fun⟩
/-- The inverse of a local homeomorphism -/
protected def symm : local_homeomorph β α :=
{ open_source := e.open_target,
open_target := e.open_source,
continuous_to_fun := e.continuous_inv_fun,
continuous_inv_fun := e.continuous_to_fun,
..e.to_local_equiv.symm }
protected lemma continuous_on : continuous_on e e.source := e.continuous_to_fun
lemma continuous_on_symm : continuous_on e.symm e.target := e.continuous_inv_fun
@[simp, mfld_simps] lemma mk_coe (e : local_equiv α β) (a b c d) :
(local_homeomorph.mk e a b c d : α → β) = e := rfl
@[simp, mfld_simps] lemma mk_coe_symm (e : local_equiv α β) (a b c d) :
((local_homeomorph.mk e a b c d).symm : β → α) = e.symm := rfl
/- Register a few simp lemmas to make sure that `simp` puts the application of a local
homeomorphism in its normal form, i.e., in terms of its coercion to a function. -/
@[simp, mfld_simps] lemma to_fun_eq_coe (e : local_homeomorph α β) : e.to_fun = e := rfl
@[simp, mfld_simps] lemma inv_fun_eq_coe (e : local_homeomorph α β) : e.inv_fun = e.symm := rfl
@[simp, mfld_simps] lemma coe_coe : (e.to_local_equiv : α → β) = e := rfl
@[simp, mfld_simps] lemma coe_coe_symm : (e.to_local_equiv.symm : β → α) = e.symm := rfl
@[simp, mfld_simps] lemma map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target :=
e.map_source' h
@[simp, mfld_simps] lemma map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source :=
e.map_target' h
@[simp, mfld_simps] lemma left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x :=
e.left_inv' h
@[simp, mfld_simps] lemma right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x :=
e.right_inv' h
lemma source_preimage_target : e.source ⊆ e ⁻¹' e.target := λ _ h, map_source e h
lemma eq_of_local_equiv_eq {e e' : local_homeomorph α β}
(h : e.to_local_equiv = e'.to_local_equiv) : e = e' :=
begin
cases e, cases e',
dsimp at *,
induction h,
refl
end
lemma eventually_left_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.source) :
∀ᶠ y in 𝓝 x, e.symm (e y) = y :=
(e.open_source.eventually_mem hx).mono e.left_inv'
lemma eventually_left_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.target) :
∀ᶠ y in 𝓝 (e.symm x), e.symm (e y) = y :=
e.eventually_left_inverse (e.map_target hx)
lemma eventually_right_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.target) :
∀ᶠ y in 𝓝 x, e (e.symm y) = y :=
(e.open_target.eventually_mem hx).mono e.right_inv'
lemma eventually_right_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.source) :
∀ᶠ y in 𝓝 (e x), e (e.symm y) = y :=
e.eventually_right_inverse (e.map_source hx)
lemma eventually_ne_nhds_within (e : local_homeomorph α β) {x} (hx : x ∈ e.source) :
∀ᶠ x' in 𝓝[{x}ᶜ] x, e x' ≠ e x :=
eventually_nhds_within_iff.2 $ (e.eventually_left_inverse hx).mono $
λ x' hx', mt $ λ h, by rw [mem_singleton_iff, ← e.left_inv hx, ← h, hx']
lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) :
e '' s = e.target ∩ e.symm ⁻¹' s :=
e.to_local_equiv.image_eq_target_inter_inv_preimage h
lemma image_inter_source_eq (s : set α) :
e '' (s ∩ e.source) = e.target ∩ e.symm ⁻¹' (s ∩ e.source) :=
e.image_eq_target_inter_inv_preimage (inter_subset_right _ _)
lemma symm_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) :
e.symm '' s = e.source ∩ e ⁻¹' s :=
e.symm.image_eq_target_inter_inv_preimage h
lemma symm_image_inter_target_eq (s : set β) :
e.symm '' (s ∩ e.target) = e.source ∩ e ⁻¹' (s ∩ e.target) :=
e.symm.image_inter_source_eq _
/-- Two local homeomorphisms are equal when they have equal `to_fun`, `inv_fun` and `source`.
It is not sufficient to have equal `to_fun` and `source`, as this only determines `inv_fun` on
the target. This would only be true for a weaker notion of equality, arguably the right one,
called `eq_on_source`. -/
@[ext]
protected lemma ext (e' : local_homeomorph α β) (h : ∀x, e x = e' x)
(hinv : ∀x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' :=
eq_of_local_equiv_eq (local_equiv.ext h hinv hs)
@[simp, mfld_simps] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl
-- The following lemmas are already simp via local_equiv
lemma symm_source : e.symm.source = e.target := rfl
lemma symm_target : e.symm.target = e.source := rfl
@[simp, mfld_simps] lemma symm_symm : e.symm.symm = e := eq_of_local_equiv_eq $ by simp
/-- A local homeomorphism is continuous at any point of its source -/
protected lemma continuous_at {x : α} (h : x ∈ e.source) : continuous_at e x :=
(e.continuous_on x h).continuous_at (mem_nhds_sets e.open_source h)
/-- A local homeomorphism inverse is continuous at any point of its target -/
lemma continuous_at_symm {x : β} (h : x ∈ e.target) : continuous_at e.symm x :=
e.symm.continuous_at h
lemma tendsto_symm (e : local_homeomorph α β) {x} (hx : x ∈ e.source) :
tendsto e.symm (𝓝 (e x)) (𝓝 x) :=
by simpa only [continuous_at, e.left_inv hx] using e.continuous_at_symm (e.map_source hx)
lemma map_nhds_eq (e : local_homeomorph α β) {x} (hx : x ∈ e.source) :
map e (𝓝 x) = 𝓝 (e x) :=
le_antisymm (e.continuous_at hx) $
le_map_of_right_inverse (e.eventually_right_inverse' hx) (e.tendsto_symm hx)
/-- Preimage of interior or interior of preimage coincide for local homeomorphisms, when restricted
to the source. -/
lemma preimage_interior (s : set β) :
e.source ∩ e ⁻¹' (interior s) = e.source ∩ interior (e ⁻¹' s) :=
begin
apply subset.antisymm,
{ exact e.continuous_on.preimage_interior_subset_interior_preimage e.open_source },
{ calc e.source ∩ interior (e ⁻¹' s)
= (e.source ∩ interior (e ⁻¹' s)) ∩ (e ⁻¹' e.target) : by mfld_set_tac
... = (e.source ∩ e ⁻¹' (e.symm ⁻¹' (interior (e ⁻¹' s)))) ∩ (e ⁻¹' e.target) :
begin
have := e.to_local_equiv.source_inter_preimage_inv_preimage _,
simp only [coe_coe_symm, coe_coe] at this,
rw this
end
... = e.source ∩ e ⁻¹' (e.target ∩ e.symm ⁻¹' (interior (e ⁻¹' s))) :
by rw [inter_comm e.target, preimage_inter, inter_assoc]
... ⊆ e.source ∩ e ⁻¹' (e.target ∩ interior (e.symm ⁻¹' (e ⁻¹' s))) : begin
apply inter_subset_inter (subset.refl _) (preimage_mono _),
exact e.continuous_on_symm.preimage_interior_subset_interior_preimage e.open_target
end
... = e.source ∩ e ⁻¹' (interior (e.target ∩ e.symm ⁻¹' (e ⁻¹' s))) :
by rw [interior_inter, e.open_target.interior_eq]
... = e.source ∩ e ⁻¹' (interior (e.target ∩ s)) :
begin
have := e.to_local_equiv.target_inter_inv_preimage_preimage,
simp only [coe_coe_symm, coe_coe] at this,
rw this
end
... = e.source ∩ e ⁻¹' e.target ∩ e ⁻¹' (interior s) :
by rw [interior_inter, preimage_inter, e.open_target.interior_eq, inter_assoc]
... = e.source ∩ e ⁻¹' (interior s) : by mfld_set_tac }
end
lemma preimage_open_of_open {s : set β} (hs : is_open s) : is_open (e.source ∩ e ⁻¹' s) :=
e.continuous_on.preimage_open_of_open e.open_source hs
lemma preimage_open_of_open_symm {s : set α} (hs : is_open s) : is_open (e.target ∩ e.symm ⁻¹' s) :=
e.symm.continuous_on.preimage_open_of_open e.open_target hs
/-- The image of an open set in the source is open. -/
lemma image_open_of_open {s : set α} (hs : is_open s) (h : s ⊆ e.source) : is_open (e '' s) :=
begin
have : e '' s = e.target ∩ e.symm ⁻¹' s :=
e.to_local_equiv.image_eq_target_inter_inv_preimage h,
rw this,
exact e.continuous_on_symm.preimage_open_of_open e.open_target hs
end
/-- The image of the restriction of an open set to the source is open. -/
lemma image_open_of_open' {s : set α} (hs : is_open s) : is_open (e '' (s ∩ e.source)) :=
begin
refine image_open_of_open _ (is_open_inter hs e.open_source) _,
simp,
end
/-- Restricting a local homeomorphism `e` to `e.source ∩ s` when `s` is open. This is sometimes hard
to use because of the openness assumption, but it has the advantage that when it can
be used then its local_equiv is defeq to local_equiv.restr -/
protected def restr_open (s : set α) (hs : is_open s) :
local_homeomorph α β :=
{ open_source := is_open_inter e.open_source hs,
open_target := (continuous_on_open_iff e.open_target).1 e.continuous_inv_fun s hs,
continuous_to_fun := e.continuous_to_fun.mono (inter_subset_left _ _),
continuous_inv_fun := e.continuous_inv_fun.mono (inter_subset_left _ _),
..e.to_local_equiv.restr s}
@[simp, mfld_simps] lemma restr_open_to_local_equiv (s : set α) (hs : is_open s) :
(e.restr_open s hs).to_local_equiv = e.to_local_equiv.restr s := rfl
-- Already simp via local_equiv
lemma restr_open_source (s : set α) (hs : is_open s) :
(e.restr_open s hs).source = e.source ∩ s := rfl
/-- Restricting a local homeomorphism `e` to `e.source ∩ interior s`. We use the interior to make
sure that the restriction is well defined whatever the set s, since local homeomorphisms are by
definition defined on open sets. In applications where `s` is open, this coincides with the
restriction of local equivalences -/
protected def restr (s : set α) : local_homeomorph α β :=
e.restr_open (interior s) is_open_interior
@[simp, mfld_simps] lemma restr_to_local_equiv (s : set α) :
(e.restr s).to_local_equiv = (e.to_local_equiv).restr (interior s) := rfl
@[simp, mfld_simps] lemma restr_coe (s : set α) : (e.restr s : α → β) = e := rfl
@[simp, mfld_simps] lemma restr_coe_symm (s : set α) : ((e.restr s).symm : β → α) = e.symm := rfl
lemma restr_source (s : set α) : (e.restr s).source = e.source ∩ interior s := rfl
lemma restr_target (s : set α) :
(e.restr s).target = e.target ∩ e.symm ⁻¹' (interior s) := rfl
lemma restr_source' (s : set α) (hs : is_open s) : (e.restr s).source = e.source ∩ s :=
by rw [e.restr_source, hs.interior_eq]
lemma restr_to_local_equiv' (s : set α) (hs : is_open s):
(e.restr s).to_local_equiv = e.to_local_equiv.restr s :=
by rw [e.restr_to_local_equiv, hs.interior_eq]
lemma restr_eq_of_source_subset {e : local_homeomorph α β} {s : set α} (h : e.source ⊆ s) :
e.restr s = e :=
begin
apply eq_of_local_equiv_eq,
rw restr_to_local_equiv,
apply local_equiv.restr_eq_of_source_subset,
have := interior_mono h,
rwa e.open_source.interior_eq at this
end
@[simp, mfld_simps] lemma restr_univ {e : local_homeomorph α β} : e.restr univ = e :=
restr_eq_of_source_subset (subset_univ _)
lemma restr_source_inter (s : set α) : e.restr (e.source ∩ s) = e.restr s :=
begin
refine local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) _,
simp [e.open_source.interior_eq],
rw [← inter_assoc, inter_self]
end
/-- The identity on the whole space as a local homeomorphism. -/
protected def refl (α : Type*) [topological_space α] : local_homeomorph α α :=
(homeomorph.refl α).to_local_homeomorph
@[simp, mfld_simps] lemma refl_local_equiv :
(local_homeomorph.refl α).to_local_equiv = local_equiv.refl α := rfl
lemma refl_source : (local_homeomorph.refl α).source = univ := rfl
lemma refl_target : (local_homeomorph.refl α).target = univ := rfl
@[simp, mfld_simps] lemma refl_symm : (local_homeomorph.refl α).symm = local_homeomorph.refl α :=
rfl
@[simp, mfld_simps] lemma refl_coe : (local_homeomorph.refl α : α → α) = id := rfl
section
variables {s : set α} (hs : is_open s)
/-- The identity local equiv on a set `s` -/
def of_set (s : set α) (hs : is_open s) : local_homeomorph α α :=
{ open_source := hs,
open_target := hs,
continuous_to_fun := continuous_id.continuous_on,
continuous_inv_fun := continuous_id.continuous_on,
..local_equiv.of_set s }
@[simp, mfld_simps] lemma of_set_to_local_equiv :
(of_set s hs).to_local_equiv = local_equiv.of_set s := rfl
lemma of_set_source : (of_set s hs).source = s := rfl
lemma of_set_target : (of_set s hs).target = s := rfl
@[simp, mfld_simps] lemma of_set_coe : (of_set s hs : α → α) = id := rfl
@[simp, mfld_simps] lemma of_set_symm : (of_set s hs).symm = of_set s hs := rfl
@[simp, mfld_simps] lemma of_set_univ_eq_refl :
of_set univ is_open_univ = local_homeomorph.refl α :=
by ext; simp
end
/-- Composition of two local homeomorphisms when the target of the first and the source of
the second coincide. -/
protected def trans' (h : e.target = e'.source) : local_homeomorph α γ :=
{ open_source := e.open_source,
open_target := e'.open_target,
continuous_to_fun := begin
apply continuous_on.comp e'.continuous_to_fun e.continuous_to_fun,
rw ← h,
exact e.to_local_equiv.source_subset_preimage_target
end,
continuous_inv_fun := begin
apply continuous_on.comp e.continuous_inv_fun e'.continuous_inv_fun,
rw h,
exact e'.to_local_equiv.target_subset_preimage_source
end,
..local_equiv.trans' e.to_local_equiv e'.to_local_equiv h }
/-- Composing two local homeomorphisms, by restricting to the maximal domain where their
composition is well defined. -/
protected def trans : local_homeomorph α γ :=
local_homeomorph.trans' (e.symm.restr_open e'.source e'.open_source).symm
(e'.restr_open e.target e.open_target) (by simp [inter_comm])
@[simp, mfld_simps] lemma trans_to_local_equiv :
(e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv := rfl
@[simp, mfld_simps] lemma coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl
@[simp, mfld_simps] lemma coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl
lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm :=
by cases e; cases e'; refl
/- This could be considered as a simp lemma, but there are many situations where it makes something
simple into something more complicated. -/
lemma trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source :=
local_equiv.trans_source e.to_local_equiv e'.to_local_equiv
lemma trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) :=
local_equiv.trans_source' e.to_local_equiv e'.to_local_equiv
lemma trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) :=
local_equiv.trans_source'' e.to_local_equiv e'.to_local_equiv
lemma image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source :=
local_equiv.image_trans_source e.to_local_equiv e'.to_local_equiv
lemma trans_target : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl
lemma trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) :=
trans_source' e'.symm e.symm
lemma trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) :=
trans_source'' e'.symm e.symm
lemma inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target :=
image_trans_source e'.symm e.symm
lemma trans_assoc (e'' : local_homeomorph γ δ) :
(e.trans e').trans e'' = e.trans (e'.trans e'') :=
eq_of_local_equiv_eq $ local_equiv.trans_assoc e.to_local_equiv e'.to_local_equiv e''.to_local_equiv
@[simp, mfld_simps] lemma trans_refl : e.trans (local_homeomorph.refl β) = e :=
eq_of_local_equiv_eq $ local_equiv.trans_refl e.to_local_equiv
@[simp, mfld_simps] lemma refl_trans : (local_homeomorph.refl α).trans e = e :=
eq_of_local_equiv_eq $ local_equiv.refl_trans e.to_local_equiv
lemma trans_of_set {s : set β} (hs : is_open s) :
e.trans (of_set s hs) = e.restr (e ⁻¹' s) :=
local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $
by simp [local_equiv.trans_source, (e.preimage_interior _).symm, hs.interior_eq]
lemma trans_of_set' {s : set β} (hs : is_open s) :
e.trans (of_set s hs) = e.restr (e.source ∩ e ⁻¹' s) :=
by rw [trans_of_set, restr_source_inter]
lemma of_set_trans {s : set α} (hs : is_open s) :
(of_set s hs).trans e = e.restr s :=
local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $
by simp [local_equiv.trans_source, hs.interior_eq, inter_comm]
lemma of_set_trans' {s : set α} (hs : is_open s) :
(of_set s hs).trans e = e.restr (e.source ∩ s) :=
by rw [of_set_trans, restr_source_inter]
@[simp, mfld_simps] lemma of_set_trans_of_set
{s : set α} (hs : is_open s) {s' : set α} (hs' : is_open s') :
(of_set s hs).trans (of_set s' hs') = of_set (s ∩ s') (is_open_inter hs hs') :=
begin
rw (of_set s hs).trans_of_set hs',
ext; simp [hs'.interior_eq]
end
lemma restr_trans (s : set α) :
(e.restr s).trans e' = (e.trans e').restr s :=
eq_of_local_equiv_eq $ local_equiv.restr_trans e.to_local_equiv e'.to_local_equiv (interior s)
/-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. They
should really be considered the same local equiv. -/
def eq_on_source (e e' : local_homeomorph α β) : Prop :=
e.source = e'.source ∧ (eq_on e e' e.source)
lemma eq_on_source_iff (e e' : local_homeomorph α β) :
eq_on_source e e' ↔ local_equiv.eq_on_source e.to_local_equiv e'.to_local_equiv :=
iff.rfl
/-- `eq_on_source` is an equivalence relation -/
instance : setoid (local_homeomorph α β) :=
{ r := eq_on_source,
iseqv := ⟨
λe, (@local_equiv.eq_on_source_setoid α β).iseqv.1 e.to_local_equiv,
λe e' h, (@local_equiv.eq_on_source_setoid α β).iseqv.2.1 ((eq_on_source_iff e e').1 h),
λe e' e'' h h', (@local_equiv.eq_on_source_setoid α β).iseqv.2.2
((eq_on_source_iff e e').1 h) ((eq_on_source_iff e' e'').1 h')⟩ }
lemma eq_on_source_refl : e ≈ e := setoid.refl _
/-- If two local homeomorphisms are equivalent, so are their inverses -/
lemma eq_on_source.symm' {e e' : local_homeomorph α β} (h : e ≈ e') : e.symm ≈ e'.symm :=
local_equiv.eq_on_source.symm' h
/-- Two equivalent local homeomorphisms have the same source -/
lemma eq_on_source.source_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.source = e'.source :=
h.1
/-- Two equivalent local homeomorphisms have the same target -/
lemma eq_on_source.target_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.target = e'.target :=
h.symm'.1
/-- Two equivalent local homeomorphisms have coinciding `to_fun` on the source -/
lemma eq_on_source.eq_on {e e' : local_homeomorph α β} (h : e ≈ e') :
eq_on e e' e.source :=
h.2
/-- Two equivalent local homeomorphisms have coinciding `inv_fun` on the target -/
lemma eq_on_source.symm_eq_on_target {e e' : local_homeomorph α β} (h : e ≈ e') :
eq_on e.symm e'.symm e.target :=
h.symm'.2
/-- Composition of local homeomorphisms respects equivalence -/
lemma eq_on_source.trans' {e e' : local_homeomorph α β} {f f' : local_homeomorph β γ}
(he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' :=
local_equiv.eq_on_source.trans' he hf
/-- Restriction of local homeomorphisms respects equivalence -/
lemma eq_on_source.restr {e e' : local_homeomorph α β} (he : e ≈ e') (s : set α) :
e.restr s ≈ e'.restr s :=
local_equiv.eq_on_source.restr he _
/-- Composition of a local homeomorphism and its inverse is equivalent to the restriction of the
identity to the source -/
lemma trans_self_symm :
e.trans e.symm ≈ local_homeomorph.of_set e.source e.open_source :=
local_equiv.trans_self_symm _
lemma trans_symm_self :
e.symm.trans e ≈ local_homeomorph.of_set e.target e.open_target :=
e.symm.trans_self_symm
lemma eq_of_eq_on_source_univ {e e' : local_homeomorph α β} (h : e ≈ e')
(s : e.source = univ) (t : e.target = univ) : e = e' :=
eq_of_local_equiv_eq $ local_equiv.eq_of_eq_on_source_univ _ _ h s t
section prod
/-- The product of two local homeomorphisms, as a local homeomorphism on the product space. -/
def prod (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : local_homeomorph (α × γ) (β × δ) :=
{ open_source := e.open_source.prod e'.open_source,
open_target := e.open_target.prod e'.open_target,
continuous_to_fun := continuous_on.prod
(e.continuous_to_fun.comp continuous_fst.continuous_on (prod_subset_preimage_fst _ _))
(e'.continuous_to_fun.comp continuous_snd.continuous_on (prod_subset_preimage_snd _ _)),
continuous_inv_fun := continuous_on.prod
(e.continuous_inv_fun.comp continuous_fst.continuous_on (prod_subset_preimage_fst _ _))
(e'.continuous_inv_fun.comp continuous_snd.continuous_on (prod_subset_preimage_snd _ _)),
..e.to_local_equiv.prod e'.to_local_equiv }
@[simp, mfld_simps] lemma prod_to_local_equiv (e : local_homeomorph α β) (e' : local_homeomorph γ δ) :
(e.prod e').to_local_equiv = e.to_local_equiv.prod e'.to_local_equiv := rfl
lemma prod_source (e : local_homeomorph α β) (e' : local_homeomorph γ δ) :
(e.prod e').source = set.prod e.source e'.source := rfl
lemma prod_target (e : local_homeomorph α β) (e' : local_homeomorph γ δ) :
(e.prod e').target = set.prod e.target e'.target := rfl
@[simp, mfld_simps] lemma prod_coe (e : local_homeomorph α β) (e' : local_homeomorph γ δ) :
(e.prod e' : α × γ → β × δ) = λp, (e p.1, e' p.2) := rfl
lemma prod_coe_symm (e : local_homeomorph α β) (e' : local_homeomorph γ δ) :
((e.prod e').symm : β × δ → α × γ) = λp, (e.symm p.1, e'.symm p.2) := rfl
@[simp, mfld_simps] lemma prod_symm (e : local_homeomorph α β) (e' : local_homeomorph γ δ) :
(e.prod e').symm = (e.symm.prod e'.symm) :=
by ext x; simp [prod_coe_symm]
@[simp, mfld_simps] lemma prod_trans
{η : Type*} {ε : Type*} [topological_space η] [topological_space ε]
(e : local_homeomorph α β) (f : local_homeomorph β γ)
(e' : local_homeomorph δ η) (f' : local_homeomorph η ε) :
(e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') :=
by ext x; simp [ext_iff]; tauto
end prod
section continuity
/-- Continuity within a set at a point can be read under right composition with a local
homeomorphism, if the point is in its target -/
lemma continuous_within_at_iff_continuous_within_at_comp_right
{f : β → γ} {s : set β} {x : β} (h : x ∈ e.target) :
continuous_within_at f s x ↔
continuous_within_at (f ∘ e) (e ⁻¹' s) (e.symm x) :=
begin
split,
{ assume f_cont,
have : e (e.symm x) = x := e.right_inv h,
rw ← this at f_cont,
have : e.source ∈ 𝓝 (e.symm x) := mem_nhds_sets e.open_source (e.map_target h),
rw [← continuous_within_at_inter this, inter_comm],
exact continuous_within_at.comp f_cont
((e.continuous_at (e.map_target h)).continuous_within_at) (inter_subset_right _ _) },
{ assume fe_cont,
have : continuous_within_at ((f ∘ e) ∘ e.symm) (s ∩ e.target) x,
{ apply continuous_within_at.comp fe_cont,
apply (e.continuous_at_symm h).continuous_within_at,
assume x hx,
simp [hx.1, hx.2, e.map_target] },
have : continuous_within_at f (s ∩ e.target) x :=
continuous_within_at.congr this (λy hy, by simp [hy.2]) (by simp [h]),
rwa continuous_within_at_inter at this,
exact mem_nhds_sets e.open_target h }
end
/-- Continuity at a point can be read under right composition with a local homeomorphism, if the
point is in its target -/
lemma continuous_at_iff_continuous_at_comp_right
{f : β → γ} {x : β} (h : x ∈ e.target) :
continuous_at f x ↔ continuous_at (f ∘ e) (e.symm x) :=
by rw [← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_right h,
preimage_univ, continuous_within_at_univ]
/-- A function is continuous on a set if and only if its composition with a local homeomorphism
on the right is continuous on the corresponding set. -/
lemma continuous_on_iff_continuous_on_comp_right {f : β → γ} {s : set β} (h : s ⊆ e.target) :
continuous_on f s ↔ continuous_on (f ∘ e) (e.source ∩ e ⁻¹' s) :=
begin
split,
{ assume f_cont x hx,
have := e.continuous_within_at_iff_continuous_within_at_comp_right (e.map_source hx.1),
rw e.left_inv hx.1 at this,
have A := f_cont _ hx.2,
rw this at A,
exact A.mono (inter_subset_right _ _), },
{ assume fe_cont x hx,
have := e.continuous_within_at_iff_continuous_within_at_comp_right (h hx),
rw this,
have : e.source ∈ 𝓝 (e.symm x) := mem_nhds_sets e.open_source (e.map_target (h hx)),
rw [← continuous_within_at_inter this, inter_comm],
exact fe_cont _ (by simp [hx, h hx, e.map_target (h hx)]) }
end
/-- Continuity within a set at a point can be read under left composition with a local
homeomorphism if a neighborhood of the initial point is sent to the source of the local
homeomorphism-/
lemma continuous_within_at_iff_continuous_within_at_comp_left
{f : γ → α} {s : set γ} {x : γ} (hx : f x ∈ e.source) (h : f ⁻¹' e.source ∈ 𝓝[s] x) :
continuous_within_at f s x ↔ continuous_within_at (e ∘ f) s x :=
begin
rw [← continuous_within_at_inter' h, ← continuous_within_at_inter' h],
split,
{ assume f_cont,
have : e.source ∈ 𝓝 (f x) := mem_nhds_sets e.open_source hx,
apply continuous_within_at.comp (e.continuous_on (f x) hx) f_cont (inter_subset_right _ _) },
{ assume fe_cont,
have : continuous_within_at (e.symm ∘ (e ∘ f)) (s ∩ f ⁻¹' e.source) x,
{ have : continuous_within_at e.symm univ (e (f x))
:= (e.continuous_at_symm (e.map_source hx)).continuous_within_at,
exact continuous_within_at.comp this fe_cont (subset_univ _) },
exact this.congr (λy hy, by simp [e.left_inv hy.2]) (by simp [e.left_inv hx]) }
end
/-- Continuity at a point can be read under left composition with a local homeomorphism if a
neighborhood of the initial point is sent to the source of the local homeomorphism-/
lemma continuous_at_iff_continuous_at_comp_left
{f : γ → α} {x : γ} (h : f ⁻¹' e.source ∈ 𝓝 x) :
continuous_at f x ↔ continuous_at (e ∘ f) x :=
begin
have hx : f x ∈ e.source := (mem_of_nhds h : _),
have h' : f ⁻¹' e.source ∈ 𝓝[univ] x, by rwa nhds_within_univ,
rw [← continuous_within_at_univ, ← continuous_within_at_univ,
e.continuous_within_at_iff_continuous_within_at_comp_left hx h']
end
/-- A function is continuous on a set if and only if its composition with a local homeomorphism
on the left is continuous on the corresponding set. -/
lemma continuous_on_iff_continuous_on_comp_left {f : γ → α} {s : set γ} (h : s ⊆ f ⁻¹' e.source) :
continuous_on f s ↔ continuous_on (e ∘ f) s :=
begin
split,
{ assume f_cont,
exact e.continuous_on.comp f_cont h },
{ assume fe_cont,
have : continuous_on (e.symm ∘ e ∘ f) s,
{ apply continuous_on.comp e.continuous_on_symm fe_cont,
assume x hx,
have : f x ∈ e.source := h hx,
simp [this] },
refine continuous_on.congr_mono this (λx hx, _) (subset.refl _),
have : f x ∈ e.source := h hx,
simp [this] }
end
end continuity
/-- If a local homeomorphism has source and target equal to univ, then it induces a homeomorphism
between the whole spaces, expressed in this definition. -/
def to_homeomorph_of_source_eq_univ_target_eq_univ (h : e.source = (univ : set α))
(h' : e.target = univ) : homeomorph α β :=
{ to_fun := e,
inv_fun := e.symm,
left_inv := λx, e.left_inv $ by { rw h, exact mem_univ _ },
right_inv := λx, e.right_inv $ by { rw h', exact mem_univ _ },
continuous_to_fun := begin
rw [continuous_iff_continuous_on_univ],
convert e.continuous_to_fun,
rw h
end,
continuous_inv_fun := begin
rw [continuous_iff_continuous_on_univ],
convert e.continuous_inv_fun,
rw h'
end }
@[simp, mfld_simps] lemma to_homeomorph_coe (h : e.source = (univ : set α)) (h' : e.target = univ) :
(e.to_homeomorph_of_source_eq_univ_target_eq_univ h h' : α → β) = e := rfl
@[simp, mfld_simps] lemma to_homeomorph_symm_coe
(h : e.source = (univ : set α)) (h' : e.target = univ) :
((e.to_homeomorph_of_source_eq_univ_target_eq_univ h h').symm : β → α) = e.symm := rfl
/-- A local homeomorphism whose source is all of `α` defines an open embedding of `α` into `β`. The
converse is also true; see `open_embedding.to_local_homeomorph`. -/
lemma to_open_embedding (h : e.source = set.univ) : open_embedding e.to_fun :=
begin
apply open_embedding_of_continuous_injective_open,
{ apply continuous_iff_continuous_on_univ.mpr,
rw ← h,
exact e.continuous_to_fun },
{ apply set.injective_iff_inj_on_univ.mpr,
rw ← h,
exact e.to_local_equiv.bij_on_source.inj_on },
{ intros U hU,
simpa only [h, subset_univ] with mfld_simps using e.image_open_of_open hU}
end
end local_homeomorph
namespace homeomorph
variables (e : homeomorph α β) (e' : homeomorph β γ)
/- Register as simp lemmas that the fields of a local homeomorphism built from a homeomorphism
correspond to the fields of the original homeomorphism. -/
@[simp, mfld_simps] lemma to_local_homeomorph_source : e.to_local_homeomorph.source = univ := rfl
@[simp, mfld_simps] lemma to_local_homeomorph_target : e.to_local_homeomorph.target = univ := rfl
@[simp, mfld_simps] lemma to_local_homeomorph_coe : (e.to_local_homeomorph : α → β) = e := rfl
@[simp, mfld_simps] lemma to_local_homeomorph_coe_symm :
(e.to_local_homeomorph.symm : β → α) = e.symm := rfl
@[simp, mfld_simps] lemma refl_to_local_homeomorph :
(homeomorph.refl α).to_local_homeomorph = local_homeomorph.refl α := rfl
@[simp, mfld_simps] lemma symm_to_local_homeomorph :
e.symm.to_local_homeomorph = e.to_local_homeomorph.symm := rfl
@[simp, mfld_simps] lemma trans_to_local_homeomorph :
(e.trans e').to_local_homeomorph = e.to_local_homeomorph.trans e'.to_local_homeomorph :=
local_homeomorph.eq_of_local_equiv_eq $ equiv.trans_to_local_equiv _ _
end homeomorph
namespace open_embedding
variables [nonempty α]
variables {f : α → β} (h : open_embedding f)
include f h
/-- An open embedding of `α` into `β`, with `α` nonempty, defines a local equivalence whose source
is all of `α`. This is mainly an auxiliary lemma for the stronger result `to_local_homeomorph`. -/
noncomputable def to_local_equiv : local_equiv α β :=
set.inj_on.to_local_equiv f set.univ (set.injective_iff_inj_on_univ.mp h.to_embedding.inj)
@[simp, mfld_simps] lemma to_local_equiv_coe : (h.to_local_equiv : α → β) = f := rfl
@[simp, mfld_simps] lemma to_local_equiv_source : h.to_local_equiv.source = set.univ := rfl
@[simp, mfld_simps] lemma to_local_equiv_target : h.to_local_equiv.target = set.range f :=
begin
rw ←local_equiv.image_source_eq_target,
ext,
split,
{ exact λ ⟨a, _, h'⟩, ⟨a, h'⟩ },
{ exact λ ⟨a, h'⟩, ⟨a, by trivial, h'⟩ }
end
lemma open_target : is_open h.to_local_equiv.target :=
by simpa only with mfld_simps using h.open_range
lemma continuous_inv_fun : continuous_on h.to_local_equiv.inv_fun h.to_local_equiv.target :=
begin
apply (continuous_on_open_iff h.open_target).mpr,
intros t ht,
simp only with mfld_simps,
convert h.open_iff_image_open.mp ht,
ext y,
have hinv : ∀ x : α, (f x = y) → h.to_local_equiv.symm y = x :=
λ x hxy, by { simpa only [hxy.symm] with mfld_simps using h.to_local_equiv.left_inv },
simp only [mem_image, mem_range] with mfld_simps,
split,
{ rintros ⟨⟨x, hxy⟩, hy⟩,
refine ⟨x, _, hxy⟩,
rwa (hinv x hxy) at hy },
{ rintros ⟨x, hx, hxy⟩,
refine ⟨⟨x, hxy⟩, _⟩,
rwa ← (hinv x hxy) at hx }
end
/-- An open embedding of `α` into `β`, with `α` nonempty, defines a local homeomorphism whose source
is all of `α`. The converse is also true; see `local_homeomorph.to_open_embedding`. -/
noncomputable def to_local_homeomorph : local_homeomorph α β :=
{ to_local_equiv := h.to_local_equiv,
open_source := is_open_univ,
open_target := h.open_target,
continuous_to_fun := by simpa only with mfld_simps using h.continuous.continuous_on,
continuous_inv_fun := h.continuous_inv_fun }
@[simp, mfld_simps] lemma to_local_homeomorph_coe : (h.to_local_homeomorph : α → β) = f := rfl
@[simp, mfld_simps] lemma source : h.to_local_homeomorph.source = set.univ := rfl
@[simp, mfld_simps] lemma target : h.to_local_homeomorph.target = set.range f :=
h.to_local_equiv_target
end open_embedding
-- We close and reopen the namespace to avoid
-- picking up the unnecessary `[nonempty α]` typeclass argument
namespace open_embedding
lemma continuous_at_iff
{f : α → β} {g : β → γ} (hf : open_embedding f) {x : α} :
continuous_at (g ∘ f) x ↔ continuous_at g (f x) :=
begin
haveI : nonempty α := ⟨x⟩,
convert ((hf.to_local_homeomorph.continuous_at_iff_continuous_at_comp_right) _).symm,
{ apply (local_homeomorph.left_inv _ _).symm,
simp, },
{ simp, },
end
end open_embedding
namespace topological_space.opens
open topological_space
variables (s : opens α) [nonempty s]
/-- The inclusion of an open subset `s` of a space `α` into `α` is a local homeomorphism from the
subtype `s` to `α`. -/
noncomputable def local_homeomorph_subtype_coe : local_homeomorph s α :=
open_embedding.to_local_homeomorph (s.2.open_embedding_subtype_coe)
@[simp, mfld_simps] lemma local_homeomorph_subtype_coe_coe :
(s.local_homeomorph_subtype_coe : s → α) = coe := rfl
@[simp, mfld_simps] lemma local_homeomorph_subtype_coe_source :
s.local_homeomorph_subtype_coe.source = set.univ := rfl
@[simp, mfld_simps] lemma local_homeomorph_subtype_coe_target :
s.local_homeomorph_subtype_coe.target = s :=
by { simp only [local_homeomorph_subtype_coe, subtype.range_coe_subtype] with mfld_simps, refl }
end topological_space.opens
namespace local_homeomorph
open topological_space
variables (e : local_homeomorph α β)
variables (s : opens α) [nonempty s]
/-- The restriction of a local homeomorphism `e` to an open subset `s` of the domain type produces a
local homeomorphism whose domain is the subtype `s`.-/
noncomputable def subtype_restr : local_homeomorph s β := s.local_homeomorph_subtype_coe.trans e
lemma subtype_restr_def : e.subtype_restr s = s.local_homeomorph_subtype_coe.trans e := rfl
@[simp, mfld_simps] lemma subtype_restr_coe : ((e.subtype_restr s : local_homeomorph s β) : s → β)
= set.restrict (e : α → β) s := rfl
@[simp, mfld_simps] lemma subtype_restr_source : (e.subtype_restr s).source = coe ⁻¹' e.source :=
by simp only [subtype_restr_def] with mfld_simps
/- This lemma characterizes the transition functions of an open subset in terms of the transition
functions of the original space. -/
lemma subtype_restr_symm_trans_subtype_restr (f f' : local_homeomorph α β) :
(f.subtype_restr s).symm.trans (f'.subtype_restr s)
≈ (f.symm.trans f').restr (f.target ∩ (f.symm) ⁻¹' s) :=
begin
simp only [subtype_restr_def, trans_symm_eq_symm_trans_symm],
have openness₁ : is_open (f.target ∩ f.symm ⁻¹' s) := f.preimage_open_of_open_symm s.2,
rw [← of_set_trans _ openness₁, ← trans_assoc, ← trans_assoc],
refine eq_on_source.trans' _ (eq_on_source_refl _),
-- f' has been eliminated !!!
have sets_identity : f.symm.source ∩ (f.target ∩ (f.symm) ⁻¹' s) = f.symm.source ∩ f.symm ⁻¹' s,
{ mfld_set_tac },
have openness₂ : is_open (s : set α) := s.2,
rw [of_set_trans', sets_identity, ← trans_of_set' _ openness₂, trans_assoc],
refine eq_on_source.trans' (eq_on_source_refl _) _,
-- f has been eliminated !!!
refine setoid.trans (trans_symm_self s.local_homeomorph_subtype_coe) _,
simp only with mfld_simps,
end
end local_homeomorph
|
cdbeec79beaca0b3cc8485d11e124a597d0d69a3 | 947b78d97130d56365ae2ec264df196ce769371a | /stage0/src/Std/Data/Queue.lean | 80b935c397b9bdf087b64c26c0772fcd8c48ad05 | [
"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 | 935 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Daniel Selsam
Simple queue implemented using two lists.
Note: this is only a temporary placeholder.
-/
namespace Std
universes u v w
structure Queue (α : Type u) :=
(eList dList : List α := [])
namespace Queue
variable {α : Type u}
def empty : Queue α :=
{ eList := [], dList := [] }
def isEmpty (q : Queue α) : Bool :=
q.dList.isEmpty && q.eList.isEmpty
def enqueue (v : α) (q : Queue α) : Queue α :=
{ q with eList := v::q.eList }
def enqueueAll (vs : List α) (q : Queue α) : Queue α :=
{ q with eList := vs ++ q.eList }
def dequeue? (q : Queue α) : Option (α × Queue α) :=
match q.dList with
| d::ds => some (d, { q with dList := ds })
| [] =>
match q.eList.reverse with
| [] => none
| d::ds => some (d, { eList := [], dList := ds })
end Queue
end Std
|
c4eed40c7c8155b6aca4bab4cd5e9970b6c8a195 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/data/complex/basic.lean | 82f76c09e97de9ceb71ad10b4b4ab31e154bcb2a | [
"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,810 | lean | /-
Copyright (c) 2017 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Mario Carneiro
-/
import data.real.sqrt
/-!
# The complex numbers
The complex numbers are modelled as ℝ^2 in the obvious way and it is shown that they form a field
of characteristic zero. The result that the complex numbers are algebraically closed, see
`field_theory.algebraic_closure`.
-/
open_locale big_operators
open set function
/-! ### Definition and basic arithmmetic -/
/-- Complex numbers consist of two `real`s: a real part `re` and an imaginary part `im`. -/
structure complex : Type :=
(re : ℝ) (im : ℝ)
notation `ℂ` := complex
namespace complex
open_locale complex_conjugate
noncomputable instance : decidable_eq ℂ := classical.dec_eq _
/-- The equivalence between the complex numbers and `ℝ × ℝ`. -/
@[simps apply]
def equiv_real_prod : ℂ ≃ (ℝ × ℝ) :=
{ to_fun := λ z, ⟨z.re, z.im⟩,
inv_fun := λ p, ⟨p.1, p.2⟩,
left_inv := λ ⟨x, y⟩, rfl,
right_inv := λ ⟨x, y⟩, rfl }
@[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z
| ⟨a, b⟩ := rfl
@[ext]
theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w
| ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl
theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im :=
⟨λ H, by simp [H], and.rec ext⟩
theorem re_surjective : surjective re := λ x, ⟨⟨x, 0⟩, rfl⟩
theorem im_surjective : surjective im := λ y, ⟨⟨0, y⟩, rfl⟩
@[simp] theorem range_re : range re = univ := re_surjective.range_eq
@[simp] theorem range_im : range im = univ := im_surjective.range_eq
instance : has_coe ℝ ℂ := ⟨λ r, ⟨r, 0⟩⟩
@[simp, norm_cast] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl
@[simp, norm_cast] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl
lemma of_real_def (r : ℝ) : (r : ℂ) = ⟨r, 0⟩ := rfl
@[simp, norm_cast] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w :=
⟨congr_arg re, congr_arg _⟩
theorem of_real_injective : function.injective (coe : ℝ → ℂ) :=
λ z w, congr_arg re
instance : can_lift ℂ ℝ :=
{ cond := λ z, z.im = 0,
coe := coe,
prf := λ z hz, ⟨z.re, ext rfl hz.symm⟩ }
/-- The product of a set on the real axis and a set on the imaginary axis of the complex plane,
denoted by `s ×ℂ t`. -/
def _root_.set.re_prod_im (s t : set ℝ) : set ℂ := re ⁻¹' s ∩ im ⁻¹' t
infix ` ×ℂ `:72 := set.re_prod_im
lemma mem_re_prod_im {z : ℂ} {s t : set ℝ} : z ∈ s ×ℂ t ↔ z.re ∈ s ∧ z.im ∈ t := iff.rfl
instance : has_zero ℂ := ⟨(0 : ℝ)⟩
instance : inhabited ℂ := ⟨0⟩
@[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl
@[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl
@[simp, norm_cast] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := rfl
@[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := of_real_inj
theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero
instance : has_one ℂ := ⟨(1 : ℝ)⟩
@[simp] lemma one_re : (1 : ℂ).re = 1 := rfl
@[simp] lemma one_im : (1 : ℂ).im = 0 := rfl
@[simp, norm_cast] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := rfl
@[simp] theorem of_real_eq_one {z : ℝ} : (z : ℂ) = 1 ↔ z = 1 := of_real_inj
theorem of_real_ne_one {z : ℝ} : (z : ℂ) ≠ 1 ↔ z ≠ 1 := not_congr of_real_eq_one
instance : has_add ℂ := ⟨λ z w, ⟨z.re + w.re, z.im + w.im⟩⟩
@[simp] lemma add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl
@[simp] lemma add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl
@[simp] lemma bit0_re (z : ℂ) : (bit0 z).re = bit0 z.re := rfl
@[simp] lemma bit1_re (z : ℂ) : (bit1 z).re = bit1 z.re := rfl
@[simp] lemma bit0_im (z : ℂ) : (bit0 z).im = bit0 z.im := eq.refl _
@[simp] lemma bit1_im (z : ℂ) : (bit1 z).im = bit0 z.im := add_zero _
@[simp, norm_cast] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s :=
ext_iff.2 $ by simp
@[simp, norm_cast] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r :=
ext_iff.2 $ by simp [bit0]
@[simp, norm_cast] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r :=
ext_iff.2 $ by simp [bit1]
instance : has_neg ℂ := ⟨λ z, ⟨-z.re, -z.im⟩⟩
@[simp] lemma neg_re (z : ℂ) : (-z).re = -z.re := rfl
@[simp] lemma neg_im (z : ℂ) : (-z).im = -z.im := rfl
@[simp, norm_cast] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := ext_iff.2 $ by simp
instance : has_sub ℂ := ⟨λ z w, ⟨z.re - w.re, z.im - w.im⟩⟩
instance : has_mul ℂ := ⟨λ z w, ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩
@[simp] lemma mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl
@[simp] lemma mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl
@[simp, norm_cast] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := ext_iff.2 $ by simp
lemma of_real_mul_re (r : ℝ) (z : ℂ) : (↑r * z).re = r * z.re := by simp
lemma of_real_mul_im (r : ℝ) (z : ℂ) : (↑r * z).im = r * z.im := by simp
lemma of_real_mul' (r : ℝ) (z : ℂ) : (↑r * z) = ⟨r * z.re, r * z.im⟩ :=
ext (of_real_mul_re _ _) (of_real_mul_im _ _)
/-! ### The imaginary unit, `I` -/
/-- The imaginary unit. -/
def I : ℂ := ⟨0, 1⟩
@[simp] lemma I_re : I.re = 0 := rfl
@[simp] lemma I_im : I.im = 1 := rfl
@[simp] lemma I_mul_I : I * I = -1 := ext_iff.2 $ by simp
lemma I_mul (z : ℂ) : I * z = ⟨-z.im, z.re⟩ :=
ext_iff.2 $ by simp
lemma I_ne_zero : (I : ℂ) ≠ 0 := mt (congr_arg im) zero_ne_one.symm
lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I :=
ext_iff.2 $ by simp
@[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z :=
ext_iff.2 $ by simp
lemma mul_I_re (z : ℂ) : (z * I).re = -z.im := by simp
lemma mul_I_im (z : ℂ) : (z * I).im = z.re := by simp
lemma I_mul_re (z : ℂ) : (I * z).re = -z.im := by simp
lemma I_mul_im (z : ℂ) : (I * z).im = z.re := by simp
@[simp] lemma equiv_real_prod_symm_apply (p : ℝ × ℝ) :
equiv_real_prod.symm p = p.1 + p.2 * I :=
by { ext; simp [equiv_real_prod] }
/-! ### Commutative ring instance and lemmas -/
/- We use a nonstandard formula for the `ℕ` and `ℤ` actions to make sure there is no
diamond from the other actions they inherit through the `ℝ`-action on `ℂ` and action transitivity
defined in `data.complex.module.lean`. -/
instance : add_comm_group ℂ :=
by refine_struct
{ zero := (0 : ℂ),
add := (+),
neg := has_neg.neg,
sub := has_sub.sub,
nsmul := λ n z, ⟨n • z.re - 0 * z.im, n • z.im + 0 * z.re⟩,
zsmul := λ n z, ⟨n • z.re - 0 * z.im, n • z.im + 0 * z.re⟩ };
intros; try { refl }; apply ext_iff.2; split; simp; {ring1 <|> ring_nf}
instance : add_group_with_one ℂ :=
{ nat_cast := λ n, ⟨n, 0⟩,
nat_cast_zero := by ext; simp [nat.cast],
nat_cast_succ := λ _, by ext; simp [nat.cast],
int_cast := λ n, ⟨n, 0⟩,
int_cast_of_nat := λ _, by ext; simp [λ n, show @coe ℕ ℂ ⟨_⟩ n = ⟨n, 0⟩, from rfl],
int_cast_neg_succ_of_nat := λ _, by ext; simp [λ n, show @coe ℕ ℂ ⟨_⟩ n = ⟨n, 0⟩, from rfl],
one := 1,
.. complex.add_comm_group }
instance : comm_ring ℂ :=
by refine_struct
{ zero := (0 : ℂ),
add := (+),
one := 1,
mul := (*),
npow := @npow_rec _ ⟨(1 : ℂ)⟩ ⟨(*)⟩,
.. complex.add_group_with_one };
intros; try { refl }; apply ext_iff.2; split; simp; {ring1 <|> ring_nf}
/-- This shortcut instance ensures we do not find `ring` via the noncomputable `complex.field`
instance. -/
instance : ring ℂ := by apply_instance
/-- This shortcut instance ensures we do not find `comm_semiring` via the noncomputable
`complex.field` instance. -/
instance : comm_semiring ℂ := infer_instance
/-- The "real part" map, considered as an additive group homomorphism. -/
def re_add_group_hom : ℂ →+ ℝ :=
{ to_fun := re,
map_zero' := zero_re,
map_add' := add_re }
@[simp] lemma coe_re_add_group_hom : (re_add_group_hom : ℂ → ℝ) = re := rfl
/-- The "imaginary part" map, considered as an additive group homomorphism. -/
def im_add_group_hom : ℂ →+ ℝ :=
{ to_fun := im,
map_zero' := zero_im,
map_add' := add_im }
@[simp] lemma coe_im_add_group_hom : (im_add_group_hom : ℂ → ℝ) = im := rfl
@[simp] lemma I_pow_bit0 (n : ℕ) : I ^ (bit0 n) = (-1) ^ n :=
by rw [pow_bit0', I_mul_I]
@[simp] lemma I_pow_bit1 (n : ℕ) : I ^ (bit1 n) = (-1) ^ n * I :=
by rw [pow_bit1', I_mul_I]
/-! ### Complex conjugation -/
/-- This defines the complex conjugate as the `star` operation of the `star_ring ℂ`. It
is recommended to use the ring endomorphism version `star_ring_end`, available under the
notation `conj` in the locale `complex_conjugate`. -/
instance : star_ring ℂ :=
{ star := λ z, ⟨z.re, -z.im⟩,
star_involutive := λ x, by simp only [eta, neg_neg],
star_mul := λ a b, by ext; simp [add_comm]; ring,
star_add := λ a b, by ext; simp [add_comm] }
@[simp] lemma conj_re (z : ℂ) : (conj z).re = z.re := rfl
@[simp] lemma conj_im (z : ℂ) : (conj z).im = -z.im := rfl
lemma conj_of_real (r : ℝ) : conj (r : ℂ) = r := ext_iff.2 $ by simp [conj]
@[simp] lemma conj_I : conj I = -I := ext_iff.2 $ by simp
lemma conj_bit0 (z : ℂ) : conj (bit0 z) = bit0 (conj z) := ext_iff.2 $ by simp [bit0]
lemma conj_bit1 (z : ℂ) : conj (bit1 z) = bit1 (conj z) := ext_iff.2 $ by simp [bit0]
@[simp] lemma conj_neg_I : conj (-I) = I := ext_iff.2 $ by simp
lemma eq_conj_iff_real {z : ℂ} : conj z = z ↔ ∃ r : ℝ, z = r :=
⟨λ h, ⟨z.re, ext rfl $ eq_zero_of_neg_eq (congr_arg im h)⟩,
λ ⟨h, e⟩, by rw [e, conj_of_real]⟩
lemma eq_conj_iff_re {z : ℂ} : conj z = z ↔ (z.re : ℂ) = z :=
eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩
lemma eq_conj_iff_im {z : ℂ} : conj z = z ↔ z.im = 0 :=
⟨λ h, add_self_eq_zero.mp (neg_eq_iff_add_eq_zero.mp (congr_arg im h)),
λ h, ext rfl (neg_eq_iff_add_eq_zero.mpr (add_self_eq_zero.mpr h))⟩
-- `simp_nf` complains about this being provable by `is_R_or_C.star_def` even
-- though it's not imported by this file.
@[simp, nolint simp_nf] lemma star_def : (has_star.star : ℂ → ℂ) = conj := rfl
/-! ### Norm squared -/
/-- The norm squared function. -/
@[pp_nodot] def norm_sq : ℂ →*₀ ℝ :=
{ to_fun := λ z, z.re * z.re + z.im * z.im,
map_zero' := by simp,
map_one' := by simp,
map_mul' := λ z w, by { dsimp, ring } }
lemma norm_sq_apply (z : ℂ) : norm_sq z = z.re * z.re + z.im * z.im := rfl
@[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r :=
by simp [norm_sq]
@[simp] lemma norm_sq_mk (x y : ℝ) : norm_sq ⟨x, y⟩ = x * x + y * y := rfl
lemma norm_sq_add_mul_I (x y : ℝ) : norm_sq (x + y * I) = x ^ 2 + y ^ 2 :=
by rw [← mk_eq_add_mul_I, norm_sq_mk, sq, sq]
lemma norm_sq_eq_conj_mul_self {z : ℂ} : (norm_sq z : ℂ) = conj z * z :=
by { ext; simp [norm_sq, mul_comm], }
@[simp] lemma norm_sq_zero : norm_sq 0 = 0 := norm_sq.map_zero
@[simp] lemma norm_sq_one : norm_sq 1 = 1 := norm_sq.map_one
@[simp] lemma norm_sq_I : norm_sq I = 1 := by simp [norm_sq]
lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z :=
add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)
@[simp] lemma range_norm_sq : range norm_sq = Ici 0 :=
subset.antisymm (range_subset_iff.2 norm_sq_nonneg) $ λ x hx,
⟨real.sqrt x, by rw [norm_sq_of_real, real.mul_self_sqrt hx]⟩
lemma norm_sq_eq_zero {z : ℂ} : norm_sq z = 0 ↔ z = 0 :=
⟨λ h, ext
(eq_zero_of_mul_self_add_mul_self_eq_zero h)
(eq_zero_of_mul_self_add_mul_self_eq_zero $ (add_comm _ _).trans h),
λ h, h.symm ▸ norm_sq_zero⟩
@[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 :=
(norm_sq_nonneg z).lt_iff_ne.trans $ not_congr (eq_comm.trans norm_sq_eq_zero)
@[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z :=
by simp [norm_sq]
@[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z :=
by simp [norm_sq]
lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w :=
norm_sq.map_mul z w
lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) =
norm_sq z + norm_sq w + 2 * (z * conj w).re :=
by dsimp [norm_sq]; ring
lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z :=
le_add_of_nonneg_right (mul_self_nonneg _)
lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z :=
le_add_of_nonneg_left (mul_self_nonneg _)
theorem mul_conj (z : ℂ) : z * conj z = norm_sq z :=
ext_iff.2 $ by simp [norm_sq, mul_comm, sub_eq_neg_add, add_comm]
theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) :=
ext_iff.2 $ by simp [two_mul]
/-- The coercion `ℝ → ℂ` as a `ring_hom`. -/
def of_real : ℝ →+* ℂ := ⟨coe, of_real_one, of_real_mul, of_real_zero, of_real_add⟩
@[simp] lemma of_real_eq_coe (r : ℝ) : of_real r = r := rfl
@[simp] lemma I_sq : I ^ 2 = -1 := by rw [sq, I_mul_I]
@[simp] lemma sub_re (z w : ℂ) : (z - w).re = z.re - w.re := rfl
@[simp] lemma sub_im (z w : ℂ) : (z - w).im = z.im - w.im := rfl
@[simp, norm_cast] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : ℂ) = r - s := ext_iff.2 $ by simp
@[simp, norm_cast] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : ℂ) = r ^ n :=
by induction n; simp [*, of_real_mul, pow_succ]
theorem sub_conj (z : ℂ) : z - conj z = (2 * z.im : ℝ) * I :=
ext_iff.2 $ by simp [two_mul, sub_eq_add_neg]
lemma norm_sq_sub (z w : ℂ) : norm_sq (z - w) =
norm_sq z + norm_sq w - 2 * (z * conj w).re :=
by { rw [sub_eq_add_neg, norm_sq_add],
simp only [ring_hom.map_neg, mul_neg, neg_re,
tactic.ring.add_neg_eq_sub, norm_sq_neg] }
/-! ### Inversion -/
noncomputable instance : has_inv ℂ := ⟨λ z, conj z * ((norm_sq z)⁻¹:ℝ)⟩
theorem inv_def (z : ℂ) : z⁻¹ = conj z * ((norm_sq z)⁻¹:ℝ) := rfl
@[simp] lemma inv_re (z : ℂ) : (z⁻¹).re = z.re / norm_sq z := by simp [inv_def, division_def]
@[simp] lemma inv_im (z : ℂ) : (z⁻¹).im = -z.im / norm_sq z := by simp [inv_def, division_def]
@[simp, norm_cast] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : ℂ) = r⁻¹ :=
ext_iff.2 $ by simp
protected lemma inv_zero : (0⁻¹ : ℂ) = 0 :=
by rw [← of_real_zero, ← of_real_inv, inv_zero]
protected theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * z⁻¹ = 1 :=
by rw [inv_def, ← mul_assoc, mul_conj, ← of_real_mul,
mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one]
/-! ### Field instance and lemmas -/
noncomputable instance : field ℂ :=
{ inv := has_inv.inv,
exists_pair_ne := ⟨0, 1, mt (congr_arg re) zero_ne_one⟩,
mul_inv_cancel := @complex.mul_inv_cancel,
inv_zero := complex.inv_zero,
..complex.comm_ring }
@[simp] lemma I_zpow_bit0 (n : ℤ) : I ^ (bit0 n) = (-1) ^ n :=
by rw [zpow_bit0', I_mul_I]
@[simp] lemma I_zpow_bit1 (n : ℤ) : I ^ (bit1 n) = (-1) ^ n * I :=
by rw [zpow_bit1', I_mul_I]
lemma div_re (z w : ℂ) : (z / w).re = z.re * w.re / norm_sq w + z.im * w.im / norm_sq w :=
by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg]
lemma div_im (z w : ℂ) : (z / w).im = z.im * w.re / norm_sq w - z.re * w.im / norm_sq w :=
by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm]
lemma conj_inv (x : ℂ) : conj (x⁻¹) = (conj x)⁻¹ := star_inv' _
@[simp, norm_cast] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : ℂ) = r / s :=
of_real.map_div r s
@[simp, norm_cast] lemma of_real_zpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : ℂ) = (r : ℂ) ^ n :=
of_real.map_zpow r n
@[simp] lemma div_I (z : ℂ) : z / I = -(z * I) :=
(div_eq_iff_mul_eq I_ne_zero).2 $ by simp [mul_assoc]
@[simp] lemma inv_I : I⁻¹ = -I :=
by simp [inv_eq_one_div]
@[simp] lemma norm_sq_inv (z : ℂ) : norm_sq z⁻¹ = (norm_sq z)⁻¹ :=
norm_sq.map_inv z
@[simp] lemma norm_sq_div (z w : ℂ) : norm_sq (z / w) = norm_sq z / norm_sq w :=
norm_sq.map_div z w
/-! ### Cast lemmas -/
@[simp, norm_cast] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : ℂ) = n :=
map_nat_cast of_real n
@[simp, norm_cast] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n :=
by rw [← of_real_nat_cast, of_real_re]
@[simp, norm_cast] lemma nat_cast_im (n : ℕ) : (n : ℂ).im = 0 :=
by rw [← of_real_nat_cast, of_real_im]
@[simp, norm_cast] theorem of_real_int_cast (n : ℤ) : ((n : ℝ) : ℂ) = n :=
of_real.map_int_cast n
@[simp, norm_cast] lemma int_cast_re (n : ℤ) : (n : ℂ).re = n :=
by rw [← of_real_int_cast, of_real_re]
@[simp, norm_cast] lemma int_cast_im (n : ℤ) : (n : ℂ).im = 0 :=
by rw [← of_real_int_cast, of_real_im]
@[simp, norm_cast] theorem of_real_rat_cast (n : ℚ) : ((n : ℝ) : ℂ) = n := map_rat_cast of_real n
@[simp, norm_cast] lemma rat_cast_re (q : ℚ) : (q : ℂ).re = q :=
by rw [← of_real_rat_cast, of_real_re]
@[simp, norm_cast] lemma rat_cast_im (q : ℚ) : (q : ℂ).im = 0 :=
by rw [← of_real_rat_cast, of_real_im]
/-! ### Characteristic zero -/
instance char_zero_complex : char_zero ℂ :=
char_zero_of_inj_zero $ λ n h,
by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h
/-- A complex number `z` plus its conjugate `conj z` is `2` times its real part. -/
theorem re_eq_add_conj (z : ℂ) : (z.re : ℂ) = (z + conj z) / 2 :=
by simp only [add_conj, of_real_mul, of_real_one, of_real_bit0,
mul_div_cancel_left (z.re:ℂ) two_ne_zero']
/-- A complex number `z` minus its conjugate `conj z` is `2i` times its imaginary part. -/
theorem im_eq_sub_conj (z : ℂ) : (z.im : ℂ) = (z - conj(z))/(2 * I) :=
by simp only [sub_conj, of_real_mul, of_real_one, of_real_bit0, mul_right_comm,
mul_div_cancel_left _ (mul_ne_zero two_ne_zero' I_ne_zero : 2 * I ≠ 0)]
/-! ### Absolute value -/
/-- The complex absolute value function, defined as the square root of the norm squared. -/
@[pp_nodot] noncomputable def abs (z : ℂ) : ℝ := (norm_sq z).sqrt
local notation `abs'` := has_abs.abs
@[simp, norm_cast] lemma abs_of_real (r : ℝ) : abs r = |r| :=
by simp [abs, norm_sq_of_real, real.sqrt_mul_self_eq_abs]
lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : abs r = r :=
(abs_of_real _).trans (abs_of_nonneg h)
lemma abs_of_nat (n : ℕ) : complex.abs n = n :=
calc complex.abs n = complex.abs (n:ℝ) : by rw [of_real_nat_cast]
... = _ : abs_of_nonneg (nat.cast_nonneg n)
lemma mul_self_abs (z : ℂ) : abs z * abs z = norm_sq z :=
real.mul_self_sqrt (norm_sq_nonneg _)
lemma sq_abs (z : ℂ) : abs z ^ 2 = norm_sq z :=
real.sq_sqrt (norm_sq_nonneg _)
@[simp] lemma sq_abs_sub_sq_re (z : ℂ) : abs z ^ 2 - z.re ^ 2 = z.im ^ 2 :=
by rw [sq_abs, norm_sq_apply, ← sq, ← sq, add_sub_cancel']
@[simp] lemma sq_abs_sub_sq_im (z : ℂ) : abs z ^ 2 - z.im ^ 2 = z.re ^ 2 :=
by rw [← sq_abs_sub_sq_re, sub_sub_cancel]
@[simp] lemma abs_zero : abs 0 = 0 := by simp [abs]
@[simp] lemma abs_one : abs 1 = 1 := by simp [abs]
@[simp] lemma abs_I : abs I = 1 := by simp [abs]
@[simp] lemma abs_two : abs 2 = 2 :=
calc abs 2 = abs (2 : ℝ) : by rw [of_real_bit0, of_real_one]
... = (2 : ℝ) : abs_of_nonneg (by norm_num)
lemma abs_nonneg (z : ℂ) : 0 ≤ abs z :=
real.sqrt_nonneg _
@[simp] lemma range_abs : range abs = Ici 0 :=
subset.antisymm (range_subset_iff.2 abs_nonneg) $ λ x hx, ⟨x, abs_of_nonneg hx⟩
@[simp] lemma abs_eq_zero {z : ℂ} : abs z = 0 ↔ z = 0 :=
(real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero
lemma abs_ne_zero {z : ℂ} : abs z ≠ 0 ↔ z ≠ 0 :=
not_congr abs_eq_zero
@[simp] lemma abs_conj (z : ℂ) : abs (conj z) = abs z :=
by simp [abs]
@[simp] lemma abs_mul (z w : ℂ) : abs (z * w) = abs z * abs w :=
by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl
/-- `complex.abs` as a `monoid_with_zero_hom`. -/
@[simps] noncomputable def abs_hom : ℂ →*₀ ℝ :=
{ to_fun := abs,
map_zero' := abs_zero,
map_one' := abs_one,
map_mul' := abs_mul }
@[simp] lemma abs_prod {ι : Type*} (s : finset ι) (f : ι → ℂ) :
abs (s.prod f) = s.prod (λ i, abs (f i)) :=
map_prod abs_hom _ _
@[simp] lemma abs_pow (z : ℂ) (n : ℕ) : abs (z ^ n) = abs z ^ n :=
map_pow abs_hom z n
@[simp] lemma abs_zpow (z : ℂ) (n : ℤ) : abs (z ^ n) = abs z ^ n :=
abs_hom.map_zpow z n
lemma abs_re_le_abs (z : ℂ) : |z.re| ≤ abs z :=
by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.re) (abs_nonneg _),
abs_mul_abs_self, mul_self_abs];
apply re_sq_le_norm_sq
lemma abs_im_le_abs (z : ℂ) : |z.im| ≤ abs z :=
by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.im) (abs_nonneg _),
abs_mul_abs_self, mul_self_abs];
apply im_sq_le_norm_sq
lemma re_le_abs (z : ℂ) : z.re ≤ abs z :=
(abs_le.1 (abs_re_le_abs _)).2
lemma im_le_abs (z : ℂ) : z.im ≤ abs z :=
(abs_le.1 (abs_im_le_abs _)).2
@[simp] lemma abs_re_lt_abs {z : ℂ} : |z.re| < abs z ↔ z.im ≠ 0 :=
by rw [abs, real.lt_sqrt (_root_.abs_nonneg _), norm_sq_apply, _root_.sq_abs, ← sq,
lt_add_iff_pos_right, mul_self_pos]
@[simp] lemma abs_im_lt_abs {z : ℂ} : |z.im| < abs z ↔ z.re ≠ 0 :=
by simpa using @abs_re_lt_abs (z * I)
/--
The **triangle inequality** for complex numbers.
-/
lemma abs_add (z w : ℂ) : abs (z + w) ≤ abs z + abs w :=
(mul_self_le_mul_self_iff (abs_nonneg _)
(add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $
begin
rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs,
add_right_comm, norm_sq_add, add_le_add_iff_left,
mul_assoc, mul_le_mul_left (@zero_lt_two ℝ _ _)],
simpa [-mul_re] using re_le_abs (z * conj w)
end
instance : is_absolute_value abs :=
{ abv_nonneg := abs_nonneg,
abv_eq_zero := λ _, abs_eq_zero,
abv_add := abs_add,
abv_mul := abs_mul }
open is_absolute_value
@[simp] lemma abs_abs (z : ℂ) : |(abs z)| = abs z :=
_root_.abs_of_nonneg (abs_nonneg _)
@[simp] lemma abs_pos {z : ℂ} : 0 < abs z ↔ z ≠ 0 := abv_pos abs
@[simp] lemma abs_neg : ∀ z, abs (-z) = abs z := abv_neg abs
lemma abs_sub_comm : ∀ z w, abs (z - w) = abs (w - z) := abv_sub abs
lemma abs_sub_le : ∀ a b c, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs
@[simp] theorem abs_inv : ∀ z, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs
@[simp] theorem abs_div : ∀ z w, abs (z / w) = abs z / abs w := abv_div abs
lemma abs_abs_sub_le_abs_sub : ∀ z w, |abs z - abs w| ≤ abs (z - w) :=
abs_abv_sub_le_abv_sub abs
lemma abs_le_abs_re_add_abs_im (z : ℂ) : abs z ≤ |z.re| + |z.im| :=
by simpa [re_add_im] using abs_add z.re (z.im * I)
lemma abs_le_sqrt_two_mul_max (z : ℂ) : abs z ≤ real.sqrt 2 * max (|z.re|) (|z.im|) :=
begin
cases z with x y,
simp only [abs, norm_sq_mk, ← sq],
wlog hle : |x| ≤ |y| := le_total (|x|) (|y|) using [x y, y x] tactic.skip,
{ calc real.sqrt (x ^ 2 + y ^ 2) ≤ real.sqrt (y ^ 2 + y ^ 2) :
real.sqrt_le_sqrt (add_le_add_right (sq_le_sq.2 hle) _)
... = real.sqrt 2 * max (|x|) (|y|) :
by rw [max_eq_right hle, ← two_mul, real.sqrt_mul two_pos.le, real.sqrt_sq_eq_abs] },
{ rwa [add_comm, max_comm] }
end
lemma abs_re_div_abs_le_one (z : ℂ) : |z.re / z.abs| ≤ 1 :=
if hz : z = 0 then by simp [hz, zero_le_one]
else by { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_re_le_abs] }
lemma abs_im_div_abs_le_one (z : ℂ) : |z.im / z.abs| ≤ 1 :=
if hz : z = 0 then by simp [hz, zero_le_one]
else by { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_im_le_abs] }
@[simp, norm_cast] lemma abs_cast_nat (n : ℕ) : abs (n : ℂ) = n :=
by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)]
@[simp, norm_cast] lemma int_cast_abs (n : ℤ) : ↑|n| = abs n :=
by rw [← of_real_int_cast, abs_of_real, int.cast_abs]
lemma norm_sq_eq_abs (x : ℂ) : norm_sq x = abs x ^ 2 :=
by rw [abs, sq, real.mul_self_sqrt (norm_sq_nonneg _)]
/--
We put a partial order on ℂ so that `z ≤ w` exactly if `w - z` is real and nonnegative.
Complex numbers with different imaginary parts are incomparable.
-/
protected def partial_order : partial_order ℂ :=
{ le := λ z w, z.re ≤ w.re ∧ z.im = w.im,
lt := λ z w, z.re < w.re ∧ z.im = w.im,
lt_iff_le_not_le := λ z w, by { dsimp, rw lt_iff_le_not_le, tauto },
le_refl := λ x, ⟨le_rfl, rfl⟩,
le_trans := λ x y z h₁ h₂, ⟨h₁.1.trans h₂.1, h₁.2.trans h₂.2⟩,
le_antisymm := λ z w h₁ h₂, ext (h₁.1.antisymm h₂.1) h₁.2 }
section complex_order
localized "attribute [instance] complex.partial_order" in complex_order
lemma le_def {z w : ℂ} : z ≤ w ↔ z.re ≤ w.re ∧ z.im = w.im := iff.rfl
lemma lt_def {z w : ℂ} : z < w ↔ z.re < w.re ∧ z.im = w.im := iff.rfl
@[simp, norm_cast] lemma real_le_real {x y : ℝ} : (x : ℂ) ≤ (y : ℂ) ↔ x ≤ y := by simp [le_def]
@[simp, norm_cast] lemma real_lt_real {x y : ℝ} : (x : ℂ) < (y : ℂ) ↔ x < y := by simp [lt_def]
@[simp, norm_cast] lemma zero_le_real {x : ℝ} : (0 : ℂ) ≤ (x : ℂ) ↔ 0 ≤ x := real_le_real
@[simp, norm_cast] lemma zero_lt_real {x : ℝ} : (0 : ℂ) < (x : ℂ) ↔ 0 < x := real_lt_real
lemma not_le_iff {z w : ℂ} : ¬(z ≤ w) ↔ w.re < z.re ∨ z.im ≠ w.im :=
by rw [le_def, not_and_distrib, not_le]
lemma not_lt_iff {z w : ℂ} : ¬(z < w) ↔ w.re ≤ z.re ∨ z.im ≠ w.im :=
by rw [lt_def, not_and_distrib, not_lt]
lemma not_le_zero_iff {z : ℂ} : ¬z ≤ 0 ↔ 0 < z.re ∨ z.im ≠ 0 := not_le_iff
lemma not_lt_zero_iff {z : ℂ} : ¬z < 0 ↔ 0 ≤ z.re ∨ z.im ≠ 0 := not_lt_iff
/--
With `z ≤ w` iff `w - z` is real and nonnegative, `ℂ` is an ordered ring.
-/
protected def ordered_comm_ring : ordered_comm_ring ℂ :=
{ zero_le_one := ⟨zero_le_one, rfl⟩,
add_le_add_left := λ w z h y, ⟨add_le_add_left h.1 _, congr_arg2 (+) rfl h.2⟩,
mul_pos := λ z w hz hw,
by simp [lt_def, mul_re, mul_im, ← hz.2, ← hw.2, mul_pos hz.1 hw.1],
.. complex.partial_order,
.. complex.comm_ring }
localized "attribute [instance] complex.ordered_comm_ring" in complex_order
/--
With `z ≤ w` iff `w - z` is real and nonnegative, `ℂ` is a star ordered ring.
(That is, a star ring in which the nonnegative elements are those of the form `star z * z`.)
-/
protected def star_ordered_ring : star_ordered_ring ℂ :=
{ nonneg_iff := λ r, by
{ refine ⟨λ hr, ⟨real.sqrt r.re, _⟩, λ h, _⟩,
{ have h₁ : 0 ≤ r.re := by { rw [le_def] at hr, exact hr.1 },
have h₂ : r.im = 0 := by { rw [le_def] at hr, exact hr.2.symm },
ext,
{ simp only [of_real_im, star_def, of_real_re, sub_zero, conj_re, mul_re, mul_zero,
←real.sqrt_mul h₁ r.re, real.sqrt_mul_self h₁] },
{ simp only [h₂, add_zero, of_real_im, star_def, zero_mul, conj_im,
mul_im, mul_zero, neg_zero] } },
{ obtain ⟨s, rfl⟩ := h,
simp only [←norm_sq_eq_conj_mul_self, norm_sq_nonneg, zero_le_real, star_def] } },
..complex.ordered_comm_ring }
localized "attribute [instance] complex.star_ordered_ring" in complex_order
end complex_order
/-! ### Cauchy sequences -/
theorem is_cau_seq_re (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).re) :=
λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij,
lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij)
theorem is_cau_seq_im (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).im) :=
λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij,
lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij)
/-- The real part of a complex Cauchy sequence, as a real Cauchy sequence. -/
noncomputable def cau_seq_re (f : cau_seq ℂ abs) : cau_seq ℝ abs' :=
⟨_, is_cau_seq_re f⟩
/-- The imaginary part of a complex Cauchy sequence, as a real Cauchy sequence. -/
noncomputable def cau_seq_im (f : cau_seq ℂ abs) : cau_seq ℝ abs' :=
⟨_, is_cau_seq_im f⟩
lemma is_cau_seq_abs {f : ℕ → ℂ} (hf : is_cau_seq abs f) :
is_cau_seq abs' (abs ∘ f) :=
λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in
⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩
/-- The limit of a Cauchy sequence of complex numbers. -/
noncomputable def lim_aux (f : cau_seq ℂ abs) : ℂ :=
⟨cau_seq.lim (cau_seq_re f), cau_seq.lim (cau_seq_im f)⟩
theorem equiv_lim_aux (f : cau_seq ℂ abs) : f ≈ cau_seq.const abs (lim_aux f) :=
λ ε ε0, (exists_forall_ge_and
(cau_seq.equiv_lim ⟨_, is_cau_seq_re f⟩ _ (half_pos ε0))
(cau_seq.equiv_lim ⟨_, is_cau_seq_im f⟩ _ (half_pos ε0))).imp $
λ i H j ij, begin
cases H _ ij with H₁ H₂,
apply lt_of_le_of_lt (abs_le_abs_re_add_abs_im _),
dsimp [lim_aux] at *,
have := add_lt_add H₁ H₂,
rwa add_halves at this,
end
instance : cau_seq.is_complete ℂ abs :=
⟨λ f, ⟨lim_aux f, equiv_lim_aux f⟩⟩
open cau_seq
lemma lim_eq_lim_im_add_lim_re (f : cau_seq ℂ abs) : lim f =
↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I :=
lim_eq_of_equiv_const $
calc f ≈ _ : equiv_lim_aux f
... = cau_seq.const abs (↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I) :
cau_seq.ext (λ _, complex.ext (by simp [lim_aux, cau_seq_re]) (by simp [lim_aux, cau_seq_im]))
lemma lim_re (f : cau_seq ℂ abs) : lim (cau_seq_re f) = (lim f).re :=
by rw [lim_eq_lim_im_add_lim_re]; simp
lemma lim_im (f : cau_seq ℂ abs) : lim (cau_seq_im f) = (lim f).im :=
by rw [lim_eq_lim_im_add_lim_re]; simp
lemma is_cau_seq_conj (f : cau_seq ℂ abs) : is_cau_seq abs (λ n, conj (f n)) :=
λ ε ε0, let ⟨i, hi⟩ := f.2 ε ε0 in
⟨i, λ j hj, by rw [← ring_hom.map_sub, abs_conj]; exact hi j hj⟩
/-- The complex conjugate of a complex Cauchy sequence, as a complex Cauchy sequence. -/
noncomputable def cau_seq_conj (f : cau_seq ℂ abs) : cau_seq ℂ abs :=
⟨_, is_cau_seq_conj f⟩
lemma lim_conj (f : cau_seq ℂ abs) : lim (cau_seq_conj f) = conj (lim f) :=
complex.ext (by simp [cau_seq_conj, (lim_re _).symm, cau_seq_re])
(by simp [cau_seq_conj, (lim_im _).symm, cau_seq_im, (lim_neg _).symm]; refl)
/-- The absolute value of a complex Cauchy sequence, as a real Cauchy sequence. -/
noncomputable def cau_seq_abs (f : cau_seq ℂ abs) : cau_seq ℝ abs' :=
⟨_, is_cau_seq_abs f.2⟩
lemma lim_abs (f : cau_seq ℂ abs) : lim (cau_seq_abs f) = abs (lim f) :=
lim_eq_of_equiv_const (λ ε ε0,
let ⟨i, hi⟩ := equiv_lim f ε ε0 in
⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩)
variables {α : Type*} (s : finset α)
@[simp, norm_cast] lemma of_real_prod (f : α → ℝ) :
((∏ i in s, f i : ℝ) : ℂ) = ∏ i in s, (f i : ℂ) :=
ring_hom.map_prod of_real _ _
@[simp, norm_cast] lemma of_real_sum (f : α → ℝ) :
((∑ i in s, f i : ℝ) : ℂ) = ∑ i in s, (f i : ℂ) :=
ring_hom.map_sum of_real _ _
@[simp] lemma re_sum (f : α → ℂ) : (∑ i in s, f i).re = ∑ i in s, (f i).re :=
re_add_group_hom.map_sum f s
@[simp] lemma im_sum (f : α → ℂ) : (∑ i in s, f i).im = ∑ i in s, (f i).im :=
im_add_group_hom.map_sum f s
end complex
|
30a3d2947906b861d7cbe6c981713a78038affe7 | bb31430994044506fa42fd667e2d556327e18dfe | /src/algebra/star/star_alg_hom.lean | 5d3c2e4682044f24a27f0ff42f1f0013416fa25f | [
"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 | 28,239 | lean | /-
Copyright (c) 2022 Jireh Loreaux. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jireh Loreaux
-/
import algebra.hom.non_unital_alg
import algebra.star.prod
import algebra.algebra.prod
/-!
# Morphisms of star algebras
This file defines morphisms between `R`-algebras (unital or non-unital) `A` and `B` where both
`A` and `B` are equipped with a `star` operation. These morphisms, namely `star_alg_hom` and
`non_unital_star_alg_hom` are direct extensions of their non-`star`red counterparts with a field
`map_star` which guarantees they preserve the star operation. We keep the type classes as generic
as possible, in keeping with the definition of `non_unital_alg_hom` in the non-unital case. In this
file, we only assume `has_star` unless we want to talk about the zero map as a
`non_unital_star_alg_hom`, in which case we need `star_add_monoid`. Note that the scalar ring `R`
is not required to have a star operation, nor do we need `star_ring` or `star_module` structures on
`A` and `B`.
As with `non_unital_alg_hom`, in the non-unital case the multiplications are not assumed to be
associative or unital, or even to be compatible with the scalar actions. In a typical application,
the operations will satisfy compatibility conditions making them into algebras (albeit possibly
non-associative and/or non-unital) but such conditions are not required here for the definitions.
The primary impetus for defining these types is that they constitute the morphisms in the categories
of unital C⋆-algebras (with `star_alg_hom`s) and of C⋆-algebras (with `non_unital_star_alg_hom`s).
TODO: add `star_alg_equiv`.
## Main definitions
* `non_unital_alg_hom`
* `star_alg_hom`
## Tags
non-unital, algebra, morphism, star
-/
set_option old_structure_cmd true
/-! ### Non-unital star algebra homomorphisms -/
/-- A *non-unital ⋆-algebra homomorphism* is a non-unital algebra homomorphism between
non-unital `R`-algebras `A` and `B` equipped with a `star` operation, and this homomorphism is
also `star`-preserving. -/
structure non_unital_star_alg_hom (R A B : Type*) [monoid R]
[non_unital_non_assoc_semiring A] [distrib_mul_action R A] [has_star A]
[non_unital_non_assoc_semiring B] [distrib_mul_action R B] [has_star B]
extends A →ₙₐ[R] B :=
(map_star' : ∀ a : A, to_fun (star a) = star (to_fun a))
infixr ` →⋆ₙₐ `:25 := non_unital_star_alg_hom _
notation A ` →⋆ₙₐ[`:25 R `] ` B := non_unital_star_alg_hom R A B
/-- Reinterpret a non-unital star algebra homomorphism as a non-unital algebra homomorphism
by forgetting the interaction with the star operation. -/
add_decl_doc non_unital_star_alg_hom.to_non_unital_alg_hom
/-- `non_unital_star_alg_hom_class F R A B` asserts `F` is a type of bundled non-unital ⋆-algebra
homomorphisms from `A` to `B`. -/
class non_unital_star_alg_hom_class (F : Type*) (R : out_param Type*) (A : out_param Type*)
(B : out_param Type*) [monoid R] [has_star A] [has_star B]
[non_unital_non_assoc_semiring A] [non_unital_non_assoc_semiring B]
[distrib_mul_action R A] [distrib_mul_action R B]
extends non_unital_alg_hom_class F R A B, star_hom_class F A B
-- `R` becomes a metavariable but that's fine because it's an `out_param`
attribute [nolint dangerous_instance] non_unital_star_alg_hom_class.to_star_hom_class
namespace non_unital_star_alg_hom_class
variables {F R A B : Type*} [monoid R]
variables [non_unital_non_assoc_semiring A] [distrib_mul_action R A] [has_star A]
variables [non_unital_non_assoc_semiring B] [distrib_mul_action R B] [has_star B]
instance [non_unital_star_alg_hom_class F R A B] : has_coe_t F (A →⋆ₙₐ[R] B) :=
{ coe := λ f,
{ to_fun := f,
map_star' := map_star f,
.. (f : A →ₙₐ[R] B) }}
end non_unital_star_alg_hom_class
namespace non_unital_star_alg_hom
section basic
variables {R A B C D : Type*} [monoid R]
variables [non_unital_non_assoc_semiring A] [distrib_mul_action R A] [has_star A]
variables [non_unital_non_assoc_semiring B] [distrib_mul_action R B] [has_star B]
variables [non_unital_non_assoc_semiring C] [distrib_mul_action R C] [has_star C]
variables [non_unital_non_assoc_semiring D] [distrib_mul_action R D] [has_star D]
instance : non_unital_star_alg_hom_class (A →⋆ₙₐ[R] B) R A B :=
{ coe := to_fun,
coe_injective' := by rintro ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩; congr,
map_smul := λ f, f.map_smul',
map_add := λ f, f.map_add',
map_zero := λ f, f.map_zero',
map_mul := λ f, f.map_mul',
map_star := λ f, f.map_star' }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`
directly. -/
instance : has_coe_to_fun (A →⋆ₙₐ[R] B) (λ _, A → B) := fun_like.has_coe_to_fun
initialize_simps_projections non_unital_star_alg_hom (to_fun → apply)
@[simp, protected] lemma coe_coe {F : Type*} [non_unital_star_alg_hom_class F R A B] (f : F) :
⇑(f : A →⋆ₙₐ[R] B) = f := rfl
@[simp] lemma coe_to_non_unital_alg_hom {f : A →⋆ₙₐ[R] B} :
(f.to_non_unital_alg_hom : A → B) = f := rfl
@[ext] lemma ext {f g : A →⋆ₙₐ[R] B} (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h
/-- Copy of a `non_unital_star_alg_hom` with a new `to_fun` equal to the old one. Useful
to fix definitional equalities. -/
protected def copy (f : A →⋆ₙₐ[R] B) (f' : A → B) (h : f' = f) : A →⋆ₙₐ[R] B :=
{ to_fun := f',
map_smul' := h.symm ▸ map_smul f,
map_zero' := h.symm ▸ map_zero f,
map_add' := h.symm ▸ map_add f,
map_mul' := h.symm ▸ map_mul f,
map_star' := h.symm ▸ map_star f }
@[simp] lemma coe_copy (f : A →⋆ₙₐ[R] B) (f' : A → B) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl
lemma copy_eq (f : A →⋆ₙₐ[R] B) (f' : A → B) (h : f' = f) : f.copy f' h = f := fun_like.ext' h
@[simp] lemma coe_mk (f : A → B) (h₁ h₂ h₃ h₄ h₅) :
((⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →⋆ₙₐ[R] B) : A → B) = f :=
rfl
@[simp] lemma mk_coe (f : A →⋆ₙₐ[R] B) (h₁ h₂ h₃ h₄ h₅) :
(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →⋆ₙₐ[R] B) = f :=
by { ext, refl, }
section
variables (R A)
/-- The identity as a non-unital ⋆-algebra homomorphism. -/
protected def id : A →⋆ₙₐ[R] A :=
{ map_star' := λ x, rfl, .. (1 : A →ₙₐ[R] A) }
@[simp] lemma coe_id : ⇑(non_unital_star_alg_hom.id R A) = id := rfl
end
/-- The composition of non-unital ⋆-algebra homomorphisms, as a non-unital ⋆-algebra
homomorphism. -/
def comp (f : B →⋆ₙₐ[R] C) (g : A →⋆ₙₐ[R] B) : A →⋆ₙₐ[R] C :=
{ map_star' := by simp only [map_star, non_unital_alg_hom.to_fun_eq_coe, eq_self_iff_true,
non_unital_alg_hom.coe_comp, coe_to_non_unital_alg_hom, function.comp_app, forall_const],
.. f.to_non_unital_alg_hom.comp g.to_non_unital_alg_hom }
@[simp] lemma coe_comp (f : B →⋆ₙₐ[R] C) (g : A →⋆ₙₐ[R] B) : ⇑(comp f g) = f ∘ g := rfl
@[simp] lemma comp_apply (f : B →⋆ₙₐ[R] C) (g : A →⋆ₙₐ[R] B) (a : A) : comp f g a = f (g a) := rfl
@[simp] lemma comp_assoc (f : C →⋆ₙₐ[R] D) (g : B →⋆ₙₐ[R] C) (h : A →⋆ₙₐ[R] B) :
(f.comp g).comp h = f.comp (g.comp h) := rfl
@[simp] lemma id_comp (f : A →⋆ₙₐ[R] B) : (non_unital_star_alg_hom.id _ _).comp f = f :=
ext $ λ _, rfl
@[simp] lemma comp_id (f : A →⋆ₙₐ[R] B) : f.comp (non_unital_star_alg_hom.id _ _) = f :=
ext $ λ _, rfl
instance : monoid (A →⋆ₙₐ[R] A) :=
{ mul := comp,
mul_assoc := comp_assoc,
one := non_unital_star_alg_hom.id R A,
one_mul := id_comp,
mul_one := comp_id, }
@[simp] lemma coe_one : ((1 : A →⋆ₙₐ[R] A) : A → A) = id := rfl
lemma one_apply (a : A) : (1 : A →⋆ₙₐ[R] A) a = a := rfl
end basic
section zero
-- the `zero` requires extra type class assumptions because we need `star_zero`
variables {R A B C D : Type*} [monoid R]
variables [non_unital_non_assoc_semiring A] [distrib_mul_action R A] [star_add_monoid A]
variables [non_unital_non_assoc_semiring B] [distrib_mul_action R B] [star_add_monoid B]
instance : has_zero (A →⋆ₙₐ[R] B) :=
⟨{ map_star' := by simp, .. (0 : non_unital_alg_hom R A B) }⟩
instance : inhabited (A →⋆ₙₐ[R] B) := ⟨0⟩
instance : monoid_with_zero (A →⋆ₙₐ[R] A) :=
{ zero_mul := λ f, ext $ λ x, rfl,
mul_zero := λ f, ext $ λ x, map_zero f,
.. non_unital_star_alg_hom.monoid,
.. non_unital_star_alg_hom.has_zero }
@[simp] lemma coe_zero : ((0 : A →⋆ₙₐ[R] B) : A → B) = 0 := rfl
lemma zero_apply (a : A) : (0 : A →⋆ₙₐ[R] B) a = 0 := rfl
end zero
end non_unital_star_alg_hom
/-! ### Unital star algebra homomorphisms -/
section unital
/-- A *⋆-algebra homomorphism* is an algebra homomorphism between `R`-algebras `A` and `B`
equipped with a `star` operation, and this homomorphism is also `star`-preserving. -/
structure star_alg_hom (R A B: Type*) [comm_semiring R] [semiring A] [algebra R A] [has_star A]
[semiring B] [algebra R B] [has_star B] extends alg_hom R A B :=
(map_star' : ∀ x : A, to_fun (star x) = star (to_fun x))
infixr ` →⋆ₐ `:25 := star_alg_hom _
notation A ` →⋆ₐ[`:25 R `] ` B := star_alg_hom R A B
/-- Reinterpret a unital star algebra homomorphism as a unital algebra homomorphism
by forgetting the interaction with the star operation. -/
add_decl_doc star_alg_hom.to_alg_hom
/-- `star_alg_hom_class F R A B` states that `F` is a type of ⋆-algebra homomorphisms.
You should also extend this typeclass when you extend `star_alg_hom`. -/
class star_alg_hom_class (F : Type*) (R : out_param Type*) (A : out_param Type*)
(B : out_param Type*) [comm_semiring R] [semiring A] [algebra R A] [has_star A]
[semiring B] [algebra R B] [has_star B] extends alg_hom_class F R A B, star_hom_class F A B
-- `R` becomes a metavariable but that's fine because it's an `out_param`
attribute [nolint dangerous_instance] star_alg_hom_class.to_star_hom_class
namespace star_alg_hom_class
variables (F R A B : Type*) [comm_semiring R] [semiring A] [algebra R A] [has_star A]
variables [semiring B] [algebra R B] [has_star B] [hF : star_alg_hom_class F R A B]
include hF
@[priority 100] /- See note [lower instance priority] -/
instance to_non_unital_star_alg_hom_class : non_unital_star_alg_hom_class F R A B :=
{ map_smul := map_smul,
.. star_alg_hom_class.to_alg_hom_class F R A B,
.. star_alg_hom_class.to_star_hom_class F R A B, }
instance : has_coe_t F (A →⋆ₐ[R] B) :=
{ coe := λ f,
{ to_fun := f,
map_star' := map_star f,
..(f : A →ₐ[R] B) } }
end star_alg_hom_class
namespace star_alg_hom
variables {F R A B C D : Type*} [comm_semiring R]
[semiring A] [algebra R A] [has_star A]
[semiring B] [algebra R B] [has_star B]
[semiring C] [algebra R C] [has_star C]
[semiring D] [algebra R D] [has_star D]
instance : star_alg_hom_class (A →⋆ₐ[R] B) R A B :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h,
begin
obtain ⟨_, _, _, _, _, _, _⟩ := f;
obtain ⟨_, _, _, _, _, _, _⟩ := g;
congr'
end,
map_mul := map_mul',
map_one := map_one',
map_add := map_add',
map_zero := map_zero',
commutes := commutes',
map_star := map_star' }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`
directly. -/
instance : has_coe_to_fun (A →⋆ₐ[R] B) (λ _, A → B) := fun_like.has_coe_to_fun
@[simp, protected] lemma coe_coe {F : Type} [star_alg_hom_class F R A B] (f : F) :
⇑(f : A →⋆ₐ[R] B) = f := rfl
initialize_simps_projections star_alg_hom (to_fun → apply)
@[simp] lemma coe_to_alg_hom {f : A →⋆ₐ[R] B} :
(f.to_alg_hom : A → B) = f := rfl
@[ext] lemma ext {f g : A →⋆ₐ[R] B} (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h
/-- Copy of a `star_alg_hom` with a new `to_fun` equal to the old one. Useful
to fix definitional equalities. -/
protected def copy (f : A →⋆ₐ[R] B) (f' : A → B) (h : f' = f) : A →⋆ₐ[R] B :=
{ to_fun := f',
map_one' := h.symm ▸ map_one f ,
map_mul' := h.symm ▸ map_mul f,
map_zero' := h.symm ▸ map_zero f,
map_add' := h.symm ▸ map_add f,
commutes' := h.symm ▸ alg_hom_class.commutes f,
map_star' := h.symm ▸ map_star f }
@[simp] lemma coe_copy (f : A →⋆ₐ[R] B) (f' : A → B) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl
lemma copy_eq (f : A →⋆ₐ[R] B) (f' : A → B) (h : f' = f) : f.copy f' h = f := fun_like.ext' h
@[simp] lemma coe_mk (f : A → B) (h₁ h₂ h₃ h₄ h₅ h₆) :
((⟨f, h₁, h₂, h₃, h₄, h₅, h₆⟩ : A →⋆ₐ[R] B) : A → B) = f :=
rfl
@[simp] lemma mk_coe (f : A →⋆ₐ[R] B) (h₁ h₂ h₃ h₄ h₅ h₆) :
(⟨f, h₁, h₂, h₃, h₄, h₅, h₆⟩ : A →⋆ₐ[R] B) = f :=
by { ext, refl, }
section
variables (R A)
/-- The identity as a `star_alg_hom`. -/
protected def id : A →⋆ₐ[R] A := { map_star' := λ x, rfl, .. alg_hom.id _ _ }
@[simp] lemma coe_id : ⇑(star_alg_hom.id R A) = id := rfl
end
instance : inhabited (A →⋆ₐ[R] A) := ⟨star_alg_hom.id R A⟩
/-- The composition of ⋆-algebra homomorphisms, as a ⋆-algebra homomorphism. -/
def comp (f : B →⋆ₐ[R] C) (g : A →⋆ₐ[R] B) : A →⋆ₐ[R] C :=
{ map_star' := by simp only [map_star, alg_hom.to_fun_eq_coe, alg_hom.coe_comp, coe_to_alg_hom,
function.comp_app, eq_self_iff_true, forall_const],
.. f.to_alg_hom.comp g.to_alg_hom }
@[simp] lemma coe_comp (f : B →⋆ₐ[R] C) (g : A →⋆ₐ[R] B) : ⇑(comp f g) = f ∘ g := rfl
@[simp] lemma comp_apply (f : B →⋆ₐ[R] C) (g : A →⋆ₐ[R] B) (a : A) : comp f g a = f (g a) := rfl
@[simp] lemma comp_assoc (f : C →⋆ₐ[R] D) (g : B →⋆ₐ[R] C) (h : A →⋆ₐ[R] B) :
(f.comp g).comp h = f.comp (g.comp h) := rfl
@[simp] lemma id_comp (f : A →⋆ₐ[R] B) : (star_alg_hom.id _ _).comp f = f := ext $ λ _, rfl
@[simp] lemma comp_id (f : A →⋆ₐ[R] B) : f.comp (star_alg_hom.id _ _) = f := ext $ λ _, rfl
instance : monoid (A →⋆ₐ[R] A) :=
{ mul := comp,
mul_assoc := comp_assoc,
one := star_alg_hom.id R A,
one_mul := id_comp,
mul_one := comp_id }
/-- A unital morphism of ⋆-algebras is a `non_unital_star_alg_hom`. -/
def to_non_unital_star_alg_hom (f : A →⋆ₐ[R] B) : A →⋆ₙₐ[R] B :=
{ map_smul' := map_smul f, .. f, }
@[simp] lemma coe_to_non_unital_star_alg_hom (f : A →⋆ₐ[R] B) :
(f.to_non_unital_star_alg_hom : A → B) = f :=
rfl
end star_alg_hom
end unital
/-! ### Operations on the product type
Note that this is copied from [`algebra/hom/non_unital_alg`](non_unital_alg). -/
namespace non_unital_star_alg_hom
section prod
variables (R A B C : Type*) [monoid R]
[non_unital_non_assoc_semiring A] [distrib_mul_action R A] [has_star A]
[non_unital_non_assoc_semiring B] [distrib_mul_action R B] [has_star B]
[non_unital_non_assoc_semiring C] [distrib_mul_action R C] [has_star C]
/-- The first projection of a product is a non-unital ⋆-algebra homomoprhism. -/
@[simps]
def fst : A × B →⋆ₙₐ[R] A :=
{ map_star' := λ x, rfl, .. non_unital_alg_hom.fst R A B }
/-- The second projection of a product is a non-unital ⋆-algebra homomorphism. -/
@[simps]
def snd : A × B →⋆ₙₐ[R] B :=
{ map_star' := λ x, rfl, .. non_unital_alg_hom.snd R A B }
variables {R A B C}
/-- The `pi.prod` of two morphisms is a morphism. -/
@[simps] def prod (f : A →⋆ₙₐ[R] B) (g : A →⋆ₙₐ[R] C) : (A →⋆ₙₐ[R] B × C) :=
{ map_star' := λ x, by simp [map_star, prod.star_def],
.. f.to_non_unital_alg_hom.prod g.to_non_unital_alg_hom }
lemma coe_prod (f : A →⋆ₙₐ[R] B) (g : A →⋆ₙₐ[R] C) : ⇑(f.prod g) = pi.prod f g := rfl
@[simp] theorem fst_prod (f : A →⋆ₙₐ[R] B) (g : A →⋆ₙₐ[R] C) :
(fst R B C).comp (prod f g) = f := by ext; refl
@[simp] theorem snd_prod (f : A →⋆ₙₐ[R] B) (g : A →⋆ₙₐ[R] C) :
(snd R B C).comp (prod f g) = g := by ext; refl
@[simp] theorem prod_fst_snd : prod (fst R A B) (snd R A B) = 1 :=
fun_like.coe_injective pi.prod_fst_snd
/-- Taking the product of two maps with the same domain is equivalent to taking the product of
their codomains. -/
@[simps] def prod_equiv : ((A →⋆ₙₐ[R] B) × (A →⋆ₙₐ[R] C)) ≃ (A →⋆ₙₐ[R] B × C) :=
{ to_fun := λ f, f.1.prod f.2,
inv_fun := λ f, ((fst _ _ _).comp f, (snd _ _ _).comp f),
left_inv := λ f, by ext; refl,
right_inv := λ f, by ext; refl }
end prod
section inl_inr
variables (R A B C : Type*) [monoid R]
[non_unital_non_assoc_semiring A] [distrib_mul_action R A] [star_add_monoid A]
[non_unital_non_assoc_semiring B] [distrib_mul_action R B] [star_add_monoid B]
[non_unital_non_assoc_semiring C] [distrib_mul_action R C] [star_add_monoid C]
/-- The left injection into a product is a non-unital algebra homomorphism. -/
def inl : A →⋆ₙₐ[R] A × B := prod 1 0
/-- The right injection into a product is a non-unital algebra homomorphism. -/
def inr : B →⋆ₙₐ[R] A × B := prod 0 1
variables {R A B}
@[simp] theorem coe_inl : (inl R A B : A → A × B) = λ x, (x, 0) := rfl
theorem inl_apply (x : A) : inl R A B x = (x, 0) := rfl
@[simp] theorem coe_inr : (inr R A B : B → A × B) = prod.mk 0 := rfl
theorem inr_apply (x : B) : inr R A B x = (0, x) := rfl
end inl_inr
end non_unital_star_alg_hom
namespace star_alg_hom
variables (R A B C : Type*) [comm_semiring R]
[semiring A] [algebra R A] [has_star A]
[semiring B] [algebra R B] [has_star B]
[semiring C] [algebra R C] [has_star C]
/-- The first projection of a product is a ⋆-algebra homomoprhism. -/
@[simps]
def fst : A × B →⋆ₐ[R] A :=
{ map_star' := λ x, rfl, .. alg_hom.fst R A B }
/-- The second projection of a product is a ⋆-algebra homomorphism. -/
@[simps]
def snd : A × B →⋆ₐ[R] B :=
{ map_star' := λ x, rfl, .. alg_hom.snd R A B }
variables {R A B C}
/-- The `pi.prod` of two morphisms is a morphism. -/
@[simps] def prod (f : A →⋆ₐ[R] B) (g : A →⋆ₐ[R] C) : (A →⋆ₐ[R] B × C) :=
{ map_star' := λ x, by simp [prod.star_def, map_star],
.. f.to_alg_hom.prod g.to_alg_hom }
lemma coe_prod (f : A →⋆ₐ[R] B) (g : A →⋆ₐ[R] C) : ⇑(f.prod g) = pi.prod f g := rfl
@[simp] theorem fst_prod (f : A →⋆ₐ[R] B) (g : A →⋆ₐ[R] C) :
(fst R B C).comp (prod f g) = f := by ext; refl
@[simp] theorem snd_prod (f : A →⋆ₐ[R] B) (g : A →⋆ₐ[R] C) :
(snd R B C).comp (prod f g) = g := by ext; refl
@[simp] theorem prod_fst_snd : prod (fst R A B) (snd R A B) = 1 :=
fun_like.coe_injective pi.prod_fst_snd
/-- Taking the product of two maps with the same domain is equivalent to taking the product of
their codomains. -/
@[simps] def prod_equiv : ((A →⋆ₐ[R] B) × (A →⋆ₐ[R] C)) ≃ (A →⋆ₐ[R] B × C) :=
{ to_fun := λ f, f.1.prod f.2,
inv_fun := λ f, ((fst _ _ _).comp f, (snd _ _ _).comp f),
left_inv := λ f, by ext; refl,
right_inv := λ f, by ext; refl }
end star_alg_hom
/-! ### Star algebra equivalences -/
/-- A *⋆-algebra* equivalence is an equivalence preserving addition, multiplication, scalar
multiplication and the star operation, which allows for considering both unital and non-unital
equivalences with a single structure. Currently, `alg_equiv` requires unital algebras, which is
why this structure does not extend it. -/
structure star_alg_equiv (R A B : Type*) [has_add A] [has_mul A] [has_smul R A] [has_star A]
[has_add B] [has_mul B] [has_smul R B] [has_star B] extends A ≃+* B :=
(map_star' : ∀ a : A, to_fun (star a) = star (to_fun a))
(map_smul' : ∀ (r : R) (a : A), to_fun (r • a) = r • to_fun a)
infixr ` ≃⋆ₐ `:25 := star_alg_equiv _
notation A ` ≃⋆ₐ[`:25 R `] ` B := star_alg_equiv R A B
/-- Reinterpret a star algebra equivalence as a `ring_equiv` by forgetting the interaction with
the star operation and scalar multiplication. -/
add_decl_doc star_alg_equiv.to_ring_equiv
/-- `star_alg_equiv_class F R A B` asserts `F` is a type of bundled ⋆-algebra equivalences between
`A` and `B`.
You should also extend this typeclass when you extend `star_alg_equiv`. -/
class star_alg_equiv_class (F : Type*) (R : out_param Type*) (A : out_param Type*)
(B : out_param Type*) [has_add A] [has_mul A] [has_smul R A] [has_star A] [has_add B] [has_mul B]
[has_smul R B] [has_star B] extends ring_equiv_class F A B :=
(map_star : ∀ (f : F) (a : A), f (star a) = star (f a))
(map_smul : ∀ (f : F) (r : R) (a : A), f (r • a) = r • f a)
-- `R` becomes a metavariable but that's fine because it's an `out_param`
attribute [nolint dangerous_instance] star_alg_equiv_class.to_ring_equiv_class
namespace star_alg_equiv_class
@[priority 50] -- See note [lower instance priority]
instance {F R A B : Type*} [has_add A] [has_mul A] [has_smul R A] [has_star A] [has_add B]
[has_mul B] [has_smul R B] [has_star B] [hF : star_alg_equiv_class F R A B] :
star_hom_class F A B :=
{ coe := λ f, f,
coe_injective' := fun_like.coe_injective,
.. hF }
-- `R` becomes a metavariable but that's fine because it's an `out_param`
attribute [nolint dangerous_instance] star_alg_equiv_class.star_hom_class
@[priority 50] -- See note [lower instance priority]
instance {F R A B : Type*} [has_add A] [has_mul A] [has_star A] [has_smul R A] [has_add B]
[has_mul B] [has_smul R B] [has_star B] [hF : star_alg_equiv_class F R A B] :
smul_hom_class F R A B :=
{ coe := λ f, f,
coe_injective' := fun_like.coe_injective,
.. hF }
-- `R` becomes a metavariable but that's fine because it's an `out_param`
attribute [nolint dangerous_instance] star_alg_equiv_class.smul_hom_class
@[priority 100] -- See note [lower instance priority]
instance {F R A B : Type*} [monoid R] [non_unital_non_assoc_semiring A] [distrib_mul_action R A]
[has_star A] [non_unital_non_assoc_semiring B] [distrib_mul_action R B] [has_star B]
[hF : star_alg_equiv_class F R A B] : non_unital_star_alg_hom_class F R A B :=
{ coe := λ f, f,
coe_injective' := fun_like.coe_injective,
map_zero := map_zero,
.. hF }
@[priority 100] -- See note [lower instance priority]
instance (F R A B : Type*) [comm_semiring R] [semiring A] [algebra R A] [has_star A]
[semiring B] [algebra R B] [has_star B] [hF : star_alg_equiv_class F R A B] :
star_alg_hom_class F R A B :=
{ coe := λ f, f,
coe_injective' := fun_like.coe_injective,
map_one := map_one,
map_zero := map_zero,
commutes := λ f r, by simp only [algebra.algebra_map_eq_smul_one, map_smul, map_one],
.. hF}
end star_alg_equiv_class
namespace star_alg_equiv
section basic
variables {F R A B C : Type*}
[has_add A] [has_mul A] [has_smul R A] [has_star A]
[has_add B] [has_mul B] [has_smul R B] [has_star B]
[has_add C] [has_mul C] [has_smul R C] [has_star C]
instance : star_alg_equiv_class (A ≃⋆ₐ[R] B) R A B :=
{ coe := to_fun,
inv := inv_fun,
left_inv := left_inv,
right_inv := right_inv,
coe_injective' := λ f g h₁ h₂, by { cases f, cases g, congr' },
map_mul := map_mul',
map_add := map_add',
map_star := map_star',
map_smul := map_smul' }
/-- Helper instance for when there's too many metavariables to apply
`fun_like.has_coe_to_fun` directly. -/
instance : has_coe_to_fun (A ≃⋆ₐ[R] B) (λ _, A → B) := ⟨star_alg_equiv.to_fun⟩
@[ext]
lemma ext {f g : A ≃⋆ₐ[R] B} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h
lemma ext_iff {f g : A ≃⋆ₐ[R] B} : f = g ↔ ∀ a, f a = g a := fun_like.ext_iff
/-- Star algebra equivalences are reflexive. -/
@[refl] def refl : A ≃⋆ₐ[R] A :=
{ map_smul' := λ r a, rfl, map_star' := λ a, rfl, ..ring_equiv.refl A }
instance : inhabited (A ≃⋆ₐ[R] A) := ⟨refl⟩
@[simp] lemma coe_refl : ⇑(refl : A ≃⋆ₐ[R] A) = id := rfl
/-- Star algebra equivalences are symmetric. -/
@[symm]
def symm (e : A ≃⋆ₐ[R] B) : B ≃⋆ₐ[R] A :=
{ map_star' := λ b, by simpa only [e.left_inv (star (e.inv_fun b)), e.right_inv b]
using congr_arg e.inv_fun (e.map_star' (e.inv_fun b)).symm,
map_smul' := λ r b, by simpa only [e.left_inv (r • e.inv_fun b), e.right_inv b]
using congr_arg e.inv_fun (e.map_smul' r (e.inv_fun b)).symm,
..e.to_ring_equiv.symm, }
/-- See Note [custom simps projection] -/
def simps.symm_apply (e : A ≃⋆ₐ[R] B) : B → A := e.symm
initialize_simps_projections star_alg_equiv (to_fun → apply, inv_fun → simps.symm_apply)
@[simp] lemma inv_fun_eq_symm {e : A ≃⋆ₐ[R] B} : e.inv_fun = e.symm := rfl
@[simp] lemma symm_symm (e : A ≃⋆ₐ[R] B) : e.symm.symm = e :=
by { ext, refl, }
lemma symm_bijective : function.bijective (symm : (A ≃⋆ₐ[R] B) → (B ≃⋆ₐ[R] A)) :=
equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩
@[simp] lemma mk_coe' (e : A ≃⋆ₐ[R] B) (f h₁ h₂ h₃ h₄ h₅ h₆) :
(⟨f, e, h₁, h₂, h₃, h₄, h₅, h₆⟩ : B ≃⋆ₐ[R] A) = e.symm :=
symm_bijective.injective $ ext $ λ x, rfl
@[simp] lemma symm_mk (f f') (h₁ h₂ h₃ h₄ h₅ h₆) :
(⟨f, f', h₁, h₂, h₃, h₄, h₅, h₆⟩ : A ≃⋆ₐ[R] B).symm =
{ to_fun := f', inv_fun := f,
..(⟨f, f', h₁, h₂, h₃, h₄, h₅, h₆⟩ : A ≃⋆ₐ[R] B).symm } := rfl
@[simp] lemma refl_symm : (star_alg_equiv.refl : A ≃⋆ₐ[R] A).symm = star_alg_equiv.refl := rfl
-- should be a `simp` lemma, but causes a linter timeout
lemma to_ring_equiv_symm (f : A ≃⋆ₐ[R] B) : (f : A ≃+* B).symm = f.symm := rfl
@[simp] lemma symm_to_ring_equiv (e : A ≃⋆ₐ[R] B) : (e.symm : B ≃+* A) = (e : A ≃+* B).symm := rfl
/-- Star algebra equivalences are transitive. -/
@[trans]
def trans (e₁ : A ≃⋆ₐ[R] B) (e₂ : B ≃⋆ₐ[R] C) : A ≃⋆ₐ[R] C :=
{ map_smul' := λ r a, show e₂.to_fun (e₁.to_fun (r • a)) = r • e₂.to_fun (e₁.to_fun a),
by rw [e₁.map_smul', e₂.map_smul'],
map_star' := λ a, show e₂.to_fun (e₁.to_fun (star a)) = star (e₂.to_fun (e₁.to_fun a)),
by rw [e₁.map_star', e₂.map_star'],
..(e₁.to_ring_equiv.trans e₂.to_ring_equiv), }
@[simp] lemma apply_symm_apply (e : A ≃⋆ₐ[R] B) : ∀ x, e (e.symm x) = x :=
e.to_ring_equiv.apply_symm_apply
@[simp] lemma symm_apply_apply (e : A ≃⋆ₐ[R] B) : ∀ x, e.symm (e x) = x :=
e.to_ring_equiv.symm_apply_apply
@[simp] lemma symm_trans_apply (e₁ : A ≃⋆ₐ[R] B) (e₂ : B ≃⋆ₐ[R] C) (x : C) :
(e₁.trans e₂).symm x = e₁.symm (e₂.symm x) := rfl
@[simp] lemma coe_trans (e₁ : A ≃⋆ₐ[R] B) (e₂ : B ≃⋆ₐ[R] C) :
⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl
@[simp] lemma trans_apply (e₁ : A ≃⋆ₐ[R] B) (e₂ : B ≃⋆ₐ[R] C) (x : A) :
(e₁.trans e₂) x = e₂ (e₁ x) := rfl
theorem left_inverse_symm (e : A ≃⋆ₐ[R] B) : function.left_inverse e.symm e := e.left_inv
theorem right_inverse_symm (e : A ≃⋆ₐ[R] B) : function.right_inverse e.symm e := e.right_inv
end basic
section bijective
variables {F G R A B : Type*} [monoid R]
variables [non_unital_non_assoc_semiring A] [distrib_mul_action R A] [has_star A]
variables [non_unital_non_assoc_semiring B] [distrib_mul_action R B] [has_star B]
variables [hF : non_unital_star_alg_hom_class F R A B] [non_unital_star_alg_hom_class G R B A]
include hF
/-- If a (unital or non-unital) star algebra morphism has an inverse, it is an isomorphism of
star algebras. -/
@[simps] def of_star_alg_hom (f : F) (g : G) (h₁ : ∀ x, g (f x) = x) (h₂ : ∀ x, f (g x) = x) :
A ≃⋆ₐ[R] B :=
{ to_fun := f,
inv_fun := g,
left_inv := h₁,
right_inv := h₂,
map_add' := map_add f,
map_mul' := map_mul f,
map_smul' := map_smul f,
map_star' := map_star f }
/-- Promote a bijective star algebra homomorphism to a star algebra equivalence. -/
noncomputable def of_bijective (f : F) (hf : function.bijective f) : A ≃⋆ₐ[R] B :=
{ to_fun := f,
map_star' := map_star f,
map_smul' := map_smul f,
.. ring_equiv.of_bijective f (hf : function.bijective (f : A → B)), }
@[simp] lemma coe_of_bijective {f : F} (hf : function.bijective f) :
(star_alg_equiv.of_bijective f hf : A → B) = f := rfl
lemma of_bijective_apply {f : F} (hf : function.bijective f) (a : A) :
(star_alg_equiv.of_bijective f hf) a = f a := rfl
end bijective
end star_alg_equiv
|
e3dc939546400c9613c2e157b001da67bf6a28f4 | d29d82a0af640c937e499f6be79fc552eae0aa13 | /src/measure_theory/integrable_on.lean | 751a0b651f6f16c9710941301ffd148bcedde716 | [
"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 | 20,474 | lean | /-
Copyright (c) 2021 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Yury Kudryashov
-/
import measure_theory.l1_space
import analysis.normed_space.indicator_function
/-! # Functions integrable on a set and at a filter
We define `integrable_on f s μ := integrable f (μ.restrict s)` and prove theorems like
`integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ`.
Next we define a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)`
saying that `f` is integrable at some set `s ∈ l` and prove that a measurable function is integrable
at `l` with respect to `μ` provided that `f` is bounded above at `l ⊓ μ.ae` and `μ` is finite
at `l`.
-/
noncomputable theory
open set filter topological_space measure_theory function
open_locale classical topological_space interval big_operators filter ennreal measure_theory
variables {α β E F : Type*} [measurable_space α]
section
variables [measurable_space β] {l l' : filter α} {f g : α → β} {μ ν : measure α}
/-- A function `f` is measurable at filter `l` w.r.t. a measure `μ` if it is ae-measurable
w.r.t. `μ.restrict s` for some `s ∈ l`. -/
def measurable_at_filter (f : α → β) (l : filter α) (μ : measure α . volume_tac) :=
∃ s ∈ l, ae_measurable f (μ.restrict s)
@[simp] lemma measurable_at_bot {f : α → β} : measurable_at_filter f ⊥ μ :=
⟨∅, mem_bot_sets, by simp⟩
protected lemma measurable_at_filter.eventually (h : measurable_at_filter f l μ) :
∀ᶠ s in l.lift' powerset, ae_measurable f (μ.restrict s) :=
(eventually_lift'_powerset' $ λ s t, ae_measurable.mono_set).2 h
protected lemma measurable_at_filter.filter_mono (h : measurable_at_filter f l μ) (h' : l' ≤ l) :
measurable_at_filter f l' μ :=
let ⟨s, hsl, hs⟩ := h in ⟨s, h' hsl, hs⟩
protected lemma ae_measurable.measurable_at_filter (h : ae_measurable f μ) :
measurable_at_filter f l μ :=
⟨univ, univ_mem_sets, by rwa measure.restrict_univ⟩
lemma ae_measurable.measurable_at_filter_of_mem {s} (h : ae_measurable f (μ.restrict s))
(hl : s ∈ l):
measurable_at_filter f l μ :=
⟨s, hl, h⟩
protected lemma measurable.measurable_at_filter (h : measurable f) :
measurable_at_filter f l μ :=
h.ae_measurable.measurable_at_filter
end
namespace measure_theory
section normed_group
lemma has_finite_integral_restrict_of_bounded [normed_group E] {f : α → E} {s : set α}
{μ : measure α} {C} (hs : μ s < ∞) (hf : ∀ᵐ x ∂(μ.restrict s), ∥f x∥ ≤ C) :
has_finite_integral f (μ.restrict s) :=
by haveI : finite_measure (μ.restrict s) := ⟨by rwa [measure.restrict_apply_univ]⟩;
exact has_finite_integral_of_bounded hf
variables [normed_group E] [measurable_space E] {f g : α → E} {s t : set α} {μ ν : measure α}
/-- A function is `integrable_on` a set `s` if it is almost everywhere measurable on `s` and if the
integral of its pointwise norm over `s` is less than infinity. -/
def integrable_on (f : α → E) (s : set α) (μ : measure α . volume_tac) : Prop :=
integrable f (μ.restrict s)
lemma integrable_on.integrable (h : integrable_on f s μ) :
integrable f (μ.restrict s) := h
@[simp] lemma integrable_on_empty : integrable_on f ∅ μ :=
by simp [integrable_on, integrable_zero_measure]
@[simp] lemma integrable_on_univ : integrable_on f univ μ ↔ integrable f μ :=
by rw [integrable_on, measure.restrict_univ]
lemma integrable_on_zero : integrable_on (λ _, (0:E)) s μ := integrable_zero _ _ _
lemma integrable_on_const {C : E} : integrable_on (λ _, C) s μ ↔ C = 0 ∨ μ s < ∞ :=
integrable_const_iff.trans $ by rw [measure.restrict_apply_univ]
lemma integrable_on.mono (h : integrable_on f t ν) (hs : s ⊆ t) (hμ : μ ≤ ν) :
integrable_on f s μ :=
h.mono_measure $ measure.restrict_mono hs hμ
lemma integrable_on.mono_set (h : integrable_on f t μ) (hst : s ⊆ t) :
integrable_on f s μ :=
h.mono hst (le_refl _)
lemma integrable_on.mono_measure (h : integrable_on f s ν) (hμ : μ ≤ ν) :
integrable_on f s μ :=
h.mono (subset.refl _) hμ
lemma integrable_on.mono_set_ae (h : integrable_on f t μ) (hst : s ≤ᵐ[μ] t) :
integrable_on f s μ :=
h.integrable.mono_measure $ restrict_mono_ae hst
lemma integrable.integrable_on (h : integrable f μ) : integrable_on f s μ :=
h.mono_measure $ measure.restrict_le_self
lemma integrable.integrable_on' (h : integrable f (μ.restrict s)) : integrable_on f s μ :=
h
lemma integrable_on.restrict (h : integrable_on f s μ) (hs : measurable_set s) :
integrable_on f s (μ.restrict t) :=
by { rw [integrable_on, measure.restrict_restrict hs], exact h.mono_set (inter_subset_left _ _) }
lemma integrable_on.left_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f s μ :=
h.mono_set $ subset_union_left _ _
lemma integrable_on.right_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f t μ :=
h.mono_set $ subset_union_right _ _
lemma integrable_on.union (hs : integrable_on f s μ) (ht : integrable_on f t μ) :
integrable_on f (s ∪ t) μ :=
(hs.add_measure ht).mono_measure $ measure.restrict_union_le _ _
@[simp] lemma integrable_on_union :
integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ :=
⟨λ h, ⟨h.left_of_union, h.right_of_union⟩, λ h, h.1.union h.2⟩
@[simp] lemma integrable_on_singleton_iff {x : α} [measurable_singleton_class α]:
integrable_on f {x} μ ↔ f x = 0 ∨ μ {x} < ∞ :=
begin
have : f =ᵐ[μ.restrict {x}] (λ y, f x),
{ filter_upwards [ae_restrict_mem (measurable_set_singleton x)],
assume a ha,
simp only [mem_singleton_iff.1 ha] },
rw [integrable_on, integrable_congr this, integrable_const_iff],
simp,
end
@[simp] lemma integrable_on_finite_union {s : set β} (hs : finite s)
{t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ :=
begin
apply hs.induction_on,
{ simp },
{ intros a s ha hs hf, simp [hf, or_imp_distrib, forall_and_distrib] }
end
@[simp] lemma integrable_on_finset_union {s : finset β} {t : β → set α} :
integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ :=
integrable_on_finite_union s.finite_to_set
lemma integrable_on.add_measure (hμ : integrable_on f s μ) (hν : integrable_on f s ν) :
integrable_on f s (μ + ν) :=
by { delta integrable_on, rw measure.restrict_add, exact hμ.integrable.add_measure hν }
@[simp] lemma integrable_on_add_measure :
integrable_on f s (μ + ν) ↔ integrable_on f s μ ∧ integrable_on f s ν :=
⟨λ h, ⟨h.mono_measure (measure.le_add_right (le_refl _)),
h.mono_measure (measure.le_add_left (le_refl _))⟩,
λ h, h.1.add_measure h.2⟩
lemma integrable_indicator_iff (hs : measurable_set s) :
integrable (indicator s f) μ ↔ integrable_on f s μ :=
by simp [integrable_on, integrable, has_finite_integral, nnnorm_indicator_eq_indicator_nnnorm,
ennreal.coe_indicator, lintegral_indicator _ hs, ae_measurable_indicator_iff hs]
lemma integrable_on.indicator (h : integrable_on f s μ) (hs : measurable_set s) :
integrable (indicator s f) μ :=
(integrable_indicator_iff hs).2 h
lemma integrable.indicator (h : integrable f μ) (hs : measurable_set s) :
integrable (indicator s f) μ :=
h.integrable_on.indicator hs
lemma integrable_indicator_const_Lp {E} [normed_group E] [measurable_space E] [borel_space E]
[second_countable_topology E] {p : ℝ≥0∞} {s : set α} (hs : measurable_set s) (hμs : μ s ≠ ∞)
(c : E) :
integrable (indicator_const_Lp p hs hμs c) μ :=
begin
rw [integrable_congr indicator_const_Lp_coe_fn, integrable_indicator_iff hs, integrable_on,
integrable_const_iff, lt_top_iff_ne_top],
right,
simpa only [set.univ_inter, measurable_set.univ, measure.restrict_apply] using hμs,
end
lemma integrable_on_Lp_of_measure_ne_top {E} [normed_group E] [measurable_space E] [borel_space E]
[second_countable_topology E] {p : ℝ≥0∞} {s : set α} (f : Lp E p μ) (hp : 1 ≤ p) (hμs : μ s ≠ ∞) :
integrable_on f s μ :=
begin
refine mem_ℒp_one_iff_integrable.mp _,
have hμ_restrict_univ : (μ.restrict s) set.univ < ∞,
by simpa only [set.univ_inter, measurable_set.univ, measure.restrict_apply, lt_top_iff_ne_top],
haveI hμ_finite : finite_measure (μ.restrict s) := ⟨hμ_restrict_univ⟩,
exact ((Lp.mem_ℒp _).restrict s).mem_ℒp_of_exponent_le hp,
end
/-- We say that a function `f` is *integrable at filter* `l` if it is integrable on some
set `s ∈ l`. Equivalently, it is eventually integrable on `s` in `l.lift' powerset`. -/
def integrable_at_filter (f : α → E) (l : filter α) (μ : measure α . volume_tac) :=
∃ s ∈ l, integrable_on f s μ
variables {l l' : filter α}
protected lemma integrable_at_filter.eventually (h : integrable_at_filter f l μ) :
∀ᶠ s in l.lift' powerset, integrable_on f s μ :=
by { refine (eventually_lift'_powerset' $ λ s t hst ht, _).2 h, exact ht.mono_set hst }
lemma integrable_at_filter.filter_mono (hl : l ≤ l') (hl' : integrable_at_filter f l' μ) :
integrable_at_filter f l μ :=
let ⟨s, hs, hsf⟩ := hl' in ⟨s, hl hs, hsf⟩
lemma integrable_at_filter.inf_of_left (hl : integrable_at_filter f l μ) :
integrable_at_filter f (l ⊓ l') μ :=
hl.filter_mono inf_le_left
lemma integrable_at_filter.inf_of_right (hl : integrable_at_filter f l μ) :
integrable_at_filter f (l' ⊓ l) μ :=
hl.filter_mono inf_le_right
@[simp] lemma integrable_at_filter.inf_ae_iff {l : filter α} :
integrable_at_filter f (l ⊓ μ.ae) μ ↔ integrable_at_filter f l μ :=
begin
refine ⟨_, λ h, h.filter_mono inf_le_left⟩,
rintros ⟨s, ⟨t, ht, u, hu, hs⟩, hf⟩,
refine ⟨t, ht, _⟩,
refine hf.integrable.mono_measure (λ v hv, _),
simp only [measure.restrict_apply hv],
refine measure_mono_ae (mem_sets_of_superset hu $ λ x hx, _),
exact λ ⟨hv, ht⟩, ⟨hv, hs ⟨ht, hx⟩⟩
end
alias integrable_at_filter.inf_ae_iff ↔ measure_theory.integrable_at_filter.of_inf_ae _
/-- If `μ` is a measure finite at filter `l` and `f` is a function such that its norm is bounded
above at `l`, then `f` is integrable at `l`. -/
lemma measure.finite_at_filter.integrable_at_filter {l : filter α} [is_measurably_generated l]
(hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l)
(hf : l.is_bounded_under (≤) (norm ∘ f)) :
integrable_at_filter f l μ :=
begin
obtain ⟨C, hC⟩ : ∃ C, ∀ᶠ s in (l.lift' powerset), ∀ x ∈ s, ∥f x∥ ≤ C,
from hf.imp (λ C hC, eventually_lift'_powerset.2 ⟨_, hC, λ t, id⟩),
rcases (hfm.eventually.and (hμ.eventually.and hC)).exists_measurable_mem_of_lift'
with ⟨s, hsl, hsm, hfm, hμ, hC⟩,
refine ⟨s, hsl, ⟨hfm, has_finite_integral_restrict_of_bounded hμ _⟩⟩,
exact C,
rw [ae_restrict_eq hsm, eventually_inf_principal],
exact eventually_of_forall hC
end
lemma measure.finite_at_filter.integrable_at_filter_of_tendsto_ae
{l : filter α} [is_measurably_generated l] (hfm : measurable_at_filter f l μ)
(hμ : μ.finite_at_filter l) {b} (hf : tendsto f (l ⊓ μ.ae) (𝓝 b)) :
integrable_at_filter f l μ :=
(hμ.inf_of_left.integrable_at_filter (hfm.filter_mono inf_le_left)
hf.norm.is_bounded_under_le).of_inf_ae
alias measure.finite_at_filter.integrable_at_filter_of_tendsto_ae ←
filter.tendsto.integrable_at_filter_ae
lemma measure.finite_at_filter.integrable_at_filter_of_tendsto {l : filter α}
[is_measurably_generated l] (hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l)
{b} (hf : tendsto f l (𝓝 b)) :
integrable_at_filter f l μ :=
hμ.integrable_at_filter hfm hf.norm.is_bounded_under_le
alias measure.finite_at_filter.integrable_at_filter_of_tendsto ← filter.tendsto.integrable_at_filter
variables [borel_space E] [second_countable_topology E]
lemma integrable_add_of_disjoint {f g : α → E}
(h : disjoint (support f) (support g)) (hf : measurable f) (hg : measurable g) :
integrable (f + g) μ ↔ integrable f μ ∧ integrable g μ :=
begin
refine ⟨λ hfg, ⟨_, _⟩, λ h, h.1.add h.2⟩,
{ rw ← indicator_add_eq_left h, exact hfg.indicator (measurable_set_support hf) },
{ rw ← indicator_add_eq_right h, exact hfg.indicator (measurable_set_support hg) }
end
end normed_group
end measure_theory
open measure_theory
variables [measurable_space E] [normed_group E]
/-- If a function is integrable at `𝓝[s] x` for each point `x` of a compact set `s`, then it is
integrable on `s`. -/
lemma is_compact.integrable_on_of_nhds_within [topological_space α] {μ : measure α} {s : set α}
(hs : is_compact s) {f : α → E} (hf : ∀ x ∈ s, integrable_at_filter f (𝓝[s] x) μ) :
integrable_on f s μ :=
is_compact.induction_on hs integrable_on_empty (λ s t hst ht, ht.mono_set hst)
(λ s t hs ht, hs.union ht) hf
/-- A function which is continuous on a set `s` is almost everywhere measurable with respect to
`μ.restrict s`. -/
lemma continuous_on.ae_measurable [topological_space α] [opens_measurable_space α] [borel_space E]
{f : α → E} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) :
ae_measurable f (μ.restrict s) :=
begin
refine ⟨indicator s f, _, (indicator_ae_eq_restrict hs).symm⟩,
apply measurable_of_is_open,
assume t ht,
obtain ⟨u, u_open, hu⟩ : ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s :=
_root_.continuous_on_iff'.1 hf t ht,
rw [indicator_preimage, set.ite, hu],
exact (u_open.measurable_set.inter hs).union ((measurable_zero ht.measurable_set).diff hs)
end
lemma continuous_on.integrable_at_nhds_within
[topological_space α] [opens_measurable_space α] [borel_space E]
{μ : measure α} [locally_finite_measure μ] {a : α} {t : set α} {f : α → E}
(hft : continuous_on f t) (ht : measurable_set t) (ha : a ∈ t) :
integrable_at_filter f (𝓝[t] a) μ :=
by haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _;
exact (hft a ha).integrable_at_filter ⟨_, self_mem_nhds_within, hft.ae_measurable ht⟩
(μ.finite_at_nhds_within _ _)
/-- A function `f` continuous on a compact set `s` is integrable on this set with respect to any
locally finite measure. -/
lemma continuous_on.integrable_on_compact
[topological_space α] [opens_measurable_space α] [borel_space E]
[t2_space α] {μ : measure α} [locally_finite_measure μ]
{s : set α} (hs : is_compact s) {f : α → E} (hf : continuous_on f s) :
integrable_on f s μ :=
hs.integrable_on_of_nhds_within $ λ x hx, hf.integrable_at_nhds_within hs.measurable_set hx
lemma continuous_on.integrable_on_Icc [borel_space E]
[conditionally_complete_linear_order β] [topological_space β] [order_topology β]
[measurable_space β] [opens_measurable_space β] {μ : measure β} [locally_finite_measure μ]
{a b : β} {f : β → E} (hf : continuous_on f (Icc a b)) :
integrable_on f (Icc a b) μ :=
hf.integrable_on_compact is_compact_Icc
lemma continuous_on.integrable_on_interval [borel_space E]
[conditionally_complete_linear_order β] [topological_space β] [order_topology β]
[measurable_space β] [opens_measurable_space β] {μ : measure β} [locally_finite_measure μ]
{a b : β} {f : β → E} (hf : continuous_on f (interval a b)) :
integrable_on f (interval a b) μ :=
hf.integrable_on_compact is_compact_interval
/-- A continuous function `f` is integrable on any compact set with respect to any locally finite
measure. -/
lemma continuous.integrable_on_compact
[topological_space α] [opens_measurable_space α] [t2_space α]
[borel_space E] {μ : measure α} [locally_finite_measure μ] {s : set α}
(hs : is_compact s) {f : α → E} (hf : continuous f) :
integrable_on f s μ :=
hf.continuous_on.integrable_on_compact hs
lemma continuous.integrable_on_Icc [borel_space E]
[conditionally_complete_linear_order β] [topological_space β] [order_topology β]
[measurable_space β] [opens_measurable_space β] {μ : measure β} [locally_finite_measure μ]
{a b : β} {f : β → E} (hf : continuous f) :
integrable_on f (Icc a b) μ :=
hf.integrable_on_compact is_compact_Icc
lemma continuous.integrable_on_interval [borel_space E]
[conditionally_complete_linear_order β] [topological_space β] [order_topology β]
[measurable_space β] [opens_measurable_space β] {μ : measure β} [locally_finite_measure μ]
{a b : β} {f : β → E} (hf : continuous f) :
integrable_on f (interval a b) μ :=
hf.integrable_on_compact is_compact_interval
/-- A continuous function with compact closure of the support is integrable on the whole space. -/
lemma continuous.integrable_of_compact_closure_support
[topological_space α] [opens_measurable_space α] [t2_space α] [borel_space E]
{μ : measure α} [locally_finite_measure μ] {f : α → E} (hf : continuous f)
(hfc : is_compact (closure $ support f)) :
integrable f μ :=
begin
rw [← indicator_eq_self.2 (@subset_closure _ _ (support f)),
integrable_indicator_iff is_closed_closure.measurable_set],
{ exact hf.integrable_on_compact hfc },
{ apply_instance }
end
lemma measure_theory.integrable_on.mul_continuous_on
[topological_space α] [opens_measurable_space α] [t2_space α]
{μ : measure α} {s : set α} {f g : α → ℝ}
(hf : integrable_on f s μ) (hg : continuous_on g s) (hs : is_compact s) :
integrable_on (λ x, f x * g x) s μ :=
begin
rcases is_compact.exists_bound_of_continuous_on hs hg with ⟨C, hC⟩,
rw [integrable_on, ← mem_ℒp_one_iff_integrable] at hf ⊢,
have : ∀ᵐ x ∂(μ.restrict s), ∥f x * g x∥ ≤ C * ∥f x∥,
{ filter_upwards [ae_restrict_mem hs.measurable_set],
assume x hx,
rw [real.norm_eq_abs, abs_mul, mul_comm, real.norm_eq_abs],
apply mul_le_mul_of_nonneg_right (hC x hx) (abs_nonneg _) },
exact mem_ℒp.of_le_mul hf (hf.ae_measurable.mul (hg.ae_measurable hs.measurable_set)) this
end
lemma measure_theory.integrable_on.continuous_on_mul
[topological_space α] [opens_measurable_space α] [t2_space α]
{μ : measure α} {s : set α} {f g : α → ℝ}
(hf : integrable_on f s μ) (hg : continuous_on g s) (hs : is_compact s) :
integrable_on (λ x, g x * f x) s μ :=
by simpa [mul_comm] using hf.mul_continuous_on hg hs
section monotone
variables
[topological_space α] [borel_space α] [borel_space E]
[conditionally_complete_linear_order α] [conditionally_complete_linear_order E]
[order_topology α] [order_topology E] [second_countable_topology E]
{μ : measure α} [locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E}
include hs
lemma integrable_on_compact_of_monotone_on (hmono : ∀ ⦃x y⦄, x ∈ s → y ∈ s → x ≤ y → f x ≤ f y) :
integrable_on f s μ :=
begin
by_cases h : s.nonempty,
{ have hbelow : bdd_below (f '' s) :=
⟨f (Inf s), λ x ⟨y, hy, hyx⟩, hyx ▸ hmono (hs.Inf_mem h) hy (cInf_le hs.bdd_below hy)⟩,
have habove : bdd_above (f '' s) :=
⟨f (Sup s), λ x ⟨y, hy, hyx⟩, hyx ▸ hmono hy (hs.Sup_mem h) (le_cSup hs.bdd_above hy)⟩,
have : metric.bounded (f '' s) := metric.bounded_of_bdd_above_of_bdd_below habove hbelow,
rcases bounded_iff_forall_norm_le.mp this with ⟨C, hC⟩,
exact integrable.mono' (continuous_const.integrable_on_compact hs)
(ae_measurable_restrict_of_monotone_on hs.measurable_set hmono)
((ae_restrict_iff' hs.measurable_set).mpr $ ae_of_all _ $
λ y hy, hC (f y) (mem_image_of_mem f hy)) },
{ rw set.not_nonempty_iff_eq_empty at h,
rw h,
exact integrable_on_empty }
end
lemma integrable_on_compact_of_antimono_on (hmono : ∀ ⦃x y⦄, x ∈ s → y ∈ s → x ≤ y → f y ≤ f x) :
integrable_on f s μ :=
@integrable_on_compact_of_monotone_on α (order_dual E) _ _ ‹_› _ _ ‹_› _ _ _ _ ‹_› _ _ _ hs _
hmono
lemma integrable_on_compact_of_monotone (hmono : monotone f) :
integrable_on f s μ :=
integrable_on_compact_of_monotone_on hs (λ x y _ _ hxy, hmono hxy)
alias integrable_on_compact_of_monotone ← monotone.integrable_on_compact
lemma integrable_on_compact_of_antimono (hmono : ∀ ⦃x y⦄, x ≤ y → f y ≤ f x) :
integrable_on f s μ :=
@integrable_on_compact_of_monotone α (order_dual E) _ _ ‹_› _ _ ‹_› _ _ _ _ ‹_› _ _ _ hs _
hmono
end monotone
|
930b9284025e74e72adc0019a65c024d4c6bd7b3 | 07c6143268cfb72beccd1cc35735d424ebcb187b | /src/category_theory/limits/opposites.lean | 1086ce57c8d505c3aebd3822d855e872f60afb72 | [
"Apache-2.0"
] | permissive | khoek/mathlib | bc49a842910af13a3c372748310e86467d1dc766 | aa55f8b50354b3e11ba64792dcb06cccb2d8ee28 | refs/heads/master | 1,588,232,063,837 | 1,587,304,803,000 | 1,587,304,803,000 | 176,688,517 | 0 | 0 | Apache-2.0 | 1,553,070,585,000 | 1,553,070,585,000 | null | UTF-8 | Lean | false | false | 3,666 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Floris van Doorn
-/
import category_theory.limits.limits category_theory.discrete_category
universes v u
open category_theory
open category_theory.functor
open opposite
namespace category_theory.limits
variables {C : Type u} [𝒞 : category.{v} C]
include 𝒞
variables {J : Type v} [small_category J]
variable (F : J ⥤ Cᵒᵖ)
instance has_limit_of_has_colimit_left_op [has_colimit.{v} F.left_op] : has_limit.{v} F :=
{ cone := cone_of_cocone_left_op (colimit.cocone F.left_op),
is_limit :=
{ lift := λ s, (colimit.desc F.left_op (cocone_left_op_of_cone s)).op,
fac' := λ s j,
begin
rw [cone_of_cocone_left_op_π_app, colimit.cocone_ι, ←op_comp,
colimit.ι_desc, cocone_left_op_of_cone_ι_app, has_hom.hom.op_unop],
refl, end,
uniq' := λ s m w,
begin
-- It's a pity we can't do this automatically.
-- Usually something like this would work by limit.hom_ext,
-- but the opposites get in the way of this firing.
have u := (colimit.is_colimit F.left_op).uniq (cocone_left_op_of_cone s) (m.unop),
convert congr_arg (λ f : _ ⟶ _, f.op) (u _), clear u,
intro j,
rw [cocone_left_op_of_cone_ι_app, colimit.cocone_ι],
convert congr_arg (λ f : _ ⟶ _, f.unop) (w (unop j)), clear w,
rw [cone_of_cocone_left_op_π_app, colimit.cocone_ι, has_hom.hom.unop_op],
refl,
end } }
instance has_limits_of_shape_op_of_has_colimits_of_shape [has_colimits_of_shape.{v} Jᵒᵖ C] :
has_limits_of_shape.{v} J Cᵒᵖ :=
{ has_limit := λ F, by apply_instance }
instance has_limits_op_of_has_colimits [has_colimits.{v} C] : has_limits.{v} Cᵒᵖ :=
{ has_limits_of_shape := λ J 𝒥, by { resetI, apply_instance } }
instance has_colimit_of_has_limit_left_op [has_limit.{v} F.left_op] : has_colimit.{v} F :=
{ cocone := cocone_of_cone_left_op (limit.cone F.left_op),
is_colimit :=
{ desc := λ s, (limit.lift F.left_op (cone_left_op_of_cocone s)).op,
fac' := λ s j,
begin
rw [cocone_of_cone_left_op_ι_app, limit.cone_π, ←op_comp,
limit.lift_π, cone_left_op_of_cocone_π_app, has_hom.hom.op_unop],
refl, end,
uniq' := λ s m w,
begin
have u := (limit.is_limit F.left_op).uniq (cone_left_op_of_cocone s) (m.unop),
convert congr_arg (λ f : _ ⟶ _, f.op) (u _), clear u,
intro j,
rw [cone_left_op_of_cocone_π_app, limit.cone_π],
convert congr_arg (λ f : _ ⟶ _, f.unop) (w (unop j)), clear w,
rw [cocone_of_cone_left_op_ι_app, limit.cone_π, has_hom.hom.unop_op],
refl,
end } }
instance has_colimits_of_shape_op_of_has_limits_of_shape [has_limits_of_shape.{v} Jᵒᵖ C] :
has_colimits_of_shape.{v} J Cᵒᵖ :=
{ has_colimit := λ F, by apply_instance }
instance has_colimits_op_of_has_limits [has_limits.{v} C] : has_colimits.{v} Cᵒᵖ :=
{ has_colimits_of_shape := λ J 𝒥, by { resetI, apply_instance } }
variables (X : Type v)
instance has_coproducts_opposite [has_limits_of_shape (discrete X) C] :
has_colimits_of_shape (discrete X) Cᵒᵖ :=
begin
haveI : has_limits_of_shape (discrete X)ᵒᵖ C :=
has_limits_of_shape_of_equivalence (discrete.opposite X).symm, apply_instance
end
instance has_products_opposite [has_colimits_of_shape (discrete X) C] :
has_limits_of_shape (discrete X) Cᵒᵖ :=
begin
haveI : has_colimits_of_shape (discrete X)ᵒᵖ C :=
has_colimits_of_shape_of_equivalence (discrete.opposite X).symm, apply_instance
end
end category_theory.limits
|
b7acbd32d3f6b432e49dea268615f42170a28fb8 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/algebraic_topology/dold_kan/projections.lean | 2439974a9359a3d4078fd37747d442ab4537b5f2 | [
"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 | 7,063 | lean | /-
Copyright (c) 2022 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import algebraic_topology.dold_kan.faces
import category_theory.idempotents.basic
/-!
# Construction of projections for the Dold-Kan correspondence
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
TODO (@joelriou) continue adding the various files referenced below
In this file, we construct endomorphisms `P q : K[X] ⟶ K[X]` for all
`q : ℕ`. We study how they behave with respect to face maps with the lemmas
`higher_faces_vanish.of_P`, `higher_faces_vanish.comp_P_eq_self` and
`comp_P_eq_self_iff`.
Then, we show that they are projections (see `P_f_idem`
and `P_idem`). They are natural transformations (see `nat_trans_P`
and `P_f_naturality`) and are compatible with the application
of additive functors (see `map_P`).
By passing to the limit, these endomorphisms `P q` shall be used in `p_infty.lean`
in order to define `P_infty : K[X] ⟶ K[X]`, see `equivalence.lean` for the general
strategy of proof of the Dold-Kan equivalence.
-/
open category_theory category_theory.category category_theory.limits
category_theory.preadditive category_theory.simplicial_object opposite
category_theory.idempotents
open_locale simplicial dold_kan
noncomputable theory
namespace algebraic_topology
namespace dold_kan
variables {C : Type*} [category C] [preadditive C] {X : simplicial_object C}
/-- This is the inductive definition of the projections `P q : K[X] ⟶ K[X]`,
with `P 0 := 𝟙 _` and `P (q+1) := P q ≫ (𝟙 _ + Hσ q)`. -/
noncomputable def P : ℕ → (K[X] ⟶ K[X])
| 0 := 𝟙 _
| (q+1) := P q ≫ (𝟙 _ + Hσ q)
/-- All the `P q` coincide with `𝟙 _` in degree 0. -/
@[simp]
lemma P_f_0_eq (q : ℕ) : ((P q).f 0 : X _[0] ⟶ X _[0]) = 𝟙 _ :=
begin
induction q with q hq,
{ refl, },
{ unfold P,
simp only [homological_complex.add_f_apply, homological_complex.comp_f,
homological_complex.id_f, id_comp, hq, Hσ_eq_zero, add_zero], },
end
/-- `Q q` is the complement projection associated to `P q` -/
def Q (q : ℕ) : K[X] ⟶ K[X] := 𝟙 _ - P q
lemma P_add_Q (q : ℕ) : P q + Q q = 𝟙 K[X] := by { rw Q, abel, }
lemma P_add_Q_f (q n : ℕ) : (P q).f n + (Q q).f n = 𝟙 (X _[n]) :=
homological_complex.congr_hom (P_add_Q q) n
@[simp]
lemma Q_eq_zero : (Q 0 : K[X] ⟶ _) = 0 := sub_self _
lemma Q_eq (q : ℕ) : (Q (q+1) : K[X] ⟶ _) = Q q - P q ≫ Hσ q :=
by { unfold Q P, simp only [comp_add, comp_id], abel, }
/-- All the `Q q` coincide with `0` in degree 0. -/
@[simp]
lemma Q_f_0_eq (q : ℕ) : ((Q q).f 0 : X _[0] ⟶ X _[0]) = 0 :=
by simp only [homological_complex.sub_f_apply, homological_complex.id_f, Q, P_f_0_eq, sub_self]
namespace higher_faces_vanish
/-- This lemma expresses the vanishing of
`(P q).f (n+1) ≫ X.δ k : X _[n+1] ⟶ X _[n]` when `k≠0` and `k≥n-q+2` -/
lemma of_P : Π (q n : ℕ), higher_faces_vanish q (((P q).f (n+1) : X _[n+1] ⟶ X _[n+1]))
| 0 := λ n j hj₁, by { exfalso, have hj₂ := fin.is_lt j, linarith, }
| (q+1) := λ n, by { unfold P, exact (of_P q n).induction, }
@[reassoc]
lemma comp_P_eq_self {Y : C} {n q : ℕ} {φ : Y ⟶ X _[n+1]}
(v : higher_faces_vanish q φ) : φ ≫ (P q).f (n+1) = φ :=
begin
induction q with q hq,
{ unfold P,
apply comp_id, },
{ unfold P,
simp only [comp_add, homological_complex.comp_f, homological_complex.add_f_apply,
comp_id, ← assoc, hq v.of_succ, add_right_eq_self],
by_cases hqn : n<q,
{ exact v.of_succ.comp_Hσ_eq_zero hqn, },
{ cases nat.le.dest (not_lt.mp hqn) with a ha,
have hnaq : n=a+q := by linarith,
simp only [v.of_succ.comp_Hσ_eq hnaq, neg_eq_zero, ← assoc],
have eq := v ⟨a, by linarith⟩
(by simp only [hnaq, fin.coe_mk, nat.succ_eq_add_one, add_assoc]),
simp only [fin.succ_mk] at eq,
simp only [eq, zero_comp], }, },
end
end higher_faces_vanish
lemma comp_P_eq_self_iff {Y : C} {n q : ℕ} {φ : Y ⟶ X _[n+1]} :
φ ≫ (P q).f (n+1) = φ ↔ higher_faces_vanish q φ :=
begin
split,
{ intro hφ,
rw ← hφ,
apply higher_faces_vanish.of_comp,
apply higher_faces_vanish.of_P, },
{ exact higher_faces_vanish.comp_P_eq_self, },
end
@[simp, reassoc]
lemma P_f_idem (q n : ℕ) :
((P q).f n : X _[n] ⟶ _) ≫ ((P q).f n) = (P q).f n :=
begin
cases n,
{ rw [P_f_0_eq q, comp_id], },
{ exact (higher_faces_vanish.of_P q n).comp_P_eq_self, }
end
@[simp, reassoc]
lemma Q_f_idem (q n : ℕ) :
((Q q).f n : X _[n] ⟶ _) ≫ ((Q q).f n) = (Q q).f n :=
idem_of_id_sub_idem _ (P_f_idem q n)
@[simp, reassoc]
lemma P_idem (q : ℕ) : (P q : K[X] ⟶ K[X]) ≫ P q = P q :=
by { ext n, exact P_f_idem q n, }
@[simp, reassoc]
lemma Q_idem (q : ℕ) : (Q q : K[X] ⟶ K[X]) ≫ Q q = Q q :=
by { ext n, exact Q_f_idem q n, }
/-- For each `q`, `P q` is a natural transformation. -/
@[simps]
def nat_trans_P (q : ℕ) :
alternating_face_map_complex C ⟶ alternating_face_map_complex C :=
{ app := λ X, P q,
naturality' := λ X Y f, begin
induction q with q hq,
{ unfold P,
dsimp only [alternating_face_map_complex],
rw [id_comp, comp_id], },
{ unfold P,
simp only [add_comp, comp_add, assoc, comp_id, hq],
congr' 1,
rw [← assoc, hq, assoc],
congr' 1,
exact (nat_trans_Hσ q).naturality' f, }
end }
@[simp, reassoc]
lemma P_f_naturality (q n : ℕ) {X Y : simplicial_object C} (f : X ⟶ Y) :
f.app (op [n]) ≫ (P q).f n = (P q).f n ≫ f.app (op [n]) :=
homological_complex.congr_hom ((nat_trans_P q).naturality f) n
@[simp, reassoc]
lemma Q_f_naturality (q n : ℕ) {X Y : simplicial_object C} (f : X ⟶ Y) :
f.app (op [n]) ≫ (Q q).f n = (Q q).f n ≫ f.app (op [n]) :=
begin
simp only [Q, homological_complex.sub_f_apply, homological_complex.id_f,
comp_sub, P_f_naturality, sub_comp, sub_left_inj],
dsimp,
simp only [comp_id, id_comp],
end
/-- For each `q`, `Q q` is a natural transformation. -/
@[simps]
def nat_trans_Q (q : ℕ) :
alternating_face_map_complex C ⟶ alternating_face_map_complex C :=
{ app := λ X, Q q, }
lemma map_P {D : Type*} [category D] [preadditive D]
(G : C ⥤ D) [G.additive] (X : simplicial_object C) (q n : ℕ) :
G.map ((P q : K[X] ⟶ _).f n) = (P q : K[((whiskering C D).obj G).obj X] ⟶ _).f n :=
begin
induction q with q hq,
{ unfold P,
apply G.map_id, },
{ unfold P,
simp only [comp_add, homological_complex.comp_f, homological_complex.add_f_apply,
comp_id, functor.map_add, functor.map_comp, hq, map_Hσ], }
end
lemma map_Q {D : Type*} [category D] [preadditive D]
(G : C ⥤ D) [G.additive] (X : simplicial_object C) (q n : ℕ) :
G.map ((Q q : K[X] ⟶ _).f n) = (Q q : K[((whiskering C D).obj G).obj X] ⟶ _).f n :=
begin
rw [← add_right_inj (G.map ((P q : K[X] ⟶ _).f n)), ← G.map_add, map_P G X q n,
P_add_Q_f, P_add_Q_f],
apply G.map_id,
end
end dold_kan
end algebraic_topology
|
5857609180307e8e2682d1e3020e3477c13e3f5c | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/analysis/convex/extreme.lean | 269b955bd292ce475dd15199de4dc8e7fd635e23 | [
"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 | 9,581 | lean | /-
Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Bhavik Mehta
-/
import analysis.convex.hull
/-!
# Extreme sets
This file defines extreme sets and extreme points for sets in a module.
An extreme set of `A` is a subset of `A` that is as far as it can get in any outward direction: If
point `x` is in it and point `y ∈ A`, then the line passing through `x` and `y` leaves `A` at `x`.
This is an analytic notion of "being on the side of". It is weaker than being exposed (see
`is_exposed.is_extreme`).
## Main declarations
* `is_extreme 𝕜 A B`: States that `B` is an extreme set of `A` (in the literature, `A` is often
implicit).
* `set.extreme_points 𝕜 A`: Set of extreme points of `A` (corresponding to extreme singletons).
* `convex.mem_extreme_points_iff_convex_diff`: A useful equivalent condition to being an extreme
point: `x` is an extreme point iff `A \ {x}` is convex.
## Implementation notes
The exact definition of extremeness has been carefully chosen so as to make as many lemmas
unconditional (in particular, the Krein-Milman theorem doesn't need the set to be convex!).
In practice, `A` is often assumed to be a convex set.
## References
See chapter 8 of [Barry Simon, *Convexity*][simon2011]
## TODO
Define intrinsic frontier and prove lemmas related to extreme sets and points.
More not-yet-PRed stuff is available on the branch `sperner_again`.
-/
open_locale classical affine
open set
variables (𝕜 : Type*) {E : Type*}
section has_scalar
variables [ordered_semiring 𝕜] [add_comm_monoid E] [has_scalar 𝕜 E]
/-- A set `B` is an extreme subset of `A` if `B ⊆ A` and all points of `B` only belong to open
segments whose ends are in `B`. -/
def is_extreme (A B : set E) : Prop :=
B ⊆ A ∧ ∀ x₁ x₂ ∈ A, ∀ x ∈ B, x ∈ open_segment 𝕜 x₁ x₂ → x₁ ∈ B ∧ x₂ ∈ B
/-- A point `x` is an extreme point of a set `A` if `x` belongs to no open segment with ends in
`A`, except for the obvious `open_segment x x`. -/
def set.extreme_points (A : set E) : set E :=
{x ∈ A | ∀ (x₁ x₂ ∈ A), x ∈ open_segment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x}
@[refl] protected lemma is_extreme.refl (A : set E) :
is_extreme 𝕜 A A :=
⟨subset.rfl, λ x₁ hx₁A x₂ hx₂A x hxA hx, ⟨hx₁A, hx₂A⟩⟩
variables {𝕜} {A B C : set E} {x : E}
protected lemma is_extreme.rfl :
is_extreme 𝕜 A A :=
is_extreme.refl 𝕜 A
@[trans] protected lemma is_extreme.trans (hAB : is_extreme 𝕜 A B) (hBC : is_extreme 𝕜 B C) :
is_extreme 𝕜 A C :=
begin
use subset.trans hBC.1 hAB.1,
rintro x₁ hx₁A x₂ hx₂A x hxC hx,
obtain ⟨hx₁B, hx₂B⟩ := hAB.2 x₁ hx₁A x₂ hx₂A x (hBC.1 hxC) hx,
exact hBC.2 x₁ hx₁B x₂ hx₂B x hxC hx,
end
protected lemma is_extreme.antisymm :
anti_symmetric (is_extreme 𝕜 : set E → set E → Prop) :=
λ A B hAB hBA, subset.antisymm hBA.1 hAB.1
instance : is_partial_order (set E) (is_extreme 𝕜) :=
{ refl := is_extreme.refl 𝕜,
trans := λ A B C, is_extreme.trans,
antisymm := is_extreme.antisymm }
lemma is_extreme.inter (hAB : is_extreme 𝕜 A B) (hAC : is_extreme 𝕜 A C) :
is_extreme 𝕜 A (B ∩ C) :=
begin
use subset.trans (inter_subset_left _ _) hAB.1,
rintro x₁ x₂ hx₁A hx₂A x ⟨hxB, hxC⟩ hx,
obtain ⟨hx₁B, hx₂B⟩ := hAB.2 x₁ x₂ hx₁A hx₂A x hxB hx,
obtain ⟨hx₁C, hx₂C⟩ := hAC.2 x₁ x₂ hx₁A hx₂A x hxC hx,
exact ⟨⟨hx₁B, hx₁C⟩, hx₂B, hx₂C⟩,
end
protected lemma is_extreme.mono (hAC : is_extreme 𝕜 A C) (hBA : B ⊆ A) (hCB : C ⊆ B) :
is_extreme 𝕜 B C :=
⟨hCB, λ x₁ hx₁B x₂ hx₂B x hxC hx, hAC.2 x₁ (hBA hx₁B) x₂ (hBA hx₂B) x hxC hx⟩
lemma is_extreme_Inter {ι : Type*} [nonempty ι] {F : ι → set E}
(hAF : ∀ i : ι, is_extreme 𝕜 A (F i)) :
is_extreme 𝕜 A (⋂ i : ι, F i) :=
begin
obtain i := classical.arbitrary ι,
use Inter_subset_of_subset i (hAF i).1,
rintro x₁ x₂ hx₁A hx₂A x hxF hx,
simp_rw mem_Inter at ⊢ hxF,
have h := λ i, (hAF i).2 x₁ x₂ hx₁A hx₂A x (hxF i) hx,
exact ⟨λ i, (h i).1, λ i, (h i).2⟩,
end
lemma is_extreme_bInter {F : set (set E)} (hF : F.nonempty)
(hAF : ∀ B ∈ F, is_extreme 𝕜 A B) :
is_extreme 𝕜 A (⋂ B ∈ F, B) :=
begin
obtain ⟨B, hB⟩ := hF,
refine ⟨(bInter_subset_of_mem hB).trans (hAF B hB).1, λ x₁ x₂ hx₁A hx₂A x hxF hx, _⟩,
simp_rw mem_Inter₂ at ⊢ hxF,
have h := λ B hB, (hAF B hB).2 x₁ x₂ hx₁A hx₂A x (hxF B hB) hx,
exact ⟨λ B hB, (h B hB).1, λ B hB, (h B hB).2⟩,
end
lemma is_extreme_sInter {F : set (set E)} (hF : F.nonempty)
(hAF : ∀ B ∈ F, is_extreme 𝕜 A B) :
is_extreme 𝕜 A (⋂₀ F) :=
begin
obtain ⟨B, hB⟩ := hF,
refine ⟨(sInter_subset_of_mem hB).trans (hAF B hB).1, λ x₁ x₂ hx₁A hx₂A x hxF hx, _⟩,
simp_rw mem_sInter at ⊢ hxF,
have h := λ B hB, (hAF B hB).2 x₁ x₂ hx₁A hx₂A x (hxF B hB) hx,
exact ⟨λ B hB, (h B hB).1, λ B hB, (h B hB).2⟩,
end
lemma extreme_points_def :
x ∈ A.extreme_points 𝕜 ↔ x ∈ A ∧ ∀ (x₁ x₂ ∈ A), x ∈ open_segment 𝕜 x₁ x₂ → x₁ = x ∧ x₂ = x :=
iff.rfl
/-- x is an extreme point to A iff {x} is an extreme set of A. -/
lemma mem_extreme_points_iff_extreme_singleton :
x ∈ A.extreme_points 𝕜 ↔ is_extreme 𝕜 A {x} :=
begin
refine ⟨_, λ hx, ⟨singleton_subset_iff.1 hx.1, λ x₁ x₂ hx₁ hx₂, hx.2 x₁ x₂ hx₁ hx₂ x rfl⟩⟩,
rintro ⟨hxA, hAx⟩,
use singleton_subset_iff.2 hxA,
rintro x₁ x₂ hx₁A hx₂A y (rfl : y = x),
exact hAx x₁ x₂ hx₁A hx₂A,
end
lemma extreme_points_subset : A.extreme_points 𝕜 ⊆ A := λ x hx, hx.1
@[simp] lemma extreme_points_empty :
(∅ : set E).extreme_points 𝕜 = ∅ :=
subset_empty_iff.1 extreme_points_subset
@[simp] lemma extreme_points_singleton :
({x} : set E).extreme_points 𝕜 = {x} :=
extreme_points_subset.antisymm $ singleton_subset_iff.2
⟨mem_singleton x, λ x₁ hx₁ x₂ hx₂ _, ⟨hx₁, hx₂⟩⟩
lemma inter_extreme_points_subset_extreme_points_of_subset (hBA : B ⊆ A) :
B ∩ A.extreme_points 𝕜 ⊆ B.extreme_points 𝕜 :=
λ x ⟨hxB, hxA⟩, ⟨hxB, λ x₁ hx₁ x₂ hx₂ hx, hxA.2 x₁ (hBA hx₁) x₂ (hBA hx₂) hx⟩
lemma is_extreme.extreme_points_subset_extreme_points (hAB : is_extreme 𝕜 A B) :
B.extreme_points 𝕜 ⊆ A.extreme_points 𝕜 :=
λ x hx, mem_extreme_points_iff_extreme_singleton.2 (hAB.trans
(mem_extreme_points_iff_extreme_singleton.1 hx))
lemma is_extreme.extreme_points_eq (hAB : is_extreme 𝕜 A B) :
B.extreme_points 𝕜 = B ∩ A.extreme_points 𝕜 :=
subset.antisymm (λ x hx, ⟨hx.1, hAB.extreme_points_subset_extreme_points hx⟩)
(inter_extreme_points_subset_extreme_points_of_subset hAB.1)
end has_scalar
section ordered_semiring
variables {𝕜} [ordered_semiring 𝕜] [add_comm_group E] [module 𝕜 E] {A B : set E} {x : E}
lemma is_extreme.convex_diff (hA : convex 𝕜 A) (hAB : is_extreme 𝕜 A B) :
convex 𝕜 (A \ B) :=
convex_iff_open_segment_subset.2 (λ x₁ x₂ ⟨hx₁A, hx₁B⟩ ⟨hx₂A, hx₂B⟩ x hx,
⟨hA.open_segment_subset hx₁A hx₂A hx, λ hxB, hx₁B (hAB.2 x₁ hx₁A x₂ hx₂A x hxB hx).1⟩)
end ordered_semiring
section linear_ordered_field
variables {𝕜} [linear_ordered_field 𝕜] [add_comm_group E] [module 𝕜 E] {A B : set E} {x : E}
/-- A useful restatement using `segment`: `x` is an extreme point iff the only (closed) segments
that contain it are those with `x` as one of their endpoints. -/
lemma mem_extreme_points_iff_forall_segment [no_zero_smul_divisors 𝕜 E] :
x ∈ A.extreme_points 𝕜 ↔ x ∈ A ∧ ∀ (x₁ x₂ ∈ A), x ∈ segment 𝕜 x₁ x₂ → x₁ = x ∨ x₂ = x :=
begin
split,
{ rintro ⟨hxA, hAx⟩,
use hxA,
rintro x₁ hx₁ x₂ hx₂ hx,
by_contra' h,
exact h.1 (hAx _ hx₁ _ hx₂ (mem_open_segment_of_ne_left_right 𝕜 h.1 h.2 hx)).1 },
rintro ⟨hxA, hAx⟩,
use hxA,
rintro x₁ x₂ hx₁ hx₂ hx,
obtain rfl | rfl := hAx x₁ x₂ hx₁ hx₂ (open_segment_subset_segment 𝕜 _ _ hx),
{ exact ⟨rfl, (left_mem_open_segment_iff.1 hx).symm⟩ },
exact ⟨right_mem_open_segment_iff.1 hx, rfl⟩,
end
lemma convex.mem_extreme_points_iff_convex_diff (hA : convex 𝕜 A) :
x ∈ A.extreme_points 𝕜 ↔ x ∈ A ∧ convex 𝕜 (A \ {x}) :=
begin
use λ hx, ⟨hx.1, (mem_extreme_points_iff_extreme_singleton.1 hx).convex_diff hA⟩,
rintro ⟨hxA, hAx⟩,
refine mem_extreme_points_iff_forall_segment.2 ⟨hxA, λ x₁ hx₁ x₂ hx₂ hx, _⟩,
rw convex_iff_segment_subset at hAx,
by_contra' h,
exact (hAx ⟨hx₁, λ hx₁, h.1 (mem_singleton_iff.2 hx₁)⟩
⟨hx₂, λ hx₂, h.2 (mem_singleton_iff.2 hx₂)⟩ hx).2 rfl,
end
lemma convex.mem_extreme_points_iff_mem_diff_convex_hull_diff (hA : convex 𝕜 A) :
x ∈ A.extreme_points 𝕜 ↔ x ∈ A \ convex_hull 𝕜 (A \ {x}) :=
by rw [hA.mem_extreme_points_iff_convex_diff, hA.convex_remove_iff_not_mem_convex_hull_remove,
mem_diff]
lemma extreme_points_convex_hull_subset :
(convex_hull 𝕜 A).extreme_points 𝕜 ⊆ A :=
begin
rintro x hx,
rw (convex_convex_hull 𝕜 _).mem_extreme_points_iff_convex_diff at hx,
by_contra,
exact (convex_hull_min (subset_diff.2 ⟨subset_convex_hull 𝕜 _, disjoint_singleton_right.2 h⟩) hx.2
hx.1).2 rfl,
end
end linear_ordered_field
|
32705e60902e011b3875166e3f560e5a68f0f983 | 5fbbd711f9bfc21ee168f46a4be146603ece8835 | /lean/natural_number_game/proposition/4.lean | a7d385623ebb7a410b7b872d57cad7a2f79aaa48 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | goedel-gang/maths | 22596f71e3fde9c088e59931f128a3b5efb73a2c | a20a6f6a8ce800427afd595c598a5ad43da1408d | refs/heads/master | 1,623,055,941,960 | 1,621,599,441,000 | 1,621,599,441,000 | 169,335,840 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 143 | lean | lemma maze (P Q R S T U: Prop)
(p : P)
(h : P → Q)
(i : Q → R)
(j : Q → T)
(k : S → T)
(l : T → U)
: U :=
begin
cc, -- whatevs
end
|
3ea26549ccae6abd6a57357a7e1af6b3088fbb77 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/list/chain.lean | 1bd5fa52aa60c7038ea080832c00fb6675443828 | [
"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 | 15,051 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kenny Lau, Yury Kudryashov
-/
import data.list.pairwise
import logic.relation
/-!
# Relation chain
This file provides basic results about `list.chain` (definition in `data.list.defs`).
A list `[a₂, ..., aₙ]` is a `chain` starting at `a₁` with respect to the relation `r` if `r a₁ a₂`
and `r a₂ a₃` and ... and `r aₙ₋₁ aₙ`. We write it `chain r a₁ [a₂, ..., aₙ]`.
A graph-specialized version is in development and will hopefully be added under `combinatorics.`
sometime soon.
-/
universes u v
open nat
namespace list
variables {α : Type u} {β : Type v} {R r : α → α → Prop} {l l₁ l₂ : list α} {a b : α}
mk_iff_of_inductive_prop list.chain list.chain_iff
theorem rel_of_chain_cons {a b : α} {l : list α}
(p : chain R a (b :: l)) : R a b :=
(chain_cons.1 p).1
theorem chain_of_chain_cons {a b : α} {l : list α}
(p : chain R a (b :: l)) : chain R b l :=
(chain_cons.1 p).2
theorem chain.imp' {S : α → α → Prop}
(HRS : ∀ ⦃a b⦄, R a b → S a b) {a b : α} (Hab : ∀ ⦃c⦄, R a c → S b c)
{l : list α} (p : chain R a l) : chain S b l :=
by induction p with _ a c l r p IH generalizing b; constructor;
[exact Hab r, exact IH (@HRS _)]
theorem chain.imp {S : α → α → Prop}
(H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l :=
p.imp' H (H a)
theorem chain.iff {S : α → α → Prop}
(H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l :=
⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩
theorem chain.iff_mem {a : α} {l : list α} :
chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l :=
⟨λ p, by induction p with _ a b l r p IH; constructor;
[exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩,
exact IH.imp (λ a b ⟨am, bm, h⟩,
⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)],
chain.imp (λ a b h, h.2.2)⟩
theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b :=
by simp only [chain_cons, chain.nil, and_true]
theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁ ++ b :: l₂) ↔
chain R a (l₁ ++ [b]) ∧ chain R b l₂ :=
by induction l₁ with x l₁ IH generalizing a;
simp only [*, nil_append, cons_append, chain.nil, chain_cons, and_true, and_assoc]
@[simp] theorem chain_append_cons_cons {a b c : α} {l₁ l₂ : list α} :
chain R a (l₁ ++ b :: c :: l₂) ↔ chain R a (l₁ ++ [b]) ∧ R b c ∧ chain R c l₂ :=
by rw [chain_split, chain_cons]
theorem chain_iff_forall₂ :
∀ {a : α} {l : list α}, chain R a l ↔ l = [] ∨ forall₂ R (a :: init l) l
| a [] := by simp
| a [b] := by simp [init]
| a (b :: c :: l) := by simp [@chain_iff_forall₂ b]
theorem chain_append_singleton_iff_forall₂ :
chain R a (l ++ [b]) ↔ forall₂ R (a :: l) (l ++ [b]) :=
by simp [chain_iff_forall₂, init]
theorem chain_map (f : β → α) {b : β} {l : list β} :
chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l :=
by induction l generalizing b; simp only [map, chain.nil, chain_cons, *]
theorem chain_of_chain_map {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α}
(p : chain S (f a) (map f l)) : chain R a l :=
((chain_map f).1 p).imp H
theorem chain_map_of_chain {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α}
(p : chain R a l) : chain S (f a) (map f l) :=
(chain_map f).2 $ p.imp H
theorem chain_pmap_of_chain {S : β → β → Prop} {p : α → Prop}
{f : Π a, p a → β}
(H : ∀ a b ha hb, R a b → S (f a ha) (f b hb))
{a : α} {l : list α}
(hl₁ : chain R a l) (ha : p a) (hl₂ : ∀ a ∈ l, p a) :
chain S (f a ha) (list.pmap f l hl₂) :=
begin
induction l with lh lt l_ih generalizing a,
{ simp },
{ simp [H _ _ _ _ (rel_of_chain_cons hl₁), l_ih _ (chain_of_chain_cons hl₁)] }
end
theorem chain_of_chain_pmap {S : β → β → Prop} {p : α → Prop}
(f : Π a, p a → β) {l : list α} (hl₁ : ∀ a ∈ l, p a)
{a : α} (ha : p a) (hl₂ : chain S (f a ha) (list.pmap f l hl₁))
(H : ∀ a b ha hb, S (f a ha) (f b hb) → R a b) :
chain R a l :=
begin
induction l with lh lt l_ih generalizing a,
{ simp },
{ simp [H _ _ _ _ (rel_of_chain_cons hl₂), l_ih _ _ (chain_of_chain_cons hl₂)] }
end
protected lemma pairwise.chain (p : pairwise R (a :: l)) : chain R a l :=
begin
cases pairwise_cons.1 p with r p', clear p,
induction p' with b l r' p IH generalizing a, {exact chain.nil},
simp only [chain_cons, forall_mem_cons] at r,
exact chain_cons.2 ⟨r.1, IH r'⟩
end
protected lemma chain.pairwise [is_trans α R] :
∀ {a : α} {l : list α}, chain R a l → pairwise R (a :: l)
| a [] chain.nil := pairwise_singleton _ _
| a _ (@chain.cons _ _ _ b l h hb) := hb.pairwise.cons begin
simp only [mem_cons_iff, forall_eq_or_imp, h, true_and],
exact λ c hc, trans h (rel_of_pairwise_cons hb.pairwise hc),
end
theorem chain_iff_pairwise [is_trans α R] {a : α} {l : list α} :
chain R a l ↔ pairwise R (a :: l) :=
⟨chain.pairwise, pairwise.chain⟩
protected lemma chain.sublist [is_trans α R] (hl : l₂.chain R a) (h : l₁ <+ l₂) : l₁.chain R a :=
by { rw chain_iff_pairwise at ⊢ hl, exact hl.sublist (h.cons_cons a) }
protected lemma chain.rel [is_trans α R] (hl : l.chain R a) (hb : b ∈ l) : R a b :=
by { rw chain_iff_pairwise at hl, exact rel_of_pairwise_cons hl hb }
theorem chain_iff_nth_le {R} : ∀ {a : α} {l : list α},
chain R a l ↔ (∀ h : 0 < length l, R a (nth_le l 0 h)) ∧ (∀ i (h : i < length l - 1),
R (nth_le l i (lt_of_lt_pred h)) (nth_le l (i+1) (lt_pred_iff.mp h)))
| a [] := by simp
| a (b :: t) :=
begin
rw [chain_cons, chain_iff_nth_le],
split,
{ rintro ⟨R, ⟨h0, h⟩⟩,
split,
{ intro w, exact R },
intros i w,
cases i,
{ apply h0 },
convert h i _ using 1,
simp only [succ_eq_add_one, add_succ_sub_one, add_zero, length, add_lt_add_iff_right] at w,
exact lt_pred_iff.mpr w, },
rintro ⟨h0, h⟩, split,
{ apply h0, simp, },
split,
{ apply h 0, },
intros i w, convert h (i+1) _ using 1,
exact lt_pred_iff.mp w,
end
theorem chain'.imp {S : α → α → Prop}
(H : ∀ a b, R a b → S a b) {l : list α} (p : chain' R l) : chain' S l :=
by cases l; [trivial, exact p.imp H]
theorem chain'.iff {S : α → α → Prop}
(H : ∀ a b, R a b ↔ S a b) {l : list α} : chain' R l ↔ chain' S l :=
⟨chain'.imp (λ a b, (H a b).1), chain'.imp (λ a b, (H a b).2)⟩
theorem chain'.iff_mem : ∀ {l : list α}, chain' R l ↔ chain' (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l
| [] := iff.rfl
| (x :: l) :=
⟨λ h, (chain.iff_mem.1 h).imp $ λ a b ⟨h₁, h₂, h₃⟩, ⟨h₁, or.inr h₂, h₃⟩,
chain'.imp $ λ a b h, h.2.2⟩
@[simp] theorem chain'_nil : chain' R [] := trivial
@[simp] theorem chain'_singleton (a : α) : chain' R [a] := chain.nil
@[simp] theorem chain'_cons {x y l} : chain' R (x :: y :: l) ↔ R x y ∧ chain' R (y :: l) :=
chain_cons
theorem chain'_is_infix : ∀ l : list α, chain' (λ x y, [x, y] <:+: l) l
| [] := chain'_nil
| [a] := chain'_singleton _
| (a::b::l) := chain'_cons.2 ⟨⟨[], l, by simp⟩,
(chain'_is_infix (b::l)).imp $ λ x y h, h.trans ⟨[a], [], by simp⟩⟩
theorem chain'_split {a : α} : ∀ {l₁ l₂ : list α}, chain' R (l₁ ++ a :: l₂) ↔
chain' R (l₁ ++ [a]) ∧ chain' R (a :: l₂)
| [] l₂ := (and_iff_right (chain'_singleton a)).symm
| (b :: l₁) l₂ := chain_split
@[simp] theorem chain'_append_cons_cons {b c : α} {l₁ l₂ : list α} :
chain' R (l₁ ++ b :: c :: l₂) ↔ chain' R (l₁ ++ [b]) ∧ R b c ∧ chain' R (c :: l₂) :=
by rw [chain'_split, chain'_cons]
theorem chain'_map (f : β → α) {l : list β} :
chain' R (map f l) ↔ chain' (λ a b : β, R (f a) (f b)) l :=
by cases l; [refl, exact chain_map _]
theorem chain'_of_chain'_map {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α}
(p : chain' S (map f l)) : chain' R l :=
((chain'_map f).1 p).imp H
theorem chain'_map_of_chain' {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α}
(p : chain' R l) : chain' S (map f l) :=
(chain'_map f).2 $ p.imp H
theorem pairwise.chain' : ∀ {l : list α}, pairwise R l → chain' R l
| [] _ := trivial
| (a :: l) h := pairwise.chain h
theorem chain'_iff_pairwise [is_trans α R] : ∀ {l : list α},
chain' R l ↔ pairwise R l
| [] := (iff_true_intro pairwise.nil).symm
| (a :: l) := chain_iff_pairwise
protected lemma chain'.sublist [is_trans α R] (hl : l₂.chain' R) (h : l₁ <+ l₂) : l₁.chain' R :=
by { rw chain'_iff_pairwise at ⊢ hl, exact hl.sublist h }
theorem chain'.cons {x y l} (h₁ : R x y) (h₂ : chain' R (y :: l)) :
chain' R (x :: y :: l) :=
chain'_cons.2 ⟨h₁, h₂⟩
theorem chain'.tail : ∀ {l} (h : chain' R l), chain' R l.tail
| [] _ := trivial
| [x] _ := trivial
| (x :: y :: l) h := (chain'_cons.mp h).right
theorem chain'.rel_head {x y l} (h : chain' R (x :: y :: l)) : R x y :=
rel_of_chain_cons h
theorem chain'.rel_head' {x l} (h : chain' R (x :: l)) ⦃y⦄ (hy : y ∈ head' l) : R x y :=
by { rw ← cons_head'_tail hy at h, exact h.rel_head }
theorem chain'.cons' {x} :
∀ {l : list α}, chain' R l → (∀ y ∈ l.head', R x y) → chain' R (x :: l)
| [] _ _ := chain'_singleton x
| (a :: l) hl H := hl.cons $ H _ rfl
theorem chain'_cons' {x l} : chain' R (x :: l) ↔ (∀ y ∈ head' l, R x y) ∧ chain' R l :=
⟨λ h, ⟨h.rel_head', h.tail⟩, λ ⟨h₁, h₂⟩, h₂.cons' h₁⟩
theorem chain'_append : ∀ {l₁ l₂ : list α},
chain' R (l₁ ++ l₂) ↔ chain' R l₁ ∧ chain' R l₂ ∧ ∀ (x ∈ l₁.last') (y ∈ l₂.head'), R x y
| [] l := by simp
| [a] l := by simp [chain'_cons', and_comm]
| (a :: b :: l₁) l₂ := by rw [cons_append, cons_append, chain'_cons, chain'_cons, ← cons_append,
chain'_append, last', and.assoc]
theorem chain'.append (h₁ : chain' R l₁) (h₂ : chain' R l₂)
(h : ∀ (x ∈ l₁.last') (y ∈ l₂.head'), R x y) :
chain' R (l₁ ++ l₂) :=
chain'_append.2 ⟨h₁, h₂, h⟩
theorem chain'.left_of_append (h : chain' R (l₁ ++ l₂)) : chain' R l₁ := (chain'_append.1 h).1
theorem chain'.right_of_append (h : chain' R (l₁ ++ l₂)) : chain' R l₂ := (chain'_append.1 h).2.1
theorem chain'.infix (h : chain' R l) (h' : l₁ <:+: l) : chain' R l₁ :=
by { rcases h' with ⟨l₂, l₃, rfl⟩, exact h.left_of_append.right_of_append }
theorem chain'.suffix (h : chain' R l) (h' : l₁ <:+ l) : chain' R l₁ := h.infix h'.is_infix
theorem chain'.prefix (h : chain' R l) (h' : l₁ <+: l) : chain' R l₁ := h.infix h'.is_infix
theorem chain'.drop (h : chain' R l) (n : ℕ) : chain' R (drop n l) := h.suffix (drop_suffix _ _)
theorem chain'.init (h : chain' R l) : chain' R l.init := h.prefix l.init_prefix
theorem chain'.take (h : chain' R l) (n : ℕ) : chain' R (take n l) := h.prefix (take_prefix _ _)
theorem chain'_pair {x y} : chain' R [x, y] ↔ R x y :=
by simp only [chain'_singleton, chain'_cons, and_true]
theorem chain'.imp_head {x y} (h : ∀ {z}, R x z → R y z) {l} (hl : chain' R (x :: l)) :
chain' R (y :: l) :=
hl.tail.cons' $ λ z hz, h $ hl.rel_head' hz
theorem chain'_reverse : ∀ {l}, chain' R (reverse l) ↔ chain' (flip R) l
| [] := iff.rfl
| [a] := by simp only [chain'_singleton, reverse_singleton]
| (a :: b :: l) := by rw [chain'_cons, reverse_cons, reverse_cons, append_assoc, cons_append,
nil_append, chain'_split, ← reverse_cons, @chain'_reverse (b :: l), and_comm, chain'_pair, flip]
theorem chain'_iff_nth_le {R} : ∀ {l : list α},
chain' R l ↔ ∀ i (h : i < length l - 1),
R (nth_le l i (lt_of_lt_pred h)) (nth_le l (i+1) (lt_pred_iff.mp h))
| [] := by simp
| [a] := by simp
| (a :: b :: t) :=
begin
rw [← and_forall_succ, chain'_cons, chain'_iff_nth_le],
simp only [length, nth_le, add_tsub_cancel_right, add_lt_add_iff_right, tsub_pos_iff_lt,
one_lt_succ_succ, true_implies_iff],
refl,
end
/-- If `l₁ l₂` and `l₃` are lists and `l₁ ++ l₂` and `l₂ ++ l₃` both satisfy
`chain' R`, then so does `l₁ ++ l₂ ++ l₃` provided `l₂ ≠ []` -/
lemma chain'.append_overlap {l₁ l₂ l₃ : list α}
(h₁ : chain' R (l₁ ++ l₂)) (h₂ : chain' R (l₂ ++ l₃)) (hn : l₂ ≠ []) :
chain' R (l₁ ++ l₂ ++ l₃) :=
h₁.append h₂.right_of_append $
by simpa only [last'_append_of_ne_nil _ hn] using (chain'_append.1 h₂).2.2
/--
If `a` and `b` are related by the reflexive transitive closure of `r`, then there is a `r`-chain
starting from `a` and ending on `b`.
The converse of `relation_refl_trans_gen_of_exists_chain`.
-/
lemma exists_chain_of_relation_refl_trans_gen (h : relation.refl_trans_gen r a b) :
∃ l, chain r a l ∧ last (a :: l) (cons_ne_nil _ _) = b :=
begin
apply relation.refl_trans_gen.head_induction_on h,
{ exact ⟨[], chain.nil, rfl⟩ },
{ intros c d e t ih,
obtain ⟨l, hl₁, hl₂⟩ := ih,
refine ⟨d :: l, chain.cons e hl₁, _⟩,
rwa last_cons_cons }
end
/--
Given a chain from `a` to `b`, and a predicate true at `b`, if `r x y → p y → p x` then
the predicate is true everywhere in the chain and at `a`.
That is, we can propagate the predicate up the chain.
-/
lemma chain.induction (p : α → Prop)
(l : list α) (h : chain r a l)
(hb : last (a :: l) (cons_ne_nil _ _) = b)
(carries : ∀ ⦃x y : α⦄, r x y → p y → p x) (final : p b) : ∀ i ∈ a :: l, p i :=
begin
induction l generalizing a,
{ cases hb,
simp [final] },
{ rw chain_cons at h,
rintro _ (rfl | _),
apply carries h.1 (l_ih h.2 hb _ (or.inl rfl)),
apply l_ih h.2 hb _ H }
end
/--
Given a chain from `a` to `b`, and a predicate true at `b`, if `r x y → p y → p x` then
the predicate is true at `a`.
That is, we can propagate the predicate all the way up the chain.
-/
@[elab_as_eliminator]
lemma chain.induction_head (p : α → Prop)
(l : list α) (h : chain r a l)
(hb : last (a :: l) (cons_ne_nil _ _) = b)
(carries : ∀ ⦃x y : α⦄, r x y → p y → p x) (final : p b) : p a :=
(chain.induction p l h hb carries final) _ (mem_cons_self _ _)
/--
If there is an `r`-chain starting from `a` and ending at `b`, then `a` and `b` are related by the
reflexive transitive closure of `r`. The converse of `exists_chain_of_relation_refl_trans_gen`.
-/
lemma relation_refl_trans_gen_of_exists_chain (l) (hl₁ : chain r a l)
(hl₂ : last (a :: l) (cons_ne_nil _ _) = b) :
relation.refl_trans_gen r a b :=
chain.induction_head _ l hl₁ hl₂ (λ x y, relation.refl_trans_gen.head) relation.refl_trans_gen.refl
end list
|
813aa837347e977afaf30943dbe95e22298ae1bf | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Lean/Meta/Basic.lean | 96fa45cb925d806b39fefbf2aeb0f82637c42b59 | [
"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 | 33,672 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Control.Reader
import Init.Lean.Data.LOption
import Init.Lean.Environment
import Init.Lean.Class
import Init.Lean.ReducibilityAttrs
import Init.Lean.Util.Trace
import Init.Lean.Util.RecDepth
import Init.Lean.Util.Closure
import Init.Lean.Meta.Exception
import Init.Lean.Meta.DiscrTreeTypes
import Init.Lean.Eval
/-
This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks.
1- Weak head normal form computation with support for metavariables and transparency modes.
2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality).
3- Type inference.
4- Type class resolution.
They are packed into the MetaM monad.
-/
namespace Lean
namespace Meta
inductive TransparencyMode
| all | default | reducible
namespace TransparencyMode
instance : Inhabited TransparencyMode := ⟨TransparencyMode.default⟩
def beq : TransparencyMode → TransparencyMode → Bool
| all, all => true
| default, default => true
| reducible, reducible => true
| _, _ => false
instance : HasBeq TransparencyMode := ⟨beq⟩
def hash : TransparencyMode → USize
| all => 7
| default => 11
| reducible => 13
instance : Hashable TransparencyMode := ⟨hash⟩
def lt : TransparencyMode → TransparencyMode → Bool
| reducible, default => true
| reducible, all => true
| default, all => true
| _, _ => false
end TransparencyMode
structure Config :=
(opts : Options := {})
(foApprox : Bool := false)
(ctxApprox : Bool := false)
(quasiPatternApprox : Bool := false)
/- When `constApprox` is set to true,
we solve `?m t =?= c` using
`?m := fun _ => c`
when `?m t` is not a higher-order pattern and `c` is not an application as -/
(constApprox : Bool := false)
/-
When the following flag is set,
`isDefEq` throws the exeption `Exeption.isDefEqStuck`
whenever it encounters a constraint `?m ... =?= t` where
`?m` is read only.
This feature is useful for type class resolution where
we may want to notify the caller that the TC problem may be solveable
later after it assigns `?m`. -/
(isDefEqStuckEx : Bool := false)
(debug : Bool := false)
(transparency : TransparencyMode := TransparencyMode.default)
structure ParamInfo :=
(implicit : Bool := false)
(instImplicit : Bool := false)
(hasFwdDeps : Bool := false)
(backDeps : Array Nat := #[])
instance ParamInfo.inhabited : Inhabited ParamInfo := ⟨{}⟩
structure FunInfo :=
(paramInfo : Array ParamInfo := #[])
(resultDeps : Array Nat := #[])
structure InfoCacheKey :=
(transparency : TransparencyMode)
(expr : Expr)
(nargs? : Option Nat)
namespace InfoCacheKey
instance : Inhabited InfoCacheKey := ⟨⟨arbitrary _, arbitrary _, arbitrary _⟩⟩
instance : Hashable InfoCacheKey :=
⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) $ mixHash (hash expr) (hash nargs)⟩
instance : HasBeq InfoCacheKey :=
⟨fun ⟨t₁, e₁, n₁⟩ ⟨t₂, e₂, n₂⟩ => t₁ == t₂ && n₁ == n₂ && e₁ == e₂⟩
end InfoCacheKey
structure Cache :=
(inferType : PersistentExprStructMap Expr := {})
(funInfo : PersistentHashMap InfoCacheKey FunInfo := {})
(synthInstance : PersistentHashMap Expr (Option Expr) := {})
(whnfDefault : PersistentExprStructMap Expr := {}) -- cache for closed terms and `TransparencyMode.default`
structure Context :=
(config : Config := {})
(lctx : LocalContext := {})
(localInstances : LocalInstances := #[])
(currRecDepth : Nat)
(maxRecDepth : Nat)
structure PostponedEntry :=
(lhs : Level)
(rhs : Level)
structure State :=
(env : Environment)
(mctx : MetavarContext := {})
(cache : Cache := {})
(ngen : NameGenerator := {})
(traceState : TraceState := {})
(postponed : PersistentArray PostponedEntry := {})
abbrev MetaM := ReaderT Context (EStateM Exception State)
instance MetaM.inhabited {α} : Inhabited (MetaM α) :=
⟨fun c s => EStateM.Result.error (arbitrary _) s⟩
@[inline] def withIncRecDepth {α} (x : MetaM α) : MetaM α := do
ctx ← read;
when (ctx.currRecDepth == ctx.maxRecDepth) $ throw $ Exception.other maxRecDepthErrorMessage;
adaptReader (fun (ctx : Context) => { currRecDepth := ctx.currRecDepth + 1, .. ctx }) x
@[inline] def getLCtx : MetaM LocalContext := do
ctx ← read; pure ctx.lctx
@[inline] def getLocalInstances : MetaM LocalInstances := do
ctx ← read; pure ctx.localInstances
@[inline] def getConfig : MetaM Config := do
ctx ← read; pure ctx.config
@[inline] def getMCtx : MetaM MetavarContext := do
s ← get; pure s.mctx
@[inline] def getEnv : MetaM Environment := do
s ← get; pure s.env
@[inline] def setEnv (env : Environment) : MetaM Unit := do
modify $ fun s => { env := env, .. s }
def mkWHNFRef : IO (IO.Ref (Expr → MetaM Expr)) :=
IO.mkRef $ fun _ => throw $ Exception.other "whnf implementation was not set"
@[init mkWHNFRef] def whnfRef : IO.Ref (Expr → MetaM Expr) := arbitrary _
def mkInferTypeRef : IO (IO.Ref (Expr → MetaM Expr)) :=
IO.mkRef $ fun _ => throw $ Exception.other "inferType implementation was not set"
@[init mkInferTypeRef] def inferTypeRef : IO.Ref (Expr → MetaM Expr) := arbitrary _
def mkIsExprDefEqAuxRef : IO (IO.Ref (Expr → Expr → MetaM Bool)) :=
IO.mkRef $ fun _ _ => throw $ Exception.other "isDefEq implementation was not set"
@[init mkIsExprDefEqAuxRef] def isExprDefEqAuxRef : IO.Ref (Expr → Expr → MetaM Bool) := arbitrary _
def mkSynthPendingRef : IO (IO.Ref (MVarId → MetaM Bool)) :=
IO.mkRef $ fun _ => pure false
@[init mkSynthPendingRef] def synthPendingRef : IO.Ref (MVarId → MetaM Bool) := arbitrary _
structure MetaExtState :=
(whnf : Expr → MetaM Expr)
(inferType : Expr → MetaM Expr)
(isDefEqAux : Expr → Expr → MetaM Bool)
(synthPending : MVarId → MetaM Bool)
instance MetaExtState.inhabited : Inhabited MetaExtState :=
⟨{ whnf := arbitrary _, inferType := arbitrary _, isDefEqAux := arbitrary _, synthPending := arbitrary _ }⟩
def mkMetaExtension : IO (EnvExtension MetaExtState) :=
registerEnvExtension $ do
whnf ← whnfRef.get;
inferType ← inferTypeRef.get;
isDefEqAux ← isExprDefEqAuxRef.get;
synthPending ← synthPendingRef.get;
pure { whnf := whnf, inferType := inferType, isDefEqAux := isDefEqAux, synthPending := synthPending }
@[init mkMetaExtension]
constant metaExt : EnvExtension MetaExtState := arbitrary _
def whnf (e : Expr) : MetaM Expr :=
withIncRecDepth $ do
env ← getEnv;
(metaExt.getState env).whnf e
def whnfForall (e : Expr) : MetaM Expr := do
e' ← whnf e;
if e'.isForall then pure e' else pure e
def inferType (e : Expr) : MetaM Expr :=
withIncRecDepth $ do
env ← getEnv;
(metaExt.getState env).inferType e
def isExprDefEqAux (t s : Expr) : MetaM Bool :=
withIncRecDepth $ do
env ← getEnv;
(metaExt.getState env).isDefEqAux t s
def synthPending (mvarId : MVarId) : MetaM Bool :=
withIncRecDepth $ do
env ← getEnv;
(metaExt.getState env).synthPending mvarId
def mkFreshId : MetaM Name := do
s ← get;
let id := s.ngen.curr;
modify $ fun s => { ngen := s.ngen.next, .. s };
pure id
def mkFreshExprMVarAt
(lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (userName : Name := Name.anonymous) (kind : MetavarKind := MetavarKind.natural)
: MetaM Expr := do
mvarId ← mkFreshId;
modify $ fun s => { mctx := s.mctx.addExprMVarDecl mvarId userName lctx localInsts type kind, .. s };
pure $ mkMVar mvarId
def mkFreshExprMVar (type : Expr) (userName : Name := Name.anonymous) (kind : MetavarKind := MetavarKind.natural) : MetaM Expr := do
lctx ← getLCtx;
localInsts ← getLocalInstances;
mkFreshExprMVarAt lctx localInsts type userName kind
def mkFreshLevelMVar : MetaM Level := do
mvarId ← mkFreshId;
modify $ fun s => { mctx := s.mctx.addLevelMVarDecl mvarId, .. s};
pure $ mkLevelMVar mvarId
@[inline] def throwEx {α} (f : ExceptionContext → Exception) : MetaM α := do
ctx ← read;
s ← get;
throw (f {env := s.env, mctx := s.mctx, lctx := ctx.lctx, opts := ctx.config.opts })
def throwBug {α} (b : Bug) : MetaM α :=
throwEx $ Exception.bug b
/-- Execute `x` only in debugging mode. -/
@[inline] private def whenDebugging {α} (x : MetaM α) : MetaM Unit := do
ctx ← read;
when ctx.config.debug (do x; pure ())
@[inline] def shouldReduceAll : MetaM Bool := do
ctx ← read; pure $ ctx.config.transparency == TransparencyMode.all
@[inline] def shouldReduceReducibleOnly : MetaM Bool := do
ctx ← read; pure $ ctx.config.transparency == TransparencyMode.reducible
@[inline] def getTransparency : MetaM TransparencyMode := do
ctx ← read; pure $ ctx.config.transparency
@[inline] def getOptions : MetaM Options := do
ctx ← read; pure ctx.config.opts
-- Remark: wanted to use `private`, but in C++ parser, `private` declarations do not shadow outer public ones.
-- TODO: fix this bug
@[inline] def isReducible (constName : Name) : MetaM Bool := do
env ← getEnv; pure $ isReducible env constName
@[inline] def withConfig {α} (f : Config → Config) (x : MetaM α) : MetaM α :=
adaptReader (fun (ctx : Context) => { config := f ctx.config, .. ctx }) x
/-- While executing `x`, ensure the given transparency mode is used. -/
@[inline] def withTransparency {α} (mode : TransparencyMode) (x : MetaM α) : MetaM α :=
withConfig (fun config => { transparency := mode, .. config }) x
@[inline] def withReducible {α} (x : MetaM α) : MetaM α :=
withTransparency TransparencyMode.reducible x
@[inline] def withAtLeastTransparency {α} (mode : TransparencyMode) (x : MetaM α) : MetaM α :=
withConfig
(fun config =>
let oldMode := config.transparency;
let mode := if oldMode.lt mode then mode else oldMode;
{ transparency := mode, .. config })
x
def getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do
mctx ← getMCtx;
match mctx.findDecl? mvarId with
| some d => pure d
| none => throwEx $ Exception.unknownExprMVar mvarId
def setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit :=
modify $ fun s => { mctx := s.mctx.setMVarKind mvarId kind, .. s}
def isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do
mvarDecl ← getMVarDecl mvarId;
mctx ← getMCtx;
pure $ mvarDecl.depth != mctx.depth
def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do
mvarDecl ← getMVarDecl mvarId;
match mvarDecl.kind with
| MetavarKind.syntheticOpaque => pure true
| _ => do
mctx ← getMCtx;
pure $ mvarDecl.depth != mctx.depth
def isReadOnlyLevelMVar (mvarId : MVarId) : MetaM Bool := do
mctx ← getMCtx;
match mctx.findLevelDepth? mvarId with
| some depth => pure $ depth != mctx.depth
| _ => throwEx $ Exception.unknownLevelMVar mvarId
def renameMVar (mvarId : MVarId) (newUserName : Name) : MetaM Unit :=
modify $ fun s => { mctx := s.mctx.renameMVar mvarId newUserName, .. s }
@[inline] def isExprMVarAssigned (mvarId : MVarId) : MetaM Bool := do
mctx ← getMCtx;
pure $ mctx.isExprAssigned mvarId
@[inline] def getExprMVarAssignment? (mvarId : MVarId) : MetaM (Option Expr) := do
mctx ← getMCtx; pure (mctx.getExprAssignment? mvarId)
def assignExprMVar (mvarId : MVarId) (val : Expr) : MetaM Unit := do
whenDebugging $ whenM (isExprMVarAssigned mvarId) $ throwBug $ Bug.overwritingExprMVar mvarId;
modify $ fun s => { mctx := s.mctx.assignExpr mvarId val, .. s }
def isDelayedAssigned (mvarId : MVarId) : MetaM Bool := do
mctx ← getMCtx;
pure $ mctx.isDelayedAssigned mvarId
def hasAssignableMVar (e : Expr) : MetaM Bool := do
mctx ← getMCtx;
pure $ mctx.hasAssignableMVar e
def dbgTrace {α} [HasToString α] (a : α) : MetaM Unit :=
_root_.dbgTrace (toString a) $ fun _ => pure ()
@[inline] private def getTraceState : MetaM TraceState := do
s ← get; pure s.traceState
def addContext (msg : MessageData) : MetaM MessageData := do
ctx ← read;
s ← get;
pure $ MessageData.withContext { env := s.env, mctx := s.mctx, lctx := ctx.lctx, opts := ctx.config.opts } msg
instance tracer : SimpleMonadTracerAdapter MetaM :=
{ getOptions := getOptions,
getTraceState := getTraceState,
addContext := addContext,
modifyTraceState := fun f => modify $ fun s => { traceState := f s.traceState, .. s } }
def getConstAux (constName : Name) (exception? : Bool) : MetaM (Option ConstantInfo) := do
env ← getEnv;
match env.find? constName with
| some (info@(ConstantInfo.thmInfo _)) =>
condM shouldReduceAll (pure (some info)) (pure none)
| some (info@(ConstantInfo.defnInfo _)) =>
condM shouldReduceReducibleOnly
(condM (isReducible constName) (pure (some info)) (pure none))
(pure (some info))
| some info => pure (some info)
| none =>
if exception? then throwEx $ Exception.unknownConst constName
else pure none
@[inline] def getConst (constName : Name) : MetaM (Option ConstantInfo) :=
getConstAux constName true
@[inline] def getConstNoEx (constName : Name) : MetaM (Option ConstantInfo) :=
getConstAux constName false
def getConstInfo (constName : Name) : MetaM ConstantInfo := do
env ← getEnv;
match env.find? constName with
| some info => pure info
| none => throwEx $ Exception.unknownConst constName
def getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do
lctx ← getLCtx;
match lctx.find? fvarId with
| some d => pure d
| none => throwEx $ Exception.unknownFVar fvarId
def getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl :=
getLocalDecl fvar.fvarId!
def instantiateMVars (e : Expr) : MetaM Expr :=
if e.hasMVar then
modifyGet $ fun s =>
let (e, mctx) := s.mctx.instantiateMVars e;
(e, { mctx := mctx, .. s })
else
pure e
@[inline] private def liftMkBindingM {α} (x : MetavarContext.MkBindingM α) : MetaM α :=
fun ctx s =>
match x ctx.lctx { mctx := s.mctx, ngen := s.ngen } with
| EStateM.Result.ok e newS =>
EStateM.Result.ok e { mctx := newS.mctx, ngen := newS.ngen, .. s}
| EStateM.Result.error (MetavarContext.MkBinding.Exception.revertFailure mctx lctx toRevert decl) newS =>
EStateM.Result.error
(Exception.revertFailure toRevert decl { lctx := lctx, mctx := mctx, env := s.env, opts := ctx.config.opts })
{ mctx := newS.mctx, ngen := newS.ngen, .. s }
def mkForall (xs : Array Expr) (e : Expr) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM $ MetavarContext.mkForall xs e
def mkLambda (xs : Array Expr) (e : Expr) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM $ MetavarContext.mkLambda xs e
def mkForallUsedOnly (xs : Array Expr) (e : Expr) : MetaM (Expr × Nat) :=
if xs.isEmpty then pure (e, 0) else liftMkBindingM $ MetavarContext.mkForallUsedOnly xs e
def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM $ MetavarContext.elimMVarDeps xs e preserveOrder
/-- Save cache, execute `x`, restore cache -/
@[inline] def savingCache {α} (x : MetaM α) : MetaM α := do
s ← get;
let savedCache := s.cache;
finally x (modify $ fun s => { cache := savedCache, .. s })
def isClassQuickConst (constName : Name) : MetaM (LOption Name) := do
env ← getEnv;
if isClass env constName then
pure (LOption.some constName)
else do
cinfo? ← getConst constName;
match cinfo? with
| some _ => pure LOption.undef
| none => pure LOption.none
partial def isClassQuick : Expr → MetaM (LOption Name)
| Expr.bvar _ _ => pure LOption.none
| Expr.lit _ _ => pure LOption.none
| Expr.fvar _ _ => pure LOption.none
| Expr.sort _ _ => pure LOption.none
| Expr.lam _ _ _ _ => pure LOption.none
| Expr.letE _ _ _ _ _ => pure LOption.undef
| Expr.proj _ _ _ _ => pure LOption.undef
| Expr.forallE _ _ b _ => isClassQuick b
| Expr.mdata _ e _ => isClassQuick e
| Expr.const n _ _ => isClassQuickConst n
| Expr.mvar mvarId _ => do
val? ← getExprMVarAssignment? mvarId;
match val? with
| some val => isClassQuick val
| none => pure LOption.none
| Expr.app f _ _ =>
match f.getAppFn with
| Expr.const n _ _ => isClassQuickConst n
| Expr.lam _ _ _ _ => pure LOption.undef
| _ => pure LOption.none
| Expr.localE _ _ _ _ => unreachable!
/-- Reset `synthInstance` cache, execute `x`, and restore cache -/
@[inline] def resettingSynthInstanceCache {α} (x : MetaM α) : MetaM α := do
s ← get;
let savedSythInstance := s.cache.synthInstance;
modify $ fun s => { cache := { synthInstance := {}, .. s.cache }, .. s };
finally x (modify $ fun s => { cache := { synthInstance := savedSythInstance, .. s.cache }, .. s })
/-- Add entry `{ className := className, fvar := fvar }` to localInstances,
and then execute continuation `k`.
It resets the type class cache using `resettingSynthInstanceCache`. -/
@[inline] def withNewLocalInstance {α} (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α :=
resettingSynthInstanceCache $
adaptReader
(fun (ctx : Context) => {
localInstances := ctx.localInstances.push { className := className, fvar := fvar },
.. ctx })
k
/--
`withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances
using free variables `fvars[j] ... fvars.back`, and execute `k`.
- `isClassExpensive` is defined later.
- The type class chache is reset whenever a new local instance is found.
- `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances.
Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/
@[specialize] partial def withNewLocalInstances {α}
(isClassExpensive : Expr → MetaM (Option Name))
(fvars : Array Expr) : Nat → MetaM α → MetaM α
| i, k =>
if h : i < fvars.size then do
let fvar := fvars.get ⟨i, h⟩;
decl ← getFVarLocalDecl fvar;
c? ← isClassQuick decl.type;
match c? with
| LOption.none => withNewLocalInstances (i+1) k
| LOption.undef => do
c? ← isClassExpensive decl.type;
match c? with
| none => withNewLocalInstances (i+1) k
| some c => withNewLocalInstance c fvar $ withNewLocalInstances (i+1) k
| LOption.some c => withNewLocalInstance c fvar $ withNewLocalInstances (i+1) k
else
k
/--
`forallTelescopeAux whnf k lctx fvars j type`
Remarks:
- `lctx` is the `MetaM` local context exteded with the declaration for `fvars`.
- `type` is the type we are computing the telescope for. It contains only
dangling bound variables in the range `[j, fvars.size)`
- if `reducing? == true` and `type` is not `forallE`, we use `whnf`.
- when `type` is not a `forallE` nor it can't be reduced to one, we
excute the continuation `k`.
Here is an example that demonstrates the `reducing?`.
Suppose we have
```
abbrev StateM s a := s -> Prod a s
```
Now, assume we are trying to build the telescope for
```
forall (x : Nat), StateM Int Bool
```
if `reducing? == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`.
if `reducing? == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)`
if `maxFVars?` is `some max`, then we interrupt the telescope construction
when `fvars.size == max`
-/
@[specialize] private partial def forallTelescopeReducingAuxAux {α}
(isClassExpensive : Expr → MetaM (Option Name))
(reducing? : Bool) (maxFVars? : Option Nat)
(k : Array Expr → Expr → MetaM α)
: LocalContext → Array Expr → Nat → Expr → MetaM α
| lctx, fvars, j, type@(Expr.forallE n d b c) => do
let process : Unit → MetaM α := fun _ => do {
let d := d.instantiateRevRange j fvars.size fvars;
fvarId ← mkFreshId;
let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo;
let fvar := mkFVar fvarId;
let fvars := fvars.push fvar;
forallTelescopeReducingAuxAux lctx fvars j b
};
match maxFVars? with
| none => process ()
| some maxFVars =>
if fvars.size < maxFVars then
process ()
else
let type := type.instantiateRevRange j fvars.size fvars;
adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $
withNewLocalInstances isClassExpensive fvars j $
k fvars type
| lctx, fvars, j, type =>
let type := type.instantiateRevRange j fvars.size fvars;
adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $
withNewLocalInstances isClassExpensive fvars j $
if reducing? then do
newType ← whnf type;
if newType.isForall then
forallTelescopeReducingAuxAux lctx fvars fvars.size newType
else
k fvars type
else
k fvars type
/- We need this auxiliary definition because it depends on `isClassExpensive`,
and `isClassExpensive` depends on it. -/
@[specialize] private def forallTelescopeReducingAux {α}
(isClassExpensive : Expr → MetaM (Option Name))
(type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do
newType ← whnf type;
if newType.isForall then do
lctx ← getLCtx;
forallTelescopeReducingAuxAux isClassExpensive true maxFVars? k lctx #[] 0 newType
else
k #[] type
partial def isClassExpensive : Expr → MetaM (Option Name)
| type => withReducible $ -- when testing whether a type is a type class, we only unfold reducible constants.
forallTelescopeReducingAux isClassExpensive type none $ fun xs type => do
match type.getAppFn with
| Expr.const c _ _ => do
env ← getEnv;
pure $ if isClass env c then some c else none
| _ => pure none
/--
Given `type` of the form `forall xs, A`, execute `k xs A`.
This combinator will declare local declarations, create free variables for them,
execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/
def forallTelescope {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do
lctx ← getLCtx;
forallTelescopeReducingAuxAux isClassExpensive false none k lctx #[] 0 type
/--
Similar to `forallTelescope`, but given `type` of the form `forall xs, A`,
it reduces `A` and continues bulding the telescope if it is a `forall`. -/
def forallTelescopeReducing {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α :=
forallTelescopeReducingAux isClassExpensive type none k
/--
Similar to `forallTelescopeReducing`, stops constructing the telescope when
it reaches size `maxFVars`. -/
def forallBoundedTelescope {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α :=
forallTelescopeReducingAux isClassExpensive type maxFVars? k
/-- Return the parameter names for the givel global declaration. -/
def getParamNames (declName : Name) : MetaM (Array Name) := do
cinfo ← getConstInfo declName;
forallTelescopeReducing cinfo.type $ fun xs _ => do
xs.mapM $ fun x => do
localDecl ← getLocalDecl x.fvarId!;
pure localDecl.userName
def isClass (type : Expr) : MetaM (Option Name) := do
c? ← isClassQuick type;
match c? with
| LOption.none => pure none
| LOption.some c => pure (some c)
| LOption.undef => isClassExpensive type
/-- Similar to `forallTelescopeAuxAux` but for lambda and let expressions. -/
private partial def lambdaTelescopeAux {α}
(k : Array Expr → Expr → MetaM α)
: LocalContext → Array Expr → Nat → Expr → MetaM α
| lctx, fvars, j, Expr.lam n d b c => do
let d := d.instantiateRevRange j fvars.size fvars;
fvarId ← mkFreshId;
let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo;
let fvar := mkFVar fvarId;
lambdaTelescopeAux lctx (fvars.push fvar) j b
| lctx, fvars, j, Expr.letE n t v b _ => do
let t := t.instantiateRevRange j fvars.size fvars;
let v := v.instantiateRevRange j fvars.size fvars;
fvarId ← mkFreshId;
let lctx := lctx.mkLetDecl fvarId n t v;
let fvar := mkFVar fvarId;
lambdaTelescopeAux lctx (fvars.push fvar) j b
| lctx, fvars, j, e =>
let e := e.instantiateRevRange j fvars.size fvars;
adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $
withNewLocalInstances isClassExpensive fvars j $ do
k fvars e
/-- Similar to `forallTelescope` but for lambda and let expressions. -/
def lambdaTelescope {α} (e : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do
lctx ← getLCtx;
lambdaTelescopeAux k lctx #[] 0 e
-- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments.
private partial def forallMetaTelescopeReducingAux
(reducing? : Bool) (maxMVars? : Option Nat) (kind : MetavarKind)
: Array Expr → Array BinderInfo → Nat → Expr → MetaM (Array Expr × Array BinderInfo × Expr)
| mvars, bis, j, type@(Expr.forallE n d b c) => do
let process : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do {
let d := d.instantiateRevRange j mvars.size mvars;
let k := if c.binderInfo.isInstImplicit then MetavarKind.synthetic else kind;
mvar ← mkFreshExprMVar d n k;
let mvars := mvars.push mvar;
let bis := bis.push c.binderInfo;
forallMetaTelescopeReducingAux mvars bis j b
};
match maxMVars? with
| none => process ()
| some maxMVars =>
if mvars.size < maxMVars then
process ()
else
let type := type.instantiateRevRange j mvars.size mvars;
pure (mvars, bis, type)
| mvars, bis, j, type =>
let type := type.instantiateRevRange j mvars.size mvars;
if reducing? then do
newType ← whnf type;
if newType.isForall then
forallMetaTelescopeReducingAux mvars bis mvars.size newType
else
pure (mvars, bis, type)
else
pure (mvars, bis, type)
/-- Similar to `forallTelescope`, but creates metavariables instead of free variables. -/
def forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) :=
forallMetaTelescopeReducingAux false none kind #[] #[] 0 e
/-- Similar to `forallTelescopeReducing`, but creates metavariables instead of free variables. -/
def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) :=
forallMetaTelescopeReducingAux true maxMVars? kind #[] #[] 0 e
/-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/
private partial def lambdaMetaTelescopeAux (maxMVars? : Option Nat)
: Array Expr → Array BinderInfo → Nat → Expr → MetaM (Array Expr × Array BinderInfo × Expr)
| mvars, bis, j, type => do
let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do {
let type := type.instantiateRevRange j mvars.size mvars;
pure (mvars, bis, type)
};
let process : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do {
match type with
| Expr.lam n d b c => do
let d := d.instantiateRevRange j mvars.size mvars;
mvar ← mkFreshExprMVar d;
let mvars := mvars.push mvar;
let bis := bis.push c.binderInfo;
lambdaMetaTelescopeAux mvars bis j b
| _ => finalize ()
};
match maxMVars? with
| none => process ()
| some maxMVars =>
if mvars.size < maxMVars then
process ()
else
finalize ()
/-- Similar to `forallMetaTelescope` but for lambda expressions. -/
def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) :=
lambdaMetaTelescopeAux maxMVars? #[] #[] 0 e
@[inline] def liftStateMCtx {α} (x : StateM MetavarContext α) : MetaM α :=
fun _ s =>
let (a, mctx) := x.run s.mctx;
EStateM.Result.ok a { mctx := mctx, .. s }
def instantiateLevelMVars (lvl : Level) : MetaM Level :=
liftStateMCtx $ MetavarContext.instantiateLevelMVars lvl
def assignLevelMVar (mvarId : MVarId) (lvl : Level) : MetaM Unit :=
modify $ fun s => { mctx := MetavarContext.assignLevel s.mctx mvarId lvl, .. s }
def mkFreshLevelMVarId : MetaM MVarId := do
mvarId ← mkFreshId;
modify $ fun s => { mctx := s.mctx.addLevelMVarDecl mvarId, .. s };
pure mvarId
def whnfD : Expr → MetaM Expr :=
fun e => withTransparency TransparencyMode.default $ whnf e
/-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`. -/
@[inline] def approxDefEq {α} (x : MetaM α) : MetaM α :=
adaptReader (fun (ctx : Context) => { config := { foApprox := true, ctxApprox := true, quasiPatternApprox := true, .. ctx.config }, .. ctx })
x
/--
Similar to `approxDefEq`, but uses all available approximations.
We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code.
For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[HasPure ?m]`.
Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved
as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to
solve `[HasPure (fun _ => IO Bool)]` -/
@[inline] def fullApproxDefEq {α} (x : MetaM α) : MetaM α :=
adaptReader (fun (ctx : Context) => { config := { foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true, .. ctx.config }, .. ctx })
x
@[inline] private def withNewFVar {α} (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do
c? ← isClass fvarType;
match c? with
| none => k fvar
| some c => withNewLocalInstance c fvar $ k fvar
def withLocalDecl {α} (n : Name) (type : Expr) (bi : BinderInfo) (k : Expr → MetaM α) : MetaM α := do
fvarId ← mkFreshId;
ctx ← read;
let lctx := ctx.lctx.mkLocalDecl fvarId n type bi;
let fvar := mkFVar fvarId;
adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $
withNewFVar fvar type k
def withLocalDeclD {α} (n : Name) (type : Expr) (k : Expr → MetaM α) : MetaM α :=
withLocalDecl n type BinderInfo.default k
def withLetDecl {α} (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) : MetaM α := do
fvarId ← mkFreshId;
ctx ← read;
let lctx := ctx.lctx.mkLetDecl fvarId n type val;
let fvar := mkFVar fvarId;
adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $
withNewFVar fvar type k
/--
Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`,
and restore saved data. -/
@[inline] def withNewMCtxDepth {α} (x : MetaM α) : MetaM α := do
s ← get;
let savedMCtx := s.mctx;
modify $ fun s => { mctx := s.mctx.incDepth, .. s };
finally x (modify $ fun s => { mctx := savedMCtx, .. s })
def withLocalContext {α} (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM α) : MetaM α := do
localInstsCurr ← getLocalInstances;
adaptReader (fun (ctx : Context) => { lctx := lctx, localInstances := localInsts, .. ctx }) $
if localInsts == localInstsCurr then
x
else
resettingSynthInstanceCache x
/--
Execute `x` using the given metavariable `LocalContext` and `LocalInstances`.
The type class resolution cache is flushed when executing `x` if its `LocalInstances` are
different from the current ones. -/
@[inline] def withMVarContext {α} (mvarId : MVarId) (x : MetaM α) : MetaM α := do
mvarDecl ← getMVarDecl mvarId;
withLocalContext mvarDecl.lctx mvarDecl.localInstances x
@[inline] def withMCtx {α} (mctx : MetavarContext) (x : MetaM α) : MetaM α := do
mctx' ← getMCtx;
modify $ fun s => { mctx := mctx, .. s };
finally x (modify $ fun s => { mctx := mctx', .. s })
/--
Create an auxiliary definition with the given name, type and value.
The parameters `type` and `value` may contain free and meta variables.
A "closure" is computed, and a term of the form `name.{u_1 ... u_n} t_1 ... t_m` is
returned where `u_i`s are universe parameters and metavariables `type` and `value` depend on,
and `t_j`s are free and meta variables `type` and `value` depend on. -/
def mkAuxDefinition (name : Name) (type : Expr) (value : Expr) : MetaM Expr := do
env ← getEnv;
opts ← getOptions;
mctx ← getMCtx;
lctx ← getLCtx;
match Lean.mkAuxDefinition env opts mctx lctx name type value with
| Except.error ex => throw $ Exception.kernel ex opts
| Except.ok (e, env) => do setEnv env; pure e
/-- Similar to `mkAuxDefinition`, but infers the type of `value`. -/
def mkAuxDefinitionFor (name : Name) (value : Expr) : MetaM Expr := do
type ← inferType value;
let type := type.headBeta;
mkAuxDefinition name type value
@[init] private def regTraceClasses : IO Unit := do
registerTraceClass `Meta;
registerTraceClass `Meta.debug
def run {α} (env : Environment) (x : MetaM α) (maxRecDepth := 10000) : Except Exception α :=
match x { maxRecDepth := maxRecDepth, currRecDepth := 0 } { env := env } with
| EStateM.Result.ok a _ => Except.ok a
| EStateM.Result.error ex _ => Except.error ex
end Meta
export Meta (MetaM)
end Lean
open Lean
open Lean.Meta
/-- Helper function for running `MetaM` methods in attributes -/
@[inline] def IO.runMeta {α} (x : MetaM α) (env : Environment) (cfg : Config := {}) : IO (α × Environment) :=
match (x { config := cfg, currRecDepth := 0, maxRecDepth := defaultMaxRecDepth }).run { env := env } with
| EStateM.Result.ok a s => pure (a, s.env)
| EStateM.Result.error ex _ => throw (IO.userError (toString ex))
|
55df760c19daf8ed51128304e83ae01c5be3022a | 7a0854479980a89e813e3c93d127f09a8e2c3a7e | /src/group/group_powers.lean | 8b2b31c183b20a0f69d667d37c9eff9cd940c1a8 | [] | no_license | cfbolz/group-theory-game | 020e382df58bf9a510dce38304f27400e4ef0b80 | b5282ce72a2a22e9ba1b48cee432ff3d77496040 | refs/heads/master | 1,668,643,052,237 | 1,594,820,769,000 | 1,594,820,769,000 | 279,899,736 | 0 | 0 | null | 1,594,825,474,000 | 1,594,825,473,000 | null | UTF-8 | Lean | false | false | 2,089 | lean | import group.level01_extended
namespace mygroup
namespace group
variable {G : Type}
variable [group G]
@[simp] lemma pow_int_of_nat {g : G} {n : ℕ} : g ^ (int.of_nat n) = g ^ n := rfl
@[simp] lemma pow_neg {g : G} {n : ℕ} : g ^ (-[1+ n]) = (g ^ (n + 1))⁻¹ := rfl
@[simp] theorem pow_neg_succ (g : G) (n : ℕ) : g ^ -[1+n] = (g ^ n.succ)⁻¹ := rfl
@[simp] lemma zero_pow_nat {g : G} : g ^ 0 = 1 := rfl
@[simp] lemma zero_pow {g : G} : g ^ (0 : ℤ) = 1 := rfl
@[simp] lemma succ_pow_nat {g : G} {n : ℕ} : g ^ (n + 1) = g ^ n * g := rfl
@[simp] lemma neg_one_pow_inv {g : G} : g ^ (-1 : ℤ) = g⁻¹ :=
begin
have : -1 = -[1+ 0] := rfl,
rw [this, pow_neg, nat.add_comm, succ_pow_nat],
simp only [mygroup.group.one_mul, mygroup.group.zero_pow_nat]
end
@[simp] lemma succ_pow {g : G} {n : ℤ} : g ^ (n + 1) = g ^ n * g :=
begin
induction n,
{rw [pow_int_of_nat, ←succ_pow_nat], refl},
sorry
end
@[simp] lemma one_mul_pow_nat {g : G} {n : ℕ} : 1 * (g ^ n) = (g ^ n) := by {simp}
@[simp] lemma pow_mul_one_nat {g : G} {n : ℕ} : (g ^ n) * 1 = (g ^ n) := by{simp}
@[simp] lemma pow_add_mul_nat {g : G} {m n : ℕ} : g ^ (m + n) = g ^ m * g ^ n :=
begin
induction n with k hk,
{rw [add_zero, zero_pow_nat, pow_mul_one_nat]},
rwa [succ_pow_nat, ←mul_assoc, ←hk, ←succ_pow_nat, nat.add_assoc]
end
@[simp] lemma pow_add_mul {g : G} {m n : ℤ} : g ^ (m + n) = g ^ m * g ^ n :=
begin
induction n,
induction m,
{repeat {rw pow_int_of_nat}, rw ←pow_add_mul_nat, refl},
repeat {sorry}
end
@[simp] lemma inv_pow {g : G} {n : ℕ} : (g ^ n)⁻¹ = g⁻¹ ^ n :=
begin
sorry
end
@[simp] lemma pow_mul_pow_nat {g : G} {m n : ℕ} : g ^ (m * n) = (g ^ m) ^ n :=
begin
induction n with k hk,
simp only [nat.nat_zero_eq_zero, zero_pow_nat, mul_zero],
show g ^ (m * k + m) = (g ^ m) ^ (k + 1),
rw [succ_pow_nat, ←hk, pow_add_mul_nat]
end
@[simp] lemma pow_mul_pow {g : G} {m n : ℤ} : g ^ (m * n) = (g ^ m) ^ n :=
begin
sorry
end
end group
end mygroup |
22724471adcbf5235dae0eb3b0f0707d6c0986fc | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Elab/Deriving/TypeName.lean | 2253090f6f58f4d85e08bc4672b27df29d7a1cf7 | [
"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 | 869 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import Lean.Elab.Deriving.Basic
namespace Lean.Elab
open Command Std Parser Term
private def deriveTypeNameInstance (declNames : Array Name) : CommandElabM Bool := do
for declName in declNames do
let cinfo ← getConstInfo declName
unless cinfo.levelParams.isEmpty do
throwError m!"{mkConst declName} has universe level parameters"
elabCommand <| ← withFreshMacroScope `(
unsafe def instImpl : TypeName @$(mkCIdent declName) := .mk _ $(quote declName)
@[implemented_by instImpl] opaque inst : TypeName @$(mkCIdent declName)
instance : TypeName @$(mkCIdent declName) := inst
)
return true
initialize
registerDerivingHandler ``TypeName deriveTypeNameInstance
|
41e4fddbad04682f9ca4a3a196662619646f9ece | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/dlist/instances.lean | a1ae395cf3291999f00429e33f584a44fb556dde | [
"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 | 963 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import control.traversable.equiv
import control.traversable.instances
/-!
# Traversable instance for dlists
This file provides the equivalence between `list α` and `dlist α` and the traversable instance
for `dlist`.
-/
open function equiv
namespace dlist
variables (α : Type*)
/-- The natural equivalence between lists and difference lists, using
`dlist.of_list` and `dlist.to_list`. -/
def list_equiv_dlist : list α ≃ dlist α :=
by refine { to_fun := dlist.of_list, inv_fun := dlist.to_list, .. };
simp [function.right_inverse,left_inverse,to_list_of_list,of_list_to_list]
instance : traversable dlist := equiv.traversable list_equiv_dlist
instance : is_lawful_traversable dlist := equiv.is_lawful_traversable list_equiv_dlist
instance {α} : inhabited (dlist α) := ⟨dlist.empty⟩
end dlist
|
b909ca5a4da11a23c034d0ad32bc3e0da9a19274 | 00de0c30dd1b090ed139f65c82ea6deb48c3f4c2 | /src/number_theory/sum_four_squares.lean | e6bb856dd4cd9a291e12140ee209b4dbdcd46b7c | [
"Apache-2.0"
] | permissive | paulvanwamelen/mathlib | 4b9c5c19eec71b475f3dd515cd8785f1c8515f26 | 79e296bdc9f83b9447dc1b81730d36f63a99f72d | refs/heads/master | 1,667,766,172,625 | 1,590,239,595,000 | 1,590,239,595,000 | 266,392,625 | 0 | 0 | Apache-2.0 | 1,590,257,277,000 | 1,590,257,277,000 | null | UTF-8 | Lean | false | false | 12,000 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
## Lagrange's four square theorem
The main result in this file is `sum_four_squares`,
a proof that every natural number is the sum of four square numbers.
# Implementation Notes
The proof used is close to Lagrange's original proof.
-/
import data.zmod.basic
import field_theory.finite
import data.int.parity
import data.fintype.card
open finset polynomial finite_field equiv
namespace int
lemma sum_two_squares_of_two_mul_sum_two_squares {m x y : ℤ} (h : 2 * m = x^2 + y^2) :
m = ((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2 :=
have (x^2 + y^2).even, by simp [h.symm, even_mul],
have hxaddy : (x + y).even, by simpa [pow_two] with parity_simps,
have hxsuby : (x - y).even, by simpa [pow_two] with parity_simps,
have (x^2 + y^2) % 2 = 0, by simp [h.symm],
(domain.mul_right_inj (show (2*2 : ℤ) ≠ 0, from dec_trivial)).1 $
calc 2 * 2 * m = (x - y)^2 + (x + y)^2 : by rw [mul_assoc, h]; ring
... = (2 * ((x - y) / 2))^2 + (2 * ((x + y) / 2))^2 :
by rw [int.mul_div_cancel' hxsuby, int.mul_div_cancel' hxaddy]
... = 2 * 2 * (((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2) :
by simp [mul_add, _root_.pow_succ, mul_comm, mul_assoc, mul_left_comm]
lemma exists_sum_two_squares_add_one_eq_k (p : ℕ) [hp : fact p.prime] :
∃ (a b : ℤ) (k : ℕ), a^2 + b^2 + 1 = k * p ∧ k < p :=
hp.eq_two_or_odd.elim (λ hp2, hp2.symm ▸ ⟨1, 0, 1, rfl, dec_trivial⟩) $ λ hp1,
let ⟨a, b, hab⟩ := zmod.sum_two_squares p (-1) in
have hab' : (p : ℤ) ∣ a.val_min_abs ^ 2 + b.val_min_abs ^ 2 + 1,
from (char_p.int_cast_eq_zero_iff (zmod p) p _).1 $ by simpa [eq_neg_iff_add_eq_zero] using hab,
let ⟨k, hk⟩ := hab' in
have hk0 : 0 ≤ k, from nonneg_of_mul_nonneg_left
(by rw ← hk; exact (add_nonneg (add_nonneg (pow_two_nonneg _) (pow_two_nonneg _)) zero_le_one))
(int.coe_nat_pos.2 hp.pos),
⟨a.val_min_abs, b.val_min_abs, k.nat_abs,
by rw [hk, int.nat_abs_of_nonneg hk0, mul_comm],
lt_of_mul_lt_mul_left
(calc p * k.nat_abs = a.val_min_abs.nat_abs ^ 2 + b.val_min_abs.nat_abs ^ 2 + 1 :
by rw [← int.coe_nat_inj', int.coe_nat_add, int.coe_nat_add, nat.pow_two, nat.pow_two,
int.nat_abs_mul_self, int.nat_abs_mul_self, ← _root_.pow_two, ← _root_.pow_two,
int.coe_nat_one, hk, int.coe_nat_mul, int.nat_abs_of_nonneg hk0]
... ≤ (p / 2) ^ 2 + (p / 2)^2 + 1 :
add_le_add
(add_le_add
(nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)
(nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _))
(le_refl _)
... < (p / 2) ^ 2 + (p / 2)^ 2 + (p % 2)^2 + ((2 * (p / 2)^2 + (4 * (p / 2) * (p % 2)))) :
by rw [hp1, nat.one_pow, mul_one];
exact (lt_add_iff_pos_right _).2
(add_pos_of_nonneg_of_pos (nat.zero_le _) (mul_pos dec_trivial
(nat.div_pos hp.two_le dec_trivial)))
... = p * p : by { conv_rhs { rw [← nat.mod_add_div p 2] }, ring })
(show 0 ≤ p, from nat.zero_le _)⟩
end int
namespace nat
open int
open_locale classical
private lemma sum_four_squares_of_two_mul_sum_four_squares {m a b c d : ℤ}
(h : a^2 + b^2 + c^2 + d^2 = 2 * m) : ∃ w x y z : ℤ, w^2 + x^2 + y^2 + z^2 = m :=
have ∀ f : fin 4 → zmod 2, (f 0)^2 + (f 1)^2 + (f 2)^2 + (f 3)^2 = 0 →
∃ i : (fin 4), (f i)^2 + f (swap i 0 1)^2 = 0 ∧ f (swap i 0 2)^2 + f (swap i 0 3)^2 = 0,
from dec_trivial,
let f : fin 4 → ℤ := vector.nth (a::b::c::d::vector.nil) in
let ⟨i, hσ⟩ := this (coe ∘ f) (by rw [← @zero_mul (zmod 2) _ m, ← show ((2 : ℤ) : zmod 2) = 0, from rfl,
← int.cast_mul, ← h]; simp only [int.cast_add, int.cast_pow]; refl) in
let σ := swap i 0 in
have h01 : 2 ∣ f (σ 0) ^ 2 + f (σ 1) ^ 2,
from (char_p.int_cast_eq_zero_iff (zmod 2) 2 _).1 $ by simpa [σ] using hσ.1,
have h23 : 2 ∣ f (σ 2) ^ 2 + f (σ 3) ^ 2,
from (char_p.int_cast_eq_zero_iff (zmod 2) 2 _).1 $ by simpa using hσ.2,
let ⟨x, hx⟩ := h01 in let ⟨y, hy⟩ := h23 in
⟨(f (σ 0) - f (σ 1)) / 2, (f (σ 0) + f (σ 1)) / 2, (f (σ 2) - f (σ 3)) / 2, (f (σ 2) + f (σ 3)) / 2,
begin
rw [← int.sum_two_squares_of_two_mul_sum_two_squares hx.symm, add_assoc,
← int.sum_two_squares_of_two_mul_sum_two_squares hy.symm,
← domain.mul_right_inj (show (2 : ℤ) ≠ 0, from dec_trivial), ← h, mul_add, ← hx, ← hy],
have : univ.sum (λ x, f (σ x)^2) = univ.sum (λ x, f x^2),
{ conv_rhs { rw ← finset.sum_equiv σ } },
have fin4univ : (univ : finset (fin 4)).1 = 0::1::2::3::0, from dec_trivial,
simpa [finset.sum_eq_multiset_sum, fin4univ, multiset.sum_cons, f, add_assoc]
end⟩
private lemma prime_sum_four_squares (p : ℕ) [hp : _root_.fact p.prime] :
∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = p :=
have hm : ∃ m < p, 0 < m ∧ ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = m * p,
from let ⟨a, b, k, hk⟩ := exists_sum_two_squares_add_one_eq_k p in
⟨k, hk.2, nat.pos_of_ne_zero $
(λ hk0, by rw [hk0, int.coe_nat_zero, zero_mul] at hk;
exact ne_of_gt (show a^2 + b^2 + 1 > 0, from add_pos_of_nonneg_of_pos
(add_nonneg (pow_two_nonneg _) (pow_two_nonneg _)) zero_lt_one) hk.1),
a, b, 1, 0, by simpa [_root_.pow_two] using hk.1⟩,
let m := nat.find hm in
let ⟨a, b, c, d, (habcd : a^2 + b^2 + c^2 + d^2 = m * p)⟩ := (nat.find_spec hm).snd.2 in
by haveI hm0 : _root_.fact (0 < m) := (nat.find_spec hm).snd.1; exact
have hmp : m < p, from (nat.find_spec hm).fst,
m.mod_two_eq_zero_or_one.elim
(λ hm2 : m % 2 = 0,
let ⟨k, hk⟩ := (nat.dvd_iff_mod_eq_zero _ _).2 hm2 in
have hk0 : 0 < k, from nat.pos_of_ne_zero $ λ _, by { simp [*, lt_irrefl] at *, exact hm0 },
have hkm : k < m, by rw [hk, two_mul]; exact (lt_add_iff_pos_left _).2 hk0,
false.elim $ nat.find_min hm hkm ⟨lt_trans hkm hmp, hk0,
sum_four_squares_of_two_mul_sum_four_squares
(show a^2 + b^2 + c^2 + d^2 = 2 * (k * p),
by rw [habcd, hk, int.coe_nat_mul, mul_assoc]; simp)⟩)
(λ hm2 : m % 2 = 1,
if hm1 : m = 1 then ⟨a, b, c, d, by simp only [hm1, habcd, int.coe_nat_one, one_mul]⟩
else --have hm1 : 1 < m, from lt_of_le_of_ne hm0 (ne.symm hm1),
let w := (a : zmod m).val_min_abs, x := (b : zmod m).val_min_abs,
y := (c : zmod m).val_min_abs, z := (d : zmod m).val_min_abs in
have hnat_abs : w^2 + x^2 + y^2 + z^2 =
(w.nat_abs^2 + x.nat_abs^2 + y.nat_abs ^2 + z.nat_abs ^ 2 : ℕ),
by simp [_root_.pow_two],
have hwxyzlt : w^2 + x^2 + y^2 + z^2 < m^2,
from calc w^2 + x^2 + y^2 + z^2
= (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs ^2 + z.nat_abs ^ 2 : ℕ) : hnat_abs
... ≤ ((m / 2) ^ 2 + (m / 2) ^ 2 + (m / 2) ^ 2 + (m / 2) ^ 2 : ℕ) :
int.coe_nat_le.2 $ add_le_add (add_le_add (add_le_add
(nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)
(nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _))
(nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _))
(nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)
... = 4 * (m / 2 : ℕ) ^ 2 : by simp [_root_.pow_two, bit0, bit1, mul_add, add_mul, add_assoc]
... < 4 * (m / 2 : ℕ) ^ 2 + ((4 * (m / 2) : ℕ) * (m % 2 : ℕ) + (m % 2 : ℕ)^2) :
(lt_add_iff_pos_right _).2 (by rw [hm2, int.coe_nat_one, _root_.one_pow, mul_one];
exact add_pos_of_nonneg_of_pos (int.coe_nat_nonneg _) zero_lt_one)
... = m ^ 2 : by conv_rhs {rw [← nat.mod_add_div m 2]};
simp [-nat.mod_add_div, mul_add, add_mul, bit0, bit1, mul_comm, mul_assoc, mul_left_comm,
_root_.pow_add, add_comm, add_left_comm],
have hwxyzabcd : ((w^2 + x^2 + y^2 + z^2 : ℤ) : zmod m) =
((a^2 + b^2 + c^2 + d^2 : ℤ) : zmod m),
by simp [w, x, y, z, pow_two],
have hwxyz0 : ((w^2 + x^2 + y^2 + z^2 : ℤ) : zmod m) = 0,
by rw [hwxyzabcd, habcd, int.cast_mul, cast_coe_nat, zmod.cast_self, zero_mul],
let ⟨n, hn⟩ := ((char_p.int_cast_eq_zero_iff _ m _).1 hwxyz0) in
have hn0 : 0 < n.nat_abs, from int.nat_abs_pos_of_ne_zero (λ hn0,
have hwxyz0 : (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs^2 + z.nat_abs^2 : ℕ) = 0,
by { rw [← int.coe_nat_eq_zero, ← hnat_abs], rwa [hn0, mul_zero] at hn },
have habcd0 : (m : ℤ) ∣ a ∧ (m : ℤ) ∣ b ∧ (m : ℤ) ∣ c ∧ (m : ℤ) ∣ d,
by simpa [@add_eq_zero_iff_eq_zero_of_nonneg ℤ _ _ _ (pow_two_nonneg _) (pow_two_nonneg _),
nat.pow_two, w, x, y, z, (char_p.int_cast_eq_zero_iff _ m _), and.assoc] using hwxyz0,
let ⟨ma, hma⟩ := habcd0.1, ⟨mb, hmb⟩ := habcd0.2.1,
⟨mc, hmc⟩ := habcd0.2.2.1, ⟨md, hmd⟩ := habcd0.2.2.2 in
have hmdvdp : m ∣ p,
from int.coe_nat_dvd.1 ⟨ma^2 + mb^2 + mc^2 + md^2,
(domain.mul_right_inj (show (m : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 hm0)).1 $
by rw [← habcd, hma, hmb, hmc, hmd]; ring⟩,
(hp.2 _ hmdvdp).elim hm1 (λ hmeqp, by simpa [lt_irrefl, hmeqp] using hmp)),
have hawbxcydz : ((m : ℕ) : ℤ) ∣ a * w + b * x + c * y + d * z,
from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by rw [← hwxyz0]; simp; ring,
have haxbwczdy : ((m : ℕ) : ℤ) ∣ a * x - b * w - c * z + d * y,
from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by simp [sub_eq_add_neg]; ring,
have haybzcwdx : ((m : ℕ) : ℤ) ∣ a * y + b * z - c * w - d * x,
from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by simp [sub_eq_add_neg]; ring,
have hazbycxdw : ((m : ℕ) : ℤ) ∣ a * z - b * y + c * x - d * w,
from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by simp [sub_eq_add_neg]; ring,
let ⟨s, hs⟩ := hawbxcydz, ⟨t, ht⟩ := haxbwczdy, ⟨u, hu⟩ := haybzcwdx, ⟨v, hv⟩ := hazbycxdw in
have hn_nonneg : 0 ≤ n,
from nonneg_of_mul_nonneg_left
(by erw [← hn]; repeat {try {refine add_nonneg _ _}, try {exact pow_two_nonneg _}})
(int.coe_nat_pos.2 hm0),
have hnm : n.nat_abs < m,
from int.coe_nat_lt.1 (lt_of_mul_lt_mul_left
(by rw [int.nat_abs_of_nonneg hn_nonneg, ← hn, ← _root_.pow_two]; exact hwxyzlt)
(int.coe_nat_nonneg m)),
have hstuv : s^2 + t^2 + u^2 + v^2 = n.nat_abs * p,
from (domain.mul_right_inj (show (m^2 : ℤ) ≠ 0, from pow_ne_zero 2
(int.coe_nat_ne_zero_iff_pos.2 hm0))).1 $
calc (m : ℤ)^2 * (s^2 + t^2 + u^2 + v^2) = ((m : ℕ) * s)^2 + ((m : ℕ) * t)^2 +
((m : ℕ) * u)^2 + ((m : ℕ) * v)^2 :
by simp [_root_.mul_pow]; ring
... = (w^2 + x^2 + y^2 + z^2) * (a^2 + b^2 + c^2 + d^2) :
by simp only [hs.symm, ht.symm, hu.symm, hv.symm]; ring
... = _ : by rw [hn, habcd, int.nat_abs_of_nonneg hn_nonneg]; dsimp [m]; ring,
false.elim $ nat.find_min hm hnm ⟨lt_trans hnm hmp, hn0, s, t, u, v, hstuv⟩)
lemma sum_four_squares : ∀ n : ℕ, ∃ a b c d : ℕ, a^2 + b^2 + c^2 + d^2 = n
| 0 := ⟨0, 0, 0, 0, rfl⟩
| 1 := ⟨1, 0, 0, 0, rfl⟩
| n@(k+2) :=
have hm : _root_.fact (min_fac (k+2)).prime := min_fac_prime dec_trivial,
have n / min_fac n < n := factors_lemma,
let ⟨a, b, c, d, h₁⟩ := show ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = min_fac n,
by exactI prime_sum_four_squares (min_fac (k+2)) in
let ⟨w, x, y, z, h₂⟩ := sum_four_squares (n / min_fac n) in
⟨(a * x - b * w - c * z + d * y).nat_abs,
(a * y + b * z - c * w - d * x).nat_abs,
(a * z - b * y + c * x - d * w).nat_abs,
(a * w + b * x + c * y + d * z).nat_abs,
begin
rw [← int.coe_nat_inj', ← nat.mul_div_cancel' (min_fac_dvd (k+2)), int.coe_nat_mul, ← h₁, ← h₂],
simp [nat.pow_two, int.coe_nat_add, int.nat_abs_mul_self'],
ring,
end⟩
end nat
|
ac64e265038c029ab4fa9e57af4d48da3b111a87 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/field_theory/mv_polynomial.lean | 87d83e1158194f48fcfd5c5342e582a4bc3c02df | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 9,746 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
Multivariate functions of the form `α^n → α` are isomorphic to multivariate polynomials in
`n` variables.
-/
import linear_algebra.finsupp_vector_space field_theory.finite data.mv_polynomial
noncomputable theory
local attribute [instance, priority 0] classical.prop_decidable
open lattice set linear_map submodule
namespace mv_polynomial
universes u v
variables {σ : Type u} {α : Type v} [decidable_eq σ]
instance [discrete_field α] : vector_space α (mv_polynomial σ α) :=
finsupp.vector_space _ _
section
variables (σ α) [discrete_field α] (m : ℕ)
def restrict_total_degree : submodule α (mv_polynomial σ α) :=
finsupp.supported _ _ {n | n.sum (λn e, e) ≤ m }
lemma mem_restrict_total_degree (p : mv_polynomial σ α) :
p ∈ restrict_total_degree σ α m ↔ p.total_degree ≤ m :=
begin
rw [total_degree, finset.sup_le_iff],
refl
end
end
section
variables (σ α)
def restrict_degree (m : ℕ) [discrete_field α] : submodule α (mv_polynomial σ α) :=
finsupp.supported _ _ {n | ∀i, n i ≤ m }
end
lemma mem_restrict_degree [discrete_field α] (p : mv_polynomial σ α) (n : ℕ) :
p ∈ restrict_degree σ α n ↔ (∀s ∈ p.support, ∀i, (s : σ →₀ ℕ) i ≤ n) :=
begin
rw [restrict_degree, finsupp.mem_supported],
refl
end
lemma mem_restrict_degree_iff_sup [discrete_field α] (p : mv_polynomial σ α) (n : ℕ) :
p ∈ restrict_degree σ α n ↔ ∀i, p.degrees.count i ≤ n :=
begin
simp only [mem_restrict_degree, degrees, multiset.count_sup, finsupp.count_to_multiset,
finset.sup_le_iff],
exact ⟨assume h n s hs, h s hs n, assume h s hs n, h n s hs⟩
end
lemma map_range_eq_map {β : Type*}
[decidable_eq α] [comm_ring α] [decidable_eq β] [comm_ring β] (p : mv_polynomial σ α)
(f : α → β) [is_semiring_hom f]:
finsupp.map_range f (is_semiring_hom.map_zero f) p = p.map f :=
begin
rw [← finsupp.sum_single p, finsupp.sum, finsupp.map_range_finset_sum,
← finset.sum_hom (map f)],
{ refine finset.sum_congr rfl (assume n _, _),
rw [finsupp.map_range_single, ← monomial, ← monomial, map_monomial] },
apply_instance
end
section
variables (σ α)
lemma is_basis_monomials [discrete_field α] :
is_basis α ((λs, (monomial s 1 : mv_polynomial σ α))) :=
suffices is_basis α (λ (sa : Σ _, unit), (monomial sa.1 1 : mv_polynomial σ α)),
begin
apply is_basis.comp this (λ (s : σ →₀ ℕ), ⟨s, punit.star⟩),
split,
{ intros x y hxy,
simpa using hxy },
{ intros x,
rcases x with ⟨x₁, x₂⟩,
use x₁,
rw punit_eq punit.star x₂ }
end,
begin
apply finsupp.is_basis_single (λ _ _, (1 : α)),
intro _,
apply is_basis_singleton_one, end
end
end mv_polynomial
namespace mv_polynomial
universe u
variables (σ : Type u) (α : Type u) [decidable_eq σ] [discrete_field α]
local attribute [instance, priority 0] classical.prop_decidable
lemma dim_mv_polynomial : vector_space.dim α (mv_polynomial σ α) = cardinal.mk (σ →₀ ℕ) :=
by rw [← cardinal.lift_inj, ← (is_basis_monomials σ α).mk_eq_dim]
end mv_polynomial
namespace mv_polynomial
variables {α : Type*} {σ : Type*}
variables [discrete_field α] [fintype α] [fintype σ] [decidable_eq σ]
def indicator (a : σ → α) : mv_polynomial σ α :=
finset.univ.prod (λn, 1 - (X n - C (a n))^(fintype.card α - 1))
lemma eval_indicator_apply_eq_one (a : σ → α) :
eval a (indicator a) = 1 :=
have 0 < fintype.card α - 1,
begin
rw [← finite_field.card_units, fintype.card_pos_iff],
exact ⟨1⟩
end,
by simp only [indicator, (finset.prod_hom (eval a)).symm, eval_sub,
is_ring_hom.map_one (eval a), is_semiring_hom.map_pow (eval a), eval_X, eval_C,
sub_self, zero_pow this, sub_zero, finset.prod_const_one]
lemma eval_indicator_apply_eq_zero (a b : σ → α) (h : a ≠ b) :
eval a (indicator b) = 0 :=
have ∃i, a i ≠ b i, by rwa [(≠), function.funext_iff, not_forall] at h,
begin
rcases this with ⟨i, hi⟩,
simp only [indicator, (finset.prod_hom (eval a)).symm, eval_sub,
is_ring_hom.map_one (eval a), is_semiring_hom.map_pow (eval a), eval_X, eval_C,
sub_self, finset.prod_eq_zero_iff],
refine ⟨i, finset.mem_univ _, _⟩,
rw [finite_field.pow_card_sub_one_eq_one, sub_self],
rwa [(≠), sub_eq_zero],
end
lemma degrees_indicator (c : σ → α) :
degrees (indicator c) ≤ finset.univ.sum (λs:σ, add_monoid.smul (fintype.card α - 1) {s}) :=
begin
rw [indicator],
refine le_trans (degrees_prod _ _) (finset.sum_le_sum $ assume s hs, _),
refine le_trans (degrees_sub _ _) _,
rw [degrees_one, ← bot_eq_zero, bot_sup_eq],
refine le_trans (degrees_pow _ _) (add_monoid.smul_le_smul_of_le_right _ _),
refine le_trans (degrees_sub _ _) _,
rw [degrees_C, ← bot_eq_zero, sup_bot_eq],
exact degrees_X _
end
set_option class.instance_max_depth 50
lemma indicator_mem_restrict_degree (c : σ → α) :
indicator c ∈ restrict_degree σ α (fintype.card α - 1) :=
begin
rw [mem_restrict_degree_iff_sup, indicator],
assume n,
refine le_trans (multiset.count_le_of_le _ $ degrees_indicator _) (le_of_eq _),
rw [← finset.sum_hom (multiset.count n)],
simp only [is_add_monoid_hom.map_smul (multiset.count n), multiset.singleton_eq_singleton,
add_monoid.smul_eq_mul, nat.cast_id],
transitivity,
refine finset.sum_eq_single n _ _,
{ assume b hb ne, rw [multiset.count_cons_of_ne ne.symm, multiset.count_zero, mul_zero] },
{ assume h, exact (h $ finset.mem_univ _).elim },
{ rw [multiset.count_cons_self, multiset.count_zero, mul_one] }
end
section
variables (α σ)
def evalₗ : mv_polynomial σ α →ₗ[α] (σ → α) → α :=
⟨ λp e, p.eval e,
assume p q, funext $ assume e, eval_add,
assume a p, funext $ assume e, by rw [smul_eq_C_mul, eval_mul, eval_C]; refl ⟩
end
section
set_option class.instance_max_depth 50
lemma evalₗ_apply (p : mv_polynomial σ α) (e : σ → α) : evalₗ α σ p e = p.eval e :=
rfl
end
lemma map_restrict_dom_evalₗ : (restrict_degree σ α (fintype.card α - 1)).map (evalₗ α σ) = ⊤ :=
begin
refine top_unique (submodule.le_def'.2 $ assume e _, mem_map.2 _),
refine ⟨finset.univ.sum (λn:σ → α, e n • indicator n), _, _⟩,
{ exact sum_mem _ (assume c _, smul_mem _ _ (indicator_mem_restrict_degree _)) },
{ ext n,
simp only [linear_map.map_sum, @pi.finset_sum_apply (σ → α) (λ_, α) _ _ _ _ _,
pi.smul_apply, linear_map.map_smul],
simp only [evalₗ_apply],
transitivity,
refine finset.sum_eq_single n _ _,
{ assume b _ h,
rw [eval_indicator_apply_eq_zero _ _ h.symm, smul_zero] },
{ assume h, exact (h $ finset.mem_univ n).elim },
{ rw [eval_indicator_apply_eq_one, smul_eq_mul, mul_one] } }
end
end mv_polynomial
namespace mv_polynomial
universe u
variables (σ : Type u) (α : Type u) [decidable_eq σ] [fintype σ] [discrete_field α] [fintype α]
def R : Type u := restrict_degree σ α (fintype.card α - 1)
instance R.add_comm_group : add_comm_group (R σ α) := by dunfold R; apply_instance
instance R.vector_space : vector_space α (R σ α) := by dunfold R; apply_instance
noncomputable instance decidable_restrict_degree (m : ℕ) :
decidable_pred (λn, n ∈ {n : σ →₀ ℕ | ∀i, n i ≤ m }) :=
by simp only [set.mem_set_of_eq]; apply_instance
set_option class.instance_max_depth 60
lemma dim_R : vector_space.dim α (R σ α) = fintype.card (σ → α) :=
calc vector_space.dim α (R σ α) =
vector_space.dim α (↥{s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card α - 1} →₀ α) :
linear_equiv.dim_eq
(finsupp.supported_equiv_finsupp {s : σ →₀ ℕ | ∀n:σ, s n ≤ fintype.card α - 1 })
... = cardinal.mk {s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card α - 1} :
by rw [finsupp.dim_eq, dim_of_field, mul_one]
... = cardinal.mk {s : σ → ℕ | ∀ (n : σ), s n < fintype.card α } :
begin
refine quotient.sound ⟨equiv.subtype_congr finsupp.equiv_fun_on_fintype $ assume f, _⟩,
refine forall_congr (assume n, nat.le_sub_right_iff_add_le _),
exact fintype.card_pos_iff.2 ⟨0⟩
end
... = cardinal.mk (σ → {n // n < fintype.card α}) :
quotient.sound ⟨@equiv.subtype_pi_equiv_pi σ (λ_, ℕ) (λs n, n < fintype.card α)⟩
... = cardinal.mk (σ → fin (fintype.card α)) :
quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) (equiv.fin_equiv_subtype _).symm⟩
... = cardinal.mk (σ → α) :
begin
refine (trunc.induction_on (fintype.equiv_fin α) $ assume (e : α ≃ fin (fintype.card α)), _),
refine quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) e.symm⟩
end
... = fintype.card (σ → α) : cardinal.fintype_card _
def evalᵢ : R σ α →ₗ[α] (σ → α) → α :=
((evalₗ α σ).comp (restrict_degree σ α (fintype.card α - 1)).subtype)
lemma range_evalᵢ : (evalᵢ σ α).range = ⊤ :=
begin
rw [evalᵢ, linear_map.range_comp, range_subtype],
exact map_restrict_dom_evalₗ
end
lemma ker_evalₗ : (evalᵢ σ α).ker = ⊥ :=
begin
refine injective_of_surjective _ _ _ (range_evalᵢ _ _),
{ rw [dim_R], exact cardinal.nat_lt_omega _ },
{ rw [dim_R, dim_fun, dim_of_field, mul_one] }
end
lemma eq_zero_of_eval_eq_zero (p : mv_polynomial σ α)
(h : ∀v:σ → α, p.eval v = 0) (hp : p ∈ restrict_degree σ α (fintype.card α - 1)) :
p = 0 :=
let p' : R σ α := ⟨p, hp⟩ in
have p' ∈ (evalᵢ σ α).ker := by rw [mem_ker]; ext v; exact h v,
show p'.1 = (0 : R σ α).1,
begin
rw [ker_evalₗ, mem_bot] at this,
rw [this]
end
end mv_polynomial
|
0750734a3ab8d668896c4c6a4dee6b646821a896 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/order/game_add.lean | dc17266a04583a31e51139db57b5346c163bb46e | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 3,052 | lean | /-
Copyright (c) 2022 Junyan Xu. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Junyan Xu
-/
import order.basic
import logic.relation
/-!
# Game addition relation
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> https://github.com/leanprover-community/mathlib4/pull/645
> Any changes to this file require a corresponding PR to mathlib4.
This file defines, given relations `rα : α → α → Prop` and `rβ : β → β → Prop`, a relation
`prod.game_add` on pairs, such that `game_add rα rβ x y` iff `x` can be reached from `y` by
decreasing either entry (with respect to `rα` and `rβ`). It is so called since it models the
subsequency relation on the addition of combinatorial games.
## Main definitions and results
- `prod.game_add`: the game addition relation on ordered pairs.
- `well_founded.prod_game_add`: formalizes induction on ordered pairs, where exactly one entry
decreases at a time.
## Todo
- Add custom `induction` and `fix` lemmas.
- Define `sym2.game_add`.
-/
variables {α β : Type*} (rα : α → α → Prop) (rβ : β → β → Prop)
namespace prod
/-- The "addition of games" relation in combinatorial game theory, on the product type: if
`rα a' a` means that `a ⟶ a'` is a valid move in game `α`, and `rβ b' b` means that `b ⟶ b'`
is a valid move in game `β`, then `game_add rα rβ` specifies the valid moves in the juxtaposition
of `α` and `β`: the player is free to choose one of the games and make a move in it,
while leaving the other game unchanged. -/
inductive game_add : α × β → α × β → Prop
| fst {a' a b} : rα a' a → game_add (a',b) (a,b)
| snd {a b' b} : rβ b' b → game_add (a,b') (a,b)
/-- `game_add` is a `subrelation` of `prod.lex`. -/
lemma game_add_le_lex : game_add rα rβ ≤ prod.lex rα rβ :=
λ _ _ h, h.rec (λ _ _ b, prod.lex.left b b) (λ a _ _, prod.lex.right a)
/-- `prod.rprod` is a subrelation of the transitive closure of `game_add`. -/
lemma rprod_le_trans_gen_game_add : prod.rprod rα rβ ≤ relation.trans_gen (game_add rα rβ) :=
λ _ _ h, h.rec begin
intros _ _ _ _ hα hβ,
exact relation.trans_gen.tail (relation.trans_gen.single $ game_add.fst hα) (game_add.snd hβ),
end
end prod
variables {rα rβ}
/-- If `a` is accessible under `rα` and `b` is accessible under `rβ`, then `(a, b)` is
accessible under `prod.game_add rα rβ`. Notice that `prod.lex_accessible` requires the
stronger condition `∀ b, acc rβ b`. -/
lemma acc.prod_game_add {a b} (ha : acc rα a) (hb : acc rβ b) : acc (prod.game_add rα rβ) (a, b) :=
begin
induction ha with a ha iha generalizing b,
induction hb with b hb ihb,
refine acc.intro _ (λ h, _),
rintro (⟨ra⟩ | ⟨rb⟩),
exacts [iha _ ra (acc.intro b hb), ihb _ rb],
end
/-- The sum of two well-founded games is well-founded. -/
lemma well_founded.prod_game_add (hα : well_founded rα) (hβ : well_founded rβ) :
well_founded (prod.game_add rα rβ) := ⟨λ ⟨a,b⟩, (hα.apply a).prod_game_add (hβ.apply b)⟩
|
a77835ff608f7b1a2c4e0e076638ad5d15a0bc05 | 01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab | /categories/currying/currying_2.lean | 3a79afc48f123abea5015dc5504e8e8c3d9bbebe | [] | no_license | PatrickMassot/lean-category-theory | 0f56a83464396a253c28a42dece16c93baf8ad74 | ef239978e91f2e1c3b8e88b6e9c64c155dc56c99 | refs/heads/master | 1,629,739,187,316 | 1,512,422,659,000 | 1,512,422,659,000 | 113,098,786 | 0 | 0 | null | 1,512,424,022,000 | 1,512,424,022,000 | null | UTF-8 | Lean | false | false | 1,235 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
-- TODO this was taking forever to compile
-- import .currying_1
-- open categories
-- open categories.isomorphism
-- open categories.functor
-- open categories.equivalence
-- namespace categories.natural_transformation
-- universes u1 v1 u2 v2 u3 v3
-- variable C : Category.{u1 v1}
-- variable D : Category.{u2 v2}
-- variable E : Category.{u3 v3}
-- definition Curry_Uncurry_to_identity
-- : NaturalTransformation (FunctorComposition (Uncurry_Functors C D E) (Curry_Functors C D E)) (IdentityFunctor _) := ♯
-- definition identity_to_Curry_Uncurry
-- : NaturalTransformation (IdentityFunctor _) (FunctorComposition (Uncurry_Functors C D E) (Curry_Functors C D E)) := ♯
-- definition Uncurry_Curry_to_identity
-- : NaturalTransformation (FunctorComposition (Curry_Functors C D E) (Uncurry_Functors C D E)) (IdentityFunctor _) := ♯
-- definition identity_to_Uncurry_Curry
-- : NaturalTransformation (IdentityFunctor _) (FunctorComposition (Curry_Functors C D E) (Uncurry_Functors C D E)) := ♯
-- end categories.natural_transformation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.